_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q250400
AbstractController.redirect
validation
protected function redirect($controller = null, $action = null) { if (null === $controller) { $controller = Application::getInstance()->getDefaultController(); } if (null === $action) { $action = Application::getInstance()->getDefaultAction(); } $destination = sprintf("Location: %s%s/%s", $this->request->getContextPrefix(), $controller, $action); header($destination); exit(); }
php
{ "resource": "" }
q250401
HttpHeadersTrait.adjustHeaders
validation
private function adjustHeaders($requestType) { if (! array_key_exists('Accept', $this->headers) && $requestType != 'HEAD') { $this->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); } if (! array_key_exists('Accept-Language', $this->headers) && $requestType != 'HEAD') { $this->setHeader('Accept-Language', 'en-US;q=0.7,en;q=0.3'); } if (! array_key_exists('User-Agent', $this->headers) && $requestType != 'HEAD') { $this->setHeader('User-Agent', 'phpGenerics 1.0'); } if (! array_key_exists('Connection', $this->headers) || strlen($this->headers['Connection']) == 0) { $this->adjustConnectionHeader($requestType); } if (! array_key_exists('Accept-Encoding', $this->headers)) { if (function_exists('gzinflate')) { $encoding = 'gzip, deflate'; } else { $encoding = 'identity'; } $this->setHeader('Accept-Encoding', $encoding); } }
php
{ "resource": "" }
q250402
HttpHeadersTrait.addParsedHeader
validation
private function addParsedHeader($line) { if (strpos($line, ':') === false) { $this->responseCode = HttpStatus::parseStatus($line)->getCode(); } else { $line = trim($line); list ($headerName, $headerValue) = explode(':', $line, 2); $this->headers[$headerName] = trim($headerValue); } }
php
{ "resource": "" }
q250403
HttpHeadersTrait.adjustNumbytes
validation
private function adjustNumbytes($numBytes): int { if (isset($this->headers['Content-Length'])) { // Try to read the whole payload at once $numBytes = intval($this->headers['Content-Length']); } return $numBytes; }
php
{ "resource": "" }
q250404
HttpHeadersTrait.getHeader
validation
private function getHeader(string $name): string { $result = ""; if (Arrays::hasElement($this->headers, $name)) { $result = $this->headers[$name]; } return $result; }
php
{ "resource": "" }
q250405
XmlFileLoader.parseNode
validation
protected function parseNode(RuleCollection $collection, \DOMElement $node, $path, $file) { if (self::NAMESPACE_URI !== $node->namespaceURI) { return; } switch ($node->localName) { case 'rule': $this->parseRule($collection, $node, $path); break; case 'import': $this->parseImport($collection, $node, $path, $file); break; default: throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "rule" or "import".', $node->localName, $path)); } }
php
{ "resource": "" }
q250406
Prototype.fields
validation
public function fields($entity = array(), $action = 'all', array $params = array()) { $fieldCollection = array(); $entity = $this->entityFactory->build($entity); if ($entity instanceof \ElggEntity) { $params['entity'] = $entity; $fields = (array) elgg_trigger_plugin_hook('prototype', $action, $params, array()); $attribute_names = $this->entityFactory->getAttributeNames($entity); if (!$entity->guid) { $fields['type'] = array('type' => 'hidden'); $fields['subtype'] = array('type' => 'hidden'); $fields['owner_guid'] = array('type' => 'hidden'); $fields['container_guid'] = array('type' => 'hidden'); } else { $fields['guid'] = array('type' => 'hidden'); } foreach ($fields as $shortname => $field) { $field['entity_type'] = $entity->getType(); $field['entity_subtype'] = $entity->getSubtype(); if (empty($field['shortname'])) { $field['shortname'] = $shortname; } if (in_array($shortname, $attribute_names)) { $field['data_type'] = 'attribute'; $field['class_name'] = Elements\AttributeField::CLASSNAME; } $fieldObj = $this->fieldFactory->build($field); if ($fieldObj instanceof Elements\Field) { $fieldCollection[] = $fieldObj; } } } return new Elements\FieldCollection($fieldCollection); }
php
{ "resource": "" }
q250407
Prototype.getValidationStatus
validation
public function getValidationStatus($action = '') { $validation_status = null; if (isset($_SESSION['prototyper_validation'][$action])) { $validation_status = $_SESSION['prototyper_validation'][$action]; } return $validation_status; }
php
{ "resource": "" }
q250408
Prototype.setFieldValidationStatus
validation
public function setFieldValidationStatus($action = '', $shortname = '', Elements\ValidationStatus $validation = null) { if (!isset($_SESSION['prototyper_validation'][$action])) { $_SESSION['prototyper_validation'][$action] = array(); } $_SESSION['prototyper_validation'][$action][$shortname] = array( 'status' => $validation->getStatus(), 'messages' => $validation->getMessages() ); }
php
{ "resource": "" }
q250409
EndpointParser.parseUrl
validation
public static function parseUrl($url): Endpoint { $url = UrlParser::parseUrl($url); return new Endpoint($url->getAddress(), $url->getPort()); }
php
{ "resource": "" }
q250410
Message.setTimestampCreated
validation
public function setTimestampCreated($postTime) { if ($postTime instanceof DateTime) { $this->timestampCreated = $postTime; } else { $this->timestampCreated = new DateTime($postTime); } return $this; }
php
{ "resource": "" }
q250411
SettingController.updateCompany
validation
public function updateCompany(\Unite\Contacts\Http\Requests\UpdateRequest $request) { $this->service->saveCompanyProfile( $request->all() ); return $this->successJsonResponse(); }
php
{ "resource": "" }
q250412
ConfigProvider.getControllerPluginConfig
validation
public function getControllerPluginConfig() { return [ 'aliases' => [ 'email' => Controller\Plugin\Email::class, 'mutex' => Controller\Plugin\Mutex::class, 'referer' => Controller\Plugin\Referer::class, 'settings' => Controller\Plugin\Settings::class, 'thumbnail' => Controller\Plugin\Thumbnail::class, 'zettaUrl' => Controller\Plugin\Url::class, ], 'factories' => [ Controller\Plugin\Email::class => Controller\Plugin\Factory\EmailFactory::class, Controller\Plugin\Mutex::class => Controller\Plugin\Factory\MutexFactory::class, Controller\Plugin\Referer::class => InvokableFactory::class, Controller\Plugin\Settings::class => Factory\WithSettingsFactory::class, Controller\Plugin\Thumbnail::class => Factory\WithThumbnailFactory::class, Controller\Plugin\Url::class => Factory\WithUrlConfigFactory::class, ], ]; }
php
{ "resource": "" }
q250413
ConfigProvider.getViewHelpers
validation
public function getViewHelpers() { return [ 'aliases' => [ 'formmulticheckbox' => Form\View\Helper\FormMultiCheckbox::class, 'formradio' => Form\View\Helper\FormRadio::class, 'zettaFlashMessenger' => View\Helper\FlashMessenger::class, 'zettaFormMultiCheckbox' => Form\View\Helper\FormMultiCheckbox::class, 'zettaFormRadio' => Form\View\Helper\FormRadio::class, 'zettaFormRow' => Form\View\Helper\FormRow::class, 'zettaPaginator' => View\Helper\Paginator::class, 'zettaReferer' => View\Helper\Referer::class, 'settings' => View\Helper\Settings::class, 'thumbnail' => View\Helper\Thumbnail::class, 'zettaUrl' => View\Helper\Url::class, ], 'factories' => [ Form\View\Helper\FormMultiCheckbox::class => InvokableFactory::class, Form\View\Helper\FormRadio::class => InvokableFactory::class, Form\View\Helper\FormRow::class => InvokableFactory::class, View\Helper\FlashMessenger::class => InvokableFactory::class, View\Helper\Paginator::class => View\Helper\Factory\PaginatorFactory::class, View\Helper\Referer::class => View\Helper\Factory\RefererFactory::class, View\Helper\Settings::class => Factory\WithSettingsFactory::class, View\Helper\Thumbnail::class => Factory\WithThumbnailFactory::class, View\Helper\Url::class => View\Helper\Factory\UrlFactory::class ], ]; }
php
{ "resource": "" }
q250414
JsonToMenuTreeTransformer.reverseTransform
validation
public function reverseTransform($jsonMenuNodes) { // TODO add exception if ($jsonMenuNodes instanceof Collection && $jsonMenuNodes->count() === 0) { return new ArrayCollection(); } $this->allNodes = []; // TODO handle no node $firstNode = json_decode($jsonMenuNodes->first())[0]; // Only handle the first collection item which contain all tree $menuItemsArray = $this->recursiveNodeHandling(json_decode($jsonMenuNodes->first())); // Remove delta which is not present anymore return new ArrayCollection($menuItemsArray); }
php
{ "resource": "" }
q250415
JsonToMenuTreeTransformer.hierarchyToFlatArray
validation
private function hierarchyToFlatArray($items) { $flatArray = []; foreach($items as $item) { $flatArray[] = $item->getId(); // TODO generalize if($items->getChildren()->count() > 0) { $flatArray = array_merge($flatArray, $this->hierarchyToFlatArray($items->getChildren())); } } return $flatArray; }
php
{ "resource": "" }
q250416
Referer.fromRoute
validation
public function fromRoute($route = null, $params = [], $options = [], $reuseMatchedParams = false) { $controller = $this->getController(); if (!$controller || !method_exists($controller, 'plugin')) { throw new Exception\DomainException('Redirect plugin requires a controller that defines the plugin() method'); } $referer = $controller->getRequest()->getHeader('Referer'); if ($referer) { $refererUrl = $referer->uri()->getPath(); // referer url $refererHost = $referer->uri()->getHost(); // referer host $host = $controller->getRequest()->getUri()->getHost(); // current host // only redirect to previous page if request comes from same host if ($refererUrl && ($refererHost == $host)) { return $refererUrl; } } // redirect to home if no referer or from another page $urlPlugin = $controller->plugin('url'); return $urlPlugin->fromRoute($route, $params, $options, $reuseMatchedParams); }
php
{ "resource": "" }
q250417
Configuration.getPlugins
validation
public function getPlugins() { // iterate over the operations and return the subjects of the actual one /** @var TechDivision\Import\Configuration\OperationInterface $operation */ foreach ($this->getOperations() as $operation) { if ($this->getOperation()->equals($operation)) { return $operation->getPlugins(); } } // throw an exception if no plugins are available throw new \Exception(sprintf('Can\'t find any plugins for operation %s', $this->getOperation())); }
php
{ "resource": "" }
q250418
Configuration.mapBoolean
validation
public function mapBoolean($value) { // try to map the passed value to a boolean if (isset($this->booleanMapping[$value])) { return $this->booleanMapping[$value]; } // throw an exception if we can't convert the passed value throw new \Exception(sprintf('Can\'t convert %s to boolean', $value)); }
php
{ "resource": "" }
q250419
Configuration.getDatabaseById
validation
public function getDatabaseById($id) { // iterate over the configured databases and return the one with the passed ID /** @var TechDivision\Import\Configuration\DatabaseInterface $database */ foreach ($this->databases as $database) { if ($database->getId() === $id) { return $database; } } // throw an exception, if the database with the passed ID is NOT configured throw new \Exception(sprintf('Database with ID %s can not be found', $id)); }
php
{ "resource": "" }
q250420
Configuration.getDatabase
validation
public function getDatabase() { // if a DB ID has been set, try to load the database if ($useDbId = $this->getUseDbId()) { return $this->getDatabaseById($useDbId); } // iterate over the configured databases and try return the default database /** @var TechDivision\Import\Configuration\DatabaseInterface $database */ foreach ($this->databases as $database) { if ($database->isDefault()) { return $database; } } // try to return the first database configurtion if ($this->databases->count() > 0) { return $this->databases->first(); } // throw an exception, if no database configuration is available throw new \Exception('There is no database configuration available'); }
php
{ "resource": "" }
q250421
AbstractView.getViewSettings
validation
final public function getViewSettings() { $rf = new \ReflectionClass($this); $this->viewName = str_replace('View', '', $rf->getShortName()); $matches = array(); if (preg_match("#@applyTo\((.*)\)#", $rf->getDocComment(), $matches)) { $params = array(); parse_str(str_replace(',', '&', $matches[1]), $params); if (is_array($params)) { foreach ($params as $param => $value) { if ($param == 'controller') { $this->controllers = explode('|', $value); } if ($param == 'action') { $this->actions = explode('|', $value); } } } } return $this; }
php
{ "resource": "" }
q250422
Memory.forget
validation
public function forget($args = []) { if (!empty($args)) { if (is_array($args)) { $args = implode('_', $args); } if (empty($this->forgetful)) { $this->forgetful = get_class_methods($this); } foreach ($this->forgetful as $method) { $cacheKey = str_replace('\\', '_', get_class($this).'_'.$method.'_'); $this->forgetByKey($cacheKey); $cacheKey = str_replace('\\', '_', get_class($this).'_'.$method.'_'.$args); $this->forgetByKey($cacheKey); } } else { $key = $this->getRememberKey(); $this->forgetByKey($key); } return $this; }
php
{ "resource": "" }
q250423
Memory.remember
validation
public function remember($value, $memoryDuration = null) { if (is_null($memoryDuration)) { $memoryDuration = $this->memoryDuration; } $key = $this->getRememberKey(); if (Cache::has($key)) { $value = Cache::get($key); } else { $expiresAt = Carbon::now()->addMinutes($memoryDuration); if (is_callable($value)) { $value = $value(); } Cache::put($key, $value, $expiresAt); } return $value; }
php
{ "resource": "" }
q250424
Memory.forgetByKey
validation
protected function forgetByKey($key) { $result = false; if (Cache::has($key)) { $result = Cache::forget($key); } return $result; }
php
{ "resource": "" }
q250425
Memory.getRememberKey
validation
protected function getRememberKey() { $backtrace = debug_backtrace(4)[2]; $args = implode('_', $backtrace['args']); $key = str_replace('\\', '_', get_class($this).'_'.$backtrace['function'].'_'.$args); return $key; }
php
{ "resource": "" }
q250426
ConfigurationFactory.toArray
validation
protected function toArray($data, $type, $format) { // load the serializer builde $serializer = SerializerBuilder::create()->build(); // deserialize the data, convert it into an array and return it return $serializer->toArray($serializer->deserialize($data, $type, $format)); }
php
{ "resource": "" }
q250427
ConfigurationFactory.mergeParams
validation
protected function mergeParams(&$data, $params) { // merge the passed params into the configuration data foreach ($params as $paramName => $paramValue) { if (is_array($paramValue)) { foreach ($paramValue as $key => $value) { foreach ($value as $name => $x) { $data[$paramName][$key][$name] = $x; } } } else { $data[$paramName] = $paramValue; } } }
php
{ "resource": "" }
q250428
GoogleCampaignPlugin.embedCampaigns
validation
public static function embedCampaigns( $html, $campaign = [], $additionalCampaigns = [] ) { $pattern = '/<a(\s[^>]*)href="([^"]*)"([^>]*)>/si'; $html = preg_replace_callback($pattern, function($matches) use ($campaign, $additionalCampaigns) { $href = GoogleCampaignPlugin::replaceLink($matches[2], $campaign, $additionalCampaigns); return "<a{$matches[1]}href=\"{$href}\"{$matches[3]}>"; }, $html); return $html; }
php
{ "resource": "" }
q250429
ClientSocket.connect
validation
public function connect() { if (!is_resource($this->handle)) { throw new SocketException("Socket is not available"); } if (! @socket_connect($this->handle, $this->endpoint->getAddress(), $this->endpoint->getPort())) { $code = socket_last_error($this->handle); throw new SocketException(socket_strerror($code), array(), $code); } $this->conntected = true; }
php
{ "resource": "" }
q250430
Presentable.present
validation
public function present() { $presenterClass = $this->getPresenterClass(); if (!class_exists($presenterClass)) { throw new Exceptions\PresenterException('The specified presenter does not exist.'); } if (!$this->presenterInstance) { $this->presenterInstance = new $presenterClass($this); } return $this->presenterInstance; }
php
{ "resource": "" }
q250431
FlashMessenger.render
validation
public function render(array $classes = [], $autoEscape = null) { $divOpen = '<div class="' . $this->divClass . '">'; $divClose = '</div>'; $hasMessages = false; foreach ($this->classes as $namespace => $namespaceClasses) { $namespaceClasses = ArrayUtils::merge($namespaceClasses, $classes); if ($this->getFlashMessengerHelper()->getPluginFlashMessenger()->hasCurrentMessages($namespace)) { $hasMessages = true; $divOpen .= $this->getFlashMessengerHelper()->renderCurrent($namespace, $namespaceClasses, $autoEscape); $this->getFlashMessengerHelper()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace($namespace); } elseif ($this->getFlashMessengerHelper()->getPluginFlashMessenger()->hasMessages($namespace)) { $hasMessages = true; $divOpen .= $this->getFlashMessengerHelper()->render($namespace, $namespaceClasses, $autoEscape); } } return $hasMessages ? $divOpen . $divClose : ''; }
php
{ "resource": "" }
q250432
Converter.convert
validation
public static function convert($identifier, $sourceFormat, $outputFormat) { $parts = Parser::parse($identifier, $sourceFormat); return Formatter::format($parts, $outputFormat); }
php
{ "resource": "" }
q250433
Manager.init
validation
public function init() { if ($this->isInitialized()) return true; // attach default listeners /** @var $sharedEvents \Zend\EventManager\SharedEventManager */ $sm = $this->getServiceManager(); $defaultListeners = $sm->get('yimaTheme.Manager.ListenerAggregate'); if ($defaultListeners instanceof self) // inject themeManager $defaultListeners->manager = $this; $sharedEvents = $this->getEventManager()->getSharedManager(); $sharedEvents->attachAggregate($defaultListeners); $this->isInitialized = true; return $this; }
php
{ "resource": "" }
q250434
Theme.init
validation
public function init() { if ($this->isInitialized()) return $this; if (!$this->getThemesPath() || !$this->getName()) throw new \Exception('Theme Cant initialize because theme name or theme paths not present.'); $themePathname = $this->getThemesPath().DS.$this->getName(); if (!is_dir($themePathname)) throw new \Exception(sprintf('Theme "%s" not found in "%s".', $this->getName(), $themePathname)); $bootstrap = $themePathname.DS.'theme.bootstrap.php'; if (file_exists($bootstrap)) { ob_start(); set_error_handler( function($errno, $errstr) { throw new \ErrorException($errstr, $errno); }, E_ALL ); include $bootstrap; // Bootstrap Theme restore_error_handler(); ob_get_clean(); } $this->initialized = true; return $this; }
php
{ "resource": "" }
q250435
Theme.addChild
validation
public function addChild(ModelInterface $child, $captureTo = null, $append = null) { parent::addChild($child, $captureTo, $append); if ($child instanceof ThemeDefaultInterface) { $child->parent = $this; } return $this; }
php
{ "resource": "" }
q250436
Theme.setThemesPath
validation
public function setThemesPath($path) { if (!is_dir($path)) { throw new \Exception( sprintf('Path "%s" not found.', $path) ); } $this->themesPath = rtrim($path, DS); return $this; }
php
{ "resource": "" }
q250437
Theme.config
validation
public function config() { if (!$this->config) { $config = array(); $configFile = $this->getThemesPath() .DIRECTORY_SEPARATOR.$this->getName() .DIRECTORY_SEPARATOR.'theme.config.php'; if (file_exists($configFile)) { ob_start(); set_error_handler( function($errno, $errstr) { throw new \ErrorException($errstr, $errno); }, E_ALL ); $config = include $configFile; restore_error_handler(); ob_get_clean(); if (!is_array($config)) throw new \Exception('Invalid "'.$this->getName().'" Theme Config File. It must return array.'); } $this->config = new Entity($config); } return $this->config; }
php
{ "resource": "" }
q250438
DiscussController.getTag
validation
public function getTag() { if (null !== $this->tag) { return $this->tag; } $categoryId = $this->getEvent()->getRouteMatch()->getParam('categoryid'); if (is_numeric($categoryId)) { return $this->tag = $this->getDiscussService()->getCategoryById($categoryId); } // Find category by topic $topicId = $this->getEvent()->getRouteMatch()->getParam('topicid'); if (is_numeric($topicId)) { // Fetch the topic $topic = $this->getDiscussService()->getTopicById($topicId); // Fetch the category return $this->tag = $this->getDiscussService()->getCategoryById($topic->getforumCategoryId()); } return false; }
php
{ "resource": "" }
q250439
UserConnection.getRedirectUrlForAuth
validation
public function getRedirectUrlForAuth() { //Oauth1 plugin to get access tokens! $oauth = new Oauth1(array( 'consumer_key' => $this->credentials->getConsumerKey(), 'consumer_secret' => $this->credentials->getConsumerSecret(), 'callback' => $this->credentials->getCallbackUrl() )); $this->guzzleClient->getEmitter()->attach($oauth); //obtain request token for the authorization popup. $requestTokenResponse = $this->guzzleClient->post( Config::get('oauth_request_token'), array( 'auth' => 'oauth' ) ); //Parse the response from Twitter $oauthToken = array(); parse_str($requestTokenResponse->getBody(), $oauthToken); //build the query parameters $params = http_build_query(array( 'oauth_token' => $oauthToken['oauth_token'] )); //return the redirect URL the user should be redirected to. return (Config::get('base_url') . Config::get('oauth_authenticate') . '?' . $params); }
php
{ "resource": "" }
q250440
UserConnection.getAccessToken
validation
public function getAccessToken($oauthToken, $oauthVerifier) { //Oauth1 plugin to get access tokens! $oauth = new Oauth1(array( 'consumer_key' => $this->credentials->getConsumerKey(), 'consumer_secret' => $this->credentials->getConsumerSecret(), 'token' => $oauthToken, 'verifier' => $oauthVerifier )); //attach oauth to request $this->guzzleClient->getEmitter()->attach($oauth); //POST to 'oauth/access_token' - get access tokens $accessTokenResponse = $this->guzzleClient->post( Config::get('oauth_access_token'), array( 'auth' => 'oauth' ) ); //handle response $response = array(); parse_str($accessTokenResponse->getBody(), $response); //set access tokens $this->credentials ->setAccessToken($response['oauth_token']) ->setAccessTokenSecret($response['oauth_token_secret']); return $response; //contains 'oauth_token', 'oauth_token_secret', 'user_id' and 'screen_name' }
php
{ "resource": "" }
q250441
UserConnection.uploadMedia
validation
public function uploadMedia($filepaths, $client = null) { //maximum number of media files that a user can upload $maxMediaIds = Config::get('max_media_ids'); //if number of media files supplied is larger than $maxMediaIds, throw exception. if(count($filepaths) > $maxMediaIds) { throw new MediaUploadLimitException("You cannot upload more than ${maxMediaIds} media files in a tweet!"); } //array list of media id's uploaded $mediaIds = array(); //create a new Guzzle client, if the user hasn't injected anything! if(is_null($client)) { $client = $this->createGuzzleClient(Config::get('base_upload_url')); } //prepend Twitter's API version to the endpoint $endpoint = $this->prependVersionToEndpoint("media/upload.json", Config::get('api_version')); //iterate over each filepath foreach ($filepaths as $filepath) { //contruct an options array to configure the request $options = $this->constructRequestOptions(array(), $client); //add body options to the POST request $options['body'] = array ( 'media' => new PostFile('media', fopen($filepath, 'r')) ); //make the POST request to the endpoint with the constructed options. $response = $client->post($endpoint, $options); //add media_id to array array_push($mediaIds, $response->json()['media_id_string']); } //return all media ID's as a string (comma seperated) return (implode(",", $mediaIds)); }
php
{ "resource": "" }
q250442
AppConnection.createBearerCredentials
validation
private function createBearerCredentials() { //URL encode the consumer key and consumer secret $consumerKey = rawurlencode($this->credentials->getConsumerKey()); $consumerSecret = rawurlencode($this->credentials->getConsumerSecret()); //create bearer token credentials by concatenating the consumer key and consumer secret, seperated by a colon. $bearerTokenCredentials = $consumerKey . ':' . $consumerSecret; //base64 encode the bearer token credentials return base64_encode($bearerTokenCredentials); }
php
{ "resource": "" }
q250443
AppConnection.createBearerToken
validation
public function createBearerToken() { //get bearer token credentials - to be used for getting the bearer token from Twitter. $bearerCredentials = $this->createBearerCredentials(); //Required Headers $headers = array( 'Authorization' => 'Basic ' . $bearerCredentials, 'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8' ); //Required Body $body = 'grant_type=client_credentials'; //Send a Post request to `oauth2/token` and convert the resulting JSON to assoc-array. $data = $this->guzzleClient->post( Config::get('oauth2_token'), array( 'headers' => $headers, 'body' => $body ) )->json(); //Set the bearer token in the AppCredentials object $this->credentials->setBearerToken($data['access_token']); //Return the current object return $this; }
php
{ "resource": "" }
q250444
Connection.get
validation
public function get($endpoint, $params = null) { //prepend Twitter's API version to the endpoint $endpoint = $this->prependVersionToEndpoint($endpoint, Config::get('api_version')); //contruct an options array to configure the request $options = $this->constructRequestOptions($params); //make the GET request to the endpoint with the constructed options. $response = $this->guzzleClient->get($endpoint, $options); //return response return $response; }
php
{ "resource": "" }
q250445
Config.get
validation
public static function get($item) { //convert the item requested to upper, just in case. $item = strtoupper($item); //get all config items as an associative array from the JSON file $config = json_decode(file_get_contents(dirname(__FILE__) . "/Config.json"), true); //if the requested config item doesn't exist, throw Twitter\Config\Exceptions\InvalidConfigItemException if( !isset($config[$item]) ) { throw new InvalidConfigItemException("Invalid Endpoint Requested!"); } //return the requested item return $config[$item]; }
php
{ "resource": "" }
q250446
BasicSeedShell.init
validation
public function init() { $path = $this->absolutePath($this->getFile()); $this->quiet('Initializing seed file: ' . $this->shortPath($path)); $this->existsOrCreate($path); }
php
{ "resource": "" }
q250447
BasicSeedShell.importTables
validation
public function importTables(array $data) { $tableCount = count($data); $this->out("<info>Starting seed of {$tableCount} table(s).</info>"); foreach ($data as $table => $records) { $this->out("<info>{$table}</info>"); // Set default field values. $defaults = []; if (array_key_exists('_defaults', $records)) { $defaults = $records['_defaults']; unset($records['_defaults']); $this->verbose("<success>{$table}: Default values set.</success>"); } // Set entity options, if present. $entityOptions = []; if (array_key_exists('_options', $records)) { $entityOptions = $records['_options']; unset($records['_options']); $this->verbose("<success>{$table}: Entity options set, but...</success>"); $this->quiet("<warning>{$table}: Deprecation notice: Change [_options] to [_entityOptions].</warning>"); } elseif (array_key_exists('_entityOptions', $records)) { $entityOptions = $records['_entityOptions']; unset($records['_entityOptions']); $this->verbose("<success>{$table}: Entity options set.</success>"); } // Set save options, if present. $saveOptions = []; if (array_key_exists('_saveOptions', $records)) { $saveOptions = $records['_saveOptions']; unset($records['_saveOptions']); $this->verbose("<success>{$table}: Table save() options set.</success>"); } // Truncate the table, if requested. $Table = $this->loadModel($table); if (array_key_exists('_truncate', $records) && $records['_truncate']) { $this->truncateTable($Table); } unset($records['_truncate']); // Create or update all defined records. $this->importTable( $Table, $this->entityGenerator($Table, $records, $defaults, $entityOptions), $saveOptions ); } $this->out("<info>Seeding complete.</info>"); }
php
{ "resource": "" }
q250448
BasicSeedShell.importTable
validation
public function importTable(Table $Table, $records, array $options = []) { $defaultOptions = [ 'checkRules' => true, 'checkExisting' => true, ]; $options = $options + $defaultOptions; foreach ($records as $record) { $action = ($record->isNew() ? 'Create' : 'Update'); $result = $Table->save($record, $options); $key = $this->findKey($Table, $record); if ($result) { $this->verbose("<success>{$Table->alias()} ({$key}): {$action} successful.</success>"); } else { $this->quiet("<warning>{$Table->alias()} ({$key}): {$action} failed.</warning>"); $this->printValidationErrors( $Table->alias(), $this->findKey($Table, $record), $record->errors() ); } } }
php
{ "resource": "" }
q250449
BasicSeedShell.truncateTable
validation
protected function truncateTable($Table) { $truncateSql = $Table->schema()->truncateSql($Table->connection())[0]; $success = $Table->connection()->query($truncateSql); if ($success) { $this->verbose("<success>{$Table->alias()}: Existing DB records truncated.</success>"); } else { $this->quiet("<warning>{$Table->alias()}: Can not truncate existing records.</warning>"); } return $success; }
php
{ "resource": "" }
q250450
BasicSeedShell.findKey
validation
protected function findKey(Table $Table, Entity $entity) { if (!empty($entity->{$Table->primaryKey()})) { $key = $entity->{$Table->primaryKey()}; } else { $key = 'unknown'; } return $key; }
php
{ "resource": "" }
q250451
BasicSeedShell.printValidationErrors
validation
protected function printValidationErrors($table, $id, $errors) { foreach ($errors as $field => $messages) { foreach ((array)$messages as $message) { $this->quiet("<warning>{$table} ({$id}): {$field}: {$message}</warning>"); } } }
php
{ "resource": "" }
q250452
BasicSeedShell.getFile
validation
protected function getFile() { $file = ($this->params['dev'] ? $this->seedDevFile : $this->seedFile); if (!empty($this->params['file'])) { $file = $this->params['file']; } return $file; }
php
{ "resource": "" }
q250453
BasicSeedShell.existsOrCreate
validation
protected function existsOrCreate($file) { if (!file_exists($file)) { $this->out('<info>Creating empty seed file: ' . $this->shortPath($file) . '</info>'); file_put_contents($file, <<<'EOD' <?php /** * BasicSeed plugin data seed file. */ namespace App\Config\BasicSeed; use Cake\ORM\TableRegistry; // Write your data import statements here. $data = [ 'TableName' => [ //'_truncate' => true, //'_entityOptions' => [ // 'validate' => false, //], //'_saveOptions' => [ // 'checkRules' => false, //], '_defaults' => [], [ 'id' => 1, 'name' => 'record 1', ], ], ]; $this->importTables($data); EOD ); } }
php
{ "resource": "" }
q250454
BasicSeedShell.getOptionParser
validation
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description( 'Provides a mechanism for loading data into any of Cake\'s configured databases.' ) ->addSubcommand('init', [ 'help' => 'Initialize a new, empty seed file. Respects both the --dev and --file options.', ]) ->addOption('dev', [ 'short' => 'd', 'boolean' => true, 'default' => false, 'help' => 'Use the "dev" seed file instead of the default.' ]) ->addOption('file', [ 'short' => 'f', 'help' => 'Manually specify the file that should be used. When this option is present, its argument will always be used explicitly, overriding the --dev option if it is also present.' ]); return $parser; }
php
{ "resource": "" }
q250455
PageController.actionCreate
validation
public function actionCreate() { $model = new StaticPage(); $model->time = date("Y-m-d H:i:s"); $model->isdel = 0; $post = Yii::$app->request->post(); if (isset($post['StaticPage']['tags'])) { if (is_array($post['StaticPage']['tags'])) { $post['StaticPage']['tags'] = implode(",",$post['StaticPage']['tags']); } } if ($model->load($post) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q250456
PageController.actionUpdate
validation
public function actionUpdate($id) { $model = $this->findModel($id); $model->tags = !empty($model->tags)?explode(",",$model->tags):[]; $post = Yii::$app->request->post(); if (isset($post['StaticPage']['tags'])) { if (is_array($post['StaticPage']['tags'])) { $post['StaticPage']['tags'] = implode(",",$post['StaticPage']['tags']); } } if ($model->load($post) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q250457
PageController.actionDelete
validation
public function actionDelete($id) { $model = $this->findModel($id); $model->isdel = 1; $model->save(); //$model->delete(); //this will true delete return $this->redirect(['index']); }
php
{ "resource": "" }
q250458
CanvasArray.parsePageLinks
validation
protected function parsePageLinks($headers = false) { $pagination = []; if (!$headers) { $headers = $this->api->lastHeader('link'); } /* parse Canvas page links */ if (preg_match_all('%<([^>]*)>\s*;\s*rel="([^"]+)"%', $headers, $links, PREG_SET_ORDER)) { foreach ($links as $link) { $pagination[$link[2]] = new CanvasPageLink($link[1], $link[2]); } } return $pagination; }
php
{ "resource": "" }
q250459
CanvasArray.pageNumberToKey
validation
protected function pageNumberToKey($pageNumber) { if (isset($this->pagination[CanvasPageLink::CURRENT])) { return ($pageNumber - 1) * $this->pagination[CanvasPageLink::CURRENT]->getPerPage(); } return false; }
php
{ "resource": "" }
q250460
CanvasArray.requestPageNumber
validation
protected function requestPageNumber($pageNumber, $forceRefresh = false) { if (!isset($this->data[$this->pageNumberToKey($pageNumber)]) || ($forceRefresh && isset($this->api))) { // assume one page if no pagination (and already loaded) if (isset($this->pagination[CanvasPageLink::CURRENT])) { $params = $this->pagination[CanvasPageLink::CURRENT]->getParams(); $params[CanvasPageLink::PARAM_PAGE_NUMBER] = $pageNumber; $page = $this->api->get($this->pagination[CanvasPageLink::CURRENT]->getEndpoint(), $params); $this->data = array_replace($this->data, $page->data); $pagination = $this->parsePageLinks(); $this->paginationPerPage[$pagination[CanvasPageLink::CURRENT]->getPageNumber()] = $pagination; return true; } } return false; }
php
{ "resource": "" }
q250461
CanvasArray.requestAllPages
validation
protected function requestAllPages($forceRefresh = false) { $_page = $this->page; $_key = $this->key; $nextPageNumber = false; if (isset($this->pagination[CanvasPageLink::NEXT])) { $nextPageNumber = $this->pagination[CanvasPageLink::NEXT]->getPageNumber(); } /* welp, here goes... let's hope we have a next page! */ while ($nextPageNumber !== false) { $this->requestPageNumber($nextPageNumber, $forceRefresh); if (isset($this->paginationPerPage[$nextPageNumber][CanvasPageLink::NEXT])) { $nextPageNumber = $this->paginationPerPage[$nextPageNumber][CanvasPageLink::NEXT]->getPageNumber(); } else { $nextPageNumber = false; } } $this->page = $_page; $this->key = $_key; }
php
{ "resource": "" }
q250462
CanvasArray.offsetExists
validation
public function offsetExists($offset) { if (!isset($this->data[$offset])) { $this->requestAllPages(); } return isset($this->data[$offset]); }
php
{ "resource": "" }
q250463
CanvasArray.serialize
validation
public function serialize() { $this->requestAllPages(); return serialize( array( 'page' => $this->page, 'key' => $this->key, 'data' => $this->data ) ); }
php
{ "resource": "" }
q250464
CanvasArray.unserialize
validation
public function unserialize($data) { $_data = unserialize($data); $this->page = $_data['page']; $this->key = $_data['key']; $this->data = $_data['data']; $this->api = null; $this->endpoint = null; $this->pagination = array(); }
php
{ "resource": "" }
q250465
CanvasPest.setupToken
validation
public function setupToken($token) { if (!empty($token)) { $this->headers['Authorization'] = "Bearer $token"; return true; } else { if ($this->throw_exceptions) { throw new CanvasPest_Exception( 'API authorization token must be a non-zero-length string', CanvasPest_Exception::INVALID_TOKEN ); } return false; } }
php
{ "resource": "" }
q250466
CanvasPest.preprocessData
validation
private function preprocessData($data) { if (is_array($data) && !array_key_exists(self::PARAM_PER_PAGE, $data)) { $data[self::PARAM_PER_PAGE] = CanvasArray::MAXIMUM_PER_PAGE; } return $data; }
php
{ "resource": "" }
q250467
CanvasPest.get
validation
public function get($path, $data = array(), $headers = array()) { return $this->postprocessResponse( parent::get($path, $this->preprocessData($data), $headers) ); }
php
{ "resource": "" }
q250468
CanvasPest.post
validation
public function post($path, $data = array(), $headers = array()) { return $this->postprocessResponse( parent::post($path, $this->preprocessData($data), $headers) ); }
php
{ "resource": "" }
q250469
CanvasPest.put
validation
public function put($path, $data = array(), $headers = array()) { return $this->postprocessResponse( parent::put($path, $this->preprocessData($data), $headers) ); }
php
{ "resource": "" }
q250470
CanvasPest.delete
validation
public function delete($path, $data = array(), $headers = array()) { if (!empty($data)) { $pathData = []; $pos = strpos($path, '?'); if ($pos !== false) { parse_str(substr($path, $pos + 1), $pathData); $path = substr($path, 0, $pos); } $path .= '?' . $this->http_build_query(array_merge($pathData, $data)); } return $this->postprocessResponse( parent::delete($path, $headers) ); }
php
{ "resource": "" }
q250471
CanvasPest.patch
validation
public function patch($path, $data = array(), $headers = array()) { if ($this->throw_exceptions) { throw new CanvasPest_Exception( 'The Canvas API does not support the PATCH method', CanvasPest_Exception::UNSUPPORTED_METHOD ); } return false; }
php
{ "resource": "" }
q250472
PostController.actionIndex
validation
public function actionIndex($format= false,$arraymap= false,$term = false,$category = false,$time = false) { $searchModel = new PostSearch(); $req = Yii::$app->request->queryParams; if ($term) { $req[basename(str_replace("\\","/",get_class($searchModel)))]["term"] = $term;} if ($category) { $req[basename(str_replace("\\","/",get_class($searchModel)))]["category"] = $category;} if ($time) { $req[basename(str_replace("\\","/",get_class($searchModel)))]["time"] = $time;} $dataProvider = $searchModel->search($req); $query = $dataProvider->query; $query->andWhere(['status'=>[1]]); if ($format == 'json') { $model = []; foreach ($dataProvider->getModels() as $d) { $obj = $d->attributes; if ($arraymap) { $map = explode(",",$arraymap); if (count($map) == 1) { $obj = (isset($d[$arraymap])?$d[$arraymap]:null); } else { $obj = []; foreach ($map as $a) { $k = explode(":",$a); $v = (count($k) > 1?$k[1]:$k[0]); $obj[$k[0]] = ($v == "Obj"?json_encode($d->attributes):(isset($d->$v)?$d->$v:null)); } } } if ($term) { if (!in_array($obj,$model)) { array_push($model,$obj); } } else { array_push($model,$obj); } } header("Access-Control-Allow-Origin: *"); header("Access-Control-Expose-Headers: X-Pagination-Per-Page,X-Pagination-Current-Page,X-Pagination-Page-Count,X-Pagination-Total-Count,Content-Type,Location"); return \yii\helpers\Json::encode($model); } else { return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } }
php
{ "resource": "" }
q250473
PostController.actionView
validation
public function actionView($id,$format= false) { $model = $this->findModel($id); if ($format == 'json') { return \yii\helpers\Json::encode($model); } else { return $this->render('view', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q250474
PostController.actionCreate
validation
public function actionCreate() { $model = new Post(); $model->time = date("Y-m-d H:i:s"); $model->author_id = Yii::$app->user->id; $model->isdel = 0; if (Yii::$app->request->post()) { $post = Yii::$app->request->post(); $category = []; if (isset($post['Post']['category'])) { $category = $post['Post']['category']; } if (is_array($post['Post']['tags'])) { $post['Post']['tags'] = implode(",",$post['Post']['tags']); } $model->load($post); $transaction = Yii::$app->db->beginTransaction(); try { if ($model->save()) { $cs = BlogCatPos::deleteAll("post_id = :id",["id"=>$model->id]); foreach ($category as $d) { $c = new BlogCatPos(); $c->post_id = $model->id; $c->category_id = $d; $c->isdel = 0; $c->save(); } $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } else { $model->id = array_merge($category,[]); $transaction->rollBack(); } } catch (Exception $e) { $transaction->rollBack(); } } return $this->render('create', [ 'model' => $model, ]); }
php
{ "resource": "" }
q250475
PostController.actionUpdate
validation
public function actionUpdate($id) { $model = $this->findModel($id); $model->tags = !empty($model->tags)?explode(",",$model->tags):[]; if (Yii::$app->request->post()) { $post = Yii::$app->request->post(); $category = []; if (isset($post['Post']['category'])) { $category = $post['Post']['category']; } if (is_array($post['Post']['tags'])) { $post['Post']['tags'] = implode(",",$post['Post']['tags']); } $model->load($post); $transaction = Yii::$app->db->beginTransaction(); try { if ($model->save()) { $cs = BlogCatPos::deleteAll("post_id = :id",["id"=>$model->id]); foreach ($category as $d) { //$c = BlogCatPos::find()->where("post_id = :id AND category_id = :aid",["id"=>$model->id,"aid"=>intval($d)])->one(); //if (!$c) //{ $c = new BlogCatPos(); //} $c->post_id = $model->id; $c->category_id = $d; $c->isdel = 0; $c->save(); } $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } else { $transaction->rollBack(); } } catch (Exception $e) { $transaction->rollBack(); } } return $this->render('update', [ 'model' => $model, ]); }
php
{ "resource": "" }
q250476
BannerController.actionCreate
validation
public function actionCreate() { $model = new Banner(); $model->time = date("Y-m-d H:i:s"); $model->position = $model->getLast(); $model->isdel = 0; $post = Yii::$app->request->post(); if (isset($post['Banner']['tags'])) { if (is_array($post['Banner']['tags'])) { $post['Banner']['tags'] = implode(",",$post['Banner']['tags']); } } $transaction = Yii::$app->db->beginTransaction(); try { if ($model->load($post) && $model->save()) { $model->updatePosition($model->position); $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } else { $transaction->rollBack(); } } catch (Exception $e) { $transaction->rollBack(); } return $this->render('create', [ 'model' => $model, ]); }
php
{ "resource": "" }
q250477
BannerController.actionUpdate
validation
public function actionUpdate($id) { $model = $this->findModel($id); $model->tags = !empty($model->tags)?explode(",",$model->tags):[]; $post = Yii::$app->request->post(); if (isset($post['Banner']['tags'])) { if (is_array($post['Banner']['tags'])) { $post['Banner']['tags'] = implode(",",$post['Banner']['tags']); } } $transaction = Yii::$app->db->beginTransaction(); try { if ($model->load($post) && $model->save()) { $model->updatePosition($model->position); $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } else { $transaction->rollBack(); } } catch (Exception $e) { $transaction->rollBack(); } return $this->render('update', [ 'model' => $model, ]); }
php
{ "resource": "" }
q250478
SchemaAnalyzer.getAmbiguityExceptionMessage
validation
private function getAmbiguityExceptionMessage(array $paths, Vertex $startVertex, Vertex $endVertex) { $textPaths = []; $i = 1; foreach ($paths as $path) { $textPaths[] = 'Path '.$i.': '.$this->getTextualPath($path, $startVertex); ++$i; } $msg = sprintf("There are many possible shortest paths between table '%s' and table '%s'\n\n", $startVertex->getId(), $endVertex->getId()); $msg .= implode("\n\n", $textPaths); return $msg; }
php
{ "resource": "" }
q250479
SchemaAnalyzer.getTextualPath
validation
private function getTextualPath(array $path, Vertex $startVertex) { $currentVertex = $startVertex; $currentTable = $currentVertex->getId(); $textPath = $currentTable; foreach ($path as $edge) { /* @var $fk ForeignKeyConstraint */ if ($fk = $edge->getAttribute('fk')) { if ($fk->getForeignTableName() == $currentTable) { $currentTable = $fk->getLocalTable()->getName(); $isForward = false; } else { $currentTable = $fk->getForeignTableName(); $isForward = true; } $columns = implode(',', $fk->getLocalColumns()); $textPath .= ' '.(!$isForward ? '<' : ''); $textPath .= '--('.$columns.')--'; $textPath .= ($isForward ? '>' : '').' '; $textPath .= $currentTable; } elseif ($junctionTable = $edge->getAttribute('junction')) { /* @var $junctionTable Table */ $junctionFks = array_values($junctionTable->getForeignKeys()); // We need to order the 2 FKs. The first one is the one that has a common point with the current table. $fk = $junctionFks[0]; if ($fk->getForeignTableName() == $currentTable) { $currentTable = $junctionFks[1]->getForeignTableName(); } else { $currentTable = $fk->getForeignTableName(); } $textPath .= ' <=('.$junctionTable->getName().')=> '.$currentTable; } else { // @codeCoverageIgnoreStart throw new SchemaAnalyzerException('Unexpected edge. We should have a fk or a junction attribute.'); // @codeCoverageIgnoreEnd } } return $textPath; }
php
{ "resource": "" }
q250480
SchemaAnalyzer.isInheritanceRelationship
validation
private function isInheritanceRelationship(ForeignKeyConstraint $fk) { if (!$fk->getLocalTable()->hasPrimaryKey()) { return false; } $fkColumnNames = $fk->getLocalColumns(); $pkColumnNames = $fk->getLocalTable()->getPrimaryKeyColumns(); sort($fkColumnNames); sort($pkColumnNames); return $fkColumnNames == $pkColumnNames; }
php
{ "resource": "" }
q250481
LanguageSwitcherHelper.renderLanguageSwitcher
validation
public function renderLanguageSwitcher() { return $this->_View->element($this->config('element'), [ 'availableLanguages' => $this->config('availableLanguages'), 'displayNames' => $this->config('displayNames'), 'imageMapping' => $this->config('imageMapping'), 'renderToggleButtonDisplayName' => $this->config('renderToggleButtonDisplayName') ]); }
php
{ "resource": "" }
q250482
LanguageSwitcherHelper.getUrl
validation
public function getUrl($language) { $lang = ['lang' => $language]; $query = Hash::merge($this->request->query, $lang); $urlArray = Hash::merge($this->request->params['pass'], ['?' => $query]); return Router::url($urlArray); }
php
{ "resource": "" }
q250483
LanguageSwitcherMiddleware.__next
validation
private function __next(ServerRequestInterface $request, ResponseInterface $response, $next) { $this->__loadConfigFiles(); return $next($request, $response); }
php
{ "resource": "" }
q250484
LanguageSwitcherMiddleware.__setCookieAndLocale
validation
private function __setCookieAndLocale($locale) { // @FIXME Should be refactored when cake 3.4 was released if (PHP_SAPI !== 'cli') { $time = $this->__getCookieExpireTime(); I18n::locale($locale); setcookie($this->__getCookieName(), $locale, $time, '/', $this->config('Cookie.domain')); } }
php
{ "resource": "" }
q250485
LanguageSwitcherMiddleware.__loadConfigFiles
validation
private function __loadConfigFiles() { $additionalConfigs = $this->config('additionalConfigFiles'); foreach ($additionalConfigs as $additionalConfig) { Configure::load($additionalConfig); } }
php
{ "resource": "" }
q250486
GroupCountBasedDataGenerator.parseDynamicGroup
validation
private function parseDynamicGroup($group) { $regex = $group['regex']; $parts = explode('|', $regex); $data = array(); foreach ($group['routeMap'] as $matchIndex => $routeData) { if (!is_array($routeData[0]) || !isset($routeData[0]['name']) || !isset($parts[$matchIndex - 1])) { continue; } $parameters = $routeData[1]; $path = $parts[$matchIndex - 1]; foreach ($parameters as $parameter) { $path = $this->replaceOnce('([^/]+)', '{'.$parameter.'}', $path); } $path = rtrim($path, '()$~'); $data[$routeData[0]['name']] = array( 'path' => $path, 'params' => $parameters, ); } return $data; }
php
{ "resource": "" }
q250487
GroupCountBasedDataGenerator.replaceOnce
validation
private function replaceOnce($search, $replace, $subject) { $pos = strpos($subject, $search); if ($pos !== false) { $subject = substr_replace($subject, $replace, $pos, strlen($search)); } return $subject; }
php
{ "resource": "" }
q250488
ClassName.from
validation
public function from(Contract $contract, string $string, callable $callback = null): string { $string = ucwords( $contract->recipe( $string, 'upperCaseFirst', function ($string) use ($contract) { if ($contract instanceof Camel) { return $string; } return strtolower($string); } ) ); return $this->callback($string, $callback); }
php
{ "resource": "" }
q250489
Camel.from
validation
public function from(Contract $contract, string $string, callable $callback = null): string { return $this->callback( $contract->recipe( $string, 'upperCaseFirst', function ($string) use ($contract) { if ($contract instanceof ClassName) { return lcfirst($string); } return strtolower($string); } ), $callback ); }
php
{ "resource": "" }
q250490
SimpleUrlGenerator.generate
validation
public function generate($name, array $parameters = array(), $absolute = false) { if (!$this->initialized) { $this->initialize(); } $path = $this->routes[$name]; if (is_array($path)) { $params = $path['params']; $path = $path['path']; foreach ($params as $param) { if (!isset($parameters[$param])) { throw new \RuntimeException('Missing required parameter "'.$param.'". Optional parameters not currently supported'); } $path = str_replace('{'.$param.'}', $parameters[$param], $path); } } if ($this->request) { $path = $this->request->getBaseUrl().$path; if ($absolute) { $path = $this->request->getSchemeAndHttpHost().$path; } } return $path; }
php
{ "resource": "" }
q250491
Application.boot
validation
public function boot() { if ($this->booted) { return; } $this->container = $this->initializeContainer(); $this->kernel = $this->container->get('http_kernel'); $this->booted = true; }
php
{ "resource": "" }
q250492
Application.addCompilerPass
validation
public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION) { $this->compilerPasses[] = array($pass, $type); }
php
{ "resource": "" }
q250493
Application.initializeContainer
validation
protected function initializeContainer() { $this->registerDefaultExtensions(); $initializer = $this->getContainerInitializer(); $this->container = $initializer->initializeContainer($this, $this->extensions, $this->compilerPasses); $this->container->set('app', $this); return $this->container; }
php
{ "resource": "" }
q250494
Application.getContainerInitializer
validation
protected function getContainerInitializer() { $initializer = new DefaultInitializer($this->getConfigurationProvider()); if ($this->cache) { $initializer = new CachedInitializer($initializer, $this->getCacheDir()); } return $initializer; }
php
{ "resource": "" }
q250495
Application.handle
validation
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { if (!$this->booted) { $this->boot(); } $request->attributes->set('app', $this); return $this->kernel->handle($request, $type, $catch); }
php
{ "resource": "" }
q250496
Application.getRootDir
validation
public function getRootDir() { if (!$this->rootDir) { $refl = new \ReflectionObject($this); $filename = $refl->getFileName(); if (false !== ($pos = strrpos($filename, '/vendor/'))) { $filename = substr($filename, 0, $pos); } else { $filename = dirname($filename).'/..'; } $this->rootDir = str_replace('\\', '/', $filename); } return $this->rootDir; }
php
{ "resource": "" }
q250497
Application.set
validation
public function set($id, $service, $scope = ContainerInterface::SCOPE_CONTAINER) { if (!$this->booted) { $this->boot(); } $this->container->set($id, $service, $scope); }
php
{ "resource": "" }
q250498
Application.get
validation
public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) { if (!$this->booted) { $this->boot(); } return $this->container->get($id, $invalidBehavior); }
php
{ "resource": "" }
q250499
CachedInitializer.dumpContainer
validation
protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass) { $dumper = new PhpDumper($container); $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass)); $cache->write($content, $container->getResources()); }
php
{ "resource": "" }