_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q100
RedirectLoginHelper.validateCsrf
train
protected function validateCsrf() { if (empty($this->getInput('state')) || ($this->getInput('state') !== $this->store->get('oauth2state')) ) { $this->store->set('oauth2state', null); throw new CsrfException('Invalid state'); } return; }
php
{ "resource": "" }
q101
Client.getAccessToken
train
public function getAccessToken($code, $grant = 'authorization_code') { $token = $this->container->get(RedirectLoginHelper::class) ->getAccessToken($code, $grant); $this->setAccessToken($token); return $token; }
php
{ "resource": "" }
q102
Client.setAccessToken
train
public function setAccessToken(AccessToken $token) { $this->container->get('config') ->set('access_token', json_encode($token->jsonSerialize())); }
php
{ "resource": "" }
q103
Profile.getData
train
public function getData($sEmail) { $this->sFormat = 'php'; $sProfile = file_get_contents($this->getUrl($sEmail)); $aProfile = unserialize($sProfile); if (is_array($aProfile) && isset($aProfile['entry'])) { return $aProfile; } }
php
{ "resource": "" }
q104
Profile.format
train
public function format($sFormat= null) { if (null === $sFormat) { return $this->getFormat(); } return $this->setFormat($sFormat); }
php
{ "resource": "" }
q105
Profile.setFormat
train
public function setFormat($sFormat = null) { if (null === $sFormat) { return $this; } if (!in_array($sFormat, $this->aValidFormats)) { $message = sprintf( 'The format "%s" is not a valid one, profile format for Gravatar can be: %s', $sFormat, implode(', ', $this->aValidFormats) ); throw new InvalidProfileFormatException($message); } $this->sFormat = $sFormat; return $this; }
php
{ "resource": "" }
q106
RegisterController.createSignup
train
protected function createSignup(array $data, $userId) { return Signup::create([ 'user_id' => $userId, 'firstname' => $data['firstname'], 'surname' => $data['surname'], 'gender' => $data['gender'], 'email' => $data['email'], 'mobile_number' => $data['mobile_number'], ]); }
php
{ "resource": "" }
q107
Guzzle.handleErrors
train
private static function handleErrors($response) { switch ($response->getStatusCode()) { case 200: return json_decode($response->getBody()); break; case 401: throw new UnauthorizedException('Unauthorized (Invalid API key or insufficient permissions)'); break; case 404: throw new NotFoundException('Object not found within your account scope'); break; case 406: throw new InvalidFormatException('Requested format is not supported - request JSON or XML only'); break; case 422: throw new ValidationException('Validation error(s) for create or update method'); break; case 500: throw new ServerException('Something went wrong on Challonge\'s end'); break; default: $decodedResponse = json_decode($response->getBody()); throw new UnexpectedErrorException($decodedResponse); break; } }
php
{ "resource": "" }
q108
LatLong.primeCoordinateParsers
train
protected function primeCoordinateParsers() { $this->latitude->getParser()->setDirection(N::LAT); $this->longitude->getParser()->setDirection(N::LONG); }
php
{ "resource": "" }
q109
DefaultController.servicosDisponiveisUnidade
train
private function servicosDisponiveisUnidade($unidade) { $rs = $this ->getDoctrine() ->getManager() ->createQueryBuilder() ->select([ 'e', 's', 'sub' ]) ->from(ServicoUnidade::class, 'e') ->join('e.servico', 's') ->leftJoin('s.subServicos', 'sub') ->where('s.mestre IS NULL') ->andWhere('e.ativo = TRUE') ->andWhere('e.unidade = :unidade') ->orderBy('s.nome', 'ASC') ->setParameter('unidade', $unidade) ->getQuery() ->getResult(); $dados = [ 'unidade' => $unidade->getNome(), 'servicos' => $rs, ]; return $dados; }
php
{ "resource": "" }
q110
PasswordlessProvider.registerEvents
train
public function registerEvents() { // Delete user tokens after login if (config('passwordless.empty_tokens_after_login') === true) { Event::listen( Authenticated::class, function (Authenticated $event) { $event->user->tokens() ->delete(); } ); } }
php
{ "resource": "" }
q111
Worker.processOne
train
public function processOne(ObjectId $id): void { $this->catchSignal(); $this->logger->debug('process job ['.$id.'] and exit', [ 'category' => get_class($this), ]); try { $job = $this->scheduler->getJob($id)->toArray(); $this->queueJob($job); } catch (\Exception $e) { $this->logger->error('failed process job ['.$id.']', [ 'category' => get_class($this), 'exception' => $e, ]); } }
php
{ "resource": "" }
q112
Worker.cleanup
train
public function cleanup() { $this->saveState(); if (null === $this->current_job) { $this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [ 'category' => get_class($this), 'pm' => $this->process, ]); $this->exit(); return null; } $this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [ 'category' => get_class($this), 'pm' => $this->process, ]); $this->updateJob($this->current_job, JobInterface::STATUS_CANCELED); $this->db->{$this->scheduler->getEventQueue()}->insertOne([ 'job' => $this->current_job['_id'], 'worker' => $this->id, 'status' => JobInterface::STATUS_CANCELED, 'timestamp' => new UTCDateTime(), ]); $options = $this->current_job['options']; $options['at'] = 0; $result = $this->scheduler->addJob($this->current_job['class'], $this->current_job['data'], $options)->getId(); $this->exit(); return $result; }
php
{ "resource": "" }
q113
Worker.saveState
train
protected function saveState(): self { foreach ($this->queue as $key => $job) { $this->db->selectCollection($this->scheduler->getJobQueue())->updateOne( ['_id' => $job['_id'], '$isolated' => true], ['$setOnInsert' => $job], ['upsert' => true] ); } return $this; }
php
{ "resource": "" }
q114
Worker.catchSignal
train
protected function catchSignal(): self { pcntl_async_signals(true); pcntl_signal(SIGTERM, [$this, 'cleanup']); pcntl_signal(SIGINT, [$this, 'cleanup']); pcntl_signal(SIGALRM, [$this, 'timeout']); return $this; }
php
{ "resource": "" }
q115
Worker.queueJob
train
protected function queueJob(array $job): bool { if (!isset($job['status'])) { return false; } if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING)) { $this->processJob($job); } elseif (JobInterface::STATUS_POSTPONED === $job['status']) { $this->logger->debug('found postponed job ['.$job['_id'].'] to requeue', [ 'category' => get_class($this), 'pm' => $this->process, ]); $this->queue[(string) $job['_id']] = $job; } return true; }
php
{ "resource": "" }
q116
Worker.processLocalQueue
train
protected function processLocalQueue(): bool { $now = time(); foreach ($this->queue as $key => $job) { $this->db->{$this->scheduler->getJobQueue()}->updateOne( ['_id' => $job['_id'], '$isolated' => true], ['$setOnInsert' => $job], ['upsert' => true] ); if ($job['options']['at'] <= $now) { $this->logger->info('postponed job ['.$job['_id'].'] ['.$job['class'].'] can now be executed', [ 'category' => get_class($this), 'pm' => $this->process, ]); unset($this->queue[$key]); $job['options']['at'] = 0; if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING, JobInterface::STATUS_POSTPONED)) { $this->processJob($job); } } } return true; }
php
{ "resource": "" }
q117
Worker.executeJob
train
protected function executeJob(array $job): bool { if (!class_exists($job['class'])) { throw new InvalidJobException('job class does not exists'); } if (null === $this->container) { $instance = new $job['class'](); } else { $instance = $this->container->get($job['class']); } if (!($instance instanceof JobInterface)) { throw new InvalidJobException('job must implement JobInterface'); } $instance ->setData($job['data']) ->setId($job['_id']) ->start(); $return = $this->updateJob($job, JobInterface::STATUS_DONE); $this->db->{$this->scheduler->getEventQueue()}->insertOne([ 'job' => $job['_id'], 'worker' => $this->id, 'status' => JobInterface::STATUS_DONE, 'timestamp' => new UTCDateTime(), ]); unset($instance); return $return; }
php
{ "resource": "" }
q118
Loader.addToHTML
train
public static function addToHTML() { if (!self::isViewingHTMLPage()) { return; } // js $paths = self::getAssetFilePaths('js'); echo sprintf( '<script>%s</script>', self::getCombinedContents($paths) ); // css $paths = self::getAssetFilePaths('css'); echo sprintf( '<style>%s</style>', self::getCombinedContents($paths) ); }
php
{ "resource": "" }
q119
Loader.isViewingHTMLPage
train
public static function isViewingHTMLPage() { if (!is_admin()) { return false; } if (!array_key_exists('SCRIPT_NAME', $_SERVER)) { return false; } $whitelisted_script_names = array( 'wp-admin/post-new.php', 'wp-admin/post.php', 'wp-admin/edit.php', ); $script_name = strstr($_SERVER['SCRIPT_NAME'], 'wp-admin'); if (!in_array($script_name, $whitelisted_script_names)) { return false; } return true; }
php
{ "resource": "" }
q120
Loader.getAssetFilePaths
train
public static function getAssetFilePaths($type) { $path = sprintf('%s/assets/%s/', __DIR__, $type); $filenames = preg_grep('/^[^\.]/', scandir($path)); if (!Arr::iterable($filenames)) { return array(); } return array_map(function ($filename) use ($path) { return $path.$filename; }, $filenames); }
php
{ "resource": "" }
q121
Loader.getCombinedContents
train
public static function getCombinedContents($paths) { if (!Arr::iterable($paths)) { return ''; } $out = array(); foreach ($paths as $path) { $out[] = file_get_contents($path); } return join("\n", $out); }
php
{ "resource": "" }
q122
Prpcrypt.decode
train
public function decode($decrypted) { $pad = ord(substr($decrypted, -1)); if ($pad < 1 || $pad > $this->blockSize) { $pad = 0; } return substr($decrypted, 0, (strlen($decrypted) - $pad)); }
php
{ "resource": "" }
q123
SchedulerValidator.validateOptions
train
public static function validateOptions(array $options): array { foreach ($options as $option => $value) { switch ($option) { case Scheduler::OPTION_AT: case Scheduler::OPTION_INTERVAL: case Scheduler::OPTION_RETRY: case Scheduler::OPTION_RETRY_INTERVAL: case Scheduler::OPTION_TIMEOUT: if (!is_int($value)) { throw new InvalidArgumentException('option '.$option.' must be an integer'); } break; case Scheduler::OPTION_IGNORE_DATA: case Scheduler::OPTION_FORCE_SPAWN: if (!is_bool($value)) { throw new InvalidArgumentException('option '.$option.' must be a boolean'); } break; case Scheduler::OPTION_ID: if (!$value instanceof ObjectId) { throw new InvalidArgumentException('option '.$option.' must be a an instance of '.ObjectId::class); } break; default: throw new InvalidArgumentException('invalid option '.$option.' given'); } } return $options; }
php
{ "resource": "" }
q124
Helper.addRedirectUriToServiceConfig
train
protected static function addRedirectUriToServiceConfig(array $config) { if (!empty($config['constructor']) && is_array($config['constructor'])) { $key = key($config['constructor']); // Key may be non-numeric if (!isset($config['constructor'][$key]['redirectUri'])) { $config['constructor'][$key]['redirectUri'] = static::getRedirectUri(); } } return $config; }
php
{ "resource": "" }
q125
Image.getUrl
train
public function getUrl($sEmail = null) { if (null !== $sEmail) { $this->setEmail($sEmail); } return static::URL .'avatar/' .$this->getHash($this->getEmail()) .$this->getParams(); }
php
{ "resource": "" }
q126
Image.size
train
public function size($iSize = null) { if (null === $iSize) { return $this->getSize(); } return $this->setSize($iSize); }
php
{ "resource": "" }
q127
Image.defaultImage
train
public function defaultImage($sDefaultImage = null, $bForce = false) { if (null === $sDefaultImage) { return $this->getDefaultImage(); } return $this->setDefaultImage($sDefaultImage, $bForce); }
php
{ "resource": "" }
q128
Image.forceDefault
train
public function forceDefault($bForceDefault = null) { if (null === $bForceDefault) { return $this->getForceDefault(); } return $this->setForceDefault($bForceDefault); }
php
{ "resource": "" }
q129
Image.rating
train
public function rating($sRating = null) { if (null === $sRating) { return $this->getMaxRating(); } return $this->setMaxRating($sRating); }
php
{ "resource": "" }
q130
Image.extension
train
public function extension($sExtension = null) { if (null === $sExtension) { return $this->getExtension(); } return $this->setExtension($sExtension); }
php
{ "resource": "" }
q131
Image.setExtension
train
public function setExtension($sExtension = null) { if (null === $sExtension) { return $this; } if (!in_array($sExtension, $this->aValidExtensions)) { $message = sprintf( 'The extension "%s" is not a valid one, extension image for Gravatar can be: %s', $sExtension, implode(', ', $this->aValidExtensions) ); throw new InvalidImageExtensionException($message); } $this->sExtension = $sExtension; return $this; }
php
{ "resource": "" }
q132
Image.getParams
train
protected function getParams() { $aParams = []; if (null !== $this->getSize()) { $aParams['s'] = $this->getSize(); } if (null !== $this->getDefaultImage()) { $aParams['d'] = $this->getDefaultImage(); } if (null !== $this->getMaxRating()) { $aParams['r'] = $this->getMaxRating(); } if ($this->forcingDefault()) { $aParams['f'] = 'y'; } return (null !== $this->sExtension ? '.'.$this->sExtension : '') .(empty($aParams) ? '' : '?'.http_build_query($aParams, '', '&amp;')); }
php
{ "resource": "" }
q133
ResponsiveImageRenderer.render
train
public function render(FileInterface $file, $width, $height, array $options = [], $usedPathsRelativeToCurrentScript = false): string { if (!array_key_exists(self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY, $options) && isset($GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY]) ) { $options[self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY] = (float)$GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY]; } $view = $this->initializeView(); $view->assignMultiple([ 'isAnimatedGif' => $this->isAnimatedGif($file), 'config' => $this->getConfig(), 'data' => $GLOBALS['TSFE']->cObj->data, 'file' => $file, 'options' => $options, ]); return $view->render('pictureTag'); }
php
{ "resource": "" }
q134
Configuration.getPattern
train
public function getPattern(PackageInterface $package) { if (isset($this->packages[$package->getName()])) { return $this->packages[$package->getName()]; } elseif (isset($this->packages[$package->getPrettyName()])) { return $this->packages[$package->getPrettyName()]; } elseif (isset($this->types[$package->getType()])) { return $this->types[$package->getType()]; } }
php
{ "resource": "" }
q135
Configuration.convert
train
protected function convert($extra) { if (isset($extra['custom-installer'])) { foreach ($extra['custom-installer'] as $pattern => $specs) { foreach ($specs as $spec) { $match = array(); // Type matching if (preg_match('/^type:(.*)$/', $spec, $match)) { $this->types[$match[1]] = $pattern; } // Else it must be the package name. else { $this->packages[$spec] = $pattern; } } } } }
php
{ "resource": "" }
q136
Controller.getReturnUrl
train
protected function getReturnUrl() { $backUrl = $this->getRequest()->getSession()->get('oauth2.backurl'); if (!$backUrl || !Director::is_site_url($backUrl)) { $backUrl = Director::absoluteBaseURL(); } return $backUrl; }
php
{ "resource": "" }
q137
Controller.authenticate
train
public function authenticate(HTTPRequest $request) { $providerName = $request->getVar('provider'); $context = $request->getVar('context'); $scope = $request->getVar('scope'); // Missing or invalid data means we can't proceed if (!$providerName || !is_array($scope)) { $this->httpError(404); return null; } /** @var ProviderFactory $providerFactory */ $providerFactory = Injector::inst()->get(ProviderFactory::class); $provider = $providerFactory->getProvider($providerName); $url = $provider->getAuthorizationUrl(['scope' => $scope]); $request->getSession()->set('oauth2', [ 'state' => $provider->getState(), 'provider' => $providerName, 'context' => $context, 'scope' => $scope, 'backurl' => $this->findBackUrl($request) ]); return $this->redirect($url); }
php
{ "resource": "" }
q138
Controller.callback
train
public function callback(HTTPRequest $request) { $session = $request->getSession(); if (!$this->validateState($request)) { $session->clear('oauth2'); $this->httpError(400, 'Invalid session state.'); return null; } $providerName = $session->get('oauth2.provider'); /** @var ProviderFactory $providerFactory */ $providerFactory = Injector::inst()->get(ProviderFactory::class); $provider = $providerFactory->getProvider($providerName); $returnUrl = $this->getReturnUrl(); try { $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $request->getVar('code') ]); $handlers = $this->getHandlersForContext($session->get('oauth2.context')); // Run handlers to process the token $results = []; foreach ($handlers as $handlerConfig) { $handler = Injector::inst()->create($handlerConfig['class']); $results[] = $handler->handleToken($accessToken, $provider); } // Handlers may return response objects foreach ($results as $result) { if ($result instanceof HTTPResponse) { $session->clear('oauth2'); // If the response is redirecting to the login page (e.g. on Security::permissionFailure()), // update the BackURL so it doesn't point to /oauth/callback/ if ($result->isRedirect()) { $location = $result->getHeader('location'); $relativeLocation = Director::makeRelative($location); // If the URL begins Security/login and a BackURL parameter is set... if ( strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0 && strpos($relativeLocation, 'BackURL') !== -1 ) { $session->set('BackURL', $returnUrl); $location = HTTP::setGetVar('BackURL', $returnUrl, $location); $result->addHeader('location', $location); } } return $result; } } } catch (IdentityProviderException $e) { /** @var LoggerInterface $logger */ $logger = Injector::inst()->get(LoggerInterface::class . '.oauth'); $logger->error('OAuth IdentityProviderException: ' . $e->getMessage()); $this->httpError(400, 'Invalid access token.'); return null; } catch (Exception $e) { /** @var LoggerInterface $logger */ $logger = Injector::inst()->get(LoggerInterface::class . '.oauth'); $logger->error('OAuth Exception: ' . $e->getMessage()); $this->httpError(400, $e->getMessage()); return null; } finally { $session->clear('oauth2'); } return $this->redirect($returnUrl); }
php
{ "resource": "" }
q139
Controller.getHandlersForContext
train
protected function getHandlersForContext($context = null) { $handlers = $this->config()->get('token_handlers'); if (empty($handlers)) { throw new Exception('No token handlers were registered'); } // If we've been given a context, limit to that context + global handlers. // Otherwise only allow global handlers (i.e. exclude named ones) $allowedContexts = ['*']; if ($context) { $allowedContexts[] = $context; } // Filter handlers by context $handlers = array_filter($handlers, function ($handler) use ($allowedContexts) { return in_array($handler['context'], $allowedContexts); }); // Sort handlers by priority uasort($handlers, function ($a, $b) { if (!array_key_exists('priority', $a) || !array_key_exists('priority', $b)) { return 0; } return ($a['priority'] < $b['priority']) ? -1 : 1; }); return $handlers; }
php
{ "resource": "" }
q140
Controller.validateState
train
public function validateState(HTTPRequest $request) { $state = $request->getVar('state'); $session = $request->getSession(); $data = $session->get('oauth2'); // If we're lacking any required data, or the session state doesn't match // the one the provider returned, the request is invalid if (empty($data['state']) || empty($data['provider']) || empty($data['scope']) || $state !== $data['state']) { $session->clear('oauth2'); return false; } return true; }
php
{ "resource": "" }
q141
Challonge.getTournaments
train
public function getTournaments() { $response = Guzzle::get('tournaments'); $tournaments = []; foreach ($response as $tourney) { $tournaments[] = new Tournament($tourney->tournament); } return $tournaments; }
php
{ "resource": "" }
q142
Challonge.getParticipants
train
public function getParticipants($tournament) { $response = Guzzle::get("tournaments/{$tournament}/participants"); $participants = []; foreach ($response as $team) { $participant = new Participant($team->participant); $participant->tournament_slug = $tournament; $participants[] = $participant; } return $participants; }
php
{ "resource": "" }
q143
Challonge.randomizeParticipants
train
public function randomizeParticipants($tournament) { $response = Guzzle::post("tournaments/{$tournament}/participants/randomize"); $participants = []; foreach ($response as $team) { $participant = new Participant($team->participant); $participant->tournament_slug = $tournament; $participants[] = $participant; } return $participants; }
php
{ "resource": "" }
q144
Challonge.getParticipant
train
public function getParticipant($tournament, $participant) { $response = Guzzle::get("tournaments/{$tournament}/participants/{$participant}"); $participant = new Participant($response->participant); $participant->tournament_slug = $tournament; return $participant; }
php
{ "resource": "" }
q145
Challonge.getMatches
train
public function getMatches($tournament) { $response = Guzzle::get("tournaments/{$tournament}/matches"); $matches = []; foreach ($response as $match) { $matchModel = new Match($match->match); $matchModel->tournament_slug = $tournament; $matches[] = $matchModel; } return $matches; }
php
{ "resource": "" }
q146
Challonge.getMatch
train
public function getMatch($tournament, $match) { $response = Guzzle::get("tournaments/{$tournament}/matches/{$match}"); $match = new Match($response->match); $match->tournament_slug = $tournament; return $match; }
php
{ "resource": "" }
q147
StubLocale.getCurrenciesData
train
public static function getCurrenciesData($locale) { if (null === self::$currencies) { self::prepareCurrencies($locale); } return self::$currencies; }
php
{ "resource": "" }
q148
StubLocale.getDisplayCurrencies
train
public static function getDisplayCurrencies($locale) { if (null === self::$currenciesNames) { self::prepareCurrencies($locale); } return self::$currenciesNames; }
php
{ "resource": "" }
q149
TranslatedFile.updateCMSFields
train
public function updateCMSFields(FieldList $fields) { // only apply the update to files (not folders) if ($this->owner->class != 'Folder') { // add the tabs from the translatable tab set to the fields /** @var TabSet $set */ $set = $this->owner->getTranslatableTabSet(); // Remove the tab of the default locale (these are in the "main" tab) $set->removeByName(Translatable::default_locale()); foreach ($set->FieldList() as $tab) { $fields->addFieldToTab('Root', $tab); } } }
php
{ "resource": "" }
q150
TranslatableDataObject.get_extra_config
train
public static function get_extra_config($class, $extension, $args) { if (!self::is_translatable_installed()) { // remain silent during a test if (SapphireTest::is_running_test()) { return null; } // raise an error otherwise user_error('Translatable module is not installed but required.', E_USER_WARNING); return null; } if ($args) { self::$arguments[$class] = $args; } return array( 'db' => self::collectDBFields($class), 'has_one' => self::collectHasOneRelations($class) ); }
php
{ "resource": "" }
q151
TranslatableDataObject.updateCMSFields
train
public function updateCMSFields(FieldList $fields) { parent::updateCMSFields($fields); if (!isset(self::$collectorCache[$this->owner->class])) { return; } // remove all localized fields from the list (generated through scaffolding) foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) { $fields->removeByName($translatableField); } // check if we're in a translation if (Translatable::default_locale() != Translatable::get_current_locale()) { /** @var TranslatableFormFieldTransformation $transformation */ $transformation = TranslatableFormFieldTransformation::create($this->owner); // iterate through all localized fields foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) { if (strpos($translatableField, Translatable::get_current_locale())) { $basename = $this->getBasename($translatableField); if ($field = $this->getLocalizedFormField($basename, Translatable::default_locale())) { $fields->replaceField($basename, $transformation->transformFormField($field)); } } } } }
php
{ "resource": "" }
q152
TranslatableDataObject.getLocalizedFormField
train
public function getLocalizedFormField($fieldName, $locale) { $baseName = $this->getBasename($fieldName); $fieldLabels = $this->owner->fieldLabels(); $localizedFieldName = self::localized_field($fieldName, $locale); $fieldLabel = isset($fieldLabels[$baseName]) ? $fieldLabels[$baseName] : $baseName; if (!$this->canTranslate(null, $locale)) { // if not allowed to translate, return the field as Readonly return ReadonlyField::create($localizedFieldName, $fieldLabel); } $dbFields = array(); Config::inst()->get($this->owner->class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $dbFields); $type = isset($dbFields[$baseName]) ? $dbFields[$baseName] : ''; $typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type; switch (strtolower($typeClean)) { case 'varchar': case 'htmlvarchar': $field = TextField::create($localizedFieldName, $fieldLabel); break; case 'text': $field = TextareaField::create($localizedFieldName, $fieldLabel); break; case 'htmltext': default: $field = HtmlEditorField::create($localizedFieldName, $fieldLabel); break; } return $field; }
php
{ "resource": "" }
q153
TranslatableDataObject.getLocalizedRelationField
train
public function getLocalizedRelationField($fieldName, $locale) { $baseName = $this->getBasename($fieldName); $localizedFieldName = self::localized_field($fieldName, $locale); $field = null; if ($field = $this->getFieldForRelation($fieldName)) { $relationField = clone $field; $relationField->setName($localizedFieldName); return $relationField; } }
php
{ "resource": "" }
q154
TranslatableDataObject.updateFieldLabels
train
public function updateFieldLabels(&$labels) { parent::updateFieldLabels($labels); $statics = self::$collectorCache[$this->ownerBaseClass]; foreach ($statics as $field => $type) { $parts = explode(TRANSLATABLE_COLUMN_SEPARATOR, $field); $labels[$field] = FormField::name_to_label($parts[0]) . ' (' . $parts[1] . ')'; } }
php
{ "resource": "" }
q155
TranslatableDataObject.isLocalizedField
train
public function isLocalizedField($fieldName) { $fields = self::get_localized_class_fields($this->ownerBaseClass); return in_array($fieldName, $fields); }
php
{ "resource": "" }
q156
TranslatableDataObject.getLocalizedFieldName
train
public function getLocalizedFieldName($fieldName) { if ($this->isLocalizedField($fieldName) || $this->isLocalizedRelation($fieldName)) { return self::localized_field($fieldName); } trigger_error("Field '$fieldName' is not a localized field", E_USER_ERROR); }
php
{ "resource": "" }
q157
TranslatableDataObject.getLocalizedRelation
train
public function getLocalizedRelation($fieldName, $strict = true) { $localizedField = $this->getLocalizedFieldName($fieldName); if ($strict) { return $this->owner->getRelation($localizedField); } // if not strict, check localized first and fallback to fieldname if ($value = $this->owner->getRelation($localizedField)) { return $value; } return $this->owner->getRelation($fieldName); }
php
{ "resource": "" }
q158
TranslatableDataObject.getLocalizedValue
train
public function getLocalizedValue($fieldName, $strict = true, $parseShortCodes = false) { $localizedField = $this->getLocalizedFieldName($fieldName); // ensure that $strict is a boolean value $strict = filter_var($strict, FILTER_VALIDATE_BOOLEAN); /** @var DBField $value */ $value = $this->owner->dbObject($localizedField); if (!$strict && !$value->exists()) { $value = $this->owner->dbObject($fieldName); } return ($parseShortCodes && $value) ? ShortcodeParser::get_active()->parse($value->getValue()) : $value; }
php
{ "resource": "" }
q159
TranslatableDataObject.onBeforeWrite
train
public function onBeforeWrite() { if (!isset(self::$localizedFields[$this->ownerBaseClass])) { return; } $fields = self::$localizedFields[$this->ownerBaseClass]; foreach ($fields as $field => $localized) { foreach (self::get_target_locales() as $locale) { $fieldName = self::localized_field($field, $locale); if ($this->owner->isChanged($fieldName, 2) && !$this->canTranslate(null, $locale)) { throw new PermissionFailureException( "You're not allowed to edit the locale '$locale' for this object"); } } } }
php
{ "resource": "" }
q160
TranslatableDataObject.get_localized_class_fields
train
public static function get_localized_class_fields($class) { $fieldNames = null; $ancestry = array_reverse(ClassInfo::ancestry($class)); foreach ($ancestry as $className) { if (isset(self::$localizedFields[$className])) { if ($fieldNames === null) { $fieldNames = array(); } foreach (self::$localizedFields[$className] as $k => $v) { $fieldNames[] = $k; } } } return array_unique($fieldNames); }
php
{ "resource": "" }
q161
TranslatableDataObject.localized_field
train
public static function localized_field($field, $locale = null) { if ($locale === null) { $locale = Translatable::get_current_locale(); } if ($locale == Translatable::default_locale()) { return $field; } return $field . TRANSLATABLE_COLUMN_SEPARATOR . $locale; }
php
{ "resource": "" }
q162
TranslatableDataObject.set_locales
train
public static function set_locales($locales) { if (is_array($locales)) { $list = array(); foreach ($locales as $locale) { if (i18n::validate_locale($locale)) { $list[] = $locale; } } $list = array_unique($list); Config::inst()->update('TranslatableDataObject', 'locales', empty($list) ? null : $list); } else { Config::inst()->update('TranslatableDataObject', 'locales', null); } }
php
{ "resource": "" }
q163
TranslatableDataObject.collectDBFields
train
protected static function collectDBFields($class) { if (isset(self::$collectorCache[$class])) { return self::$collectorCache[$class]; } if (isset(self::$collectorLock[$class]) && self::$collectorLock[$class]) { return null; } self::$collectorLock[$class] = true; // Get all DB Fields $fields = array(); Config::inst()->get($class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $fields); // Get all arguments $arguments = self::get_arguments($class); $locales = self::get_target_locales(); // remove the default locale if (($index = array_search(Translatable::default_locale(), $locales)) !== false) { array_splice($locales, $index, 1); } // fields that should be translated $fieldsToTranslate = array(); // validate the arguments if ($arguments) { foreach ($arguments as $field) { // only allow fields that are actually in our field list if (array_key_exists($field, $fields)) { $fieldsToTranslate[] = $field; } } } else { // check for the given default field types and add all fields of that type foreach ($fields as $field => $type) { $typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type; $defaultFields = self::config()->default_field_types; if (is_array($defaultFields) && in_array($typeClean, $defaultFields)) { $fieldsToTranslate[] = $field; } } } // gather all the DB fields $additionalFields = array(); self::$localizedFields[$class] = array(); foreach ($fieldsToTranslate as $field) { self::$localizedFields[$class][$field] = array(); foreach ($locales as $locale) { $localizedName = self::localized_field($field, $locale); self::$localizedFields[$class][$field][] = $localizedName; $additionalFields[$localizedName] = $fields[$field]; } } self::$collectorCache[$class] = $additionalFields; self::$collectorLock[$class] = false; return $additionalFields; }
php
{ "resource": "" }
q164
TranslatableDataObject.get_target_locales
train
protected static function get_target_locales() { // if locales are explicitly set, use these if (is_array(self::config()->locales)) { return (array)self::config()->locales; // otherwise check the allowed locales. If these have been set, use these } else if (is_array(Translatable::get_allowed_locales())) { return (array)Translatable::get_allowed_locales(); } // last resort is to take the existing content languages return array_keys(Translatable::get_existing_content_languages()); }
php
{ "resource": "" }
q165
TranslatableDataObject.get_arguments
train
protected static function get_arguments($class) { if (isset(self::$arguments[$class])) { return self::$arguments[$class]; } else { if ($staticFields = Config::inst()->get($class, 'translatable_fields', Config::FIRST_SET)) { if (is_array($staticFields) && !empty($staticFields)) { return $staticFields; } } } return null; }
php
{ "resource": "" }
q166
TranslatableDataObject.setFieldForRelation
train
public function setFieldForRelation($fieldName, FormField $field) { if (self::isLocalizedRelation($fieldName)) { self::$localizedFields[$this->ownerBaseClass . '_has_one'][$fieldName]['FormField'] = $field; } }
php
{ "resource": "" }
q167
Locale.getDisplayCountries
train
public static function getDisplayCountries($locale) { if (!isset(self::$countries[$locale])) { self::$countries[$locale] = Intl::getRegionBundle()->getCountryNames($locale); } return self::$countries[$locale]; }
php
{ "resource": "" }
q168
Locale.getDisplayLanguages
train
public static function getDisplayLanguages($locale) { if (!isset(self::$languages[$locale])) { self::$languages[$locale] = Intl::getLanguageBundle()->getLanguageNames($locale); } return self::$languages[$locale]; }
php
{ "resource": "" }
q169
Locale.getDisplayLocales
train
public static function getDisplayLocales($locale) { if (!isset(self::$locales[$locale])) { self::$locales[$locale] = Intl::getLocaleBundle()->getLocaleNames($locale); } return self::$locales[$locale]; }
php
{ "resource": "" }
q170
Queue.exitWorkerManager
train
public function exitWorkerManager(int $sig, array $pid): void { $this->logger->debug('fork manager ['.$pid['pid'].'] exit with ['.$sig.']', [ 'category' => get_class($this), ]); pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED); $this->cleanup(SIGTERM); }
php
{ "resource": "" }
q171
Queue.initWorkerManager
train
protected function initWorkerManager() { $pid = pcntl_fork(); $this->manager_pid = $pid; if (-1 === $pid) { throw new SpawnForkException('failed to spawn fork manager'); } if (!$pid) { $manager = $this->factory->buildManager(); $manager->process(); exit(); } }
php
{ "resource": "" }
q172
Queue.main
train
protected function main(): void { $this->logger->info('start job listener', [ 'category' => get_class($this), ]); $cursor_jobs = $this->jobs->getCursor([ '$or' => [ ['status' => JobInterface::STATUS_WAITING], ['status' => JobInterface::STATUS_POSTPONED], ], ]); $cursor_events = $this->events->getCursor([ 'timestamp' => ['$gte' => new UTCDateTime()], 'job' => ['$exists' => true], 'status' => ['$gt' => JobInterface::STATUS_POSTPONED], ]); $this->catchSignal(); while ($this->loop()) { while ($this->loop()) { if (null === $cursor_events->current()) { if ($cursor_events->getInnerIterator()->isDead()) { $this->logger->error('event queue cursor is dead, is it a capped collection?', [ 'category' => get_class($this), ]); $this->events->create(); $this->main(); break; } $this->events->next($cursor_events, function () { $this->main(); }); } $event = $cursor_events->current(); $this->events->next($cursor_events, function () { $this->main(); }); if($event === null) { break; } $this->handleEvent($event); } if (null === $cursor_jobs->current()) { if ($cursor_jobs->getInnerIterator()->isDead()) { $this->logger->error('job queue cursor is dead, is it a capped collection?', [ 'category' => get_class($this), ]); $this->jobs->create(); $this->main(); break; } $this->jobs->next($cursor_jobs, function () { $this->main(); }); continue; } $job = $cursor_jobs->current(); $this->jobs->next($cursor_jobs, function () { $this->main(); }); $this->handleJob($job); } }
php
{ "resource": "" }
q173
WPUpdatePhp.does_it_meet_required_php_version
train
public function does_it_meet_required_php_version( $version = PHP_VERSION ) { if ( $this->version_passes_requirement( $this->minimum_version, $version ) ) { return true; } $this->load_version_notice( array( $this, 'minimum_admin_notice' ) ); return false; }
php
{ "resource": "" }
q174
WPUpdatePhp.does_it_meet_recommended_php_version
train
public function does_it_meet_recommended_php_version( $version = PHP_VERSION ) { if ( $this->version_passes_requirement( $this->recommended_version, $version ) ) { return true; } $this->load_version_notice( array( $this, 'recommended_admin_notice' ) ); return false; }
php
{ "resource": "" }
q175
WPUpdatePhp.get_admin_notice
train
public function get_admin_notice( $level = 'minimum' ) { if ( 'recommended' === $level ) { if ( ! empty( $this->plugin_name ) ) { return '<p>' . $this->plugin_name . ' recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>'; } else { return '<p>This plugin recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>'; } } if ( ! empty( $this->plugin_name ) ) { return '<p>Unfortunately, ' . $this->plugin_name . ' cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>'; } else { return '<p>Unfortunately, this plugin cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>'; } }
php
{ "resource": "" }
q176
Navigator.splAutoloader
train
private static function splAutoloader($class_name) { if('Treffynnon\\Navigator' === substr(ltrim($class_name, '\\'), 0, 20)) { $class_path = realpath(__DIR__ . '/..') . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $class_name); require_once $class_path . '.php'; } }
php
{ "resource": "" }
q177
Navigator.distanceFactory
train
public static function distanceFactory($lat1, $long1, $lat2, $long2) { $point1 = new L(new C($lat1), new C($long1)); $point2 = new L(new C($lat2), new C($long2)); return new D($point1, $point2); }
php
{ "resource": "" }
q178
Navigator.getDistance
train
public static function getDistance($lat1, $long1, $lat2, $long2) { return self::distanceFactory($lat1, $long1, $lat2, $long2)->get(); }
php
{ "resource": "" }
q179
WorkerManager.exitWorker
train
public function exitWorker(int $sig, array $pid): self { $this->logger->debug('worker ['.$pid['pid'].'] exit with ['.$sig.']', [ 'category' => get_class($this), ]); pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED); foreach ($this->forks as $id => $process) { if ($process === $pid['pid']) { unset($this->forks[$id]); if (isset($this->job_map[$id])) { unset($this->job_map[$id]); } } } $this->spawnMinimumWorkers(); return $this; }
php
{ "resource": "" }
q180
WorkerManager.spawnInitialWorkers
train
protected function spawnInitialWorkers() { $this->logger->debug('spawn initial ['.$this->min_children.'] workers', [ 'category' => get_class($this), ]); if (self::PM_DYNAMIC === $this->pm || self::PM_STATIC === $this->pm) { for ($i = $this->count(); $i < $this->min_children; ++$i) { $this->spawnWorker(); } } }
php
{ "resource": "" }
q181
WorkerManager.spawnMinimumWorkers
train
protected function spawnMinimumWorkers() { $this->logger->debug('verify that the minimum number ['.$this->min_children.'] of workers are running', [ 'category' => get_class($this), ]); for ($i = $this->count(); $i < $this->min_children; ++$i) { $this->spawnWorker(); } }
php
{ "resource": "" }
q182
Scheduler.getJob
train
public function getJob(ObjectId $id): Process { $result = $this->db->{$this->job_queue}->findOne([ '_id' => $id, ], [ 'typeMap' => self::TYPE_MAP, ]); if (null === $result) { throw new JobNotFoundException('job '.$id.' was not found'); } return new Process($result, $this, $this->events); }
php
{ "resource": "" }
q183
Scheduler.cancelJob
train
public function cancelJob(ObjectId $id): bool { $result = $this->updateJob($id, JobInterface::STATUS_CANCELED); if (1 !== $result->getMatchedCount()) { throw new JobNotFoundException('job '.$id.' was not found'); } $this->db->{$this->event_queue}->insertOne([ 'job' => $id, 'status' => JobInterface::STATUS_CANCELED, 'timestamp' => new UTCDateTime(), ]); return true; }
php
{ "resource": "" }
q184
Scheduler.addJob
train
public function addJob(string $class, $data, array $options = []): Process { $document = $this->prepareInsert($class, $data, $options); $result = $this->db->{$this->job_queue}->insertOne($document); $this->logger->debug('queue job ['.$result->getInsertedId().'] added to ['.$class.']', [ 'category' => get_class($this), 'params' => $options, 'data' => $data, ]); $this->db->{$this->event_queue}->insertOne([ 'job' => $result->getInsertedId(), 'status' => JobInterface::STATUS_WAITING, 'timestamp' => new UTCDateTime(), ]); $document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getInsertedId()], [ 'typeMap' => self::TYPE_MAP, ]); $process = new Process($document, $this, $this->events); return $process; }
php
{ "resource": "" }
q185
Scheduler.addJobOnce
train
public function addJobOnce(string $class, $data, array $options = []): Process { $filter = [ 'class' => $class, '$or' => [ ['status' => JobInterface::STATUS_WAITING], ['status' => JobInterface::STATUS_POSTPONED], ['status' => JobInterface::STATUS_PROCESSING], ], ]; $requested = $options; $document = $this->prepareInsert($class, $data, $options); if (true !== $options[self::OPTION_IGNORE_DATA]) { $filter = ['data' => $data] + $filter; } $result = $this->db->{$this->job_queue}->updateOne($filter, ['$setOnInsert' => $document], [ 'upsert' => true, '$isolated' => true, ]); if ($result->getMatchedCount() > 0) { $document = $this->db->{$this->job_queue}->findOne($filter, [ 'typeMap' => self::TYPE_MAP, ]); if (array_intersect_key($document['options'], $requested) !== $requested || ($data !== $document['data'] && true === $options[self::OPTION_IGNORE_DATA])) { $this->logger->debug('job ['.$document['_id'].'] options/data changed, reschedule new job', [ 'category' => get_class($this), 'data' => $data, ]); $this->cancelJob($document['_id']); return $this->addJobOnce($class, $data, $options); } return new Process($document, $this, $this->events); } $this->logger->debug('queue job ['.$result->getUpsertedId().'] added to ['.$class.']', [ 'category' => get_class($this), 'params' => $options, 'data' => $data, ]); $this->db->{$this->event_queue}->insertOne([ 'job' => $result->getUpsertedId(), 'status' => JobInterface::STATUS_WAITING, 'timestamp' => new UTCDateTime(), ]); $document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getUpsertedId()], [ 'typeMap' => self::TYPE_MAP, ]); return new Process($document, $this, $this->events); }
php
{ "resource": "" }
q186
Scheduler.listen
train
public function listen(Closure $callback, array $query = []): self { if (0 === count($query)) { $query = [ 'timestamp' => ['$gte' => new UTCDateTime()], ]; } $cursor = $this->events->getCursor($query); while (true) { if (null === $cursor->current()) { if ($cursor->getInnerIterator()->isDead()) { $this->logger->error('events queue cursor is dead, is it a capped collection?', [ 'category' => get_class($this), ]); $this->events->create(); return $this->listen($callback, $query); } $this->events->next($cursor, function () use ($callback, $query) { return $this->listen($callback, $query); }); continue; } $result = $cursor->current(); $this->events->next($cursor, function () use ($callback, $query) { $this->listen($callback, $query); }); $process = new Process($result, $this, $this->events); if (true === $callback($process)) { return $this; } } }
php
{ "resource": "" }
q187
Scheduler.prepareInsert
train
protected function prepareInsert(string $class, $data, array &$options = []): array { $defaults = [ self::OPTION_AT => $this->default_at, self::OPTION_INTERVAL => $this->default_interval, self::OPTION_RETRY => $this->default_retry, self::OPTION_RETRY_INTERVAL => $this->default_retry_interval, self::OPTION_FORCE_SPAWN => false, self::OPTION_TIMEOUT => $this->default_timeout, self::OPTION_IGNORE_DATA => false, ]; $options = array_merge($defaults, $options); $options = SchedulerValidator::validateOptions($options); $document = [ 'class' => $class, 'status' => JobInterface::STATUS_WAITING, 'created' => new UTCDateTime(), 'started' => new UTCDateTime(), 'ended' => new UTCDateTime(), 'worker' => new ObjectId(), 'data' => $data, ]; if (isset($options[self::OPTION_ID])) { $id = $options[self::OPTION_ID]; unset($options[self::OPTION_ID]); $document['_id'] = $id; } $document['options'] = $options; return $document; }
php
{ "resource": "" }
q188
TranslatableFormFieldTransformation.transformFormField
train
public function transformFormField(FormField $field) { $newfield = $field->performReadOnlyTransformation(); $fieldname = $field->getName(); if ($this->original->isLocalizedField($fieldname)) { $field->setName($this->original->getLocalizedFieldName($fieldname)); $value = $this->original->getLocalizedValue($fieldname); if ($value instanceof DBField) { $field->setValue($value->getValue()); } else { $field->setValue($value); } } return $this->baseTransform($newfield, $field, $fieldname); }
php
{ "resource": "" }
q189
Tournament.start
train
public function start() { if ($this->state != 'pending') { throw new AlreadyStartedException('Tournament is already underway.'); } $response = Guzzle::post("tournaments/{$this->id}/start"); return $this->updateModel($response->tournament); }
php
{ "resource": "" }
q190
Tournament.finalize
train
public function finalize() { if ($this->state != 'awaiting_review') { throw new StillRunningException('Tournament is still running.'); } $response = Guzzle::post("tournaments/{$this->id}/finalize"); return $this->updateModel($response->tournament); }
php
{ "resource": "" }
q191
Tournament.update
train
public function update($params = []) { $response = Guzzle::put("tournaments/{$this->id}", $params); return $this->updateModel($response->tournament); }
php
{ "resource": "" }
q192
Distance.get
train
public function get(D\Calculator\CalculatorInterface $calculator = null, D\Converter\ConverterInterface $unit_converter = null) { if (is_null($calculator)) { $calculator = new D\Calculator\Vincenty; } $distance = $calculator->calculate($this->point1, $this->point2); if (!is_null($unit_converter)) { $distance = $unit_converter->convert($distance); } return $distance; }
php
{ "resource": "" }
q193
CustomInstaller.getPackageReplacementTokens
train
protected function getPackageReplacementTokens(PackageInterface $package) { $vars = array( '{$type}' => $package->getType(), ); $prettyName = $package->getPrettyName(); if (strpos($prettyName, '/') !== false) { $pieces = explode('/', $prettyName); $vars['{$vendor}'] = $pieces[0]; $vars['{$name}'] = $pieces[1]; } else { $vars['{$vendor}'] = ''; $vars['{$name}'] = $prettyName; } return $vars; }
php
{ "resource": "" }
q194
CustomInstaller.getPluginConfiguration
train
protected function getPluginConfiguration() { if (!isset($this->configuration)) { $extra = $this->composer->getPackage()->getExtra(); // We check if we need to support the legacy configuration. $legacy = false; if (isset($extra['custom-installer'])) { // Legacy $legacy = true; foreach ($extra['custom-installer'] as $key => $val) { if (is_array($val)) { $legacy = false; break; } } } if ($legacy) { $this->configuration = new ConfigurationAlpha1($extra); } else { $this->configuration = new Configuration($extra); } } return $this->configuration; }
php
{ "resource": "" }
q195
Term.getTaxonomyKey
train
public function getTaxonomyKey() { $called_class_segments = explode('\\', get_called_class()); $class_name = end($called_class_segments); return (is_null($this->taxonomy_key)) ? Str::machine(Str::camelToHuman($class_name), Base::SEPARATOR) : $this->taxonomy_key; }
php
{ "resource": "" }
q196
Term.getOptionID
train
public function getOptionID($term_id = null) { return join('_', array( $this->getTaxonomyKey(), ($term_id) ? $term_id : $this->get(self::ID) )); }
php
{ "resource": "" }
q197
Term.renderAdminColumn
train
public function renderAdminColumn($column_name, $term_id) { $this->load($term_id); parent::renderAdminColumn($column_name, $term_id); }
php
{ "resource": "" }
q198
Term.getEditPermalink
train
public function getEditPermalink($object_type = null) { // WordPress get_edit_term_link requires an object_type // but if this object was created by \Taco\Post::getTerms // then it will have an object_id, which also works if (is_null($object_type)) { $object_type = $this->get('object_id'); if (!$object_type) { throw new \Exception('No object_type nor object_id'); } } return get_edit_term_link( $this->get('term_id'), $this->getTaxonomyKey(), $object_type ); }
php
{ "resource": "" }
q199
Term.getWhere
train
public static function getWhere($args = array()) { $instance = Term\Factory::create(get_called_class()); // Allow sorting both by core fields and custom fields // See: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters $default_args = array( 'orderby' => $instance->getDefaultOrderBy(), 'order' => $instance->getDefaultOrder(), 'hide_empty' => false, // Note: This goes against a WordPress get_terms default. But this seems more practical. ); $criteria = array_merge($default_args, $args); // Custom ordering $orderby = null; $order = null; $wordpress_sortable_fields = array('id', 'name', 'count', 'slug', 'term_group', 'none'); if (array_key_exists('orderby', $criteria) && !in_array($criteria['orderby'], $wordpress_sortable_fields)) { $orderby = $criteria['orderby']; $order = (array_key_exists('order', $criteria)) ? strtoupper($criteria['order']) : 'ASC'; unset($criteria['orderby']); unset($criteria['order']); } $criteria['taxonomy'] = $instance->getTaxonomyKey(); $terms = Term\Factory::createMultiple(get_terms($criteria)); // We might be done if (!Arr::iterable($terms)) { return $terms; } if (!$orderby) { return $terms; } // Custom sorting that WordPress can't do $field = $instance->getField($orderby); // Make sure we're sorting numerically if appropriate // because WordPress is storing strings for all vals if ($field['type'] === 'number') { foreach ($terms as &$term) { if (!isset($term->$orderby)) { continue; } if ($term->$orderby === '') { continue; } $term->$orderby = (float) $term->$orderby; } } // Sorting $sort_flag = ($field['type'] === 'number') ? SORT_NUMERIC : SORT_STRING; $terms = Collection::sortBy($terms, $orderby, $sort_flag); if (strtoupper($order) === 'DESC') { $terms = array_reverse($terms, true); } // Convert back to string as WordPress stores it if ($field['type'] === 'number') { foreach ($terms as &$term) { if (!isset($term->$orderby)) { continue; } if ($term->$orderby === '') { continue; } $term->$orderby = (string) $term->$orderby; } } return $terms; }
php
{ "resource": "" }