_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q5300
View.resolveFullViewPath
train
private function resolveFullViewPath($viewPath) { if (strlen($this->getPartialsDir()) > 0 && strpos($viewPath, $this->getPartialsDir()) === 0) { return $this->resolvePartialPath($viewPath); } if (strpos($viewPath, $this->getLayoutsDir()) === 0) { return $this->resolveLayoutPath($viewPath); } return $this->resolveViewPath($viewPath); }
php
{ "resource": "" }
q5301
View.resolveViewPath
train
private function resolveViewPath($viewPath) { $path = realpath($this->_viewsDir . dirname($viewPath)) . DIRECTORY_SEPARATOR . basename($viewPath); return $path; }
php
{ "resource": "" }
q5302
View.resolvePartialPath
train
private function resolvePartialPath($viewPath) { $tempViewPath = str_replace($this->getPartialsDir(), '', $viewPath); if (strpos($tempViewPath, '../') === 0 || strpos($tempViewPath, '/../') === 0) { return $this->resolveRelativePath($tempViewPath); } else if (strpos($tempViewPath, './') === 0) { return $this->resolveLocalPath($tempViewPath); } else if (!in_array(dirname($tempViewPath), ['.','..']) && file_exists(dirname($tempViewPath))) { return $tempViewPath; } return $this->resolveGlobalPath($tempViewPath); }
php
{ "resource": "" }
q5303
View.resolveLocalPath
train
private function resolveLocalPath($partialPath) { $partialDir = str_replace('./', '', dirname($partialPath)); $partialsDir = realpath(sprintf('%s%s', $this->_viewsDir, $partialDir )) . DIRECTORY_SEPARATOR; return $partialsDir . basename($partialPath); }
php
{ "resource": "" }
q5304
View.resolveRelativePath
train
private function resolveRelativePath($partialPath) { $partialsDirPath = realpath(sprintf('%s%s', $this->_viewsDir, dirname($partialPath) )) . DIRECTORY_SEPARATOR; return $partialsDirPath . basename($partialPath); }
php
{ "resource": "" }
q5305
View.render
train
public function render($controllerName, $actionName, $params = null) { if (empty($this->controllerViewPath)) { $this->setControllerViewPath($controllerName); } parent::render($this->controllerViewPath, $actionName, $params); }
php
{ "resource": "" }
q5306
View.setControllerViewPath
train
public function setControllerViewPath($controllerName) { $this->controllerViewPath = str_replace('\\','/',strtolower($controllerName)); $this->controllerFullViewPath = $this->_viewsDir . $this->controllerViewPath; }
php
{ "resource": "" }
q5307
DfOAuthTwoProvider.getUserFromTokenResponse
train
public function getUserFromTokenResponse($response) { $user = $this->mapUserToObject($this->getUserByToken( $token = $this->parseAccessToken($response) )); $this->credentialsResponseBody = $response; if ($user instanceof User) { $user->setAccessTokenResponseBody($this->credentialsResponseBody); } return $user->setToken($token) ->setRefreshToken($this->parseRefreshToken($response)) ->setExpiresIn($this->parseExpiresIn($response)); }
php
{ "resource": "" }
q5308
Database.getDbConfig
train
private function getDbConfig() { if (file_exists(MODULES_DIR . DS . $this->currentRoute['module'] . '/Config/database.php')) { $dbConfig = require_once MODULES_DIR . DS . $this->currentRoute['module'] . '/Config/database.php'; if (!empty($dbConfig) && is_array($dbConfig)) { return $dbConfig; } else { throw new \Exception(ExceptionMessages::INCORRECT_CONFIG); } } else { if (file_exists(BASE_DIR . '/config/database.php')) { $dbConfig = require_once BASE_DIR . '/config/database.php'; if (!empty($dbConfig) && is_array($dbConfig)) { return $dbConfig; } else { throw new \Exception(ExceptionMessages::INCORRECT_CONFIG); } } else { throw new \Exception(ExceptionMessages::DB_CONFIG_NOT_FOUND); } } }
php
{ "resource": "" }
q5309
Cache.getInstance
train
public static function getInstance($name) { if (!isset(static::$instances[$name])) { static::$instances[$name] = new CacheInstance(); } return static::$instances[$name]; }
php
{ "resource": "" }
q5310
Moderator.reloadBlacklist
train
public function reloadBlacklist() { $this->cache->flush($this->getCacheKey()); $this->blackListRegex = null; $this->loadBlacklist(); }
php
{ "resource": "" }
q5311
Moderator.check
train
public function check($model) { $moderated = false; foreach ($model->getModerateList() as $id => $moderation) { $rules = explode('|', $moderation); foreach ($rules as $rule) { $action = explode(':', $rule); $options = isset($action[1]) ? $action[1] : null; $method = $action[0]; if ($this->$method($model->$id, $options)) { return $moderated = true; } } // No reason to keep going if ($moderated === true) { return $moderated; } } return $moderated; }
php
{ "resource": "" }
q5312
Moderator.getDriver
train
public function getDriver() { if ($this->driver) { return $this->driver; } // Get driver configuration $config = $this->getConfig('drivers.' . $this->getConfig('driver'), []); // Get driver class $driver = Arr::pull($config, 'class'); // Create driver instance return $this->driver = new $driver($config, $this->locale); }
php
{ "resource": "" }
q5313
Moderator.loadBlacklist
train
protected function loadBlacklist() { // Check if caching is enabled if ($this->getConfig('cache.enabled', false) === false) { return $this->blackListRegex = $this->createRegex(); } // Get Black list items return $this->blackListRegex = $this->cache->rememberForever($this->getCacheKey(), function () { return $this->createRegex(); }); }
php
{ "resource": "" }
q5314
Moderator.createRegex
train
protected function createRegex() { // Load list from driver if (empty($list = $this->getDriver()->getList())) { return null; } return sprintf('/\b(%s)\b/i', implode('|', array_map(function ($value) { if (isset($value[0]) && $value[0] == '[') { return $value; } else if (preg_match("/\r\n|\r|\n/", $value)) { return preg_replace("/\r\n|\r|\n/", "|", $value); } return preg_quote($value); }, $list))); }
php
{ "resource": "" }
q5315
Inviqa_SymfonyContainer_Model_StoreConfigCompilerPass.process
train
public function process(ContainerBuilder $container) { $taggedServices = $container->findTaggedServiceIds( self::TAG_NAME ); foreach ($taggedServices as $id => $tag) { $definition = $container->findDefinition($id); $this->processTag($tag, $definition); } }
php
{ "resource": "" }
q5316
DiskCache.path
train
public static function path($filename) { if ($filename[0] != "/") { $filename = static::$path . "/" . $filename; } if (substr($filename, -5) != ".json") { $filename .= ".json"; } $path = pathinfo($filename, PATHINFO_DIRNAME); # Ensure the cache directory exists if (!is_dir($path)) { if (!mkdir($path, 0777, true)) { throw new \Exception("Unable to create cache directory (" . $path . ")"); } } # Ensure directory is writable if (!is_writable($path)) { if (!chmod($path, 0777)) { throw new \Exception("Cache directory (" . $path . ") is not writable"); } } return $filename; }
php
{ "resource": "" }
q5317
DiskCache.check
train
public static function check($filename) { if (!$filename = static::path($filename)) { return null; } if (!file_exists($filename)) { return null; } return filemtime($filename); }
php
{ "resource": "" }
q5318
DiskCache.get
train
public static function get($filename, $mins = 0) { if (!$cache = static::check($filename)) { return null; } $limit = time() - ($mins * 60); if (!$mins || $cache > $limit) { $filename = static::path($filename); $return = Json::decodeFromFile($filename); if ($return instanceof \ArrayObject) { $return = $return->asArray(); } if (array_key_exists("_disk_cache", $return)) { $return = $return["_disk_cache"]; } return $return; } return null; }
php
{ "resource": "" }
q5319
DiskCache.set
train
public static function set($filename, $data) { $data = ["_disk_cache" => $data]; $filename = static::path($filename); Json::encodeToFile($filename, $data); }
php
{ "resource": "" }
q5320
DiskCache.clear
train
public static function clear($filename) { $filename = static::path($filename); if (!file_exists($filename)) { return; } if (!unlink($filename)) { throw new \Exception("Unable to delete file (" . $filename . ")"); } }
php
{ "resource": "" }
q5321
DiskCache.call
train
public static function call($key, callable $func) { $trace = debug_backtrace(); if ($function = $trace[1]["function"]) { $key = $function . "_" . $key; if ($class = $trace[1]["class"]) { $key = str_replace("\\", "_", $class) . "_" . $key; } } if (static::check($key)) { return static::get($key); } $return = $func(); static::set($key, $return); return $return; }
php
{ "resource": "" }
q5322
PackageImporter.cleanupPackages
train
public function cleanupPackages(Storage $storage, callable $callback = null) { $count = 0; $storageNode = $storage->node(); $query = new FlowQuery([$storageNode]); $query = $query->find('[instanceof Neos.MarketPlace:Package]'); $upstreamPackages = $this->getProcessedPackages(); foreach ($query as $package) { /** @var NodeInterface $package */ if (in_array($package->getProperty('title'), $upstreamPackages)) { continue; } $package->remove(); if ($callback !== null) { $callback($package); } $this->emitPackageDeleted($package); $count++; } return $count; }
php
{ "resource": "" }
q5323
PackageImporter.cleanupVendors
train
public function cleanupVendors(Storage $storage, callable $callback = null) { $count = 0; $storageNode = $storage->node(); $query = new FlowQuery([$storageNode]); $query = $query->find('[instanceof Neos.MarketPlace:Vendor]'); foreach ($query as $vendor) { /** @var NodeInterface $vendor */ $hasPackageQuery = new FlowQuery([$vendor]); $packageCount = $hasPackageQuery->find('[instanceof Neos.MarketPlace:Package]')->count(); if ($packageCount > 0) { continue; } $vendor->remove(); if ($callback !== null) { $callback($vendor); } $this->emitVendorDeleted($vendor); $count++; } return $count; }
php
{ "resource": "" }
q5324
Renderer.filterResponse
train
private function filterResponse(Response $response, Request $request, int $type): string { $event = new FilterResponseEvent($this->kernel, $request, $type, $response); $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event); $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this->kernel, $request, $type)); $request->attributes->remove('data'); $request->attributes->set('_controller', 'typo3'); $response = $event->getResponse(); if ($response instanceof RedirectResponse) { $response->send(); $this->kernel->terminate($request, $response); exit(); } if (\count($response->headers) || 200 !== $response->getStatusCode()) { $response->sendHeaders(); } return $response->getContent(); }
php
{ "resource": "" }
q5325
Renderer.varToString
train
private function varToString($var): string { if (\is_object($var)) { return \sprintf('an object of type %s', \get_class($var)); } if (\is_array($var)) { $a = []; foreach ($var as $k => $v) { $a[] = \sprintf('%s => ...', $k); } return \sprintf('an array ([%s])', \mb_substr(\implode(', ', $a), 0, 255)); } if (\is_resource($var)) { return \sprintf('a resource (%s)', \get_resource_type($var)); } if (null === $var) { return 'null'; } if (false === $var) { return 'a boolean value (false)'; } if (true === $var) { return 'a boolean value (true)'; } if (\is_string($var)) { return \sprintf('a string ("%s%s")', \mb_substr($var, 0, 255), \mb_strlen($var) > 255 ? '...' : ''); } if (\is_numeric($var)) { return \sprintf('a number (%s)', (string) $var); } return (string) $var; }
php
{ "resource": "" }
q5326
Person.removeElectronicAddress
train
public function removeElectronicAddress(ElectronicAddress $electronicAddress) { $this->electronicAddresses->removeElement($electronicAddress); if ($electronicAddress === $this->primaryElectronicAddress) { $this->primaryElectronicAddress = null; } }
php
{ "resource": "" }
q5327
Person.setElectronicAddresses
train
public function setElectronicAddresses(Collection $electronicAddresses) { if ($this->primaryElectronicAddress !== null && !$this->electronicAddresses->contains($this->primaryElectronicAddress)) { $this->primaryElectronicAddress = null; } $this->electronicAddresses = $electronicAddresses; }
php
{ "resource": "" }
q5328
ExecuteQuery.fetch
train
public function fetch(Input $input) { return $this->bus->handle( $this->messageCreator->create($this->query, $input) ); }
php
{ "resource": "" }
q5329
ExceptionListener.beforeException
train
public function beforeException() { /** * @param \Phalcon\Events\Event $event * @param \Phalcon\Dispatcher $dispatcher * @param \Exception $exception * @return callable */ return function(Event $event, Dispatcher $dispatcher, \Exception $exception) { $resolver = new ExceptionResolver(); $resolver->setDI($dispatcher->getDI()); $resolver->resolve($exception); return false; }; }
php
{ "resource": "" }
q5330
Analytics.render
train
public function render() { if (!$this->isEnabled()) { return; } if ($this->isAutomatic()) { $this->addItem("ga('send', '" . self::TYPE_PAGEVIEW . "');"); } if ($this->isAnonymised()) { $this->addItem("ga('set', 'anonymizeIp', true);"); } if ($this->application->environment() === 'dev') { $this->addItem("ga('create', '{$this->id}', { 'cookieDomain': 'none' });"); } else { $this->addItem("ga('create', '{$this->id}', '{$this->domain}');"); } return $this->view->make('googlitics::analytics')->withItems(array_reverse($this->getItems()))->render(); }
php
{ "resource": "" }
q5331
Analytics.trackPage
train
public function trackPage($page = null, $title = null, $type = self::TYPE_PAGEVIEW) { if (!defined('self::TYPE_'. strtoupper($type))) { throw new AnalyticsArgumentException('Type variable can\'t be of this type.'); } $item = "ga('send', 'pageview');"; if ($page !== null || $title !== null) { $page = ($page === null ? "window.location.href" : "'{$page}'"); $title = ($title === null ? "document.title" : "'{$title}'"); $item = "ga('send', { 'hitType': '{$type}', 'page': {$page}, 'title': {$title} });"; } $this->addItem($item); }
php
{ "resource": "" }
q5332
Analytics.trackEvent
train
public function trackEvent($category, $action, $label = null, $value = null) { $item = "ga('send', 'event', '{$category}', '{$action}'" . ($label !== null ? ", '{$label}'" : '') . ($value !== null && is_numeric($value) ? ", {$value}" : '') . ");"; $this->addItem($item); }
php
{ "resource": "" }
q5333
Analytics.trackTransaction
train
public function trackTransaction($id, array $options = []) { $options['id'] = $id; $this->trackEcommerce(self::ECOMMERCE_TRANSACTION, $options); }
php
{ "resource": "" }
q5334
Analytics.trackItem
train
public function trackItem($id, $name, array $options = []) { $options['id'] = $id; $options['name'] = $name; $this->trackEcommerce(self::ECOMMERCE_ITEM, $options); }
php
{ "resource": "" }
q5335
Analytics.trackMetric
train
public function trackMetric($category, array $options = []) { $item = "ga('send', 'event', '{$category}'"; if (!empty($options)) { $item .= ", 'action', { "; foreach ($options as $key => $value) { $item .= "'{$key}': {$value}, "; } $item = rtrim($item, ', ') . " }"; } $item .= ");"; $this->addItem($item); }
php
{ "resource": "" }
q5336
Analytics.trackException
train
public function trackException($description = null, $fatal = false) { $item = "ga('send', '" . self::TYPE_EXCEPTION . "'"; if ($description !== null && is_bool($fatal)) { $item .= ", { " . "'exDescription': '{$description}', " . "'exFatal': " . ($fatal ? 'true' : 'false') . " }"; } $item .= ");"; $this->addItem($item); }
php
{ "resource": "" }
q5337
RegisterFiltersTrait.registerFilters
train
public function registerFilters () { foreach (glob($this->getFiltersDirectoryPath() . '*.php') as $file) { $filterName = pathinfo($file, PATHINFO_FILENAME); $this->registerFilter(lcfirst($filterName)); } }
php
{ "resource": "" }
q5338
BaseOAuthService.handleLogin
train
public function handleLogin($request) { /** @var RedirectResponse $response */ $response = $this->provider->redirect(); $traitsUsed = class_uses($this->provider); $traitTwo = DfOAuthTwoProvider::class; $traitOne = DfOAuthOneProvider::class; if (isset($traitsUsed[$traitTwo])) { $state = $this->provider->getState(); if (!empty($state)) { $key = static::CACHE_KEY_PREFIX . $state; \Cache::put($key, $this->getName(), 3); } } elseif (isset($traitsUsed[$traitOne])) { $token = $this->provider->getOAuthToken(); if (!empty($token)) { $key = static::CACHE_KEY_PREFIX . $token; \Cache::put($key, $this->getName(), 3); } } if (!$request->ajax()) { return $response; } $url = $response->getTargetUrl(); $result = ['response' => ['redirect' => true, 'url' => $url]]; return $result; }
php
{ "resource": "" }
q5339
BaseOAuthService.handleOAuthCallback
train
public function handleOAuthCallback() { $provider = $this->getProvider(); /** @var OAuthUserContract $user */ $user = $provider->user(); return $this->loginOAuthUser($user); }
php
{ "resource": "" }
q5340
BaseOAuthService.loginOAuthUser
train
public function loginOAuthUser(OAuthUserContract $user) { /** @noinspection PhpUndefinedFieldInspection */ $responseBody = $user->accessTokenResponseBody; /** @noinspection PhpUndefinedFieldInspection */ $token = $user->token; $dfUser = $this->createShadowOAuthUser($user); $dfUser->last_login_date = Carbon::now()->toDateTimeString(); $dfUser->confirm_code = null; $dfUser->save(); $map = OAuthTokenMap::whereServiceId($this->id)->whereUserId($dfUser->id)->first(); if (empty($map)) { OAuthTokenMap::create( [ 'user_id' => $dfUser->id, 'service_id' => $this->id, 'token' => $token, 'response' => $responseBody ]); } else { $map->update(['token' => $token, 'response' => $responseBody]); } Session::setUserInfoWithJWT($dfUser); $response = Session::getPublicInfo(); $response['oauth_token'] = $token; if (isset($responseBody['id_token'])) { $response['id_token'] = $responseBody['id_token']; } return $response; }
php
{ "resource": "" }
q5341
BaseOAuthService.createShadowOAuthUser
train
public function createShadowOAuthUser(OAuthUserContract $OAuthUser) { $fullName = $OAuthUser->getName(); @list($firstName, $lastName) = explode(' ', $fullName); $email = $OAuthUser->getEmail(); $serviceName = $this->getName(); $providerName = $this->getProviderName(); if (empty($email)) { $email = $OAuthUser->getId() . '+' . $serviceName . '@' . $serviceName . '.com'; } else { list($emailId, $domain) = explode('@', $email); $email = $emailId . '+' . $serviceName . '@' . $domain; } $user = User::whereEmail($email)->first(); if (empty($user)) { $data = [ 'username' => $email, 'name' => $fullName, 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'is_active' => true, 'oauth_provider' => $providerName, ]; $user = User::create($data); } // todo Should this be done only if the user was not already there? if (!empty($defaultRole = $this->getDefaultRole())) { User::applyDefaultUserAppRole($user, $defaultRole); } if (!empty($serviceId = $this->getServiceId())) { User::applyAppRoleMapByService($user, $serviceId); } return $user; }
php
{ "resource": "" }
q5342
ReadNestedAttributeTrait.traverseObject
train
private function traverseObject($obj, $keys) { if (empty($keys)) { return $obj; } $key = current($keys); if (is_array($obj) && isset($obj[$key])) { return $this->traverseObject($obj[$key], array_slice($keys, 1)); } else if (is_object($obj) && isset($obj->{$key})) { return $this->traverseObject($obj->{$key}, array_slice($keys, 1)); } else { return null; } }
php
{ "resource": "" }
q5343
TaskListener.beforeHandleTask
train
public function beforeHandleTask($argv) { return function(Event $event, Console $console, Dispatcher $dispatcher) use ($argv) { //parse parameters $parsedOptions = OptionParser::parse($argv); $dispatcher->setParams(array( 'activeTask' => isset($parsedOptions[0]) ? $parsedOptions[0] : false, 'activeAction' => isset($parsedOptions[1]) ? $parsedOptions[1] : false, 'args' => count($parsedOptions) > 2 ? array_slice($parsedOptions, 2) : [] )); }; }
php
{ "resource": "" }
q5344
Router.findPattern
train
private function findPattern($matches) { switch ($matches[1]) { case ':num': $replacement = '([0-9]'; break; case ':alpha': $replacement = '([a-zA-Z]'; break; case ':any': $replacement = '([^\/]'; break; } if (isset($matches[3]) && is_numeric($matches[3])) { if (isset($matches[4]) && $matches[4] == '?') { $replacement .= '{0,' . $matches[3] . '})'; } else { $replacement .= '{' . $matches[3] . '})'; } } else { if (isset($matches[4]) && $matches[4] == '?') { $replacement .= '*)'; } else { $replacement .= '+)'; } } return $replacement; }
php
{ "resource": "" }
q5345
MappingHelperTrait.toMappedArray
train
public function toMappedArray() { $values = $this->toArray(); $mappedValues = []; foreach ($values as $key => $value) { $mappedValues[$key] = $this->readMapped($key); } return $mappedValues; }
php
{ "resource": "" }
q5346
MappingHelperTrait.readMapped
train
public function readMapped($name) { if (!$this->hasMapping($name) && isset($this->mappings[$name])) { $this->addMapping($name, $this->mappings[$name]); } $value = $this->readAttribute($name); $value = $this->resolveMapping($name, $value); return $value; }
php
{ "resource": "" }
q5347
Dict.value
train
public static function value(array $data, $key, $default = null) { $value = static::valueIfSet($data, $key, $default); if ($value) { return $value; } else { return $default; } }
php
{ "resource": "" }
q5348
SqlUserRepository.exist
train
private function exist(User $aUser) { $count = $this->execute( 'SELECT COUNT(*) FROM user WHERE id = :id', [':id' => $aUser->id()->id()] )->fetchColumn(); return (int) $count === 1; }
php
{ "resource": "" }
q5349
SqlUserRepository.insert
train
private function insert(User $aUser) { $sql = 'INSERT INTO user ( id, confirmation_token_token, confirmation_token_created_on, created_on, email, invitation_token_token, invitation_token_created_on, last_login, password, salt, remember_password_token_token, remember_password_token_created_on, roles, updated_on ) VALUES ( :id, :confirmationTokenToken, :confirmationTokenCreatedOn, :createdOn, :email, :invitationTokenToken, :invitationTokenCreatedOn, :lastLogin, :password, :salt, :rememberPasswordTokenToken, :rememberPasswordTokenCreatedOn, :roles, :updatedOn )'; $this->execute($sql, [ 'id' => $aUser->id()->id(), 'confirmationTokenToken' => $aUser->confirmationToken() ? $aUser->confirmationToken()->token() : null, 'confirmationTokenCreatedOn' => $aUser->confirmationToken() ? $aUser->confirmationToken()->createdOn() : null, 'createdOn' => $aUser->createdOn()->format(self::DATE_FORMAT), 'email' => $aUser->email()->email(), 'invitationTokenToken' => $aUser->invitationToken() ? $aUser->invitationToken()->token() : null, 'invitationTokenCreatedOn' => $aUser->invitationToken() ? $aUser->invitationToken()->createdOn() : null, 'lastLogin' => $aUser->lastLogin() ? $aUser->lastLogin()->format(self::DATE_FORMAT) : null, 'password' => $aUser->password()->encodedPassword(), 'salt' => $aUser->password()->salt(), 'rememberPasswordTokenToken' => $aUser->rememberPasswordToken() ? $aUser->rememberPasswordToken()->token() : null, 'rememberPasswordTokenCreatedOn' => $aUser->rememberPasswordToken() ? $aUser->rememberPasswordToken()->createdOn() : null, 'roles' => $this->rolesToString($aUser->roles()), 'updatedOn' => $aUser->updatedOn()->format(self::DATE_FORMAT), ]); }
php
{ "resource": "" }
q5350
SqlUserRepository.execute
train
private function execute($aSql, array $parameters) { $statement = $this->pdo->prepare($aSql); $statement->execute($parameters); return $statement; }
php
{ "resource": "" }
q5351
SqlUserRepository.buildUser
train
private function buildUser($row) { $createdOn = new \DateTimeImmutable($row['created_on']); $updatedOn = new \DateTimeImmutable($row['updated_on']); $lastLogin = null === $row['last_login'] ? null : new \DateTimeImmutable($row['last_login']); $confirmationToken = null; if (null !== $row['confirmation_token_token']) { $confirmationToken = new UserToken($row['confirmation_token_token']); $this->set($confirmationToken, 'createdOn', new \DateTimeImmutable($row['confirmation_token_created_on'])); } $invitationToken = null; if (null !== $row['invitation_token_token']) { $invitationToken = new UserToken($row['invitation_token_token']); $this->set($invitationToken, 'createdOn', new \DateTimeImmutable($row['invitation_token_created_on'])); } $rememberPasswordToken = null; if (null !== $row['remember_password_token_token']) { $rememberPasswordToken = new UserToken($row['remember_password_token_token']); $this->set($rememberPasswordToken, 'createdOn', new \DateTimeImmutable($row['remember_password_token_created_on'])); } $user = User::signUp( new UserId($row['id']), new UserEmail($row['email']), UserPassword::fromEncoded($row['password'], $row['salt']), $this->rolesToArray($row['roles']) ); $user = $this->set($user, 'createdOn', $createdOn); $user = $this->set($user, 'updatedOn', $updatedOn); $user = $this->set($user, 'lastLogin', $lastLogin); $user = $this->set($user, 'confirmationToken', $confirmationToken); $user = $this->set($user, 'invitationToken', $invitationToken); $user = $this->set($user, 'rememberPasswordToken', $rememberPasswordToken); return $user; }
php
{ "resource": "" }
q5352
Searcher.setFields
train
public function setFields(array $models) { try { // need to return << true $this->validator->verify($models, [ 'isArray', 'isNotEmpty', 'isExists' ], 'where'); } catch(ExceptionFactory $e) { echo $e->getMessage(); } return $this; }
php
{ "resource": "" }
q5353
Searcher.setThreshold
train
public function setThreshold($threshold) { // need to return << true if (is_array($threshold) === true) { $threshold = array_map('intval', array_splice($threshold, 0, 2)); } else { $threshold = intval($threshold); } $this->validator->verify($threshold, [], 'threshold'); return $this; }
php
{ "resource": "" }
q5354
Searcher.setQuery
train
public function setQuery($query = null) { try { // need to return << true $this->validator->verify($query, ['isNotNull', 'isAcceptLength']); if (false === $this->exact) { $this->query = ['query' => '%' . $query . '%']; } else { $this->query = ['query' => $query]; } } catch(ExceptionFactory $e) { echo $e->getMessage(); } return $this; }
php
{ "resource": "" }
q5355
Searcher.run
train
final public function run($hydratorset = null, $callback = null) { try { // call to get result $result = (new Builder($this))->loop($hydratorset, $callback); return $result; } catch (ExceptionFactory $e) { echo $e->getMessage(); } }
php
{ "resource": "" }
q5356
ApiController.soapServerAction
train
public function soapServerAction() { try { $apiModel = $this->_getModelName($this->obj); //parametry WSDL $wsdlParams = [ 'module' => 'cms', 'controller' => 'api', 'action' => 'wsdl', 'obj' => $this->obj, ]; //prywatny serwer if (\Mmi\App\FrontController::getInstance()->getEnvironment()->authUser) { $apiModel .= 'Private'; $auth = new \Mmi\Security\Auth; $auth->setModelName($apiModel); $auth->httpAuth('Private API', 'Access denied!'); $wsdlParams['type'] = 'private'; } //ścieżka do WSDL $url = $this->view->url($wsdlParams, true, true, $this->_isSsl()); //typ odpowiedzi na application/xml $this->getResponse()->setTypeXml(); //powołanie klasy serwera SOAP $soap = new SoapServer($url); $soap->setClass($apiModel); //obsługa żądania $soap->handle(); return ''; } catch (\Exception $e) { //rzuca wyjątek internal return $this->_internalError($e); } }
php
{ "resource": "" }
q5357
File._checkAndCopyFile
train
protected static function _checkAndCopyFile(\Mmi\Http\RequestFile $file, $allowedTypes = []) { //pomijanie plików typu bmp (bitmapy windows - nieobsługiwane w PHP) if ($file->type == 'image/x-ms-bmp' || $file->type == 'image/tiff') { $file->type = 'application/octet-stream'; } //plik nie jest dozwolony if (!empty($allowedTypes) && !in_array($file->type, $allowedTypes)) { return null; } //pozycja ostatniej kropki w nazwie - rozszerzenie pliku $pointPosition = strrpos($file->name, '.'); //kalkulacja nazwy systemowej $name = md5(microtime(true) . $file->tmpName) . (($pointPosition !== false) ? substr($file->name, $pointPosition) : ''); //określanie ścieżki $dir = BASE_PATH . '/var/data/' . $name[0] . '/' . $name[1] . '/' . $name[2] . '/' . $name[3]; //tworzenie ścieżki if (!file_exists($dir)) { mkdir($dir, 0777, true); } //zmiana uprawnień chmod($file->tmpName, 0664); //kopiowanie pliku copy($file->tmpName, $dir . '/' . $name); return $name; }
php
{ "resource": "" }
q5358
File.move
train
public static function move($srcObject, $srcId, $destObject, $destId) { $i = 0; //przenoszenie plików foreach (CmsFileQuery::byObject($srcObject, $srcId)->find() as $file) { //nowy obiekt i id $file->object = $destObject; $file->objectId = $destId; //zapis $file->save(); $i++; } return $i; }
php
{ "resource": "" }
q5359
File.copy
train
public static function copy($srcObject, $srcId, $destObject, $destId) { $i = 0; //kopiowanie plików foreach (CmsFileQuery::byObject($srcObject, $srcId)->find() as $file) { try { //tworzenie kopii $copy = new \Mmi\Http\RequestFile([ 'name' => $file->original, 'tmp_name' => $file->getRealPath(), 'size' => $file->size ]); } catch (\Mmi\App\KernelException $e) { \Mmi\App\FrontController::getInstance()->getLogger()->warning('Unable to copy file, file not found: ' . $file->getRealPath()); continue; } $newFile = clone $file; $newFile->id = null; //dołączanie pliku self::_copyFile($copy, $destObject, $destId, $newFile); $i++; } return $i; }
php
{ "resource": "" }
q5360
File._updateRecordFromRequestFile
train
protected static function _updateRecordFromRequestFile(\Mmi\Http\RequestFile $file, \Cms\Orm\CmsFileRecord $record) { //typ zasobu $record->mimeType = $file->type; //klasa zasobu $class = explode('/', $file->type); $record->class = $class[0]; //oryginalna nazwa pliku $record->original = $file->name; //rozmiar pliku $record->size = $file->size; //daty dodania i modyfikacji if (!$record->dateAdd) { $record->dateAdd = date('Y-m-d H:i:s'); } if (!$record->dateModify) { $record->dateModify = date('Y-m-d H:i:s'); } //właściciel pliku $record->cmsAuthId = \App\Registry::$auth ? \App\Registry::$auth->getId() : null; if ($record->active === null) { //domyślnie aktywny $record->active = 1; } return $record; }
php
{ "resource": "" }
q5361
RegistrationController.setContainer
train
public function setContainer(ContainerInterface $container = NULL) { parent::setContainer($container); if(!$this->container->getParameter('fom_user.selfregister')) throw new AccessDeniedHttpException(); }
php
{ "resource": "" }
q5362
TaskGettextScanner.extract
train
public function extract($path, $regex = null) { $directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($directory); if ($regex) { $iterator = new RegexIterator($iterator, $regex); } $this->iterator->attachIterator($iterator); return $this; }
php
{ "resource": "" }
q5363
TaskGettextScanner.scan
train
private function scan(Translations $translations) { foreach ($this->iterator as $each) { foreach ($each as $file) { if ($file === null || !$file->isFile()) { continue; } $target = $file->getPathname(); if (($fn = $this->getFunctionName('addFrom', $target, 'File'))) { $translations->$fn($target); } } } }
php
{ "resource": "" }
q5364
TaskGettextScanner.getFunctionName
train
private function getFunctionName($prefix, $file, $suffix, $key = 0) { if (preg_match(self::getRegex(), strtolower($file), $matches)) { $format = self::$suffixes[$matches[1]]; if (is_array($format)) { $format = $format[$key]; } return sprintf('%s%s%s', $prefix, $format, $suffix); } }
php
{ "resource": "" }
q5365
TaskGettextScanner.getRegex
train
private static function getRegex() { if (self::$regex === null) { self::$regex = '/('.str_replace('.', '\\.', implode('|', array_keys(self::$suffixes))).')$/'; } return self::$regex; }
php
{ "resource": "" }
q5366
UserHelper.setPassword
train
public function setPassword(User $user, $password) { $encoder = $this->container->get('security.encoder_factory') ->getEncoder($user); $salt = $this->createSalt(); $encryptedPassword = $encoder->encodePassword($password, $salt); $user ->setPassword($encryptedPassword) ->setSalt($salt); }
php
{ "resource": "" }
q5367
UserHelper.createSalt
train
private function createSalt($max = 15) { $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $i = 0; $salt = ""; do { $salt .= $characterList{mt_rand(0,strlen($characterList)-1)}; $i++; } while ($i < $max); return $salt; }
php
{ "resource": "" }
q5368
UserHelper.giveOwnRights
train
public function giveOwnRights($user) { $aclProvider = $this->container->get('security.acl.provider'); $maskBuilder = new MaskBuilder(); $usid = UserSecurityIdentity::fromAccount($user); $uoid = ObjectIdentity::fromDomainObject($user); foreach($this->container->getParameter("fom_user.user_own_permissions") as $permission) { $maskBuilder->add($permission); } $umask = $maskBuilder->get(); try { $acl = $aclProvider->findAcl($uoid); } catch(\Exception $e) { $acl = $aclProvider->createAcl($uoid); } $acl->insertObjectAce($usid, $umask); $aclProvider->updateAcl($acl); }
php
{ "resource": "" }
q5369
MongodbController.modelCommand
train
public function modelCommand($input, $modelName, $optimized = false) { if (strpos($modelName, '\\') === false) { $modelName = 'App\\Models\\' . ucfirst($modelName); } $fieldTypes = $this->_inferFieldTypes([$input]); $model = $this->_renderModel($fieldTypes, $modelName, 'mongodb', $optimized); $file = '@tmp/mongodb_model/' . substr($modelName, strrpos($modelName, '\\') + 1) . '.php'; $this->filesystem->filePut($file, $model); $this->console->writeLn(['write model to :file', 'file' => $file]); }
php
{ "resource": "" }
q5370
MongodbController.modelsCommand
train
public function modelsCommand($services = [], $namespace = 'App\Models', $optimized = false, $sample = 1000, $db = []) { if (strpos($namespace, '\\') === false) { $namespace = 'App\\' . ucfirst($namespace) . '\\Models'; } foreach ($this->_getServices($services) as $service) { /** * @var \ManaPHP\Mongodb $mongodb */ $mongodb = $this->_di->getShared($service); $defaultDb = $mongodb->getDefaultDb(); foreach ($defaultDb ? [$defaultDb] : $mongodb->listDatabases() as $cdb) { if (in_array($cdb, ['admin', 'local'], true) || ($db && !in_array($cdb, $db, true))) { continue; } foreach ($mongodb->listCollections($cdb) as $collection) { if (strpos($collection, '.')) { continue; } if (!$docs = $mongodb->aggregate("$cdb.$collection", [['$sample' => ['size' => $sample]]])) { continue; } $plainClass = Text::camelize($collection); $fileName = "@tmp/mongodb_models/$plainClass.php"; $this->console->progress(['`:collection` processing...', 'collection' => $collection], ''); $fieldTypes = $this->_inferFieldTypes($docs); $modelClass = $namespace . '\\' . $plainClass; $model = $this->_renderModel($fieldTypes, $modelClass, $service, $defaultDb ? $collection : "$cdb.$collection", $optimized); $this->filesystem->filePut($fileName, $model); $this->console->progress([ ' `:namespace` collection saved to `:file`', 'namespace' => "$cdb.$collection", 'file' => $fileName]); $pending_fields = []; foreach ($fieldTypes as $field => $type) { if ($type === '' || strpos($type, '|') !== false) { $pending_fields[] = $field; } } if ($pending_fields) { $this->console->warn(['`:collection` has pending fields: :fields', 'collection' => $collection, 'fields' => implode(', ', $pending_fields)]); } } } } }
php
{ "resource": "" }
q5371
MongodbController.csvCommand
train
public function csvCommand($services = [], $collection_pattern = '', $bom = false) { foreach ($this->_getServices($services) as $service) { /** * @var \ManaPHP\Mongodb $mongodb */ $mongodb = $this->_di->getShared($service); $defaultDb = $mongodb->getDefaultDb(); foreach ($defaultDb ? [$defaultDb] : $mongodb->listDatabases() as $db) { if (in_array($db, ['admin', 'local'], true)) { continue; } foreach ($mongodb->listCollections($db) as $collection) { if ($collection_pattern && !fnmatch($collection_pattern, $collection)) { continue; } $fileName = "@tmp/mongodb_csv/$db/$collection.csv"; $this->console->progress(['`:collection` processing...', 'collection' => $collection], ''); $this->filesystem->dirCreate(dirname($fileName)); $file = fopen($this->alias->resolve($fileName), 'wb'); if ($bom) { fprintf($file, "\xEF\xBB\xBF"); } $docs = $mongodb->fetchAll("$db.$collection"); if ($docs) { $columns = []; foreach ($docs[0] as $k => $v) { if ($k === '_id' && is_object($v)) { continue; } $columns[] = $k; } fputcsv($file, $columns); } $linesCount = 0; $startTime = microtime(true); if (count($docs) !== 0) { foreach ($docs as $doc) { $line = []; foreach ($doc as $k => $v) { if ($k === '_id' && is_object($v)) { continue; } $line[] = $v; } $linesCount++; fputcsv($file, $line); } } fclose($file); $this->console->progress(['write to `:file` success: :count [:time]', 'file' => $fileName, 'count' => $linesCount, 'time' => round(microtime(true) - $startTime, 4)]); /** @noinspection DisconnectedForeachInstructionInspection */ } } } }
php
{ "resource": "" }
q5372
MongodbController.listCommand
train
public function listCommand($services = [], $collection_pattern = '', $field = '', $db = []) { foreach ($this->_getServices($services) as $service) { /** * @var \ManaPHP\Mongodb $mongodb */ $mongodb = $this->_di->getShared($service); $defaultDb = $mongodb->getDefaultDb(); foreach ($defaultDb ? [$defaultDb] : $mongodb->listDatabases() as $cdb) { if ($db && !in_array($cdb, $db, true)) { continue; } $this->console->writeLn(['---`:db` db of `:service` service---', 'db' => $cdb, 'service' => $service], Console::BC_CYAN); foreach ($mongodb->listCollections($cdb) as $row => $collection) { if ($collection_pattern && !fnmatch($collection_pattern, $collection)) { continue; } if ($field) { if (!$docs = $mongodb->fetchAll("$cdb.$collection", [$field => ['$exists' => 1]], ['limit' => 1])) { continue; } } else { $docs = $mongodb->fetchAll("$cdb.$collection", [], ['limit' => 1]); } $columns = $docs ? array_keys($docs[0]) : []; $this->console->writeLn([' :row :namespace(:columns)', 'row' => sprintf('%2d ', $row + 1), 'namespace' => $this->console->colorize("$cdb.$collection", Console::FC_GREEN), 'columns' => implode(', ', $columns)]); } } } }
php
{ "resource": "" }
q5373
Filter.addDefinition
train
public function addDefinition($type, $value, $field) { $definition = new \stdClass(); $definition->type = $type; $definition->value = $value; $definition->field = $field; $this->_filter[] = $definition; }
php
{ "resource": "" }
q5374
Model.rise
train
public function rise(array $params, $line, $filename) { $this->invoke = [ 'MODEL_DOES_NOT_EXISTS' => function ($params, $filename, $line) { // set message for not existing column $this->message = "Model `" . $params[1] . "` not exists. File: " . $filename . " Line: " . $line; }]; $this->invoke[current($params)]($params, $filename, $line); return $this; }
php
{ "resource": "" }
q5375
RoleAjax.postDeleteRole
train
public function postDeleteRole() { $response = (object)array( 'method' => 'deleterole', 'success' => false, 'status' => 200, 'error_code' => 0, 'error_message' => '' ); // decode json data $data = json_decode(file_get_contents("php://input")); if( empty($data)) { $data = (object) $_POST; } $requiredParams = array('id'); try { AuthorizerHelper::can(RoleValidator::ROLE_CAN_DELETE); $data = (array) $data; foreach ($requiredParams as $param){ if (empty($data[$param])) { throw new \Exception(ucfirst($param) .' is required.'); } } $roleModel = new \erdiko\users\models\Role(); $roleId = $roleModel->delete($data['id']); $responseRoleId = array('id' => $roleId); $response->success = true; $response->role = $responseRoleId; unset($response->error_code); unset($response->error_message); } catch (\Exception $e) { $response->success = false; $response->error_code = $e->getCode(); $response->error_message = $e->getMessage(); } $this->setContent($response); }
php
{ "resource": "" }
q5376
Flash.output
train
public function output($remove = true) { $context = $this->_context; foreach ($context->messages as $message) { echo $message; } if ($remove) { $context->messages = []; } }
php
{ "resource": "" }
q5377
TextController.editAction
train
public function editAction() { $form = new \CmsAdmin\Form\Text(new \Cms\Orm\CmsTextRecord($this->id)); $this->view->textForm = $form; //brak wysłanych danych if (!$form->isMine()) { return; } //zapisany if ($form->isSaved()) { $this->getMessenger()->addMessage('messenger.text.text.saved', true); $this->getResponse()->redirect('cmsAdmin', 'text'); } $this->getMessenger()->addMessage('messenger.text.text.error', false); }
php
{ "resource": "" }
q5378
Youtube.getThumbnailUrl
train
public function getThumbnailUrl(Tube $video) { if (0 === strlen($this->thumbnailSize)) { return false; } return sprintf('http://img.youtube.com/vi/%s/%s.jpg', $video->id, $this->thumbnailSize); }
php
{ "resource": "" }
q5379
ClassMetadata.getPropertyValue
train
public function getPropertyValue($user, $property = self::LOGIN_PROPERTY, $strict = false) { if ($this->checkProperty($property, $strict)) { $oid = spl_object_hash($user); if (null !== $cacheHit = $this->resolveCache($oid, $property)) { return $cacheHit; } if (is_string($this->properties[$property])) { $this->properties[$property] = new ReflectionProperty($user, $this->properties[$property]); } $this->properties[$property]->setAccessible(true); return $this->lazyValueCache[$oid][$property] = $this->properties[$property]->getValue($user); } }
php
{ "resource": "" }
q5380
ClassMetadata.getPropertyName
train
public function getPropertyName($property = self::LOGIN_PROPERTY, $strict = false) { if ($this->checkProperty($property, $strict)) { if (is_string($this->properties[$property])) { return $this->properties[$property]; } if (isset($this->lazyPropertyNameCache[$property])) { return $this->lazyPropertyNameCache[$property]; } return $this->lazyPropertyNameCache[$property] = $this->properties[$property]->getName(); } }
php
{ "resource": "" }
q5381
ClassMetadata.modifyProperty
train
public function modifyProperty($user, $newValue, $property = self::LOGIN_PROPERTY) { $this->checkProperty($property, true); $propertyObject = $this->properties[$property]; if (is_string($propertyObject)) { $this->properties[$property] = $propertyObject = new ReflectionProperty($user, $propertyObject); } $propertyObject->setAccessible(true); $propertyObject->setValue($user, $newValue); $oid = spl_object_hash($user); if (!array_key_exists($oid, $this->lazyValueCache)) { $this->lazyValueCache[$oid] = array(); } $this->lazyValueCache[$oid][$property] = $newValue; }
php
{ "resource": "" }
q5382
ClassMetadata.checkProperty
train
private function checkProperty($property = self::LOGIN_PROPERTY, $strict = false) { if (!isset($this->properties[$property])) { if ($strict) { throw new \LogicException(sprintf( 'Cannot get property "%s"!', $property )); } return false; } return true; }
php
{ "resource": "" }
q5383
ClassMetadata.resolveCache
train
private function resolveCache($oid, $property) { if (isset($this->lazyValueCache[$oid])) { if (isset($this->lazyValueCache[$oid][$property])) { return $this->lazyValueCache[$oid][$property]; } return; } $this->lazyValueCache[$oid] = array(); }
php
{ "resource": "" }
q5384
RepositoryGeneratorServiceProvider.registerMakeCommand
train
protected function registerMakeCommand() { $this->app->singleton('command.repository.make', function ($app) { $prefix = $app['config']['repository.prefix']; $suffix = $app['config']['repository.suffix']; $contract = $app['config']['repository.contract']; $namespace = $app['config']['repository.namespace']; $creator = $app['repository.creator']; $files = $app['files']; return new RepositoryMakeCommand($creator, $prefix, $suffix, $contract, $namespace, $files); }); $this->commands('command.repository.make'); }
php
{ "resource": "" }
q5385
Response.setCookie
train
public function setCookie($name, $value, $expire = 0, $path = null, $domain = null, $secure = false, $httpOnly = true) { $context = $this->_context; if ($expire > 0) { $current = time(); if ($expire < $current) { $expire += $current; } } $context->cookies[$name] = [ 'name' => $name, 'value' => $value, 'expire' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure, 'httpOnly' => $httpOnly ]; $globals = $this->request->getGlobals(); $globals->_COOKIE[$name] = $value; return $this; }
php
{ "resource": "" }
q5386
Response.setStatus
train
public function setStatus($code, $text = null) { $context = $this->_context; $context->status_code = (int)$code; $context->status_text = $text ?: $this->getStatusText($code); return $this; }
php
{ "resource": "" }
q5387
Response.setHeader
train
public function setHeader($name, $value) { $context = $this->_context; $context->headers[$name] = $value; return $this; }
php
{ "resource": "" }
q5388
Response.redirect
train
public function redirect($location, $temporarily = true) { if ($temporarily) { $this->setStatus(302, 'Temporarily Moved'); } else { $this->setStatus(301, 'Permanently Moved'); } $this->setHeader('Location', $this->url->get($location)); throw new AbortException(); /** @noinspection PhpUnreachableStatementInspection */ return $this; }
php
{ "resource": "" }
q5389
Response.setContent
train
public function setContent($content) { $context = $this->_context; $context->content = (string)$content; return $this; }
php
{ "resource": "" }
q5390
Response.setJsonContent
train
public function setJsonContent($content) { $context = $this->_context; $this->setHeader('Content-Type', 'application/json; charset=utf-8'); if (is_array($content)) { if (!isset($content['code'])) { $content = ['code' => 0, 'message' => '', 'data' => $content]; } } elseif ($content instanceof \JsonSerializable) { $content = ['code' => 0, 'message' => '', 'data' => $content]; } elseif (is_string($content)) { null; } elseif (is_int($content)) { $content = ['code' => $content, 'message' => '']; } elseif ($content === null) { $content = ['code' => 0, 'message' => '', 'data' => null]; } elseif ($content instanceof ValidatorException) { $content = ['code' => -2, 'message' => $content->getMessage()]; } elseif ($content instanceof \Exception) { if ($content instanceof \ManaPHP\Exception) { $this->setStatus($content->getStatusCode()); $content = $content->getJson(); } else { $this->setStatus(500); $content = ['code' => 500, 'message' => 'Server Internal Error']; } } $context->content = $this->_jsonEncode($content); return $this; }
php
{ "resource": "" }
q5391
FileGarbageCollectorCommand._checkForFile
train
protected function _checkForFile($directory, $file) { //szukamy tylko plików w przedziale 33 - 37 znaków if (strlen($file) < 33 || strlen($file) > 37) { echo $file . "\n"; return; } //brak pliku w plikach CMS if (null === $fr = (new \Cms\Orm\CmsFileQuery) ->whereName()->equals($file) ->findFirst() ) { $this->_size += filesize($directory . '/' . $file); $this->_count++; unlink($directory . '/' . $file); return $this->_reportLine($directory . '/' . $file); } $this->_found++; }
php
{ "resource": "" }
q5392
FiddlerController.webCommand
train
public function webCommand($id = '', $ip = '') { $options = []; if ($id) { $options['id'] = $id; } if ($ip) { $options['ip'] = $ip; } $this->fiddlerPlugin->subscribeWeb($options); }
php
{ "resource": "" }
q5393
FiddlerController.cliCommand
train
public function cliCommand($id = '') { $options = []; if ($id) { $options['id'] = $id; } $this->fiddlerPlugin->subscribeCli($options); }
php
{ "resource": "" }
q5394
Parser.register_node_class
train
function register_node_class( $s, $class ){ if( ! class_exists($class) ){ $s = $this->token_name( $s ); throw new Exception( "If you want to register class `$class' for symbol `$s' you should include it first" ); } $this->node_classes[$s] = $class; }
php
{ "resource": "" }
q5395
Parser.create_node
train
function create_node( $s ){ if( isset($this->node_classes[$s]) ){ // custom node class $class = $this->node_classes[$s]; } else { // vanilla flavour node $class = $this->default_node_class; } return new $class( $s ); }
php
{ "resource": "" }
q5396
Parser.token_name
train
function token_name ( $t ){ $t = self::token_to_symbol( $t ); if( ! is_int($t) ){ return $t; } return $this->Lex->name( $t ); }
php
{ "resource": "" }
q5397
Parser.current_token
train
protected function current_token(){ if( !isset($this->tok) ){ $this->tok = current( $this->input ); $this->t = self::token_to_symbol( $this->tok ); } return $this->tok; }
php
{ "resource": "" }
q5398
Parser.next_token
train
protected function next_token(){ $this->tok = next( $this->input ); $this->t = self::token_to_symbol( $this->tok ); return $this->tok; }
php
{ "resource": "" }
q5399
Parser.prev_token
train
protected function prev_token(){ $this->tok = prev( $this->input ); $this->t = self::token_to_symbol( $this->tok ); return $this->tok; }
php
{ "resource": "" }