_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
language
stringclasses
1 value
meta_information
dict
q5100
FixedDateTimeTrait.getDateTimeInstance
train
protected function getDateTimeInstance(string $time = "now", \DateTimeZone $timezone = null): DateTime { $result =
php
{ "resource": "" }
q5101
DfOAuthOneProvider.getOAuthToken
train
public function getOAuthToken() { if (!$this->isStateless()) { return \Cache::get('oauth.temp'); } else { /** @var TemporaryCredentials $temp */
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'); }
php
{ "resource": "" }
q5103
MappingManager.find
train
public static function find($mappingName) { if (!array_key_exists($mappingName, self::$container)) {
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'));
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();
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);
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
php
{ "resource": "" }
q5108
Mapper.cacheMap
train
private function cacheMap($cacheFilePath, $map) { if (!file_exists(dirname($cacheFilePath))) { mkdir(dirname($cacheFilePath), 0777, 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()
php
{ "resource": "" }
q5110
Option.matchParam
train
public function matchParam($paramName) { return (0 == strcasecmp($this->name, $paramName)) ||
php
{ "resource": "" }
q5111
Option.validate
train
public function validate($value) { $result = !$this->isRequired; if ($this->isRequired()) { $result =
php
{ "resource": "" }
q5112
Option.getValue
train
public function getValue($args, $default = null) { if (isset($args[$this->name])) { return $args[$this->name]; }
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, ' ',
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)) {
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(
php
{ "resource": "" }
q5116
AggregateCursor.skip
train
public function skip($by = 1) { $i = 0; while($this->cursor->valid() &&
php
{ "resource": "" }
q5117
File.getContents
train
public static function getContents($filename) { $contents = file_get_contents($filename); if ($contents === false) {
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) {
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) {
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;
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) {
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()) {
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);
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
php
{ "resource": "" }
q5125
KeywordsRepository.storeKeywords
train
protected function storeKeywords($key, $minutes = null, array $keywords = []) { $keywords = empty($keywords) ? $this->keywords : $keywords; $this->determineKeywordsState($key, $keywords);
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);
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']) {
php
{ "resource": "" }
q5128
AnalyticsBase.trackEcommerce
train
protected function trackEcommerce($type = self::ECOMMERCE_TRANSACTION, array $options = []) { $this->addItem("ga('require', 'ecommerce');");
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);
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"
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"
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 []; }
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 );
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),
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);
php
{ "resource": "" }
q5136
CacheInstance.clear
train
public function clear($key = null) { if (isset($key)) { if (isset($this->data[$key])) { unset($this->data[$key]);
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
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(); }
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);
php
{ "resource": "" }
q5140
IlluminateDriver.getElapsedTime
train
protected function getElapsedTime($start) { if ($this->elapsedTimeMethod === null) { $reflection = new ReflectionClass($this->getConnect()); $this->elapsedTimeMethod = $reflection->getMethod('getElapsedTime');
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) {
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) {
php
{ "resource": "" }
q5143
RenderDefinitionCollection.addCollection
train
public function addCollection(self $collection) { $this->renderDefinitions = \array_merge($this->renderDefinitions, $collection->all());
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(),
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);
php
{ "resource": "" }
q5146
Request.hasFile
train
public static function hasFile($key) { if (isset($_FILES[$key]) === false || (isset($_FILES[$key]['error']) && $_FILES[$key]['error'] != 0))
php
{ "resource": "" }
q5147
Request.getAuthorizationBearer
train
public function getAuthorizationBearer() { $allHeaders = array_change_key_case(parent::getHeaders(), CASE_UPPER); if (array_key_exists('AUTHORIZATION', $allHeaders)) {
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());
php
{ "resource": "" }
q5149
ErrorHandlerInitializerTrait.errorHandler
train
public function errorHandler($code, $message, $file, $line) { $this->debug->setShowBackTrace(false);
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
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)) {
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.",
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) {
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');
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);
php
{ "resource": "" }
q5156
Mailer.createStringAttachments
train
private function createStringAttachments($attachments) { if (array_key_exists('string', $attachments)) { $this->mailer->addStringAttachment($attachments['string'], $attachments['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();
php
{ "resource": "" }
q5158
Pagination.checkBoundary
train
private function checkBoundary() { if($this->page->current > $this->page->total_pages) { $queryLink = !empty($this->page->currentUri) ? '&' : '?'; $redirectUrl =
php
{ "resource": "" }
q5159
Pagination.renderPreviousButton
train
private function renderPreviousButton() { $before = $this->page->before; $extraClass = $before ? '' : ' not-active'; if (empty($before)) { $before = 1; }
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; }
php
{ "resource": "" }
q5161
Pagination.renderElement
train
private function renderElement($page, $title, $class = '') { $href = sprintf($this->htmlHref, $this->currentUri, $page); $href .= $this->getUrlParams();
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,
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) {
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; }
php
{ "resource": "" }
q5165
Authenticator.forceUser
train
public function forceUser(UserInterface $user, $remember = true) { $user = $this->sentinel->authenticate($user, $remember); if ( ! ($user instanceof CartalystUserInterface)) {
php
{ "resource": "" }
q5166
Authenticator.forceUserStateless
train
public function forceUserStateless(UserInterface $user) { $user = $this->sentinel->authenticate($user, false, false);
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; }
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)) {
php
{ "resource": "" }
q5169
Authenticator.removeRole
train
public function removeRole($role) { if ( ! ($roleModel = $this->sentinel->findRoleBySlug($role))) { return false; } /** @var EloquentRole $roleModel */
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);
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);
php
{ "resource": "" }
q5172
Authenticator.createUser
train
public function createUser($username, $password, array $data = []) { /** @var UserInterface|EloquentUser $user */ $user = $this->sentinel->registerAndActivate([ 'email' => $username,
php
{ "resource": "" }
q5173
Authenticator.deleteUser
train
public function deleteUser($username) { /** @var UserInterface|EloquentUser $user */ if ( ! ($user = $this->sentinel->findByCredentials(['email' => $username]))) { return false; } //
php
{ "resource": "" }
q5174
Authenticator.updatePassword
train
public function updatePassword($username, $password) { /** @var UserInterface|EloquentUser $user */ if ( ! ($user = $this->sentinel->findByCredentials(['email' => $username]))) { return false;
php
{ "resource": "" }
q5175
CacheTask.cleanAction
train
public function cleanAction() { $this->putText("Cleaning cache..."); $di = DI::getDefault(); if ($di->has('config')) { $config = $di->get('config');
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)) {
php
{ "resource": "" }
q5177
RouteListener.filterActionMethodName
train
protected function filterActionMethodName($name) { $filter = new FilterChain; $filter->attachByName('Zend\Filter\Word\CamelCaseToDash'); $filter->attachByName('StringToLower');
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() ],
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] = [
php
{ "resource": "" }
q5180
RouteListener.isValidForRootNode
train
public function isValidForRootNode(Route $annotation) { if (!$annotation->name) {
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); }
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
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'],
php
{ "resource": "" }
q5184
PaletteExtension.getLatteService
train
protected function getLatteService() { $builder = $this->getContainerBuilder(); return $builder->hasDefinition('nette.latteFactory')
php
{ "resource": "" }
q5185
FileWriter.write
train
public static function write($filePath, $content, $compareContents = false) { if ($compareContents &&
php
{ "resource": "" }
q5186
FileWriter.writeObject
train
public static function writeObject($filePath, $object, $compareContents = false) {
php
{ "resource": "" }
q5187
FileWriter.compareContents
train
private static function compareContents($filePath, $newContent) { if (file_exists($filePath)) { $currentContent = file_get_contents($filePath);
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());
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());
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 //
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) {
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) {
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 &&
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'])) {
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)) {
php
{ "resource": "" }
q5196
CrudAbstract.indexAction
train
public function indexAction() { $this->initializeScaffolding(); $paginator = $this->scaffolding->doPaginate($this->request->get('page', 'int', 1));
php
{ "resource": "" }
q5197
CrudAbstract.showAction
train
public function showAction($id) { $this->initializeScaffolding(); $this->beforeRead(); $this->view->record = $this->scaffolding->doRead($id);
php
{ "resource": "" }
q5198
CrudAbstract.newAction
train
public function newAction() { $this->initializeScaffolding();
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(); }
php
{ "resource": "" }