_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5100 | FixedDateTimeTrait.getDateTimeInstance | train | protected function getDateTimeInstance(string $time = "now", \DateTimeZone $timezone = null): DateTime
{
$result = new self::$_dateTimeClassName($time, $timezone);
return $result;
} | php | {
"resource": ""
} |
q5101 | DfOAuthOneProvider.getOAuthToken | train | public function getOAuthToken()
{
if (!$this->isStateless()) {
return \Cache::get('oauth.temp');
} else {
/** @var TemporaryCredentials $temp */
$temp = unserialize(\Cache::get('oauth_temp'));
return $temp->getIdentifier();
}
} | php | {
"resource": ""
} |
q5102 | MappingManager.add | train | public function add($mappingClass)
{
try {
if ($mappingClass instanceof MappingInterface) {
$mappingClassInstance = $mappingClass;
} else {
$reflectionClass = new \ReflectionClass($mappingClass);
$mappingClassInstance = $reflectionClass->newInstance();
if (!$mappingClassInstance instanceof MappingInterface) {
throw new InvalidMappingClassException('Mapping class must be an instance of MappingInterface');
}
}
self::$container[$mappingClassInstance->getName()] = $mappingClassInstance;
} catch (\Exception $ex) {
throw new InvalidMappingClassException($ex->getMessage());
}
return $this;
} | php | {
"resource": ""
} |
q5103 | MappingManager.find | train | public static function find($mappingName)
{
if (!array_key_exists($mappingName, self::$container)) {
throw new MappingClassNotFoundException($mappingName);
}
return self::$container[$mappingName];
} | php | {
"resource": ""
} |
q5104 | SessionManager.getSessionHandler | train | public static function getSessionHandler() {
$sessionDriver = get_config('session_driver');
self::$sessionDriver = $sessionDriver ? $sessionDriver : 'native';
if (self::$sessionDriver) {
switch (self::$sessionDriver) {
case 'native':
self::$sessionHandler = new Session(get_config('session_timeout'));
break;
case 'database':
self::$sessionHandler = new DbSession(get_config('session_timeout'));
break;
}
}
if (self::$sessionHandler) {
return self::$sessionHandler;
} else {
throw new \Exception(ExceptionMessages::MISCONFIGURED_SESSION_HANDLER);
}
} | php | {
"resource": ""
} |
q5105 | Mapper.create | train | public function create($cacheFilePath = null)
{
$map = [];
if ($cacheFilePath) {
$map = $this->resolveCachedMap($cacheFilePath);
}
if (!is_array($map)) {
$map = $this->createMap();
if ($cacheFilePath) {
$this->cacheMap($cacheFilePath, $map);
}
}
$this->map = $map;
return $map;
} | php | {
"resource": ""
} |
q5106 | Mapper.resolveModel | train | public function resolveModel($collectionName)
{
if (!array_key_exists($collectionName, $this->map)) {
throw new CannotResolveModelException($collectionName);
}
$modelClassName = $this->map[$collectionName];
try {
if (!array_key_exists($modelClassName, $this->modelInstances)) {
$reflectionClass = new \ReflectionClass($modelClassName);
$modelInstance = $reflectionClass->newInstance();
$this->modelInstances[$modelClassName] = $modelInstance;
}
return $this->modelInstances[$modelClassName];
} catch (\Exception $e) {
throw new CannotResolveModelException($collectionName);
}
} | php | {
"resource": ""
} |
q5107 | Mapper.createMap | train | private function createMap()
{
$map = [];
//browse directories recursively
$directoryIterator = new \RecursiveDirectoryIterator($this->inputDirectory);
$iterator = new \RecursiveIteratorIterator($directoryIterator);
foreach ($iterator as $file) {
if ($file->getFileName() == '.' || $file->getFileName() == '..') {
continue;
}
if (!preg_match($this->modelClassPattern, $file->getPathname())) {
continue;
}
//resolves name of class
$className = $this->resolveFileClassName($file);
try {
$classInstance = $this->instantiateClass($className);
if ($classInstance instanceof \Phalcon\Mvc\Collection) {
$map[$classInstance->getSource()] = $className;
}
} catch (\Exception $e) {
continue;
}
}
return $map;
} | php | {
"resource": ""
} |
q5108 | Mapper.cacheMap | train | private function cacheMap($cacheFilePath, $map)
{
if (!file_exists(dirname($cacheFilePath))) {
mkdir(dirname($cacheFilePath), 0777, true);
}
return FileWriter::writeObject($cacheFilePath, $map, true);
} | php | {
"resource": ""
} |
q5109 | Mapper.resolveFileClassName | train | protected function resolveFileClassName(\SplFileInfo $fileInfo)
{
$relativeFilePath = str_replace(
$this->inputDirectory,
'',
$fileInfo->getPath()) . DIRECTORY_SEPARATOR .
$fileInfo->getBasename('.' . $fileInfo->getExtension()
);
//converts file path to namespace
//DIRECTORY_SEPARATOR will be converted to namespace separator => \
//each directory name will be converted to first upper case
$splitPath = explode(DIRECTORY_SEPARATOR, $relativeFilePath);
$namespace = implode('\\', array_map(function($item) {
return ucfirst($item);
}, $splitPath));
return $namespace;
} | php | {
"resource": ""
} |
q5110 | Option.matchParam | train | public function matchParam($paramName)
{
return (0 == strcasecmp($this->name, $paramName))
|| (0 == strcasecmp($this->shortName, $paramName));
} | php | {
"resource": ""
} |
q5111 | Option.validate | train | public function validate($value)
{
$result = !$this->isRequired;
if ($this->isRequired()) {
$result = !empty($value);
}
if (is_callable($this->validator)) {
$result = call_user_func($this->validator, $value);
}
return $result;
} | php | {
"resource": ""
} |
q5112 | Option.getValue | train | public function getValue($args, $default = null)
{
if (isset($args[$this->name])) {
return $args[$this->name];
}
if (isset($args[$this->shortName])) {
return $args[$this->shortName];
}
return $default;
} | php | {
"resource": ""
} |
q5113 | ShortenText.prepare | train | public function prepare($text, $length = 100, $endString = '...')
{
$substring = strip_tags(preg_replace('/<br.?\/?>/', ' ',$text));
$textLength = mb_strlen($substring);
if($textLength > $length) {
$lastWordPosition = mb_strpos($substring, ' ', $length);
if($lastWordPosition) {
$substring = mb_substr($substring, 0, $lastWordPosition);
} else {
$substring = mb_substr($substring, 0, $length);
}
$substring.= $endString;
}
return $substring;
} | php | {
"resource": ""
} |
q5114 | InputValidation.permissionList | train | public static function permissionList($permissionListStr)
{
// make sure the string is valid JSON array containing just strings
$permissionList = Json::decode($permissionListStr);
foreach ($permissionList as $permission) {
if (!\is_string($permission)) {
throw new InputValidationException('invalid "permissionList"');
}
}
return $permissionList;
} | php | {
"resource": ""
} |
q5115 | ModuleTask.dumpAction | train | public function dumpAction()
{
$this->putText("Dumping modules & services files...");
if ($this->isConfigured()) {
$config = $this->getDI()->get('config');
$moduleLoader = new \Vegas\Mvc\Module\Loader($this->getDI());
$moduleLoader->dump(
$config->application->moduleDir,
$config->application->configDir
);
$serviceProviderLoader = new \Vegas\DI\ServiceProviderLoader($this->getDI());
$serviceProviderLoader->autoload(
$config->application->serviceDir,
$config->application->configDir
);
$this->putSuccess("Done.");
}
} | php | {
"resource": ""
} |
q5116 | AggregateCursor.skip | train | public function skip($by = 1)
{
$i = 0;
while($this->cursor->valid() && $i < $by) {
$this->cursor->next();
$i++;
}
return $this;
} | php | {
"resource": ""
} |
q5117 | File.getContents | train | public static function getContents($filename)
{
$contents = file_get_contents($filename);
if ($contents === false) {
throw new \RuntimeException("Cannot read the file: " . $filename);
}
return $contents;
} | php | {
"resource": ""
} |
q5118 | File.putContents | train | public static function putContents($filename, $contents)
{
$result = file_put_contents($filename, $contents, \LOCK_EX | \LOCK_NB);
if ($result === false) {
throw new \RuntimeException("Cannot write the file: " . $filename);
}
} | php | {
"resource": ""
} |
q5119 | File.appendContents | train | public static function appendContents($filename, $contents)
{
$result = file_put_contents($filename, $contents, \LOCK_EX | \LOCK_NB | \FILE_APPEND);
if ($result === false) {
throw new \RuntimeException("Cannot append to the file: " . $filename);
}
} | php | {
"resource": ""
} |
q5120 | AbstractPipeline.pipe | train | public function pipe($stages): void
{
if ($stages instanceof PipelineInterface) {
$stages = $stages->stages();
}
if (!\is_array($stages)) {
$this->stages[] = $stages;
return;
}
foreach ($stages as $stage) {
$this->pipe($stage);
}
} | php | {
"resource": ""
} |
q5121 | KeywordsRepository.keywords | train | public function keywords($keywords = [])
{
$args = func_get_args();
$this->mergeKeywords = (is_bool(end($args)) || is_int(end($args))) ? array_pop($args) : false;
$keywords = is_array($keywords) ? $keywords : $args;
array_walk($keywords, function (&$value) {
$value = is_object($value) ? get_class($value) : $value;
});
$this->keywords = array_unique($keywords);
return $this;
} | php | {
"resource": ""
} |
q5122 | KeywordsRepository.writeCacheRecord | train | protected function writeCacheRecord($method, $args)
{
$this->checkReservedKeyPattern($args['key']);
call_user_func_array([$this, 'storeKeywords'], array_only($args, ['key', 'minutes', 'keywords']));
if (! $this->operatingOnKeywords()) {
$this->resetCurrentKeywords();
}
call_user_func_array(['parent', $method], array_values($args));
} | php | {
"resource": ""
} |
q5123 | KeywordsRepository.fetchDefaultCacheRecord | train | protected function fetchDefaultCacheRecord($method, $args)
{
// Instead of using has() we directly implement the value getter
// to avoid additional cache hits if the key exists.
if (is_null($value = parent::get($args['key']))) {
$this->checkReservedKeyPattern($args['key']);
call_user_func_array([$this, 'storeKeywords'], array_only($args, ['key', 'minutes', 'keywords']));
$this->setKeywordsOperation(true);
$value = call_user_func_array(['parent', $method], array_values($args));
$this->setKeywordsOperation(false);
}
if (! $this->operatingOnKeywords()) {
$this->resetCurrentKeywords();
}
return $value;
} | php | {
"resource": ""
} |
q5124 | KeywordsRepository.determineKeywordsState | train | protected function determineKeywordsState($key, array $newKeywords = [], array $oldKeywords = [])
{
$this->setKeywordsOperation(true);
static $state = [];
// Build state if:
// - not built yet
// - $newKeywords or $oldKeywords is provided
if (! isset($state[$key]) || func_num_args() > 1) {
$old = empty($oldKeywords) ? parent::get($this->generateInverseIndexKey($key), []) : $oldKeywords;
$new = $this->mergeKeywords ? array_unique(array_merge($old, $newKeywords)) : $newKeywords;
$state[$key] = [
'old' => $old,
'new' => $new,
'obsolete' => array_diff($old, $new),
];
}
$this->setKeywordsOperation(false);
return $state[$key];
} | php | {
"resource": ""
} |
q5125 | KeywordsRepository.storeKeywords | train | protected function storeKeywords($key, $minutes = null, array $keywords = [])
{
$keywords = empty($keywords) ? $this->keywords : $keywords;
$this->determineKeywordsState($key, $keywords);
$this->updateKeywordIndex($key);
$this->updateInverseIndex($key, $minutes);
} | php | {
"resource": ""
} |
q5126 | KeywordsRepository.updateKeywordIndex | train | protected function updateKeywordIndex($key)
{
$this->setKeywordsOperation(true);
$keywordsState = $this->determineKeywordsState($key);
foreach (array_merge($keywordsState['new'], $keywordsState['obsolete']) as $keyword) {
$indexKey = $this->generateIndexKey($keyword);
$oldIndex = parent::pull($indexKey, []);
$newIndex = in_array($keyword, $keywordsState['obsolete']) ?
array_values(array_diff($oldIndex, [$key])) :
array_values(array_unique(array_merge($oldIndex, [$key])));
if (! empty($newIndex)) {
parent::forever($indexKey, $newIndex);
}
}
$this->setKeywordsOperation(false);
} | php | {
"resource": ""
} |
q5127 | KeywordsRepository.updateInverseIndex | train | protected function updateInverseIndex($key, $minutes = null)
{
$this->setKeywordsOperation(true);
$keywordsState = $this->determineKeywordsState($key);
$inverseIndexKey = $this->generateInverseIndexKey($key);
if (empty($keywordsState['new'])) {
parent::forget($inverseIndexKey);
} elseif ($keywordsState['old'] != $keywordsState['new']) {
$newInverseIndex = array_values($keywordsState['new']);
is_null($minutes) ?
parent::forever($inverseIndexKey, $newInverseIndex) :
parent::put($inverseIndexKey, $newInverseIndex, $minutes);
}
$this->setKeywordsOperation(false);
} | php | {
"resource": ""
} |
q5128 | AnalyticsBase.trackEcommerce | train | protected function trackEcommerce($type = self::ECOMMERCE_TRANSACTION, array $options = [])
{
$this->addItem("ga('require', 'ecommerce');");
$item = "ga('ecommerce:{$type}', { ";
$item .= $this->assembleParameters($options);
$item = rtrim($item, ', ') . " });";
$this->addItem($item);
$this->addItem("ga('ecommerce:send');");
} | php | {
"resource": ""
} |
q5129 | Posts.getForumPostsAll | train | public function getForumPostsAll($searchCriteria)
{
$allPosts = [];
$currentPage = 1;
do {
$response = $this->getForumPostsByPage($searchCriteria, $currentPage);
$allPosts = array_merge($allPosts, $response->results);
$currentPage++;
} while ($currentPage <= $response->totalPages);
return $allPosts;
} | php | {
"resource": ""
} |
q5130 | Posts.createForumPost | train | public function createForumPost($topicID, $authorID, $post, $extra = [])
{
$data = ["topic" => $topicID, "author" => $authorID, "post" => $post];
$data = array_merge($data, $extra);
$validator = \Validator::make($data, [
"topic" => "required|numeric",
"author" => "required|numeric",
"post" => "required|string",
"author_name" => "required_if:author,0|string",
"date" => "date_format:YYYY-mm-dd H:i:s",
"ip_address" => "ip",
"hidden" => "in:-1,0,1",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/posts", $data);
} | php | {
"resource": ""
} |
q5131 | Posts.updateForumPost | train | public function updateForumPost($postId, $data = [])
{
$validator = \Validator::make($data, [
"author" => "numeric",
"author_name" => "required_if:author,0|string",
"post" => "string",
"hidden" => "in:-1,0,1",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/posts/" . $postId, $data);
} | php | {
"resource": ""
} |
q5132 | Client.getPaymentMethodGroups | train | public function getPaymentMethodGroups()
{
$response = $this->sendRequest(
$this->serviceBaseUrl . 'GetPaymentMethods',
['MerchantLogin' => $this->auth->getMerchantLogin(), 'Language' => $this->culture],
$this->requestMethod
);
$sxe = simplexml_load_string($response);
$this->parseError($sxe);
if (!$sxe->Methods->Method) {
return [];
}
$methods = [];
foreach ($sxe->Methods->Method as $method) {
$methods[(string)$method->attributes()->Code] = (string)$method->attributes()->Description;
}
return $methods;
} | php | {
"resource": ""
} |
q5133 | Client.getRates | train | public function getRates($shopSum, $paymentMethod = '', $culture = null)
{
if (null === $culture) {
$culture = $this->culture;
}
$response = $this->sendRequest(
$this->serviceBaseUrl . 'GetRates',
[
'MerchantLogin' => $this->auth->getMerchantLogin(),
'IncCurrLabel' => $paymentMethod,
'OutSum' => $shopSum,
'Language' => $culture
],
$this->requestMethod
);
$sxe = simplexml_load_string($response);
$this->parseError($sxe);
if (!$sxe->Groups->Group) {
return [];
}
$groups = [];
foreach ($sxe->Groups->Group as $i => $group) {
$items = [];
foreach ($group->Items->Currency as $item) {
$clientSum = (double)$item->Rate->attributes()->IncSum;
$item = (array)$item;
$items[] = $item['@attributes'] + ['ClientSum' => $clientSum];
}
$groups[] = [
'Code' => (string)$group->attributes()->Code,
'Description' => (string)$group->attributes()->Description,
'Items' => $items,
];
}
return $groups;
} | php | {
"resource": ""
} |
q5134 | Client.getInvoice | train | public function getInvoice($invoiceId = null)
{
$signature = $this->auth->getSignatureHash('{ml}:{ii}:{vp}', [
'ml' => $this->auth->getMerchantLogin(),
'ii' => $invoiceId,
'vp' => $this->auth->getValidationPassword(),
]);
$response = $this->sendRequest(
$this->serviceBaseUrl . 'OpState',
[
'MerchantLogin' => $this->auth->getMerchantLogin(),
'InvoiceID' => $invoiceId,
'Signature' => $signature
],
$this->requestMethod
);
$sxe = simplexml_load_string($response);
$this->parseError($sxe);
return [
'InvoiceId' => (int)$invoiceId,
'StateCode' => (int)$sxe->State->Code,
'RequestDate' => new \DateTime((string)$sxe->State->RequestDate),
'StateDate' => new \DateTime((string)$sxe->State->StateDate),
'PaymentMethod' => (string)$sxe->Info->IncCurrLabel,
'ClientSum' => (float)$sxe->Info->IncSum,
'ClientAccount' => (string)$sxe->Info->IncAccount,
'PaymentMethodCode' => (string)$sxe->Info->PaymentMethod->Code,
'PaymentMethodDescription' => (string)$sxe->Info->PaymentMethod->Description,
'Currency' => (string)$sxe->Info->OutCurrLabel,
'ShopSum' => (float)$sxe->Info->OutSum,
];
} | php | {
"resource": ""
} |
q5135 | Client.sendRequest | train | protected function sendRequest($url, array $params, $method)
{
$method = strtolower($method);
$options = [
CURLOPT_RETURNTRANSFER => true,
];
if (self::REQUEST_METHOD_GET === $method) {
$url .= '?' . http_build_query($params);
} else {
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = http_build_query($params);
}
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if (!$response) {
throw new \RuntimeException('cURL: ' . curl_error($ch), curl_errno($ch));
}
curl_close($ch);
return $response;
} | php | {
"resource": ""
} |
q5136 | CacheInstance.clear | train | public function clear($key = null)
{
if (isset($key)) {
if (isset($this->data[$key])) {
unset($this->data[$key]);
}
} else {
$this->data = [];
}
} | php | {
"resource": ""
} |
q5137 | SymfonyRouteResolver.createFakeRequest | train | private function createFakeRequest(ServerRequestInterface $psrRequest): Request
{
$server = [];
$uri = $psrRequest->getUri();
if ($uri instanceof UriInterface) {
$server['SERVER_NAME'] = $uri->getHost();
$server['SERVER_PORT'] = $uri->getPort();
$server['REQUEST_URI'] = $uri->getPath();
$server['QUERY_STRING'] = $uri->getQuery();
}
$server['REQUEST_METHOD'] = $psrRequest->getMethod();
$server = \array_replace($server, $psrRequest->getServerParams());
$parsedBody = $psrRequest->getParsedBody();
$parsedBody = \is_array($parsedBody) ? $parsedBody : [];
$request = new Request(
$psrRequest->getQueryParams(),
$parsedBody,
$psrRequest->getAttributes(),
$psrRequest->getCookieParams(),
[],
$server,
''
);
$request->headers->replace($psrRequest->getHeaders());
return $request;
} | php | {
"resource": ""
} |
q5138 | ProtectedResourceComponent.verifyExpiration | train | protected function verifyExpiration(array $tokenData)
{
if (!isset($tokenData['expirationDateTime'])) {
return;
}
$expirationDateTime = \DateTime::createFromFormat(\DateTime::ISO8601, $tokenData['expirationDateTime']);
if ($this->now instanceof DependencyProxy) {
$this->now->_activateDependency();
}
if ($expirationDateTime < $this->now) {
throw new AccessDeniedException(sprintf('Token expired!%sThis token expired at "%s"', chr(10),
$expirationDateTime->format(\DateTime::ISO8601)), 1429697439);
}
} | php | {
"resource": ""
} |
q5139 | ProtectedResourceComponent.verifySecurityContextHash | train | protected function verifySecurityContextHash(array $tokenData, HttpRequest $httpRequest)
{
if (!isset($tokenData['securityContextHash'])) {
return;
}
/** @var $actionRequest ActionRequest */
$actionRequest = $this->objectManager->get(ActionRequest::class, $httpRequest);
$this->securityContext->setRequest($actionRequest);
if ($tokenData['securityContextHash'] !== $this->securityContext->getContextHash()) {
$this->emitInvalidSecurityContextHash($tokenData, $httpRequest);
throw new AccessDeniedException(sprintf('Invalid security hash!%sThis request is signed for a security context hash of "%s", but the current hash is "%s"',
chr(10), $tokenData['securityContextHash'], $this->securityContext->getContextHash()), 1429705633);
}
} | php | {
"resource": ""
} |
q5140 | IlluminateDriver.getElapsedTime | train | protected function getElapsedTime($start)
{
if ($this->elapsedTimeMethod === null) {
$reflection = new ReflectionClass($this->getConnect());
$this->elapsedTimeMethod = $reflection->getMethod('getElapsedTime');
$this->elapsedTimeMethod->setAccessible(true);
}
return $this->elapsedTimeMethod->invoke($this->getConnect(), $start);
} | php | {
"resource": ""
} |
q5141 | MarketPlaceCommandController.cleanupPackages | train | protected function cleanupPackages(Storage $storage)
{
$this->outputLine();
$this->outputLine('Cleanup packages ...');
$this->outputLine('--------------------');
$count = $this->importer->cleanupPackages($storage, function (NodeInterface $package) {
$this->outputLine(sprintf('%s deleted', $package->getLabel()));
});
if ($count > 0) {
$this->outputLine(sprintf(' Deleted %d package(s)', $count));
}
} | php | {
"resource": ""
} |
q5142 | MarketPlaceCommandController.cleanupVendors | train | protected function cleanupVendors(Storage $storage)
{
$this->outputLine();
$this->outputLine('Cleanup vendors ...');
$this->outputLine('-------------------');
$count = $this->importer->cleanupVendors($storage, function (NodeInterface $vendor) {
$this->outputLine(sprintf('%s deleted', $vendor->getLabel()));
});
if ($count > 0) {
$this->outputLine(sprintf(' Deleted %d vendor(s)', $count));
}
} | php | {
"resource": ""
} |
q5143 | RenderDefinitionCollection.addCollection | train | public function addCollection(self $collection)
{
$this->renderDefinitions = \array_merge($this->renderDefinitions, $collection->all());
$this->resources = \array_merge($this->resources, $collection->getResources());
} | php | {
"resource": ""
} |
q5144 | ContentElementConfigLoader.loadTypoScript | train | private function loadTypoScript(): string
{
if (null === $this->options['cache_dir']) {
return $this->concatenateTypoScript();
}
$cache = $this->getConfigCacheFactory()
->cache($this->options['cache_dir'].'/content_elements.typoscript',
function (ConfigCacheInterface $cache) {
$cache->write(
$this->concatenateTypoScript(),
$this->getRenderDefinitionCollection()->getResources()
);
}
)
;
return \file_get_contents($cache->getPath());
} | php | {
"resource": ""
} |
q5145 | JWToken.compose | train | public function compose($keyId = null, $head = null) {
if (!$this->payload)
throw new \Firebase\JWT\BeforeValidException(ExceptionMessages::JWT_PAYLOAD_NOT_FOUND);
return parent::encode($this->payload, $this->key, $this->algorithm, $keyId, $head);
} | php | {
"resource": ""
} |
q5146 | Request.hasFile | train | public static function hasFile($key) {
if (isset($_FILES[$key]) === false || (isset($_FILES[$key]['error']) && $_FILES[$key]['error'] != 0)) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q5147 | Request.getAuthorizationBearer | train | public function getAuthorizationBearer() {
$allHeaders = array_change_key_case(parent::getHeaders(), CASE_UPPER);
if (array_key_exists('AUTHORIZATION', $allHeaders)) {
if (preg_match('/Bearer\s(\S+)/', $allHeaders['AUTHORIZATION'], $matches)) {
return $matches[1];
}
} else {
throw new \Exception(ExceptionMessages::AUTH_BEARER_NOT_FOUND);
}
} | php | {
"resource": ""
} |
q5148 | ErrorHandlerInitializerTrait.initErrorHandler | train | public function initErrorHandler(Config $config)
{
if ($this->getDI()->get('environment') === Constants::PROD_ENV) {
return;
}
$this->debug = new Debug();
$this->debug->listen();
set_error_handler([$this, 'errorHandler'], error_reporting());
register_shutdown_function(function() {
if ((error_reporting() & E_ERROR) === E_ERROR) {
$lastError = error_get_last();
if ($lastError['type'] === E_ERROR) {
// fatal error
$this->errorHandler(E_ERROR, $lastError['message'], $lastError['file'], $lastError['line']);
}
}
});
} | php | {
"resource": ""
} |
q5149 | ErrorHandlerInitializerTrait.errorHandler | train | public function errorHandler($code, $message, $file, $line)
{
$this->debug->setShowBackTrace(false);
$this->debug->onUncaughtException(new \ErrorException($message, $code, 0, $file, $line));
} | php | {
"resource": ""
} |
q5150 | Custom_Sniffs_CodeAnalysis_VariableAnalysisSniff.processVariable | train | protected function processVariable(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$varName = $this->normalizeVarName($token['content']);
if (($currScope = $this->findVariableScope($phpcsFile, $stackPtr)) === false) {
return;
}
//static $dump_token = false;
//if ($varName == 'property') {
// $dump_token = true;
//}
//if ($dump_token) {
// echo "Found variable {$varName} on line {$token['line']} in scope {$currScope}.\n" . print_r($token, true);
// echo "Prev:\n" . print_r($tokens[$stackPtr - 1], true);
//}
// Determine if variable is being assigned or read.
// Read methods that preempt assignment:
// Are we a $object->$property type symbolic reference?
// Possible assignment methods:
// Is a mandatory function/closure parameter
// Is an optional function/closure parameter with non-null value
// Is closure use declaration of a variable defined within containing scope
// catch (...) block start
// $this within a class (but not within a closure).
// $GLOBALS, $_REQUEST, etc superglobals.
// $var part of class::$var static member
// Assignment via =
// Assignment via list (...) =
// Declares as a global
// Declares as a static
// Assignment via foreach (... as ...) { }
// Pass-by-reference to known pass-by-reference function
// Are we a $object->$property type symbolic reference?
if ($this->checkForSymbolicObjectProperty($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a function or closure parameter?
if ($this->checkForFunctionPrototype($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a catch parameter?
if ($this->checkForCatchBlock($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we $this within a class?
if ($this->checkForThisWithinClass($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a $GLOBALS, $_REQUEST, etc superglobal?
if ($this->checkForSuperGlobal($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// $var part of class::$var static member
if ($this->checkForStaticMember($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Is the next non-whitespace an assignment?
if ($this->checkForAssignment($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// OK, are we within a list (...) = construct?
if ($this->checkForListAssignment($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a global declaration?
if ($this->checkForGlobalDeclaration($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a static declaration?
if ($this->checkForStaticDeclaration($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we a foreach loopvar?
if ($this->checkForForeachLoopVar($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// Are we pass-by-reference to known pass-by-reference function?
if ($this->checkForPassByReferenceFunctionCall($phpcsFile, $stackPtr, $varName, $currScope)) {
return;
}
// OK, we don't appear to be a write to the var, assume we're a read.
$this->markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope);
} | php | {
"resource": ""
} |
q5151 | Custom_Sniffs_CodeAnalysis_VariableAnalysisSniff.processVariableInString | train | protected function processVariableInString(
PHP_CodeSniffer_File
$phpcsFile,
$stackPtr
) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if (!preg_match_all($this->_double_quoted_variable_regexp, $token['content'], $matches)) {
return;
}
$currScope = $this->findVariableScope($phpcsFile, $stackPtr);
foreach ($matches[1] as $varName) {
$varName = $this->normalizeVarName($varName);
// Are we $this within a class?
if ($this->checkForThisWithinClass($phpcsFile, $stackPtr, $varName, $currScope)) {
continue;
}
if ($this->checkForSuperGlobal($phpcsFile, $stackPtr, $varName, $currScope)) {
continue;
}
$this->markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope);
}
} | php | {
"resource": ""
} |
q5152 | Custom_Sniffs_CodeAnalysis_VariableAnalysisSniff.processScopeClose | train | protected function processScopeClose(
PHP_CodeSniffer_File
$phpcsFile,
$stackPtr
) {
$scopeInfo = $this->getScopeInfo($stackPtr, false);
if (is_null($scopeInfo)) {
return;
}
foreach ($scopeInfo->variables as $varInfo) {
if ($varInfo->ignoreUnused || isset($varInfo->firstRead)) {
continue;
}
if ($this->allowUnusedFunctionParameters && $varInfo->scopeType == 'param') {
continue;
}
if ($varInfo->passByReference && isset($varInfo->firstInitialized)) {
// If we're pass-by-reference then it's a common pattern to
// use the variable to return data to the caller, so any
// assignment also counts as "variable use" for the purposes
// of "unused variable" warnings.
continue;
}
if (isset($varInfo->firstDeclared)) {
$phpcsFile->addWarning(
"Unused %s %s.",
$varInfo->firstDeclared,
'UnusedVariable',
array(
VariableInfo::$scopeTypeDescriptions[$varInfo->scopeType],
"\${$varInfo->name}",
)
);
}
if (isset($varInfo->firstInitialized)) {
$phpcsFile->addWarning(
"Unused %s %s.",
$varInfo->firstInitialized,
'UnusedVariable',
array(
VariableInfo::$scopeTypeDescriptions[$varInfo->scopeType],
"\${$varInfo->name}",
)
);
}
}
} | php | {
"resource": ""
} |
q5153 | Action.validate | train | public function validate($args)
{
$matched = false;
//validates arguments
foreach ($args as $arg => $value) {
//non-named option are skipped from validation
if (is_numeric($arg)) continue;
//validates action options
foreach ($this->options as $option) {
//checks if options matches specified parameter
if ($option->matchParam($arg)) {
//validates option
if (!$option->validate($value)) {
throw new InvalidArgumentException($arg, $value);
}
$matched = true;
}
}
if (!$matched) {
throw new InvalidOptionException($arg);
}
}
//validates required options
foreach ($this->options as $option) {
if (!$option->isRequired()) {
continue;
}
if (!$option->getValue($args)) {
throw new MissingRequiredArgumentException($option->getName());
}
}
return true;
} | php | {
"resource": ""
} |
q5154 | Mailer.phpMailerSettings | train | private function phpMailerSettings() {
$phpMailer = new PHPMailer();
if (strlen(env('MAIL_HOST')) > 0) {
$phpMailer->SMTPDebug = 0;
$phpMailer->isSMTP();
$phpMailer->Host = env('MAIL_HOST');
$phpMailer->SMTPAuth = true;
$phpMailer->SMTPSecure = env('MAIL_SMTP_SECURE');
$phpMailer->Port = env('MAIL_PORT');
$phpMailer->Username = env('MAIL_USERNAME');
$phpMailer->Password = env('MAIL_PASSWORD');
} else {
$phpMailer->isMail();
}
$phpMailer->isHTML(true);
$this->mailer = $phpMailer;
} | php | {
"resource": ""
} |
q5155 | Mailer.createFromTemplate | train | private function createFromTemplate($message, $template) {
ob_start();
ob_implicit_flush(false);
if (is_array($message) && !empty($message)) {
extract($message, EXTR_OVERWRITE);
}
$current_module = RouteController::$currentRoute['module'];
$templatePath = MODULES_DIR . '/' . $current_module . '/Views/' . $template . '.php';
require $templatePath;
return ob_get_clean();
} | php | {
"resource": ""
} |
q5156 | Mailer.createStringAttachments | train | private function createStringAttachments($attachments)
{
if (array_key_exists('string', $attachments)) {
$this->mailer->addStringAttachment($attachments['string'], $attachments['name']);
} else {
foreach ($attachments as $attachment) {
$this->mailer->addStringAttachment($attachment['string'], $attachment['name']);
}
}
} | php | {
"resource": ""
} |
q5157 | Pagination.render | train | public function render($page, $settings=array())
{
$this->settings = array_merge($this->settings, $settings);
if (!empty($page->currentUri)) {
$this->htmlAHref = str_replace('?', '&', $this->htmlAHref);
$this->currentUri = $page->currentUri;
} else {
$this->currentUri = $this->di->get('router')->getRewriteUri();
}
$html = '';
if ($page->total_pages > 1) {
$this->page = $page;
$this->checkBoundary();
$html .= '<ul class="pagination">';
$html .= $this->renderPreviousButton();
$html .= $this->renderPages();
$html .= $this->renderNextButton();
$html .= '</ul>';
}
return $html;
} | php | {
"resource": ""
} |
q5158 | Pagination.checkBoundary | train | private function checkBoundary()
{
if($this->page->current > $this->page->total_pages) {
$queryLink = !empty($this->page->currentUri) ? '&' : '?';
$redirectUrl = substr($this->currentUri, 1) . $queryLink . 'page=' . $this->page->total_pages;
$this->di->get('response')->redirect($redirectUrl);
}
} | php | {
"resource": ""
} |
q5159 | Pagination.renderPreviousButton | train | private function renderPreviousButton()
{
$before = $this->page->before;
$extraClass = $before ? '' : ' not-active';
if (empty($before)) {
$before = 1;
}
return $this->renderElement($before, $this->settings['label_previous'], 'prev'.$extraClass);
} | php | {
"resource": ""
} |
q5160 | Pagination.renderNextButton | train | private function renderNextButton()
{
$next = $this->page->next;
$extraClass = $next ? '' : ' not-active';
if (empty($next)) {
$next = $this->page->total_pages;
}
return $this->renderElement($next, $this->settings['label_next'], 'next'.$extraClass);
} | php | {
"resource": ""
} |
q5161 | Pagination.renderElement | train | private function renderElement($page, $title, $class = '')
{
$href = sprintf($this->htmlHref, $this->currentUri, $page);
$href .= $this->getUrlParams();
$element = sprintf($this->htmlAHref, $href, $title);
return sprintf($this->htmlElement, $class, $element);
} | php | {
"resource": ""
} |
q5162 | Pagination.renderPages | train | private function renderPages()
{
$html = '';
for($i=1; $i<=$this->page->total_pages; $i++) {
if ($i == $this->page->current) {
$html .= $this->renderElement($i, $i, 'active');
} elseif($this->isPrintablePage($i)) {
$html .= $this->renderElement($i, $i);
} elseif($this->isMiddleOffsetPage($i)) {
$html .= $this->renderElement($this->page->current, '...', 'more');
}
}
return $html;
} | php | {
"resource": ""
} |
q5163 | AggregateMongo.getResults | train | public function getResults()
{
$skip = ($this->page-1)*$this->limit;
$cursor = $this->getCursor();
$cursor->skip($skip);
$results = array();
$i = 0;
while($cursor->valid() && $cursor->current() && $i++ < $this->limit) {
$object = new $this->modelName();
$object->writeAttributes($cursor->current());
$pseudoCursor = new \stdClass();
foreach ($object as $key => $value) {
$pseudoCursor->$key = $value;
}
$results[] = $pseudoCursor;
$cursor->skip();
}
return $results;
} | php | {
"resource": ""
} |
q5164 | Authenticator.stateless | train | public function stateless($username, $password)
{
$user = $this->sentinel->stateless(
[
'email' => $username,
'password' => $password,
]
);
if ( ! ($user instanceof CartalystUserInterface)) {
return false;
}
// This is still a login, and while we don't want persistence, we do want it to be recorded
$this->sentinel->getUserRepository()->recordLogin($user);
event( new CmsUserLoggedIn($user, true) );
return true;
} | php | {
"resource": ""
} |
q5165 | Authenticator.forceUser | train | public function forceUser(UserInterface $user, $remember = true)
{
$user = $this->sentinel->authenticate($user, $remember);
if ( ! ($user instanceof CartalystUserInterface)) {
return false;
}
event( new CmsUserLoggedIn($user, false, true) );
return true;
} | php | {
"resource": ""
} |
q5166 | Authenticator.forceUserStateless | train | public function forceUserStateless(UserInterface $user)
{
$user = $this->sentinel->authenticate($user, false, false);
if ( ! ($user instanceof CartalystUserInterface)) {
return false;
}
event( new CmsUserLoggedIn($user, true, true) );
return true;
} | php | {
"resource": ""
} |
q5167 | Authenticator.assign | train | public function assign($role, UserInterface $user)
{
$roles = is_array($role) ? $role : [ $role ];
$count = 0;
foreach ($roles as $singleRole) {
$count += $this->assignSingleRole($singleRole, $user) ? 1 : 0;
}
if ($count !== count($roles)) {
return false;
}
$this->fireUserPermissionChangeEvent($user);
return true;
} | php | {
"resource": ""
} |
q5168 | Authenticator.unassign | train | public function unassign($role, UserInterface $user)
{
$roles = is_array($role) ? $role : [ $role ];
$count = 0;
foreach ($roles as $singleRole) {
$count += $this->unassignSingleRole($singleRole, $user) ? 1 : 0;
}
if ($count !== count($roles)) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
$this->fireUserPermissionChangeEvent($user);
return true;
} | php | {
"resource": ""
} |
q5169 | Authenticator.removeRole | train | public function removeRole($role)
{
if ( ! ($roleModel = $this->sentinel->findRoleBySlug($role))) {
return false;
}
/** @var EloquentRole $roleModel */
$roleModel->delete();
$this->fireRoleChangeEvent();
return true;
} | php | {
"resource": ""
} |
q5170 | Authenticator.grantToRole | train | public function grantToRole($permission, $role)
{
/** @var EloquentRole $roleModel */
if ( ! ($roleModel = $this->sentinel->findRoleBySlug($role))) {
return false;
}
$permissions = is_array($permission) ? $permission : [ $permission ];
foreach ($permissions as $singlePermission) {
$this->grantSinglePermissionToRole($singlePermission, $roleModel);
}
if ( ! $roleModel->save()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
$this->fireRoleChangeEvent();
return true;
} | php | {
"resource": ""
} |
q5171 | Authenticator.revokeFromRole | train | public function revokeFromRole($permission, $role)
{
/** @var EloquentRole $roleModel */
if ( ! ($roleModel = $this->sentinel->findRoleBySlug($role))) {
return false;
}
$permissions = is_array($permission) ? $permission : [ $permission ];
foreach ($permissions as $singlePermission) {
$this->revokeSinglePermissionFromRole($singlePermission, $roleModel);
}
if ( ! $roleModel->save()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
$this->fireRoleChangeEvent();
return true;
} | php | {
"resource": ""
} |
q5172 | Authenticator.createUser | train | public function createUser($username, $password, array $data = [])
{
/** @var UserInterface|EloquentUser $user */
$user = $this->sentinel->registerAndActivate([
'email' => $username,
'password' => $password,
]);
if ( ! $user) {
// @codeCoverageIgnoreStart
throw new \Exception("Failed to create user '{$username}'");
// @codeCoverageIgnoreEnd
}
$user->update($data);
return $user;
} | php | {
"resource": ""
} |
q5173 | Authenticator.deleteUser | train | public function deleteUser($username)
{
/** @var UserInterface|EloquentUser $user */
if ( ! ($user = $this->sentinel->findByCredentials(['email' => $username]))) {
return false;
}
// The super admin may not be deleted.
if ($user->isAdmin()) {
return false;
}
return (bool) $user->delete();
} | php | {
"resource": ""
} |
q5174 | Authenticator.updatePassword | train | public function updatePassword($username, $password)
{
/** @var UserInterface|EloquentUser $user */
if ( ! ($user = $this->sentinel->findByCredentials(['email' => $username]))) {
return false;
}
return $this->sentinel->update($user, ['password' => $password]) instanceof UserInterface;
} | php | {
"resource": ""
} |
q5175 | CacheTask.cleanAction | train | public function cleanAction()
{
$this->putText("Cleaning cache...");
$di = DI::getDefault();
if ($di->has('config')) {
$config = $di->get('config');
if (!empty($config->application->view->cacheDir)) {
$this->removeFilesFromDir($config->application->view->cacheDir);
}
$this->putSuccess("Done.");
}
} | php | {
"resource": ""
} |
q5176 | CacheTask.removeFilesFromDir | train | private function removeFilesFromDir($dir)
{
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry == "." || $entry == "..") {
continue;
}
if (!unlink($dir.DIRECTORY_SEPARATOR.$entry)) {
$this->putWarning("Can not remove: ".$dir.DIRECTORY_SEPARATOR.$entry);
}
}
closedir($handle);
}
} | php | {
"resource": ""
} |
q5177 | RouteListener.filterActionMethodName | train | protected function filterActionMethodName($name)
{
$filter = new FilterChain;
$filter->attachByName('Zend\Filter\Word\CamelCaseToDash');
$filter->attachByName('StringToLower');
return rtrim(preg_replace('/action$/', '', $filter->filter($name)), '-');
} | php | {
"resource": ""
} |
q5178 | RouteListener.getRouteConfig | train | protected function getRouteConfig(Route $annotation)
{
return [
$annotation->getName() => [
'type' => $annotation->getType(),
'options' => [
'route' => $annotation->getRoute(),
'defaults' => $annotation->getDefaults(),
'constraints' => $annotation->getConstraints()
],
'priority' => (int) $annotation->getPriority(),
'may_terminate' => (bool) $annotation->getMayTerminate(),
'child_routes' => []
]
];
} | php | {
"resource": ""
} |
q5179 | RouteListener.& | train | protected function &getReferenceForPath(array $path, array &$config)
{
$path = array_filter($path, function ($value) {
return (bool) $value;
});
$ref = &$config;
if (empty($path)) {
return $ref;
}
foreach ($path as $key) {
if (!isset($ref[$key])) {
$ref[$key] = [
'child_routes' => []
];
}
$ref = &$ref[$key]['child_routes'];
}
return $ref;
} | php | {
"resource": ""
} |
q5180 | RouteListener.isValidForRootNode | train | public function isValidForRootNode(Route $annotation)
{
if (!$annotation->name) {
return false;
}
if (!$annotation->route) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q5181 | Lang.load | train | public function load($lang) {
$langDir = MODULES_DIR . DS . RouteController::$currentModule . '/Views/lang/' . $lang;
$files = glob($langDir . "/*.php");
if (count($files) == 0) {
throw new \Exception(ExceptionMessages::TRANSLATION_FILES_NOT_FOUND);
}
foreach ($files as $file) {
$fileInfo = pathinfo($file);
self::$translations[$fileInfo['filename']] = require_once $file;
}
} | php | {
"resource": ""
} |
q5182 | Lang.set | train | public static function set($lang = NULL) {
$languages = get_config('langs');
if (!$languages) {
throw new \Exception(ExceptionMessages::MISCONFIGURED_LANG_CONFIG);
}
if (!get_config('lang_default')) {
throw new \Exception(ExceptionMessages::MISCONFIGURED_LANG_DEFAULT_CONFIG);
}
if (empty($lang) || !in_array($lang, $languages)) {
$lang = get_config('lang_default');
}
self::$currentLang = $lang;
self::load($lang);
} | php | {
"resource": ""
} |
q5183 | PaletteExtension.loadConfiguration | train | public function loadConfiguration()
{
// Load extension configuration
$config = $this->getConfig();
if(!isset($config['path']))
{
throw new ServiceCreationException('Missing required path parameter in PaletteExtension configuration');
}
if(!isset($config['url']))
{
throw new ServiceCreationException('Missing required url parameter in PaletteExtension configuration');
}
// Register extension services
$builder = $this->getContainerBuilder();
// Register palette service
$builder->addDefinition($this->prefix('service'))
->setClass('NettePalette\Palette', array(
$config['path'],
$config['url'],
$config['basepath'],
empty($config['fallbackImage']) ? NULL : $config['fallbackImage'],
empty($config['template']) ? NULL : $config['template'],
empty($config['websiteUrl']) ? NULL : $config['websiteUrl'],
empty($config['pictureLoader']) ? NULL : $config['pictureLoader'],
))
->addSetup('setHandleExceptions', [
!isset($config['handleException']) ? TRUE : $config['handleException'],
]);
// Register latte filter service
$builder->addDefinition($this->prefix('filter'))
->setClass('NettePalette\LatteFilter', [$this->prefix('@service')]);
// Register latte filter
$this->getLatteService()
->addSetup('addFilter', ['palette', $this->prefix('@filter')]);
// Register extension presenter
$builder->getDefinition('nette.presenterFactory')
->addSetup('setMapping', [['Palette' => 'NettePalette\*Presenter']]);
} | php | {
"resource": ""
} |
q5184 | PaletteExtension.getLatteService | train | protected function getLatteService()
{
$builder = $this->getContainerBuilder();
return $builder->hasDefinition('nette.latteFactory')
? $builder->getDefinition('nette.latteFactory')
: $builder->getDefinition('nette.latte');
} | php | {
"resource": ""
} |
q5185 | FileWriter.write | train | public static function write($filePath, $content, $compareContents = false)
{
if ($compareContents && self::compareContents($filePath, $content)) {
return 0;
}
return file_put_contents($filePath, $content);
} | php | {
"resource": ""
} |
q5186 | FileWriter.writeObject | train | public static function writeObject($filePath, $object, $compareContents = false)
{
$content = '<?php return ' . var_export($object, true) . ';';
return self::write($filePath, $content, $compareContents);
} | php | {
"resource": ""
} |
q5187 | FileWriter.compareContents | train | private static function compareContents($filePath, $newContent)
{
if (file_exists($filePath)) {
$currentContent = file_get_contents($filePath);
return strcmp($currentContent, $newContent) === 0;
}
return false;
} | php | {
"resource": ""
} |
q5188 | Volt.registerFilter | train | public function registerFilter($filterName)
{
$className = __CLASS__ . '\\Filter\\' . ucfirst($filterName);
try {
$filterInstance = $this->getClassInstance($className);
if (!$filterInstance instanceof VoltFilterAbstract) {
throw new InvalidFilterException();
}
$this->getCompiler()->addFilter($filterName, $filterInstance->getFilter());
} catch (\ReflectionException $e) {
throw new UnknownFilterException(sprintf('Filter \'%s\' does not exist', $filterName));
} catch (\Exception $e) {
throw new InvalidFilterException(sprintf('Invalid filter \'%s\'', $filterName));
}
} | php | {
"resource": ""
} |
q5189 | Volt.registerHelper | train | public function registerHelper($helperName)
{
$className = __CLASS__ . '\\Helper\\' . ucfirst($helperName);
try {
$helperInstance = $this->getClassInstance($className);
if (!$helperInstance instanceof VoltHelperAbstract) {
throw new InvalidHelperException();
}
$this->getCompiler()->addFunction($helperName, $helperInstance->getHelper());
} catch (\ReflectionException $e) {
throw new UnknownHelperException(sprintf('Helper \'%s\' does not exist', $helperName));
} catch (\Exception $e) {
throw new InvalidHelperException(sprintf('Invalid helper \'%s\'', $helperName));
}
} | php | {
"resource": ""
} |
q5190 | Router.controller | train | public function controller($uri, $controller, $names = [])
{
$arr = explode('\\', $controller);
$controllerClassName = $arr[ sizeof($arr) -1 ];
$routable = (new ControllerInspector)->getRoutable($this->addGroupNamespace($controller), $uri);
foreach ($routable as $method => $routes) {
if ($method == 'getMethodProperties') {
continue;
}
foreach ($routes as $route) {
// original code
// $this->{$route['verb']}($route['uri'], [
// 'uses' => $controller.'@'.$method,
// 'as' => array_get($names, $method)
// ]);
// Route::{$route['verb']}( $route['uri'] , "{$controller}@{$method}" );
// should add middleware support later
Route::{$route['verb']}( $route['uri'] , "{$controllerClassName}@{$method}" );
// middleware support not working as following
// Route::{$route['verb']}( $route['uri'] , [
// 'uses' => $controller.'@'.$method,
// 'as' => array_get($names, $method)
// ]);
}
}
} | php | {
"resource": ""
} |
q5191 | Router.addGroupNamespace | train | protected function addGroupNamespace($controller)
{
if (! empty($this->groupStack)) {
$group = end($this->groupStack);
if (isset($group['namespace']) && strpos($controller, '\\') !== 0) {
return $group['namespace'].'\\'.$controller;
}
}
return $controller;
} | php | {
"resource": ""
} |
q5192 | Router.addRouteMiddlewares | train | protected function addRouteMiddlewares(array $action)
{
foreach ([static::API_RATE_LIMIT_MIDDLEWARE, static::API_AUTH_MIDDLEWARE] as $middleware) {
if (($key = array_search($middleware, $action['middleware'])) !== false) {
unset($action['middleware'][$key]);
}
array_unshift($action['middleware'], $middleware);
}
return $action;
} | php | {
"resource": ""
} |
q5193 | W3CMarkupValidatorMessage.initializeType | train | private function initializeType(array $data)
{
if (isset($data['type']) === false) {
return;
}
if ($data['type'] === 'error') {
$this->type = self::TYPE_ERROR;
} elseif ($data['type'] === 'info') {
if (isset($data['subType']) === true &&
$data['subType'] === 'warning'
) {
$this->type = self::TYPE_WARNING;
} else {
$this->type = self::TYPE_INFO;
}
}
} | php | {
"resource": ""
} |
q5194 | Route.extend | train | public function extend($annotation)
{
$params = get_object_vars($annotation);
foreach ($params as $property => $value) {
if (property_exists($this, $property) && !in_array($property, ['name', 'route'])) {
if (!$this->$property) {
$this->$property = $value;
}
}
}
} | php | {
"resource": ""
} |
q5195 | FilterParser.parse | train | protected function parse(string $key): array
{
if (strpos($key, '(') === false && strpos($key, ')') === false) {
return ['field' => trim($key), 'operator' => ''];
}
if (!preg_match(static::REGEXP, $key, $matches)) {
throw new InvalidFilterException("Invalid filter item '$key': Bad use of parentheses");
}
return array_only($matches, ['field', 'operator']) + ['operator' => ''];
} | php | {
"resource": ""
} |
q5196 | CrudAbstract.indexAction | train | public function indexAction()
{
$this->initializeScaffolding();
$paginator = $this->scaffolding->doPaginate($this->request->get('page', 'int', 1));
$this->view->page = $paginator->getPaginate();
$this->view->fields = $this->indexFields;
} | php | {
"resource": ""
} |
q5197 | CrudAbstract.showAction | train | public function showAction($id)
{
$this->initializeScaffolding();
$this->beforeRead();
$this->view->record = $this->scaffolding->doRead($id);
$this->view->fields = $this->showFields;
$this->afterRead();
} | php | {
"resource": ""
} |
q5198 | CrudAbstract.newAction | train | public function newAction()
{
$this->initializeScaffolding();
$this->beforeNew();
$this->view->form = $this->scaffolding->getForm();
$this->afterNew();
} | php | {
"resource": ""
} |
q5199 | CrudAbstract.createAction | train | public function createAction()
{
$this->initializeScaffolding();
$this->checkRequest();
try {
$this->beforeCreate();
$this->scaffolding->doCreate($this->request->getPost());
$this->flash->success($this->successMessage);
return $this->afterCreate();
} catch (Exception $e) {
$this->flash->error($e->getMessage());
$this->afterCreateException();
}
return $this->dispatcher->forward(['action' => 'new']);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.