_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q267400
RbacMigration.init
test
public function init() { parent::init(); $this->authManager = Yii::$app->getAuthManager(); if (!$this->authManager instanceof DbManager) { throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.'); } }
php
{ "resource": "" }
q267401
RbacMigration.createRole
test
function createRole($name, $description) { if ($user = $this->authManager->getRole($name)) { echo "{$name} role already exists\n"; } else { $user = $this->authManager->createRole($name); $user->description = $description; $this->authManager->add($user); echo "{$name} role created\n"; } return $user; }
php
{ "resource": "" }
q267402
RbacMigration.assignChildRole
test
function assignChildRole($parent, $child) { if (!$this->authManager->hasChild($parent, $child)) { $this->authManager->addChild($parent, $child); echo "New child '{$child->name}' added to '{$parent->name}'\n"; } else { echo "Role '{$child->name}' was already added to '{$parent->name}'\n"; } }
php
{ "resource": "" }
q267403
MockRegistry.register
test
public function register(FunctionProphecy $prophecy) { $name = $prophecy->getFQName(); if ($this->has($name)) { throw new \Exception(); } if (! function_exists($name)) { Generator::generate($prophecy); } $this->mocks[$name] = $prophecy->getNamespace(); return $this; }
php
{ "resource": "" }
q267404
MockRegistry.call
test
public function call($name, $uqfn, array $args) { if (! $this->has($name)) { throw new \Exception(); } return $this->mocks[$name]->call($uqfn, $args); }
php
{ "resource": "" }
q267405
ParameterBag.get
test
public function get($key) { $key = strtolower($key); if (!array_key_exists($key, $this->parameters)) { throw new ParameterNotFoundException($key); } return $this->parameters[$key]; }
php
{ "resource": "" }
q267406
ParameterBag.resolveString
test
public function resolveString($value, array $resolving = array()) { $parts = explode('%', $value); $keyOnly = (bool) preg_match('/^%([^%\s]+)%$/', $value); $return = $parts[0]; for ($i = 1, $last = count($parts) - 1; $i <= $last; ++$i) { $part = $parts[$i]; $key = strtolower($part); if (0 === $i % 2) { $return .= $part; } elseif ($last === $i) { $return .= '%' . $part; } elseif (empty($part) || preg_match('/ /', $part)) { $return .= '%' . $part . '%'; } elseif (isset($resolving[$key])) { throw new ParameterCircularReferenceException($key, array_keys($resolving)); } else { $resolved = $this->get($key); if (true === $keyOnly) { return $this->resolved ? $resolved : $this->resolveValue($resolved, array_merge($resolving, array($key => true))); } elseif (!is_string($resolved) && !is_numeric($resolved)) { throw new RuntimeException('Resolved value is not a string or numbers'); } $resolved = (string) $resolved; $return .= $this->resolved ? $resolved : $this->resolveValue($resolved, array_merge($resolving, array($key => true))); } } return $return; }
php
{ "resource": "" }
q267407
Twitter.queryToMeta
test
protected function queryToMeta($query) { $query = str_replace(' ', '+', $query); if (preg_match('~^(?:hashtag:|#)(\w+)$~i', $query, $matches)) { $type = 'hashtag'; $url = 'https://twitter.com/hashtag/' . $matches[1] . '?f=tweets'; } elseif (preg_match('~^(?:user:|@)(\w+)$~i', $query, $matches)) { $type = 'user'; $url = 'https://twitter.com/' . $matches[1]; } elseif (preg_match('~^(?:search:)(.+)$~i', $query, $matches)) { $type = 'search'; $url = 'https://twitter.com/search?f=tweets&q=' . $matches[1]; } else { $type = 'search'; $url = 'https://twitter.com/search?f=tweets&q=' . $query; } return [ 'query' => $query, 'type' => $type, 'url' => $url ]; }
php
{ "resource": "" }
q267408
Twitter.twitter
test
public function twitter($query) { $meta = $this->queryToMeta($query); if (! $page = NoAPI::curl($meta['url'])) return false; return $this->parse($page, $meta); }
php
{ "resource": "" }
q267409
Tabs.renderPanes
test
public function renderPanes($panes) { return $this->renderTabContent ? "\n" . $this->htmlHlp->tag('div', implode("\n", $panes), $this->tabContentOptions) : ''; }
php
{ "resource": "" }
q267410
RegistrationForm.register
test
public function register() { if (!$this->validate()) { return false; } /** @var User $user */ $user = Yii::createObject(User::className()); $user->setScenario('register'); $this->loadAttributes($user); if (!$user->register()) { return false; } Yii::$app->session->setFlash( 'info', Yii::t('user', 'Your account has been created and a message with further instructions has been sent to your email') ); return true; }
php
{ "resource": "" }
q267411
Zend_Filter_Encrypt_Mcrypt.setVector
test
public function setVector($vector = null) { $cipher = $this->_openCipher(); $size = mcrypt_enc_get_iv_size($cipher); if (empty($vector)) { $this->_srand(); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) { $method = MCRYPT_RAND; } else { if (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) { $method = MCRYPT_DEV_URANDOM; } elseif (file_exists('/dev/random')) { $method = MCRYPT_DEV_RANDOM; } else { $method = MCRYPT_RAND; } } $vector = mcrypt_create_iv($size, $method); } else if (strlen($vector) != $size) { throw new Zend_Filter_Exception('The given vector has a wrong size for the set algorithm'); } $this->_encryption['vector'] = $vector; $this->_closeCipher($cipher); return $this; }
php
{ "resource": "" }
q267412
Zend_Filter_Encrypt_Mcrypt._openCipher
test
protected function _openCipher() { $cipher = mcrypt_module_open( $this->_encryption['algorithm'], $this->_encryption['algorithm_directory'], $this->_encryption['mode'], $this->_encryption['mode_directory']); if ($cipher === false) { throw new Zend_Filter_Exception('Mcrypt can not be opened with your settings'); } return $cipher; }
php
{ "resource": "" }
q267413
Zend_Filter_Encrypt_Mcrypt._initCipher
test
protected function _initCipher($cipher) { $key = $this->_encryption['key']; $keysizes = mcrypt_enc_get_supported_key_sizes($cipher); if (empty($keysizes) || ($this->_encryption['salt'] == true)) { $this->_srand(); $keysize = mcrypt_enc_get_key_size($cipher); $key = substr(md5($key), 0, $keysize); } else if (!in_array(strlen($key), $keysizes)) { throw new Zend_Filter_Exception('The given key has a wrong size for the set algorithm'); } $result = mcrypt_generic_init($cipher, $key, $this->_encryption['vector']); if ($result < 0) { throw new Zend_Filter_Exception('Mcrypt could not be initialize with the given setting'); } return $this; }
php
{ "resource": "" }
q267414
Auth.connect
test
public static function connect(array $clientCredentials, array $endPoints, $userDataUrl) { $instance = new static; if (! $instance->protocol = self::getAuthProtocol($clientCredentials)) { throw new \InvalidArgumentException('Credential keys are invalid.'); } $instance->credentials = $clientCredentials; $instance->endPoints = $endPoints; $tokenCredentials = $instance->fetchTokenCredentials(); $instance->addToCredentials($tokenCredentials); $instance->filterCredentialsByKey('token_credentials'); return $instance->fetchUserData($userDataUrl); }
php
{ "resource": "" }
q267415
Auth.verifyCredentials
test
public static function verifyCredentials(array $tokenCredentials, $userDataUrl) { $instance = new static; if (! $instance->protocol = self::getAuthProtocol($tokenCredentials)) { throw new \InvalidArgumentException('Credential keys are invalid.'); } $instance->addToCredentials($tokenCredentials); $instance->filterCredentialsByKey('token_credentials'); return $instance->fetchUserData($userDataUrl); }
php
{ "resource": "" }
q267416
Auth.fetchUserData
test
protected function fetchUserData($userDataUrl) { $plugins = [ 'auth' => $this->newAuthExtension(), ]; $request = $this->newRequest(); $userData = $request::init($userDataUrl) ->addPlugins($plugins) ->GET() ->getBody(); $this->addDataTokens($userData, $this->credentials); return $userData; }
php
{ "resource": "" }
q267417
Auth.newAuthExtension
test
public function newAuthExtension(RequestPluginAdapter $authExtension = null) { if (empty($authExtension)) { $authExtension = new GuzzleAuth($this->credentials); } return $authExtension; }
php
{ "resource": "" }
q267418
Auth.addDataTokens
test
protected function addDataTokens(&$object, $tokenCredentials) { $tokens = &$object->tokens; $callback = function ($value, $key) use (&$tokens) { $tokens = array_add($tokens, $key, $value); }; array_walk($tokenCredentials, $callback); }
php
{ "resource": "" }
q267419
Auth.getAuthProtocol
test
public static function getAuthProtocol(array $credentials) { $instance = new static; $credentialKeys = array_keys($credentials); if ($instance->isOauth1($credentialKeys)) { return 'oauth1'; } if ($instance->isOauth2($credentialKeys)) { return 'oauth2'; } return false; }
php
{ "resource": "" }
q267420
Auth.isOauth1
test
protected function isOauth1($credentialsKeys) { $keys = $this->getOauth1Keys(); foreach ($keys as $value) { if (subarray($value, $credentialsKeys)) { return true; } } return false; }
php
{ "resource": "" }
q267421
Auth.isOauth2
test
protected function isOauth2($credentialsKeys) { $keys = $this->getOauth2Keys(); foreach ($keys as $value) { if (subarray($value, $credentialsKeys)) { return true; } } return false; }
php
{ "resource": "" }
q267422
NativeStream.close
test
public function close(): void { // If there is no stream if (null === $this->stream) { // Don't do anything return; } // Detach the stream $resource = $this->detach(); // Close the stream fclose($resource); }
php
{ "resource": "" }
q267423
NativeStream.attach
test
public function attach(string $stream, string $mode = null): void { $this->setStream($stream, $mode); }
php
{ "resource": "" }
q267424
NativeStream.getContents
test
public function getContents(): string { // If the stream isn't readable if (! $this->isReadable()) { // Throw a runtime exception throw new RuntimeException('Stream is not readable'); } // Get the stream contents $result = stream_get_contents($this->stream); // If there was a failure in getting the stream contents if (false === $result) { // Throw a runtime exception throw new RuntimeException('Error reading from stream'); } return $result; }
php
{ "resource": "" }
q267425
NativeStream.setStream
test
protected function setStream(string $stream, string $mode = null): void { // Set the mode $mode = $mode ?? 'r'; // Open a new resource stream $resource = fopen($stream, $mode); // If the resource isn't a resource or a stream resource type if (! \is_resource($resource) || 'stream' !== get_resource_type( $resource ) ) { // Throw a new invalid stream exception throw new InvalidStream( 'Invalid stream provided; must be a string stream identifier or stream resource' ); } // Set the stream $this->stream = $resource; }
php
{ "resource": "" }
q267426
FileWriter.write
test
public function write(array $data, array $options) { if (!isset($options['file'])) { throw new \InvalidArgumentException( 'Parameter "file" is mandatory.' ); } if (!is_string($options['file'])) { throw new \InvalidArgumentException( 'Parameter "file" must be a string.' ); } $file = $this->_factory->createInstance($options['file'], null, $options); $file->setContents($data) ->save($options); }
php
{ "resource": "" }
q267427
Transaction.getAccountVirtual
test
protected function getAccountVirtual() { $accountIdVirtual = (int) Post::getInstance()->get('editAccountIdVirtual'); $accountUserMapper = new AccountUserMapper(Database::get('money')); $accountMapper = new AccountMapper(Database::get('money')); //~ Update virtual account if necessary if ($accountIdVirtual <= 0) { return $accountMapper->newDataInstance(); } $accountUser = $accountUserMapper->findByKeys([ 'account_id' => $accountIdVirtual, 'user_id' => Session::getInstance()->get('id'), ]); if ($accountUser->getUserId() !== Session::getInstance()->get('id')) { throw new \Exception('Not Allowed!'); } $account = $accountUser->getAccount(); if (!$account->isVirtual()) { return $accountMapper->newDataInstance(); } return $account; }
php
{ "resource": "" }
q267428
Transaction.getPreviousAccount
test
public function getPreviousAccount($previousId) { $accountMapper = new AccountMapper(Database::get('money')); if ($previousId <= 0) { return $accountMapper->newDataInstance(); } return $accountMapper->findById($previousId); }
php
{ "resource": "" }
q267429
Transaction.updateAccountVirtual
test
protected function updateAccountVirtual(Account $account, Account $previousAccount, $amount, $previousAmount) { $accountMapper = new AccountMapper(Database::get('money')); //~ Revert previous amount on previous account if ($previousAccount->getId() > 0) { if ($previousAccount->getId() !== $account->getId()) { $previousAccount->addAmount(-$previousAmount); $accountMapper->update($previousAccount); } else { $account->addAmount(-$previousAmount); } } //~ Update amount of current account $account->addAmount($amount); $accountMapper->update($account); }
php
{ "resource": "" }
q267430
Command.cache
test
public function cache($duration = null) { $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration; return $this; }
php
{ "resource": "" }
q267431
Command.setConnection
test
public function setConnection($connection = null) { if ($connection instanceof TransactionInterface) { $connection = $connection->getConnection(); } $this->connection = $connection; if ($connection instanceof EventEmitterWildcardInterface) { //Remove connection instance on close $this->connection->once(ConnectionInterface::EVENT_CLOSE, function() use ($connection) { if ($this->connection === $connection) { $this->connection = null; } }); } return $this; }
php
{ "resource": "" }
q267432
Command.fetchResultsRow
test
public function fetchResultsRow($row = [], $fetchMethod = self::FETCH_ALL, $fetchMode = self::FETCH_MODE_ASSOC, $colIndex = 0) { if (in_array($fetchMethod, [static::FETCH_ALL, static::FETCH_ROW])) { $this->processResultRow($row); return $fetchMode === static::FETCH_MODE_OBJECT ? (object)$row : $row; } elseif (in_array($fetchMethod, [static::FETCH_COLUMN, static::FETCH_FIELD]) && $colIndex < count($row)) { $rowIndexed = array_values($row); $this->processResultRow($rowIndexed[$colIndex]); return $rowIndexed[$colIndex]; } return null; }
php
{ "resource": "" }
q267433
Command.insertAndReturn
test
public function insertAndReturn($table, $columns) { $params = []; $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params); $tableSchema = $this->db->getSchema()->getTableSchema($table); $returnColumns = $tableSchema->getColumnNames(); if (!empty($returnColumns)) { $returning = []; foreach ((array)$returnColumns as $name) { $returning[] = $this->db->quoteColumnName($name); } $sql .= ' RETURNING ' . implode(', ', $returning); } return $this->setSql($sql)->bindValues($params); }
php
{ "resource": "" }
q267434
Command.execute
test
public function execute($lazy = true) { $sql = $this->getSql(); $rawSql = $this->getRawSql(); if ($sql == '') { return reject(false); } $execPromise = $this->internalExecute($rawSql, [], $lazy); $needResCount = $this->needResultsCount(); $thenCallback = function($results = []) use ($needResCount) { $result = $needResCount ? count($results) : true; return $this->refreshTableSchema()->then( function() use ($result) { return $result; } ); }; return $execPromise instanceof LazyPromiseInterface ? $execPromise->thenLazy($thenCallback) : $execPromise->then($thenCallback); }
php
{ "resource": "" }
q267435
Command.logQuery
test
protected function logQuery($category) { if ($this->db->enableLogging) { $rawSql = $this->getRawSql(); $message = sprintf("SQL: \"%s\"\nCategory: %s", $rawSql, $category); \Reaction::info($message); } if (!$this->db->enableProfiling) { return [false, isset($rawSql) ? $rawSql : null]; } return [true, isset($rawSql) ? $rawSql : $this->getRawSql()]; }
php
{ "resource": "" }
q267436
Command.queryScalar
test
public function queryScalar() { return $this->queryInternal(static::FETCH_FIELD)->thenLazy( function($result) { if (is_resource($result) && get_resource_type($result) === 'stream') { return stream_get_contents($result); } return $result; } ); }
php
{ "resource": "" }
q267437
Command.queryInternal
test
protected function queryInternal($fetchMethod, $fetchMode = null, $lazy = true) { $fetchMode = isset($fetchMode) ? $fetchMode : $this->fetchMode; list($profile, $rawSql) = $this->logQuery(__METHOD__); $self = $this; $execPromise = $this->internalExecute($this->sql, $this->params, $lazy); if ($execPromise instanceof LazyPromiseInterface) { return $execPromise->thenLazy( function($results) use ($fetchMethod, $fetchMode) { return $this->fetchResults($results, $fetchMethod, $fetchMode); } ); } else { $profileId = $profile ? \Reaction::$app->logger->profile('Query: ' . $rawSql) : null; return $execPromise->then( function($results) use ($self, $fetchMethod, $fetchMode) { return $self->fetchResults($results, $fetchMethod, $fetchMode); } )->then( function($data) use ($profileId) { \Reaction::profileEnd($profileId); return $data; }, function($error = null) use ($profileId) { \Reaction::profileEnd($profileId); return reject($error); } ); } }
php
{ "resource": "" }
q267438
Command.checkQueryByPattern
test
protected function checkQueryByPattern($pattern, $sql = null) { if (!isset($sql)) { $sql = $this->getSql(); } if ($sql === "") { return false; } return preg_match($pattern, $sql) > 0; }
php
{ "resource": "" }
q267439
Command.internalExecute
test
protected function internalExecute($sql, $params = [], $lazy = true) { return isset($this->connection) ? $this->connection->executeSql($sql, $params, $lazy) : $this->db->executeSql($sql, $params, $lazy); }
php
{ "resource": "" }
q267440
TClosureInvocation.invokeClosure
test
protected function invokeClosure(array $arguments, Closure $action) { $reflection = new ReflectionFunction($action); $parameters = []; foreach ($reflection->getParameters() as $parameter) { if (isset($arguments[$parameter->name])) { $parameters[] = $arguments[$parameter->name]; } elseif ($parameter->isDefaultValueAvailable()) { $parameters[] = $parameter->getDefaultValue(); } else { $message = "{$parameter->name} argument cannot be resolved."; throw new DispatcherException($message, $arguments, $action); } } return $reflection->invokeArgs($parameters); }
php
{ "resource": "" }
q267441
PEAR_Command_Config._checkLayer
test
function _checkLayer($layer = null) { if (!empty($layer) && $layer != 'default') { $layers = $this->config->getLayers(); if (!in_array($layer, $layers)) { return " only the layers: \"" . implode('" or "', $layers) . "\" are supported"; } } return false; }
php
{ "resource": "" }
q267442
FrontController.prepareDom
test
protected function prepareDom() { $dom_refs = array( 'page_menu', 'page_content', 'page_header', 'page_footer', 'page_title' ); foreach($dom_refs as $_ref) { HtmlHelper::getNewId($_ref, true); } return $this; }
php
{ "resource": "" }
q267443
FrontController.distribute
test
public function distribute() { $this ->_processSessionValues() ->_processQueryArguments() ; // if kernerl has booting errors, treat them first if (CarteBlanche::getContainer()->get('kernel')->hasBootErrors()) { $routing = array(CarteBlanche::getContainer()->get('kernel')->getBootErrors()); if (CarteBlanche::getContainer()->get('request')->isCli()) { $routing['controller'] = CarteBlanche::getConfig('routing.cli.default_controller'); $routing['action'] = CarteBlanche::getConfig('routing.cli.booterrors_action'); } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) { $routing['controller'] = CarteBlanche::getConfig('routing.ajax.default_controller'); $routing['action'] = CarteBlanche::getConfig('routing.ajax.booterrors_action'); } else { $routing['controller'] = CarteBlanche::getConfig('routing.mvc.default_controller'); $routing['action'] = CarteBlanche::getConfig('routing.mvc.booterrors_action'); } } else { $routing = CarteBlanche::getContainer()->get('router') ->distribute() ->getRouteParsed(); // controller if (empty($routing['controller'])) { if (CarteBlanche::getContainer()->get('request')->isCli()) { $routing['controller'] = CarteBlanche::getConfig('routing.cli.default_controller'); } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) { $routing['controller'] = CarteBlanche::getConfig('routing.ajax.default_controller'); } else { $routing['controller'] = CarteBlanche::getConfig('routing.mvc.default_controller'); } } // action if (empty($routing['action'])) { if (CarteBlanche::getContainer()->get('request')->isCli()) { $routing['action'] = CarteBlanche::getConfig('routing.cli.default_action'); } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) { $routing['action'] = CarteBlanche::getConfig('routing.ajax.default_action'); } else { $routing['action'] = CarteBlanche::getConfig('routing.mvc.default_action'); } } } // arguments $primary_args = $routing; unset($primary_args['all']); $args = isset($routing['all']) ? array_merge($primary_args, $routing['all']) : $primary_args; // dispatch return $this->dispatch( $routing['controller'], $routing['action'], $args ); }
php
{ "resource": "" }
q267444
FrontController.renderError
test
public function renderError($params = null, $code = 404, $exception = null) { $mode_data = CarteBlanche::getKernelMode(true); if (!is_array($mode_data) || !isset($mode_data['debug']) || false==$mode_data['debug'] ) { $action = 'error'.$code.'Action'; $_ctrl = CarteBlanche::getContainer() ->get('locator')->locateController('Error'); if (!empty($_ctrl) && class_exists($_ctrl)) { $_routes['controller'] = $_ctrl; $this->setController(new $_ctrl(CarteBlanche::getContainer())); } else { trigger_error("Controller 'Error' can't be found!", E_USER_ERROR); } // don't execute `shutdown` kernel steps CarteBlanche::getContainer()->get('kernel') ->setShutdown(false); return CodeHelper::fetchArguments( $action, $params, $this->getController() ); } else { if (!empty($exception)) { if (!isset($params['message'])) $params['message'] = ''; $params['message'] .= method_exists($exception, 'getAppMessage') ? $exception->getAppMessage() : $exception->getMessage(); } $debug = \CarteBlanche\App\Debugger::getInstance(); $this->renderDebug($params, null, false); $params['title'] = $debug->getDebuggerTitle(); $tpl = 'profiler/template_profiler'; // don't execute `shutdown` kernel steps // CarteBlanche::getContainer()->get('kernel')->setShutdown(false); return $this->view($tpl, $params, true, true); } }
php
{ "resource": "" }
q267445
FrontController.renderDebug
test
public function renderDebug(&$params = null, $dbg = 'all', $parse_template = true) { $all_debug_infos = array( 'backtrace', 'php', 'server', 'session', 'constants', 'headers', 'system', 'router', 'registry', 'db' ); if (!is_array($dbg)) { if ($dbg=='all' || $dbg==1) $dbg = $all_debug_infos; else $dbg = array( $dbg ); } $debug = \CarteBlanche\App\Debugger::getInstance(); foreach($dbg as $_dbg_info) { switch($_dbg_info) { case 'router': $debug->addStack('object', CarteBlanche::getContainer()->get('router'), 'Router Object Dump'); break; case 'registry': $debug->addStack('object', CarteBlanche::getContainer()->get('config')->getRegistry(), 'Registry Object Dump'); break; case 'db': $debug->addStack('object', CarteBlanche::getContainer()->get('database'), 'Database Object Dump'); break; default:break; } } $params['debug'] = $debug; if ($parse_template) { $url_ref = str_replace('&', '&amp;', $_SERVER['HTTP_REFERER']); $params['return_url'] = $url_ref; $debug->setDebuggerTitle( 'CarteBlanche - Debugging request <a href="'.$url_ref.'" title="Back to this page"><em>'.str_replace(_ROOTHTTP, '/', $url_ref).'</em></a>' ); $params['title'] = $debug->getDebuggerTitle(); $tpl = 'profiler/template_profiler'; return $this->view( $tpl, $params, true, true); } return; }
php
{ "resource": "" }
q267446
FrontController.view
test
public function view($view = null, array $params = array(), $display = false, $exit = false) { $view_file = CarteBlanche::getContainer() ->get('locator')->locateView( $view ); CarteBlanche::getContainer()->get('config') ->getRegistry()->loadStack('views'); CarteBlanche::getContainer()->get('config') ->getRegistry()->setEntry(uniqid(), array( 'tpl'=>$view, 'params'=>$params )); CarteBlanche::getContainer()->get('config') ->getRegistry()->saveStack('views', true); $output = CarteBlanche::getContainer()->get('template_engine') ->render($view_file, $params, $display, $exit); if ($display===true) { CarteBlanche::getContainer()->get('response') ->addContent(null, $output) ->send(); return; } else { return $output; } }
php
{ "resource": "" }
q267447
CannedResponsePlugin.init
test
public function init() { $this->addResponses(); $config = $this->bot->getConfig(); // detects someone speaking to the bot $responses = $this->responses; $address_re = "/(^{$config['nick']}(.+)|(.+){$config['nick']}[!.?]*)$/i"; $this->bot->onChannel($address_re, function(Event $event) use ($responses) { $matches = $event->getMatches(); $message = $matches[1] ? $matches[1] : $matches[2]; foreach ($responses as $regex => $function) { if (preg_match($regex, $message, $matches)) { $event->addResponse( Response::msg($event->getRequest()->getSource(), $function($matches)) ); } } }); }
php
{ "resource": "" }
q267448
CannedResponsePlugin.addResponses
test
private function addResponses() { // workaround for $this being unavailable in closures $plugin = $this; // basic response $this->addResponse('/i (love|<3) (you|u)/i', function($matches) { return 'Shutup baby, I know it!'; }); // matches things like "bot: you're the greatest thing ever!" and saves the attribute for later $this->addResponse('/(you are|you\'re) (the |a |an )*([\w ]+)/i', function($matches) use ($plugin) { $plugin->addAttribute(trim($matches[2] .' '. trim($matches[3]))); return "No, *you're* {$matches[2]} ". trim($matches[3]) .'!'; }); // matches things like "bot is amazing!" and saves the attribute for later $this->addResponse('/is (the |a |an )*([\w ]+)/i', function($matches) use ($plugin) { $plugin->addAttribute(trim($matches[1] .' '. trim($matches[2]))); return "No, *you're* {$matches[1]} ". trim($matches[2]) .'!'; }); // responds to things like "who is bot?" with a remembered attribute $this->addResponse('/(what|who) (are you|is)/i', function($matches) use ($plugin) { return "I'm ". $plugin->getRandomAttribute(); }); }
php
{ "resource": "" }
q267449
ShortCodesProcessor.registerShortCode
test
public function registerShortCode($tag, $callback) { if (is_callable($callback)) { $this->shortCodesTags[$tag] = $callback; } return $this; }
php
{ "resource": "" }
q267450
ShortCodesProcessor.removeShortCode
test
public function removeShortCode($tag) { if (isset($this->shortCodesTags[$tag])) { unset($this->shortCodesTags[$tag]); } return $this; }
php
{ "resource": "" }
q267451
ShortCodesProcessor.parseShortCodeTag
test
public function parseShortCodeTag($matches) { // allow [[foo]] syntax for escaping a tag if ($matches[1] == '[' && $matches[6] == ']') { return substr($matches[0], 1, -1); } $tag = $matches[2]; $attributes = $this->parseShortCodeAttributes($matches[3]); if (isset($matches[5])) { // enclosing tag - extra parameter return $matches[1] . call_user_func( $this->shortCodesTags[$tag], $attributes, $matches[5], $tag, $this ) . $matches[6]; } else { // self-closing tag return $matches[1] . call_user_func( $this->shortCodesTags[$tag], $attributes, null, $tag, $this ) . $matches[6]; } }
php
{ "resource": "" }
q267452
ShortCodesProcessor.parseShortCodeAttributes
test
protected function parseShortCodeAttributes($text) { $attributes = array(); $pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s' . '|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/'; $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text); if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { if (!empty($match[1])) { $attributes[strtolower($match[1])] = stripcslashes($match[2]); } elseif (!empty($match[3])) { $attributes[strtolower($match[3])] = stripcslashes($match[4]); } elseif (!empty($match[5])) { $attributes[strtolower($match[5])] = stripcslashes($match[6]); } elseif (isset($match[7]) and strlen($match[7])) { $attributes[] = stripcslashes($match[7]); } elseif (isset($match[8])) { $attributes[] = stripcslashes($match[8]); } } } else { $attributes = ltrim($text); } return $attributes; }
php
{ "resource": "" }
q267453
PEAR_REST_10.getDownloadURL
test
function getDownloadURL($base, $packageinfo, $prefstate, $installed, $channel = false) { $states = $this->betterStates($prefstate, true); if (!$states) { return PEAR::raiseError('"' . $prefstate . '" is not a valid state'); } $channel = $packageinfo['channel']; $package = $packageinfo['package']; $state = isset($packageinfo['state']) ? $packageinfo['state'] : null; $version = isset($packageinfo['version']) ? $packageinfo['version'] : null; $restFile = $base . 'r/' . strtolower($package) . '/allreleases.xml'; $info = $this->_rest->retrieveData($restFile, false, false, $channel); if (PEAR::isError($info)) { return PEAR::raiseError('No releases available for package "' . $channel . '/' . $package . '"'); } if (!isset($info['r'])) { return false; } $release = $found = false; if (!is_array($info['r']) || !isset($info['r'][0])) { $info['r'] = array($info['r']); } foreach ($info['r'] as $release) { if (!isset($this->_rest->_options['force']) && ($installed && version_compare($release['v'], $installed, '<'))) { continue; } if (isset($state)) { // try our preferred state first if ($release['s'] == $state) { $found = true; break; } // see if there is something newer and more stable // bug #7221 if (in_array($release['s'], $this->betterStates($state), true)) { $found = true; break; } } elseif (isset($version)) { if ($release['v'] == $version) { $found = true; break; } } else { if (in_array($release['s'], $states)) { $found = true; break; } } } return $this->_returnDownloadURL($base, $package, $release, $info, $found, false, $channel); }
php
{ "resource": "" }
q267454
PEAR_REST_10.listCategory
test
function listCategory($base, $category, $info = false, $channel = false) { // gives '404 Not Found' error when category doesn't exist $packagelist = $this->_rest->retrieveData($base.'c/'.urlencode($category).'/packages.xml', false, false, $channel); if (PEAR::isError($packagelist)) { return $packagelist; } if (!is_array($packagelist) || !isset($packagelist['p'])) { return array(); } if (!is_array($packagelist['p']) || !isset($packagelist['p'][0])) { // only 1 pkg $packagelist = array($packagelist['p']); } else { $packagelist = $packagelist['p']; } if ($info == true) { // get individual package info PEAR::pushErrorHandling(PEAR_ERROR_RETURN); foreach ($packagelist as $i => $packageitem) { $url = sprintf('%s'.'r/%s/latest.txt', $base, strtolower($packageitem['_content'])); $version = $this->_rest->retrieveData($url, false, false, $channel); if (PEAR::isError($version)) { break; // skipit } $url = sprintf('%s'.'r/%s/%s.xml', $base, strtolower($packageitem['_content']), $version); $info = $this->_rest->retrieveData($url, false, false, $channel); if (PEAR::isError($info)) { break; // skipit } $packagelist[$i]['info'] = $info; } PEAR::popErrorHandling(); } return $packagelist; }
php
{ "resource": "" }
q267455
PEAR_REST_10._sortReleasesByVersionNumber
test
function _sortReleasesByVersionNumber($a, $b) { if (version_compare($a['v'], $b['v'], '=')) { return 0; } if (version_compare($a['v'], $b['v'], '>')) { return -1; } if (version_compare($a['v'], $b['v'], '<')) { return 1; } }
php
{ "resource": "" }
q267456
ScheduleReceiver.getArrayData
test
public function getArrayData($id, $sens = 1, $date) { $this->date = $date; $this->uri = new Uri('/horaires_ligne/index.asp'); $this->uri->addParam('rub_code', 6); $this->uri->addParam('thm_id', 2); $this->uri->addParam('gpl_id', 0); $this->uri->addParam('lign_id', $id); $this->uri->addParam('sens', $sens); $this->uri->addParam('date', $this->date->format('d/m/Y')); return $this->allHours(); }
php
{ "resource": "" }
q267457
ScheduleReceiver.allHours
test
private function allHours() { $index = 1; $same = false; $hours = array(); while(!$same) { # Get the page $this->uri->addParam('index', $index); $request = $this->client->get($this->uri); $resource = $request->getResource(); if(!$resource->code(200)) { return array('error' => 'fail to call Stac website'); } $page = $resource->getContent(); # Get page array representation $array = $this->parser($page); if(isset($previousArray)) { # End condition when same page is called $compareId = 0; do { $comparePrevious = $previousArray[$compareId]['hours'][0]; $compareCurrent = $array[$compareId]['hours'][0]; $compareId++; } while($comparePrevious === '-'); if($comparePrevious === $compareCurrent) { $same = true; } else { # Add new array informations $previousArray = $array; foreach($array as $pKey => $place) { foreach($place['hours'] as $hour){ $hours[$pKey]['hours'][] = $hour; } } } } else { # First save of informations $previousArray = $array; $hours = $array; } $index+=6; } return $hours; }
php
{ "resource": "" }
q267458
ScheduleReceiver.parser
test
private function parser($page) { $templateTime = clone $this->date; $hours = array(); $array = array(); # Get only table $page = preg_replace('#(.+)\<tbody\>(.+)\<\/tbody\>(.+)#siU', '<table>$2</table>', $page); # save to DomDocument $dom = new DomDocument(); libxml_use_internal_errors(true); # Load and save informations $dom->loadHTML($page); $raws = $dom->getElementsByTagName('tr'); foreach($raws as $cKey => $raw) { if($cKey > 1) { $cells = $raw->getElementsByTagName('td'); foreach($cells as $rKey => $cell) { $hours[$rKey][] = mb_convert_encoding($cell->nodeValue, mb_internal_encoding(), 'ISO-8859-1'); } } } # Informations restructuration foreach($hours[0] as $placeKey => $place) { $size = count($hours); $array[$placeKey] = array( 'place' => $place, 'hours' => array() ); for($i = 1; $i<$size; $i++) { $hourValue = $hours[$i][$placeKey]; $hourValue = ($hourValue == '-') ? null : $hourValue; if(null !== $hourValue) { $cellHour = explode(':', $hourValue); $templateTime->setTime(intval($cellHour[0]), intval($cellHour[1])); $hourValue = $templateTime->getTimestamp(); } $array[$placeKey]['hours'][] = $hourValue; } } return $array; }
php
{ "resource": "" }
q267459
AccountMapper.findAllAccountByUserId
test
public function findAllAccountByUserId($userId, $excludeVirtual = true) { $this->addWhere('user_id', $userId); if ($excludeVirtual) { $this->addWhere('account_id_parent', 0); } $query = 'SELECT ' . $this->getQueryFields() . ' FROM ' . $this->getTable() . ' ' . ' INNER JOIN money_account_user USING(account_id) ' . $this->getQueryWhere() . ' ' . $this->getQueryOrderBy() . ' ' . $this->getQueryLimit(); return $this->query($query); }
php
{ "resource": "" }
q267460
CommandHandler.applicationMessage
test
protected function applicationMessage(): void { output()->formatter()->magenta(); output()->writeMessage('Valkyrja Application'); output()->formatter()->resetColor(); output()->writeMessage(' version '); output()->formatter()->cyan(); output()->writeMessage(Application::VERSION, true); output()->formatter()->resetColor(); }
php
{ "resource": "" }
q267461
CommandHandler.usageMessage
test
protected function usageMessage(string $message = null): void { $message = $message ?? $this->usagePath(); $this->sectionTitleMessage('Usage'); output()->writeMessage(static::TAB); output()->writeMessage($message, true); }
php
{ "resource": "" }
q267462
CommandHandler.usagePath
test
protected function usagePath(): string { $message = static::COMMAND; if ($this->getOptions()) { $message .= ' [options]'; } foreach ($this->getArguments() as $argument) { $message .= ' ' . ($argument->getMode() === ArgumentMode::OPTIONAL ? '[' : '') . '<' . $argument->getName() . '>' . ($argument->getMode() === ArgumentMode::OPTIONAL ? ']' : ''); } return $message; }
php
{ "resource": "" }
q267463
CommandHandler.argumentsSection
test
protected function argumentsSection(Argument ...$arguments): void { if (! $arguments) { $arguments = $this->getArguments(); } if (! $arguments) { return; } $longestLength = 0; $this->sectionDivider(); $this->sectionTitleMessage('Arguments'); foreach ($arguments as $argument) { $longestLength = max(\strlen($argument->getName()), $longestLength); } foreach ($arguments as $argument) { $this->sectionMessage( static::TAB . $argument->getName(), $argument->getDescription(), $longestLength ); } }
php
{ "resource": "" }
q267464
CommandHandler.optionsSection
test
protected function optionsSection(Option ...$options): void { if (! $options) { $options = $this->getOptions(); } if (! $options) { return; } $longestLength = 0; $this->sectionDivider(); $this->sectionTitleMessage('Options'); foreach ($options as $option) { $longestLength = max(\strlen($this->getOptionName($option)), $longestLength); } foreach ($options as $option) { $this->sectionMessage( $this->getOptionName($option), $option->getDescription(), $longestLength ); } }
php
{ "resource": "" }
q267465
CommandHandler.getOptionName
test
protected function getOptionName(Option $option): string { $name = ''; if ($option->getShortcut()) { $name .= '-' . $option->getShortcut() . ', '; } else { $name .= static::DOUBLE_TAB; } $name .= '--' . $option->getName(); return $name; }
php
{ "resource": "" }
q267466
Roller2d6DrdPlus.generateRoll
test
public function generateRoll($rollSummary): Roll2d6DrdPlus { $rollSummary = ToInteger::toInteger($rollSummary); $bonusDiceRolls = []; $malusDiceRolls = []; if ($rollSummary <= 2) { // two ones = malus rolls and one "not valid" malus roll $standardDiceRolls = [new Dice1d6Roll(1, 1), new Dice1d6Roll(1, 2)]; // two ones = malus rolls $sequenceNumber = 3; for ($malusRollsCount = 2 - $rollSummary, $malusRollNumber = 1; $malusRollNumber <= $malusRollsCount; $malusRollNumber++) { /** @noinspection PhpUnhandledExceptionInspection */ $malusDiceRolls[] = new Dice1d6DrdPlusMalusRoll(\random_int(1, 3), $sequenceNumber); // malus roll is valid only in range 1..3 $sequenceNumber++; } /** @noinspection PhpUnhandledExceptionInspection */ $malusDiceRolls[] = new Dice1d6DrdPlusMalusRoll(\random_int(4, 6), $sequenceNumber); // last malus roll was not "valid" - broke the chain } elseif ($rollSummary < 12) { $randomRange = 12 - $rollSummary; // 1..11 $firstRandomMinimum = 6 - $randomRange; if ($firstRandomMinimum < 1) { $firstRandomMinimum = 1; } $firstRandomMaximum = $rollSummary - $firstRandomMinimum; /** @noinspection PhpUnhandledExceptionInspection */ $firstRoll = \random_int($firstRandomMinimum, $firstRandomMaximum); $secondRoll = $rollSummary - $firstRoll; $firstDiceRoll = new Dice1d6Roll($firstRoll, 1); $secondDiceRoll = new Dice1d6Roll($secondRoll, 2); $standardDiceRolls = [$firstDiceRoll, $secondDiceRoll]; } else { // two sixes = bonus rolls and one "not valid" bonus roll $standardDiceRolls = [new Dice1d6Roll(6, 1), new Dice1d6Roll(6, 2)]; $sequenceNumber = 3; for ($bonusRollsCount = $rollSummary - 12, $bonusRollNumber = 1; $bonusRollNumber <= $bonusRollsCount; $bonusRollNumber++) { /** @noinspection PhpUnhandledExceptionInspection */ $bonusDiceRolls[] = new Dice1d6DrdPlusBonusRoll(\random_int(4, 6), $sequenceNumber); // bonus roll is valid only in range 4..6 $sequenceNumber++; } /** @noinspection PhpUnhandledExceptionInspection */ $bonusDiceRolls[] = new Dice1d6DrdPlusBonusRoll(\random_int(1, 3), $sequenceNumber); // last bonus roll was not "valid" - broke the chain } return $this->createRoll($standardDiceRolls, $bonusDiceRolls, $malusDiceRolls); }
php
{ "resource": "" }
q267467
TableSearch.columns
test
public function columns(array $columns, $prefixColumnsWithTable = true) { $this->has_modified_columns = true; $this->select->columns($columns, $prefixColumnsWithTable); return $this; }
php
{ "resource": "" }
q267468
TableSearch.having
test
public function having($predicate, $combination = Predicate\PredicateSet::OP_AND) { $this->select->having($predicate, $combination); return $this; }
php
{ "resource": "" }
q267469
TableSearch.where
test
public function where($predicate, $combination = null) { $this->select->where($predicate, $combination); return $this; }
php
{ "resource": "" }
q267470
TableSearch.join
test
public function join($table, $on, $columns = []) { $prefixed_table = $this->prefixTableJoinCondition($table); //$this->columns($this->getPrefixedColumns()); $this->select->join($prefixed_table, $on, $columns, Select::JOIN_INNER); return $this; }
php
{ "resource": "" }
q267471
TableSearch.joinLeft
test
public function joinLeft($table, $on, $columns = []) { $prefixed_table = $this->prefixTableJoinCondition($table); $this->select->join($prefixed_table, $on, $columns, Select::JOIN_LEFT); return $this; }
php
{ "resource": "" }
q267472
TableSearch.joinRight
test
public function joinRight($table, $on, $columns = []) { $prefixed_table = $this->prefixTableJoinCondition($table); $this->select->join($prefixed_table, $on, $columns, Select::JOIN_RIGHT); return $this; }
php
{ "resource": "" }
q267473
TableSearch.getSql
test
public function getSql() { $adapterPlatform = $this->table->getTableManager()->getDbAdapter()->getPlatform(); return $this->select->getSqlString($adapterPlatform); }
php
{ "resource": "" }
q267474
TableSearch.execute
test
public function execute() { $rs = new ResultSet($this->select, $this->table, !$this->has_modified_columns); return $rs; }
php
{ "resource": "" }
q267475
TableSearch.prefixTableJoinCondition
test
protected function prefixTableJoinCondition($table) { $tm = $this->table->getTableManager(); if (is_array($table)) { $alias = key($table); $prefixed_table = $tm->getPrefixedTable($table[$alias]); $table = [$alias => $prefixed_table]; } elseif (is_string($table)) { $prefixed_table = $tm->getPrefixedTable($table); $table = $prefixed_table; } return $table; }
php
{ "resource": "" }
q267476
Collection.get
test
public function get(string $key, $default = null) // : mixed { return $this->has($key) ? $this->collection[$key] : $default; }
php
{ "resource": "" }
q267477
Collection.set
test
public function set(string $key, $value): self { $this->collection[$key] = $value; return $this; }
php
{ "resource": "" }
q267478
Collection.remove
test
public function remove(string $key): self { if (! $this->has($key)) { return $this; } unset($this->collection[$key]); return $this; }
php
{ "resource": "" }
q267479
SQL.insert
test
public static function insert($table, array $set) { $sql = $values = $fields = $holders = []; $sql[] = 'INSERT INTO ' . static::e($table); foreach($set as $field => $value) { $fields[] = static::e($field); $holders[] = '?'; $values[] = $value; } $sql[] = '(' . implode(', ', $fields) . ')'; $sql[] = 'VALUES (' . implode(', ', $holders) . ')'; $sql = implode("\n", $sql); return [$sql, $values]; }
php
{ "resource": "" }
q267480
PEAR_ErrorStack.PEAR_ErrorStack
test
function PEAR_ErrorStack($package, $msgCallback = false, $contextCallback = false, $throwPEAR_Error = false) { $this->_package = $package; $this->setMessageCallback($msgCallback); $this->setContextCallback($contextCallback); $this->_compat = $throwPEAR_Error; }
php
{ "resource": "" }
q267481
PEAR_ErrorStack.&
test
function &singleton($package, $msgCallback = false, $contextCallback = false, $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack') { if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; } if (!class_exists($stackClass)) { if (function_exists('debug_backtrace')) { $trace = debug_backtrace(); } PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS, 'exception', array('stackclass' => $stackClass), 'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)', false, $trace); } $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] = new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error); return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; }
php
{ "resource": "" }
q267482
PEAR_ErrorStack._handleError
test
function _handleError($err) { if ($err['level'] == 'exception') { $message = $err['message']; if (isset($_SERVER['REQUEST_URI'])) { echo '<br />'; } else { echo "\n"; } var_dump($err['context']); die($message); } }
php
{ "resource": "" }
q267483
PEAR_ErrorStack.setMessageCallback
test
function setMessageCallback($msgCallback) { if (!$msgCallback) { $this->_msgCallback = array(&$this, 'getErrorMessage'); } else { if (is_callable($msgCallback)) { $this->_msgCallback = $msgCallback; } } }
php
{ "resource": "" }
q267484
PEAR_ErrorStack.setDefaultCallback
test
function setDefaultCallback($callback = false, $package = false) { if (!is_callable($callback)) { $callback = false; } $package = $package ? $package : '*'; $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback; }
php
{ "resource": "" }
q267485
PEAR_ErrorStack.pop
test
function pop() { $err = @array_shift($this->_errors); if (!is_null($err)) { @array_pop($this->_errorsByLevel[$err['level']]); if (!count($this->_errorsByLevel[$err['level']])) { unset($this->_errorsByLevel[$err['level']]); } } return $err; }
php
{ "resource": "" }
q267486
PEAR_ErrorStack.staticPop
test
function staticPop($package) { if ($package) { if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { return false; } return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->pop(); } }
php
{ "resource": "" }
q267487
PEAR_ErrorStack.hasErrors
test
function hasErrors($level = false) { if ($level) { return isset($this->_errorsByLevel[$level]); } return count($this->_errors); }
php
{ "resource": "" }
q267488
PEAR_ErrorStack.getErrors
test
function getErrors($purge = false, $level = false) { if (!$purge) { if ($level) { if (!isset($this->_errorsByLevel[$level])) { return array(); } else { return $this->_errorsByLevel[$level]; } } else { return $this->_errors; } } if ($level) { $ret = $this->_errorsByLevel[$level]; foreach ($this->_errorsByLevel[$level] as $i => $unused) { // entries are references to the $_errors array $this->_errorsByLevel[$level][$i] = false; } // array_filter removes all entries === false $this->_errors = array_filter($this->_errors); unset($this->_errorsByLevel[$level]); return $ret; } $ret = $this->_errors; $this->_errors = array(); $this->_errorsByLevel = array(); return $ret; }
php
{ "resource": "" }
q267489
PEAR_ErrorStack.staticHasErrors
test
function staticHasErrors($package = false, $level = false) { if ($package) { if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { return false; } return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level); } foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { if ($obj->hasErrors($level)) { return true; } } return false; }
php
{ "resource": "" }
q267490
PEAR_ErrorStack.staticGetErrors
test
function staticGetErrors($purge = false, $level = false, $merge = false, $sortfunc = array('PEAR_ErrorStack', '_sortErrors')) { $ret = array(); if (!is_callable($sortfunc)) { $sortfunc = array('PEAR_ErrorStack', '_sortErrors'); } foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level); if ($test) { if ($merge) { $ret = array_merge($ret, $test); } else { $ret[$package] = $test; } } } if ($merge) { usort($ret, $sortfunc); } return $ret; }
php
{ "resource": "" }
q267491
PEAR_ErrorStack.getErrorMessage
test
function getErrorMessage(&$stack, $err, $template = false) { if ($template) { $mainmsg = $template; } else { $mainmsg = $stack->getErrorMessageTemplate($err['code']); } $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg); if (is_array($err['params']) && count($err['params'])) { foreach ($err['params'] as $name => $val) { if (is_array($val)) { // @ is needed in case $val is a multi-dimensional array $val = @implode(', ', $val); } if (is_object($val)) { if (method_exists($val, '__toString')) { $val = $val->__toString(); } else { PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING, 'warning', array('obj' => get_class($val)), 'object %obj% passed into getErrorMessage, but has no __toString() method'); $val = 'Object'; } } $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg); } } return $mainmsg; }
php
{ "resource": "" }
q267492
ContainerBuilder.registerConfiguration
test
public function registerConfiguration(array $configuration): void { foreach ($configuration as $identifier => $value) { $this->container->addEntry($identifier, new MixedEntry($value)); } }
php
{ "resource": "" }
q267493
ContainerBuilder.registerProvider
test
public function registerProvider(EntryProvider $provider): void { $class = \get_class($provider); $this->container->addEntry($class, new CallableEntry([\get_class($provider), 'initialize'])); foreach ($provider->getMethods() as $identifier => $method) { $this->container->addEntry($identifier, new ProviderEntry([$provider, $method])); } }
php
{ "resource": "" }
q267494
ContainerBuilder.registerAutowiredClasses
test
public function registerAutowiredClasses(array $classes, array $overrides = []): void { foreach ($classes as $class) { $reflection = new \ReflectionClass($class); $name = $reflection->getName(); $parameters = $this->getWiredParameters($reflection, $overrides); $this->container->addEntry($name, new WiredEntry($name, $parameters)); } }
php
{ "resource": "" }
q267495
ContainerBuilder.getWiredParameters
test
private function getWiredParameters(\ReflectionClass $reflection, array $overrides): array { $constructor = $reflection->getConstructor(); if (!$constructor instanceof \ReflectionMethod) { return []; } $parameters = []; foreach ($constructor->getParameters() as $parameter) { $name = '$' . $parameter->getName(); if (isset($overrides[$name])) { $parameters[] = $overrides[$name]; continue; } $type = $parameter->getType(); if (!$type instanceof \ReflectionType || $type->isBuiltin()) { throw new \InvalidArgumentException( sprintf("Missing autowired parameter '%s' for '%s'", $name, $reflection->getName()) ); } $parameters[] = $type->getName(); } return $parameters; }
php
{ "resource": "" }
q267496
Zend_Filter_Compress_Tar.setTarget
test
public function setTarget($target) { if (!file_exists(dirname($target))) { throw new Zend_Filter_Exception("The directory '$target' does not exist"); } $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $target); $this->_options['target'] = (string) $target; return $this; }
php
{ "resource": "" }
q267497
Zend_Filter_Compress_Tar.setMode
test
public function setMode($mode) { $mode = ucfirst(strtolower($mode)); if (($mode != 'Bz2') && ($mode != 'Gz')) { throw new Zend_Filter_Exception("The mode '$mode' is unknown"); } if (($mode == 'Bz2') && (!extension_loaded('bz2'))) { throw new Zend_Filter_Exception('This mode needs the bz2 extension'); } if (($mode == 'Gz') && (!extension_loaded('zlib'))) { throw new Zend_Filter_Exception('This mode needs the zlib extension'); } }
php
{ "resource": "" }
q267498
NativeRouteAnnotations.getRoutes
test
public function getRoutes(string ...$classes): array { $routes = $this->getClassRoutes($classes); /** @var \Valkyrja\Routing\Route[] $finalRoutes */ $finalRoutes = []; // Iterate through all the routes foreach ($routes as $route) { // Set the route's properties $this->setRouteProperties($route); $classAnnotations = $this->classAnnotationsType( $this->routeAnnotationType, $route->getClass() ); // If this route's class has annotations if ($classAnnotations) { /** @var Route $annotation */ // Iterate through all the annotations foreach ($classAnnotations as $annotation) { // And set a new route with the controller defined annotation additions $finalRoutes[] = $this->getRouteFromAnnotation( $this->getControllerBuiltRoute($annotation, $route) ); } } else { // Validate the path before setting the route $route->setPath($this->validatePath($route->getPath())); // Otherwise just set the route in the final array $finalRoutes[] = $this->getRouteFromAnnotation($route); } } return $finalRoutes; }
php
{ "resource": "" }
q267499
NativeRouteAnnotations.setRouteProperties
test
protected function setRouteProperties(Route $route): void { if (null === $route->getProperty()) { $methodReflection = $this->getMethodReflection( $route->getClass(), $route->getMethod() ?? '__construct' ); // Set the dependencies $route->setDependencies( $this->getDependencies(...$methodReflection->getParameters()) ); } // Avoid having large arrays in cached routes file $route->setMatches(); if (null === $route->getPath()) { throw new InvalidRoutePath( 'Invalid route name for route : ' . $route->getClass() . '@' . $route->getMethod() ); } }
php
{ "resource": "" }