_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q266800
AuthItem.save
test
public function save() { if ($this->validate() == false) { return false; } if ($isNewItem = ($this->item === null)) { $this->item = $this->createItem($this->name); } else { $oldName = $this->item->name; } $this->item->name = $this->name; $this->item->description = $this->description; if (!empty($this->rule)) { $rule = \Yii::createObject($this->rule); if (null === $this->manager->getRule($rule->name)) { $this->manager->add($rule); } $this->item->ruleName = $rule->name; } else { $this->item->ruleName = null; } if ($isNewItem) { \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been created')); $this->manager->add($this->item); } else { \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been updated')); $this->manager->update($oldName, $this->item); } $this->updateChildren(); return true; }
php
{ "resource": "" }
q266801
Error.toString
test
public function toString(/*boolean*/ $includeFile = false) { $format = true === $includeFile ? '%s #%d (%s): %s in %s(%d)' : '%s #%d (%s): %s'; return sprintf( $format, $this->getType(), $this->getCode(), $this->getMagic(), $this->getMessage(), $this->getFile(), $this->getLine() ); }
php
{ "resource": "" }
q266802
TagConverter.xml
test
public static function xml($original) { $array = self::convert($original); $xml_data = new \SimpleXMLElement('<?xml version="1.0"?><data></data>'); self::arrayToXml($array, $xml_data); return $xml_data->asXML(); }
php
{ "resource": "" }
q266803
TagConverter.convert
test
protected static function convert($original = '') { $array = []; // Only search for tags within header section, if demarcated. $header_split = preg_split('/<End Header>/', $original); preg_match_all("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", $header_split[0], $matches, PREG_SET_ORDER); if (isset($matches[0])) { // Store <TAGNAME: VALUE> strings. foreach ($matches as $key => $values) { $values[2] = trim($values[2]); $multiple_terms = preg_grep('/;/', explode("\n", $values[2])); if (!empty($multiple_terms)) { $terms = preg_split('/;/', $values[2]); foreach ($terms as $i => &$term) { if (empty($term)) { unset($terms[$i]); } $term = (string) trim($term); } } else { $terms = (string) trim($values[2]); } $array[trim($values[1])] = $terms; } } // Remove tags and parse each line into an array element. if (isset($header_split[1])) { $untagged = $header_split[1]; } else { $untagged = preg_replace("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", "", $original); $untagged = str_replace('<End Header>', '', $untagged); } $clean = ''; $lines = preg_split('/((\r?\n)|(\n?\r))/', htmlspecialchars($untagged, ENT_NOQUOTES)); $end = end($lines); foreach ($lines as $key => $line) { if ($line != '') { $clean .= $line; if ($key != $end) { $clean .= PHP_EOL; } } } // Add a new array element, 'text', to the array. If nothing else, the // $array array will now contain the 'text' element with an empty string. $array['text'] = $clean; return $array; }
php
{ "resource": "" }
q266804
Config.load
test
public function load($filename, $merge_globals = true, $stack_name = null, $handler = null) { $file = new \SplFileInfo($filename); if ($file->isFile()) { if (empty($handler)) { $handler = $file->getExtension(); } $factory = \Library\Factory::create() ->factoryName(__CLASS__) ->mustImplement(Kernel::CONFIG_FILETYPE_INTERFACE) ->defaultNamespace(Kernel::CONFIG_FILETYPE_DEFAULT_NAMESPACE) ->classNameMask(array('%s', '%s'.Kernel::CONFIG_FILETYPE_SUFFIX)) ; $config = $factory->build($handler); $values = $config->parse($file); if (!empty($values)) { $this->set($values, $merge_globals, $stack_name); $this->_registerConfigFile($filename, count($values)); } else { $this->_registerConfigFile($filename, 'empty content'); } } else { throw new ErrorException( sprintf('Configuration file "%s" not found!', $filename) ); } return $this; }
php
{ "resource": "" }
q266805
Config.set
test
public function set(array $config, $merge_globals = true, $stack_name = null) { if (!empty($config)) { $config = $this->_buildConfigStack($config); if (!empty($stack_name)) { $this->getRegistry()->loadStack($stack_name); } foreach ($config as $index=>$val) { $this->getRegistry()->setEntry($index, $val); } if (!empty($stack_name)) { $this->getRegistry()->saveStack($stack_name); } } if (!$merge_globals) { return $config; } else { $this->getRegistry()->loadStack(self::$global_config_id); $globals = array_replace_recursive( $this->getRegistry()->dump(), $config ); foreach ($globals as $index=>$val) { $this->getRegistry()->setEntry($index, $val); } $this->getRegistry()->saveStack(self::$global_config_id); return $this; } }
php
{ "resource": "" }
q266806
Config.get
test
public function get($index, $flag = self::NOT_FOUND_GRACEFULLY, $default = null, $stack_name = 'global') { $value = null; if ($stack_name==='global') { $config = $this->getRegistry()->dumpStack(self::$global_config_id); } else { if ($this->getRegistry()->isStack($stack_name)) { $config = $this->getRegistry()->dumpStack($stack_name); } else { if ($flag & self::NOT_FOUND_ERROR) { throw new InvalidArgumentException( sprintf('Unknown configuration stack "%s"!', $stack_name) ); } else { return $default; } } } if (strpos($index, self::$depth_separator_char)!==false) { $depth_index = explode(self::$depth_separator_char, $index); $tmp_conf =& $config; foreach ($depth_index as $count=>$_i) { if (array_key_exists($_i, $tmp_conf)) { $tmp_conf =& $tmp_conf[$_i]; } else { if ($count===0) { $stack_name = array_shift($depth_index); return $this->get( implode(self::$depth_separator_char, $depth_index), $flag, $default, $stack_name ); } $tmp_conf = array(); } } if (!empty($tmp_conf)) { $value = $this->_parseConfig($tmp_conf, $stack_name); } } else { if (array_key_exists($index, $config)) { $value = $this->_parseConfig($config[$index], $stack_name); } } if (!$value) { if ($flag & self::NOT_FOUND_GRACEFULLY) { return $default; } else { throw new InvalidArgumentException( sprintf('Unknown configuration entry "%s"!', $index) ); } } else { return $value; } }
php
{ "resource": "" }
q266807
Config._buildConfigStack
test
protected function _buildConfigStack(array $config_array) { $config = array(); foreach ($config_array as $index=>$val) { $index = $this->_slugify($index); $val = $this->_treatValue($val); if (strpos($index, self::$depth_separator_char)!==false) { $depth_index = explode(self::$depth_separator_char, $index); $tmp_conf =& $config; foreach ($depth_index as $count=>$_i) { if (!array_key_exists($_i, $tmp_conf)) { $tmp_conf[$_i] = array(); } $tmp_conf =& $tmp_conf[$_i]; if ($count===count($depth_index)-1) { $tmp_conf = $val; } } unset($config[$index]); } else { if (is_array($val)) { foreach ($val as $val_index=>$val_val) { if (strpos($val_index, self::$depth_separator_char)!==false) { $val = $this->_buildConfigStack($val); } } } $config[$index] = $val; } } return $config; }
php
{ "resource": "" }
q266808
Config._parseConfig
test
protected function _parseConfig($conf, $stack_name = 'global') { if (is_string($conf)) { $this->_parseConfigRecursive($conf, null, $stack_name); } elseif (is_array($conf)) { array_walk_recursive($conf, array($this, '_parseConfigRecursive'), $stack_name); $conf = array_filter($conf); } return $conf; }
php
{ "resource": "" }
q266809
Config._parseConfigRecursive
test
protected function _parseConfigRecursive(&$value, $key = null, $stack_name = 'global') { if (!is_string($value)) return; // escape any '\%' $hash = 'XH'.uniqid(); $value = str_replace('\%', $hash, $value); // configuration value notation : %name% while (is_string($value) && 0!=preg_match('/^(.*)\%(.*)\%(.*)$/i', $value, $matches) && count($matches)>1) { $_cf = $matches[2]; if ($_cfg_val = $this->get($_cf, self::NOT_FOUND_GRACEFULLY, null, $stack_name)) { if (is_array($_cfg_val)) { $value = $_cfg_val; } else { $value = $matches[1].$_cfg_val.$matches[3]; } } $matches = array(); } // un-escape any '\%' if (is_string($value)) { $value = str_replace($hash, '%', $value); } // configuration stack notation : {name} if (is_string($value) && 0!=preg_match('/^\{(.*)\}$/i', $value, $matches)) { $_cf = $matches[1]; if (substr(trim($_cf), 0, strlen('function'))!=='function') { $_cf = 'function(){ '.$_cf.'; }'; } @eval("\$_cfg_closure = $_cf;"); if ($_cfg_closure && is_callable($_cfg_closure)) { $value = call_user_func($_cfg_closure); } } }
php
{ "resource": "" }
q266810
Grammar.compileJoinConstraint
test
protected function compileJoinConstraint(array $clause) { $firstColumn = $this->wrap($clause['firstColumn']); if ($clause['where']) { if ($clause['operator'] === 'in' || $clause['operator'] === 'not in') { $secondColumn = '('.implode(', ', array_fill(0, $clause['secondColumn'], '?')).')'; } else { $secondColumn = '?'; } } else { $secondColumn = $this->wrap($clause['secondColumn']); } return "{$clause['boolean']} $firstColumn {$clause['operator']} $secondColumn"; }
php
{ "resource": "" }
q266811
Grammar.whereNull
test
protected function whereNull(Builder $query, $where) { $null = $where['not'] ? 'not null' : 'null'; return $this->wrap($where['column']).' is '.$null; }
php
{ "resource": "" }
q266812
Grammar.compileInsert
test
public function compileInsert(Builder $query) { $table = $this->wrap($query->from[0]); $columns = $this->columnize(array_keys(reset($query->inserts))); // We need to build a list of parameter place-holders of values that are bound // to the query. Each insert should have the exact same amount of parameter // bindings so we can just go off the first list of values in this array. $parameters = $this->parameterize(reset($query->inserts)); $value = array_fill(0, count($query->inserts), "($parameters)"); $parameters = implode(', ', $value); return "insert into $table ($columns) values $parameters"; }
php
{ "resource": "" }
q266813
Grammar.compileUpdate
test
public function compileUpdate(Builder $query) { $table = $this->wrap($query->from[0]); // Each one of the columns in the update statements needs to be wrapped in the // keyword identifiers, also a place-holder needs to be created for each of // the values in the list of bindings so we can make the sets statements. $columns = array(); foreach ($query->updates as $key => $value) { $columns[] = $this->wrap($key).' = ?'; } $columns = implode(', ', $columns); $joins = isset($query->joins) ? ' '.$this->compileJoins($query, $query->joins) : ''; // Of course, update queries may also be constrained by where clauses so we'll // need to compile the where clauses and attach it to the query so only the // intended records are updated by the SQL statements we generate to run. $where = $this->compileWheres($query); $sql = trim("update {$table}{$joins} set {$columns} {$where}"); if (isset($query->orders)) { $sql .= ' '.$this->compileOrders($query, $query->orders); } if (isset($query->limit)) { $sql .= ' '.$this->compileLimit($query, $query->limit); } return trim($sql); }
php
{ "resource": "" }
q266814
Grammar.compileDelete
test
public function compileDelete(Builder $query) { $table = $this->wrap($query->from[0]); $where = $this->compileWheres($query); if (isset($query->joins)) { $joins = ' '.$this->compileJoins($query, $query->joins); $sql = trim("delete $table from {$table}{$joins} $where"); } else { $sql = trim("delete from $table $where"); if (isset($query->orders)) { $sql .= ' '.$this->compileOrders($query, $query->orders); } if (isset($query->limit)) { $sql .= ' '.$this->compileLimit($query, $query->limit); } } return $sql; }
php
{ "resource": "" }
q266815
Grammar.wrap
test
private function wrap($value) { if (strpos(strtolower($value), 'null') !== false) { return $value; } // If the value being wrapped has a column alias we will need to separate out // the pieces so we can wrap each of the segments of the expression on it // own, and then joins them both back together with the "as" connector. if (strpos(strtolower($value), ' as ') !== false) { $segments = explode(' ', $value); return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[2]); } $wrapped = array(); $segments = explode('.', $value); // If the value is not an aliased table expression, we'll just wrap it like // normal, so if there is more than one segment, we will wrap the first // segments as if it was a table and the rest as just regular values. foreach ($segments as $key => $segment) { $wrapped[] = $this->wrapValue($segment); } return implode('.', $wrapped); }
php
{ "resource": "" }
q266816
FunctionProphecy.withArguments
test
public function withArguments($arguments) { if (is_array($arguments)) { $arguments = new Argument\ArgumentsWildcard($arguments); } if (!$arguments instanceof Argument\ArgumentsWildcard) { throw new InvalidArgumentException(sprintf( "Either an array or an instance of ArgumentsWildcard expected as\n". 'a `FunctionProphecy::withArguments()` argument, but got %s.', gettype($arguments) )); } $this->argumentsWildcard = $arguments; return $this; }
php
{ "resource": "" }
q266817
FunctionProphecy.will
test
public function will($promise) { if (is_callable($promise)) { $promise = new Promise\CallbackPromise($promise); } if (!$promise instanceof Promise\PromiseInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PromiseInterface, but got %s.', gettype($promise) )); } $this->bind(); $this->promise = $promise; return $this; }
php
{ "resource": "" }
q266818
FunctionProphecy.should
test
public function should($prediction) { if (is_callable($prediction)) { $prediction = new Prediction\CallbackPrediction($prediction); } if (!$prediction instanceof Prediction\PredictionInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PredictionInterface, but got %s.', gettype($prediction) )); } $this->bind(); $this->prediction = $prediction; return $this; }
php
{ "resource": "" }
q266819
FunctionProphecy.shouldHave
test
public function shouldHave($prediction) { if (is_callable($prediction)) { $prediction = new Prediction\CallbackPrediction($prediction); } if (!$prediction instanceof Prediction\PredictionInterface) { throw new InvalidArgumentException(sprintf( 'Expected callable or instance of PredictionInterface, but got %s.', gettype($prediction) )); } if (null === $this->promise) { $this->willReturn(); } $calls = $this->namespaceProphecy->findCalls($this->name, $this->getArgumentsWildcard()); try { $prediction->check($calls, $this); $this->checkedPredictions[] = $prediction; } catch (\Exception $e) { $this->checkedPredictions[] = $prediction; throw $e; } return $this; }
php
{ "resource": "" }
q266820
RestGallery.newGallery
test
public function newGallery(GalleryAdapter $gallery = null) { if (empty($gallery)) { $class = $this->getNamespaceService() . 'Gallery'; $gallery = new $class; } if (! empty($this->plugins)) { array_walk($this->plugins, [$gallery, 'addPlugin']); } return $gallery; }
php
{ "resource": "" }
q266821
RestGallery.connect
test
public static function connect($callback = '') { $instance = new static; $user = $instance->newUser(); if (! empty($callback)) { $instance->clientCredentials['callback'] = $callback; } return $user->connect($instance->clientCredentials); }
php
{ "resource": "" }
q266822
Creator.create
test
public function create($params = array()) { $this->adapter->execute($this->toSql(), array_merge($this->params(), $this->params(true), $params)); return true; }
php
{ "resource": "" }
q266823
Creator.toSql
test
public function toSql() { $table = $this->table(); $values = $this->values(); $quoteChar = $this->quoteChar(); if(is_null($table)){ throw new \Exception("Define table to insert."); } if (empty($this->values)) { throw new \Exception("No values to insert."); } // usuwam rzeczy zwiazane z przetwarzaniem zapytania $this->reset(true); // zliczam ilosc kolumn $count = count($this->columns); // tworze naglowek $scolumns = ""; for ($i=0; $i < $count; $i++) { $column = $this->columns[$i]; $scolumns .= "{$quoteChar}{$column}{$quoteChar}"; if ($i != $count-1) { $scolumns .= ","; } } // values $svalues = ""; $ccount = count($this->columns); $vcount = count($this->values); for ($i=0; $i < $vcount; $i++) { // pobieram wszystkie wartosci $values = $this->values[$i]; // pobieram klucze $keys = array_keys($values); // zmienna przetrzymuje wartosci dla VALUES w insercie $svalues .= "("; for ($j=0; $j < $ccount; $j++) { // nazwa kolumny $column = $this->columns[$j]; if (!in_array($column, $keys)) { throw new \Exception("Incorrect values to insert."); } // pobieram wartosc kolumny $value = $values[$column]; $direct = false; if (is_int($value)) { $value = (int)$value; $direct = true; } if (is_float($value)) { $value = (float)$value; $direct = true; } if (is_null($value)) { $value = "null"; $direct = true; } if ($direct) { $svalues .= "{$value}"; }else{ $uId = \Labi\Database\Utility\Uid::uId(); $svalues .= ":$uId"; $this->param($uId, $value, true); } if ($j !== $ccount-1) { $svalues .= ","; } } $svalues .= ")"; if ($i !== $vcount-1) { $svalues .= ","; } } // budowanie insertu $sql = "insert into {$quoteChar}{$table}{$quoteChar} ({$scolumns}) VALUES {$svalues}"; return $sql; }
php
{ "resource": "" }
q266824
ResourceScanner.scan
test
public function scan(GenericResource $resource, $content) { // Match all URL references. preg_match_all(self::PATH_PATTERN, $content, $matches); foreach ($matches[1] as $path) { try { $this->queue->add(new GenericResource($resource->resolvePath($path))); } catch (\InvalidArgumentException $e) { // Ignore unrecognized paths. } } }
php
{ "resource": "" }
q266825
Some.flatMap
test
public function flatMap($flatMapper) { if (!is_callable($flatMapper)) { throw new Exception("Can't call Some#flatMap with a non callable."); } $flatMapped = $flatMapper($this->_value); if (!($flatMapped instanceof Option)) { throw new Exception( "Function passed to Some#flatMap must retrun Option" ); } return $flatMapped; }
php
{ "resource": "" }
q266826
Some.filter
test
public function filter($predicate) { if (!is_callable($predicate)) { throw new Exception("Can't call Some#filter with a non callable."); } if ($predicate($this->_value)) { return $this; } else { return new None(); } }
php
{ "resource": "" }
q266827
Callback._executeCallbackStack
test
protected function _executeCallbackStack() { if (!empty($this->callback_stack)) { $_meth = '_executeCallbackAs'.ucfirst($this->callback_response_type); foreach ($this->callback_stack as $_callback) { $response = $this->$_meth( $_callback, $this->value ); } return $response; } return null; }
php
{ "resource": "" }
q266828
Callback._executeCallbackAsReference
test
protected function _executeCallbackAsReference($fct, &$entry_value) { list($fct_name, $args) = $this->_parseCallbackFunctionName($fct); array_unshift($args, $entry_value); $entry_value = $this->_executeCallback($fct_name, $args); return $entry_value; }
php
{ "resource": "" }
q266829
Callback._parseCallbackFunctionName
test
protected function _parseCallbackFunctionName($fct) { $fct_name = $fct; $args = array(); // case "fct_name(arg1,arg2)" if (0!=preg_match('/^ ([^\(]+) # the function name \( # the opening parenthesis of arguments (?: ([^\)]+) # anything but a coma ){1,} # 1 or more times \) # the closing parenthesis of arguments $/xi', $fct, $matches)) { $fct_name = $matches[1]; $args = explode(',', $matches[2]); } return array($fct_name, $args); }
php
{ "resource": "" }
q266830
CroppableType.getConstraints
test
public function getConstraints($options) { $constraints = array(); if ($options['validate']) { $constraints[] = new Image(array( 'mimeTypes' => array( 'image/gif', 'image/png', 'image/jpg', 'image/jpeg' ), 'minWidth' => $this->calcMin('width', $options), 'minHeight' => $this->calcMin('height', $options) )); } return $constraints; }
php
{ "resource": "" }
q266831
CroppableType.calcMin
test
public function calcMin($option, array $options) { $min = (isset($options[$option]) ? (int)$options[$option] : 0); if (isset($options['instances']) && is_array($options['instances'])) { foreach ($options['instances'] as $instance) { $value = (isset($instance[$option]) ? (int)$instance[$option] : 0); if ($value > $min) { $min = $value; } } } return $min; }
php
{ "resource": "" }
q266832
Route.getController
test
public function getController() { if (!isset($this->_controller)) { $data = $this->_dispatchedData; if (isset($data[1]) && $data[1] instanceof ControllerInterface) { $this->_controller = $data[1]; } } return $this->_controller; }
php
{ "resource": "" }
q266833
Route.getAction
test
public function getAction() { if (!isset($this->_action)) { $data = $this->_dispatchedData; if (isset($data[2]) && is_string($data[2])) { $this->_action = $data[2]; } } return $this->_action; }
php
{ "resource": "" }
q266834
Route.resolve
test
public function resolve() { $callable = [$this->_controller, $this->_controllerMethod]; $args = $this->_params; array_unshift($args, $this->app, $this->_action); $promise = new Promise(function($r) use ($callable, $args) { $result = call_user_func_array($callable, $args); $r($result); }); return $promise->then( function($response) { return $this->processResponse($response); } ); }
php
{ "resource": "" }
q266835
Route.processDispatchedData
test
protected function processDispatchedData() { list($code, $controller, $action, $params) = $this->_dispatchedData; if ($code === RouterInterface::ERROR_OK) { $this->_controllerMethod = static::CONTROLLER_RESOLVE_ACTION; $this->_controller = $controller; $this->_action = $action; $this->_params = $this->_paramsClean = $params; //Overwrite query parameters if (ArrayHelper::isAssociative($this->_params)) { $queryParams = ArrayHelper::merge($this->app->reqHelper->getQueryParams(), $this->_params); $this->app->reqHelper->setQueryParams($queryParams); } } else { $exception = $this->getRouterException($code); throw $exception; } }
php
{ "resource": "" }
q266836
Route.processResponse
test
protected function processResponse($response) { if ($response instanceof ResponseInterface) { return $response; } if ($response instanceof ResponseBuilderInterface) { return $response->build(); } //Do not throw error on console app if (Reaction::isConsoleApp()) { return $response; } $type = is_object($response) ? get_class($response) : gettype($response); $message = sprintf('Return value must be instance of "%s", but "%s" given', ResponseInterface::class, $type); throw new InvalidArgumentException($message); }
php
{ "resource": "" }
q266837
Route.getRouterException
test
protected function getRouterException($code) { $errors = [ RouterInterface::ERROR_NOT_FOUND => NotFoundException::class, RouterInterface::ERROR_METHOD_NOT_ALLOWED => MethodNotAllowedException::class, '*' => NotSupportedException::class, ]; $errorClass = isset($errors[$code]) ? $errors[$code] : $errors['*']; try { $exception = Reaction::create($errorClass); } catch (InvalidConfigException $createException) { return $createException; } return $exception; }
php
{ "resource": "" }
q266838
System.getTerminalSizes
test
public static function getTerminalSizes() { if (self::getOperatingSystem()->equals(OS::WINDOWS) || self::getOperatingSystem()->equals(OS::UNKNOWN)) { return ['width' => 100, 'height' => 100]; } preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output); if (sizeof($output) == 3) { return [ "height" => @$output[1][0], "width" => @$output[2][0] ]; } else { return [ "width" => 100, "height" => 100 ]; } }
php
{ "resource": "" }
q266839
System.getOperatingSystem
test
public static function getOperatingSystem() { if (is_null(self::$operatingSystem)) { $name = strtolower(php_uname()); $operatingSystem = OS::UNKNOWN; if (strpos($name, 'darwin') !== false) { $operatingSystem = OS::DARWIN; } elseif (strpos($name, 'win') !== false) { $operatingSystem = OS::WINDOWS; } elseif (strpos($name, 'linux') !== false) { $operatingSystem = OS::LINUX; } self::$operatingSystem = new OS($operatingSystem); } return self::$operatingSystem; }
php
{ "resource": "" }
q266840
CarteBlanche.trans
test
public static function trans($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null) { $i18n = self::getContainer()->get('i18n'); if (is_object($arg1) && ($arg1 instanceof \DateTime)) { if (empty($i18n)) { return $arg1->format( !empty($arg2) ? $arg2 : 'Y-m-d H:i:s'); } return \I18n\I18n::getLocalizedDateString($arg1, $arg2, $arg3, $arg4); } elseif (is_array($arg1)) { if (empty($i18n)) { return isset($arg1[$arg2]) ? $arg1[$arg2] : array_shift($arg1); } return \I18n\I18n::pluralize($arg1, $arg2, $arg3, $arg4); } elseif (is_string($arg1)) { if ($arg1==='number') { if (empty($i18n)) { return $arg2; } return \I18n\I18n::getLocalizedNumberString($arg2, $arg3); } elseif($arg1==='price') { if (empty($i18n)) { return $arg2; } return \I18n\I18n::getLocalizedPriceString($arg2, $arg3); } else { if (empty($i18n)) { return $arg1; } return \I18n\I18n::translate($arg1, $arg2, $arg3); } } else { return null; } }
php
{ "resource": "" }
q266841
CarteBlanche.locate
test
public static function locate($filename, $type = null) { $locator = self::getContainer()->get('locator'); switch ($type) { case 'data': return $locator->locateData($filename); break; case 'config': return $locator->locateConfig($filename, true); break; case 'language': case 'i18n': return $locator->locateLanguage($filename, true); break; case 'view': return $locator->locateView($filename, true); break; case 'controller': return $locator->locateController($filename); break; default: return $locator->locate($filename); break; } }
php
{ "resource": "" }
q266842
Formatter.asText
test
public function asText($value, $encoding = null) { if ($value === null) { return $this->nullDisplay; } return Html::encode($value, true, $encoding); }
php
{ "resource": "" }
q266843
Formatter.asEmail
test
public function asEmail($value, $options = [], $encoding = null) { if ($value === null) { return $this->nullDisplay; } return Html::mailto(Html::encode($value, true, $encoding), $value, $options); }
php
{ "resource": "" }
q266844
Formatter.asDecimal
test
public function asDecimal($value, $decimals = null, $options = [], $textOptions = []) { if ($value === null) { return $this->nullDisplay; } $value = $this->normalizeNumericValue($value); if ($this->_intlLoaded) { $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions); if (($result = $f->format($value)) === false) { throw new InvalidArgumentException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); } return $result; } if ($decimals === null) { $decimals = 2; } return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator); }
php
{ "resource": "" }
q266845
Formatter.asShortSize
test
public function asShortSize($value, $decimals = null, $options = [], $textOptions = []) { if ($value === null) { return $this->nullDisplay; } list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions); if ($this->sizeFormatBase == 1024) { switch ($position) { case 0: return Reaction::t('rct', '{nFormatted} B', $params, $this->locale); case 1: return Reaction::t('rct', '{nFormatted} KiB', $params, $this->locale); case 2: return Reaction::t('rct', '{nFormatted} MiB', $params, $this->locale); case 3: return Reaction::t('rct', '{nFormatted} GiB', $params, $this->locale); case 4: return Reaction::t('rct', '{nFormatted} TiB', $params, $this->locale); default: return Reaction::t('rct', '{nFormatted} PiB', $params, $this->locale); } } else { switch ($position) { case 0: return Reaction::t('rct', '{nFormatted} B', $params, $this->locale); case 1: return Reaction::t('rct', '{nFormatted} KB', $params, $this->locale); case 2: return Reaction::t('rct', '{nFormatted} MB', $params, $this->locale); case 3: return Reaction::t('rct', '{nFormatted} GB', $params, $this->locale); case 4: return Reaction::t('rct', '{nFormatted} TB', $params, $this->locale); default: return Reaction::t('rct', '{nFormatted} PB', $params, $this->locale); } } }
php
{ "resource": "" }
q266846
ItemControllerAbstract.actionCreate
test
public function actionCreate() { /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */ $model = \Yii::createObject([ 'class' => $this->modelClass, 'scenario' => 'create', ]); $this->performAjaxValidation($model); if ($model->load(\Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index']); } return $this->render('create', [ 'model' => $model, ]); }
php
{ "resource": "" }
q266847
ItemControllerAbstract.actionUpdate
test
public function actionUpdate($name) { /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */ $item = $this->getItem($name); $model = \Yii::createObject([ 'class' => $this->modelClass, 'scenario' => 'update', 'item' => $item, ]); $this->performAjaxValidation($model); if ($model->load(\Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index']); } return $this->render('update', [ 'model' => $model, ]); }
php
{ "resource": "" }
q266848
Classfile.exists
test
public function exists(): bool { // convert namespace into path $class = str_replace('\\', '/', $this->classname); // append .php? if (strpos($class, '.php') === false) { $class .= '.php'; } $class = $this->replaceDirectorySeperator($class); if (!empty($this->basedir)) { $class = $this->basedir .= DIRECTORY_SEPARATOR; } return file_exists($class); }
php
{ "resource": "" }
q266849
DB.fetchObject
test
public function fetchObject($query, array $values, $instance, $fetchMode = PDO::FETCH_INTO) { $obj = null; try { $statement = $this->pdo->prepare($query); $statement->setFetchMode($fetchMode, $instance); if ($statement->execute($values)) { $obj = $statement->fetch($fetchMode); if (!$obj) return null; } else { $errorInfo = $statement->errorInfo(); error_log($errorInfo[2]); } } catch (PDOException $e) { error_log($e->getMessage()); } return $obj; }
php
{ "resource": "" }
q266850
DB.fetchColumn
test
public function fetchColumn($query, array $values) { $col = null; try { $statement = $this->pdo->prepare($query); if ($statement->execute($values)) { $col = $statement->fetchColumn(); if (!$col) return null; } else { $errorInfo = $statement->errorInfo(); error_log($errorInfo[2]); } } catch (PDOException $e) { error_log($e->getMessage()); } return $col; }
php
{ "resource": "" }
q266851
SoftDeletes.scopeExcludeTrashed
test
protected function scopeExcludeTrashed(QueryBuilder $query) { $time = new DateTime(); return $query ->andWhere('o.deletedAt is NULL') ->orWhere('o.deletedAt > :currentTimestamp') ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s')); }
php
{ "resource": "" }
q266852
SoftDeletes.scopeOnlyTrashed
test
protected function scopeOnlyTrashed(QueryBuilder $query) { $time = new DateTime(); return $query ->andWhere('o.deletedAt is not NULL') ->andWhere(':currentTimestamp > o.deletedAt') ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s')); }
php
{ "resource": "" }
q266853
StaticApplicationConsole.runConsoleRequest
test
public function runConsoleRequest() { $promise = resolve(true); //Delayed stop $loopStop = function() { $this->loop->addTimer(0.5, function() { $this->loop->stop(); }); }; $promise->then( function() { return $this->processRequest($this->createRequest()); } )->then( function($response = null) { if ($response instanceof Response) { $body = $response->getBody(); if (is_object($body) && method_exists($body, '__toString')) { $body = (string)$body; } return $body; } return $response; } )->done(function($result = null) use ($loopStop) { if (is_string($result)) { $this->logger->logRaw($result); } $loopStop(); }, function($error) use ($loopStop) { \Reaction::error($error); $loopStop(); }); }
php
{ "resource": "" }
q266854
ArrayUtil.getUnset
test
public static function getUnset (&$arr, $key, $default = null) { $value = isset($arr[$key]) ? $arr[$key] : $default; if (isset($arr[$key])) unset($arr[$key]); return $value; }
php
{ "resource": "" }
q266855
Message.getHeader
test
public function getHeader($name) { $headers = []; $name = strtolower((string)$name); foreach ($this->headers as $k => $v) { if ($name == strtolower($k)) { $headers = array_merge($headers, $v); } } return array_unique($headers); }
php
{ "resource": "" }
q266856
Message.withoutHeader
test
public function withoutHeader($name) { $message = clone $this; $name = strtolower((string)$name); foreach (array_keys($message->headers) as $k) { if ($name == strtolower($k)) { unset($message->headers[$k]); } } return $message; }
php
{ "resource": "" }
q266857
Message.withBody
test
public function withBody(StreamInterface $body) { if (false) { // Body is forced to a StreamInterface in parameters. // How can it be invalid ? throw new InvalidArgumentException('Body is not valid.'); } $message = clone $this; $message->stream = $body; return $message; }
php
{ "resource": "" }
q266858
Type.getIcon
test
public function getIcon($isNegativeAmount = true) { switch ($this->getType()) { case self::CB: $icon = 'credit-card'; break; case self::VIR: $icon = 'arrow-circle-o-' . ($isNegativeAmount ? 'up' : 'down'); break; case self::PRE: $icon = 'arrow-circle-up'; break; case self::CHQ: $icon = 'money'; break; case self::PPL: $icon = 'paypal'; break; default: $icon = 'money'; } return $icon; }
php
{ "resource": "" }
q266859
Type.getAllTypes
test
public static function getAllTypes() { $list = array( self::CB, self::VIR, self::PRE, self::PPL, self::CHQ, ); $types = array(); foreach ($list as $value) { $types[$value] = new self($value); } return $types; }
php
{ "resource": "" }
q266860
Tailor.bind
test
public function bind(string $alias, string $template, array $params = []): void { $this->bindCallback($alias, function(Generator $generator) use($template, $params): void { $compiled = $generator->generate($template, $params); $generator->includeFile($compiled); }); }
php
{ "resource": "" }
q266861
ErrorHandler.renderException
test
protected function renderException($exception) { if ($exception instanceof UnknownCommandException) { // display message and suggest alternatives in case of unknown command $message = $this->formatMessage($exception->getName() . ': ') . $exception->command; $alternatives = $exception->getSuggestedAlternatives(); if (count($alternatives) === 1) { $message .= "\n\nDid you mean \"" . reset($alternatives) . '"?'; } elseif (count($alternatives) > 1) { $message .= "\n\nDid you mean one of these?\n - " . implode("\n - ", $alternatives); } } elseif ($exception instanceof Exception && ($exception instanceof UserException || !Reaction::isDebug())) { $message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage(); } elseif (Reaction::isDebug()) { if ($exception instanceof Exception) { $message = $this->formatMessage("Exception ({$exception->getName()})"); } elseif ($exception instanceof ErrorException) { $message = $this->formatMessage($exception->getName()); } else { $message = $this->formatMessage('Exception'); } $message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE]) . ' with message ' . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n" . "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD]) . ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n"; $trace = static::getExceptionTrace($exception, true); //$trace = $exception->getTraceAsString(); $message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $trace; } else { $message = $this->formatMessage('Error: ') . $exception->getMessage(); } if (Reaction::isConsoleApp()) { Console::stderr($message . "\n"); } else { echo $message . "\n"; } }
php
{ "resource": "" }
q266862
ErrorHandler.formatMessage
test
protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD]) { $stream = Reaction::isConsoleApp() ? \STDERR : \STDOUT; // try controller first to allow check for --color switch if (Reaction::isConsoleApp() && Console::streamSupportsAnsiColors($stream)) { $message = Console::ansiFormat($message, $format); } return $message; }
php
{ "resource": "" }
q266863
Cookie.getForHeader
test
public function getForHeader($validationKey = null) { if ($this->expire != 1 && isset($validationKey)) { $value = \Reaction::$app->security->hashData(serialize([$this->name, $this->value]), $validationKey); } $value = isset($value) && $value !== "" ? urlencode($value) : ''; $name = urlencode($this->name); $data = [ 'Secure' => $this->secure ? null : '', 'HttpOnly' => $this->httpOnly ? null : '', 'Domain' => isset($this->domain) ? $this->domain : '', 'Path' => isset($this->path) ? $this->path : '', 'Expires' => !empty($this->expire) ? gmdate('D, d M Y H:i:s T', $this->expire) : '', ]; foreach ($data as $key => $val) { if ($val === '') { unset($data[$key]); } } $data = ArrayHelper::merge([$name => $value], $data); return $this->convertArrayToHeaderString($data); }
php
{ "resource": "" }
q266864
Cookie.convertArrayToHeaderString
test
protected function convertArrayToHeaderString(array $data) { $strings = []; foreach ($data as $key => $val) { if (null === $val) { $strings[] = $key; continue; } if (is_bool($val)) { $val = !empty($val) ? 1 : 0; } $strings[] = $key . '=' . $val; } return implode('; ', $strings); }
php
{ "resource": "" }
q266865
Config.combine
test
protected function combine($array, $section_sep) { foreach ($array as $section_spec => $settings) { $section_spec = array_map("trim", explode($section_sep, $section_spec)); if (count($section_spec) > 1) { $sections[$section_spec[0]] = array_merge( $sections[$section_spec[1]], $settings ); } else { $sections[$section_spec[0]] = $settings; } } return $sections; }
php
{ "resource": "" }
q266866
Config.walk
test
protected function walk(&$ptr, $key, $val, $key_sep) { foreach (explode($key_sep, $key) as $sub) { $ptr = &$ptr[$sub]; } $ptr = $val; }
php
{ "resource": "" }
q266867
StringHelper.explode
test
public function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false) { return $this->proxy(__FUNCTION__, [$string, $delimiter, $trim, $skipEmpty]); }
php
{ "resource": "" }
q266868
ErrorController.reportAction
test
public function reportAction($code = null) { $referer = $this->getContainer()->get('router')->getReferer(); $txt_message = $this->view( 'error_mail_content', array( 'url'=>$referer, 'code'=>$code ) ); $webmaster_email = CarteBlanche::getConfig('app.webmaster_email', null); $webmaster_name = CarteBlanche::getConfig('app.webmaster_name', null); $mail = new \MimeEmail\Lib\MimeEmail(); $mail ->setTo($webmaster_email, $webmaster_name) ->setSubject($this->trans('Error report')) ->setText($txt_message); $ok = $mail->send(true); if ($ok) { $this->getContainer()->get('session') ->setFlash("info:".$this->trans('OK - A report has been sent concerning your error. Thank you.')); } else { $this->getContainer()->get('session') ->setFlash("error:".$this->trans('ERROR - An error occurred while trying to send email ...')); } $this->getContainer()->get('router')->redirect($_SERVER['HTTP_REFERER']); }
php
{ "resource": "" }
q266869
ErrorController.error403Action
test
public function error403Action() { $this->getContainer()->get('router')->setReferer(); $_args=array( 'offset'=>null,'limit'=>null,'table'=>null,'altdb'=>null, 'orderby'=>null, 'orderway'=>null ); $url_args = CarteBlanche::getConfig('routing.arguments_mapping'); foreach ($_args as $_arg_var=>$_arg_val) { if (!empty($_arg_val)) { if (in_array($_arg_var, $url_args)) $args[ array_search($_arg_var, $url_args) ] = $_arg_val; else $args[ $_arg_var ] = $_arg_val; } } $searchbox = new \Tool\SearchBox(array( 'hiddens'=>$_args, 'advanced_search'=>true )); $ctt = (string) $searchbox; $_f = CarteBlanche::getContainer()->get('locator')->locateView(self::$views_dir.'403.md'); $_txt = new \Tool\Text(array( // 'original_str'=>file_get_contents(CarteBlanche::getPath('root_path')._CarteBlanche_DIR._VIEWSDIR.self::$views_dir.'404.md'), 'original_str'=>file_get_contents($_f), 'markdown'=>true, )); $ctt .= $_txt; $params = array( 'title'=>$this->trans('OOPS ! You can\'t access this page !!'), 'content'=>$ctt, 'sitemap_url'=>CarteBlanche::getContainer()->get('router')->buildUrl(array( 'controller'=>'cms','action'=>'sitemap' )), 'report_error'=>CarteBlanche::getContainer()->get('router')->buildUrl(array( 'controller'=>'error','action'=>'report','code'=>'403' )) ); $params['output'] = CarteBlanche::getContainer()->get('front_controller') ->view(self::$views_dir.'error', $params); return CarteBlanche::getContainer()->get('front_controller')->render($params); }
php
{ "resource": "" }
q266870
Route.extractParameters
test
public function extractParameters(string $path): array { if ($this->routeParameters === []) { return []; } $parameters = []; $pathArray = explode('/', $path); array_shift($pathArray); foreach ($this->routeParameters as $index => $parameter) { $parameterAction = $this->routeParametersOptions[$parameter] ?? function (string $parameter): string { return $parameter; }; $parameters[$parameter] = $parameterAction($pathArray[$index]); } return $parameters; }
php
{ "resource": "" }
q266871
ControllerResolver.getController
test
public function getController() { $params = $this->requestDataReader->getRequestData()->getParameters(); $controllerName = $this->appConfig->getDefaultInteractor(); if (isset($params['interactor'])) { $controllerName = $params['interactor']; }; $controllerArrayKey = $controllerName.'Controller'; if (!array_key_exists($controllerArrayKey, $this->controllerFactories)) { throw new ControllerNotFoundException('Controller \''.$controllerName.'\' not found.'); } return $this->controllerFactories[$controllerArrayKey]->createInstance(); }
php
{ "resource": "" }
q266872
GridView._getButtons
test
private function _getButtons($buttons, $row) { $html = ''; foreach($buttons as $value) { if(isset($value['audit']) && $value['audit']($row) == 0) { continue; } $tmp='<a href="'; if(isset($value['url'])) { $tmp .= $this->evaluateExpression($value['url'], array('data'=>$row)); } elseif(isset($value['action'])) { $value['options']['class']='gridview-'.$value['action']; $tmp.=url().'/'.$this->controller->id.'/'.$value['action'].'?id='.$row['id'].'&from='.urlencode($_SERVER['REQUEST_URI']); } $tmp .= '"'; if (isset($value['options']) && is_array($value['options']) && !empty($value['options'])) { $tmp.=$this->_getOptions($value['options']); } $tmp.='">'.$value['name'].'</a>&nbsp;&nbsp;'; $html.=$tmp; } return $html; }
php
{ "resource": "" }
q266873
GridView._getOptions
test
private function _getOptions($options) { $optionsHtml=''; if (!empty($options)) { if(is_array($options)) { foreach($options as $key => $value) { $optionsHtml.=' '.$key.'="'.$value.'"'; } } else { $optionsHtml=' class="'.$options.'"'; } } return $optionsHtml; }
php
{ "resource": "" }
q266874
GridView.evaluateExpression
test
public function evaluateExpression($_expression_, $_data_) { // debug($_data_); // debug($_expression_); // die; if (is_string($_expression_)) { extract($_data_); return eval('return '.$_expression_.';'); } else { $_data_[]=$this; return call_user_func_array($_expression_, $_data_); } }
php
{ "resource": "" }
q266875
BIND.getZone
test
public function getZone(String $zone) { $this->path = "zone/" . $zone; $response = $this->request(); return new Zone($response); }
php
{ "resource": "" }
q266876
BIND.addRecord
test
public function addRecord(String $domain, int $ttl, String $recordType, String $value) { return $this->manage($domain, $ttl, $recordType, $value); }
php
{ "resource": "" }
q266877
TableManager.table
test
public function table($table_name) { if (!is_string($table_name)) { throw new Exception\InvalidArgumentException(__METHOD__ . ": Table name must be a string"); } if (!$this->localTableCache->offsetExists($table_name)) { $tables = $this->metadata()->getTables(); if (!in_array($table_name, $tables)) { throw new Exception\TableNotFoundException(__METHOD__ . ": Table $table_name is not found in database, if table exists please make sure cache is updated."); } $table = new Table($table_name, $this); $this->localTableCache->offsetSet($table_name, $table); } return $this->localTableCache->offsetGet($table_name); }
php
{ "resource": "" }
q266878
TableManager.transaction
test
public function transaction() { if ($this->transaction === null) { $this->transaction = new Transaction($this->adapter); } return $this->transaction; }
php
{ "resource": "" }
q266879
TableManager.loadDefaultMetadata
test
protected function loadDefaultMetadata() { $adapterName = $this->adapter->getPlatform()->getName(); switch (strtolower($adapterName)) { case 'mysql': // supported break; default: throw new Exception\UnsupportedFeatureException(__METHOD__ . ": Adapter '$adapterName' is not yet supported."); } $this->metadata = $this->driver->getMetadata(); }
php
{ "resource": "" }
q266880
CategoryAbstract.setParentId
test
public function setParentId($parentId) { $parentId = (int) $parentId; if ($this->parentId < 0) { throw new \UnderflowException('Value of "parentId" must be greater than 0'); } if ($this->exists() && $this->parentId !== $parentId) { $this->updated['parentId'] = true; } $this->parentId = $parentId; return $this; }
php
{ "resource": "" }
q266881
CategoryAbstract.getBudgetCategory
test
public function getBudgetCategory($isForceReload = false) { if ($isForceReload || null === $this->joinOneCacheBudgetCategory) { $mapper = new BudgetCategoryMapper($this->dependencyContainer->getDatabase('money')); $this->joinOneCacheBudgetCategory = $mapper->findByKeys(array( 'category_id' => $this->getId(), )); } return $this->joinOneCacheBudgetCategory; }
php
{ "resource": "" }
q266882
CategoryAbstract.getAllCategoryWord
test
public function getAllCategoryWord($isForceReload = false) { if ($isForceReload || null === $this->joinManyCacheCategoryWord) { $mapper = new CategoryWordMapper($this->dependencyContainer->getDatabase('money')); $mapper->addWhere('category_id', $this->getId()); $this->joinManyCacheCategoryWord = $mapper->select(); } return $this->joinManyCacheCategoryWord; }
php
{ "resource": "" }
q266883
Assistant.flushCache
test
public function flushCache() { foreach ($this->tags as $tag) { $this->_removeCacheDatas($tag); } $this->items = []; return $this; }
php
{ "resource": "" }
q266884
Assistant.add
test
public function add(string $key) { foreach ($this->items as &$items) { array_push($items, $key); } return $this; }
php
{ "resource": "" }
q266885
Assistant.remove
test
public function remove(string $key) { foreach ($this->items as &$items) { if ($pos = array_search($key, $items)) { array_splice($items, $pos, 1); } } return $this; }
php
{ "resource": "" }
q266886
Assistant._removeCacheDatas
test
private function _removeCacheDatas($tag) { // 删除缓存的数据 $this->manager->deleteMultiple($this->items[$tag]); $key = $this->normalizeTagForKey($tag); // 删除缓存键 $this->manager->delete($key); // 删除数据库存储的键 try { Entity::where('key', '=', $key)->delete(); } catch (\Exception $e) { if ($this->manager->debug()) { throw $e; } else { $logger = $this->manager->logger(); if ($logger) { $logger->warning($e->getMessage(), ['tag' => $tag, 'key' => $key]); } } } return $this; }
php
{ "resource": "" }
q266887
Params.getBoolean
test
public function getBoolean($key, $default = null) { $value = $this->get($key, $default); if (is_numeric($value)) { $value = intval($value); } elseif (is_string($value)) { $value = strtolower($value) == 'true' ? true : false; } return $value ? true : false; }
php
{ "resource": "" }
q266888
Params.create
test
public static function create($params = null, Request $request = null) { if ($params === null) { return new Params(); } elseif (is_array($params)) { return new Params($params); } elseif ($params instanceof \Traversable) { return new Params(self::extractParamsFromCollection($params)); } elseif ($params instanceof \Zend\Mvc\Controller\Plugin\Params) { $results = array(); /* @var $r \Zend\Http\Request */ foreach (array( $params->fromQuery(), $params->fromPost(), self::getBodyData($request), $params->fromRoute(), $params->fromFiles(), ) as $collection) { $results = array_merge($results, $collection); } return new Params($results); } elseif ($params instanceof Param) { return new Params($params->get()); } throw new \InvalidArgumentException("Unrecognized parameter collection"); }
php
{ "resource": "" }
q266889
Params.extractParamsFromCollection
test
public static function extractParamsFromCollection($collection) { $result = array(); foreach ($collection as $key => $value) { $result[$key] = $value; } return $result; }
php
{ "resource": "" }
q266890
LoggerListener.onConsoleCommandLoaded
test
public function onConsoleCommandLoaded(ConsoleEvent $event) { $command = $event->getCommand(); $command->getApplication()->getContainer()['monolog']->addInfo( sprintf( 'Command \'%s\' Loaded as \'%s\'', get_class($command), $command->getName() ) ); }
php
{ "resource": "" }
q266891
Router.pushGroup
test
public function pushGroup($pattern, $callable) { $group = new Group($pattern, $callable); array_push($this->routeGroups, $group); return $group; }
php
{ "resource": "" }
q266892
NativeContainerAnnotations.getAllClassesAnnotationsByType
test
protected function getAllClassesAnnotationsByType(string $type, string ...$classes): array { $annotations = []; // Iterate through all the classes foreach ($classes as $class) { // Get all the annotations for each class and iterate through them /** @var \Valkyrja\Annotations\Annotation $annotation */ foreach ($this->classAndMembersAnnotationsType( $type, $class ) as $annotation) { $this->setServiceProperties($annotation); // If this annotation is a service if ($type === $this->servicesAnnotationType) { /* @var \Valkyrja\Container\Annotations\Service $annotation */ $annotations[] = $this->getServiceFromAnnotation($annotation); continue; } // If this annotation is a context service if ($type === $this->contextServicesAnnotationType) { /* @var \Valkyrja\Container\Annotations\ServiceContext $annotation */ $annotations[] = $this->getServiceContextFromAnnotation($annotation); continue; } // Set the annotation in the annotations list $annotations[] = $annotation; } } return $annotations; }
php
{ "resource": "" }
q266893
NativeContainerAnnotations.setServiceProperties
test
protected function setServiceProperties(Annotation $annotation): void { if (null === $annotation->getProperty()) { $parameters = $this->getMethodReflection( $annotation->getClass(), $annotation->getMethod() ?? '__construct' ) ->getParameters(); // Set the dependencies $annotation->setDependencies( $this->getDependencies(...$parameters) ); } $annotation->setMatches(); }
php
{ "resource": "" }
q266894
NativeContainerAnnotations.getServiceFromAnnotation
test
protected function getServiceFromAnnotation(Service $service): ContainerService { $containerService = new ContainerService(); $containerService ->setDefaults($service->getDefaults()) ->setSingleton($service->isSingleton()) ->setId($service->getId()) ->setName($service->getName()) ->setClass($service->getClass()) ->setProperty($service->getProperty()) ->setMethod($service->getMethod()) ->setStatic($service->isStatic()) ->setFunction($service->getFunction()) ->setMatches($service->getMatches()) ->setDependencies($service->getDependencies()) ->setArguments($service->getArguments()); return $containerService; }
php
{ "resource": "" }
q266895
NativeContainerAnnotations.getServiceContextFromAnnotation
test
protected function getServiceContextFromAnnotation(ServiceContext $service): ContainerContextService { $containerService = new ContainerContextService(); $containerService ->setContextClass($service->getContextClass()) ->setContextProperty($service->getContextProperty()) ->setContextMethod($service->getContextMethod()) ->setContextFunction($service->getContextFunction()) ->setDefaults($service->getDefaults()) ->setSingleton($service->isSingleton()) ->setId($service->getId()) ->setName($service->getName()) ->setClass($service->getClass()) ->setProperty($service->getProperty()) ->setMethod($service->getMethod()) ->setStatic($service->isStatic()) ->setFunction($service->getFunction()) ->setMatches($service->getMatches()) ->setDependencies($service->getDependencies()) ->setArguments($service->getArguments()); return $containerService; }
php
{ "resource": "" }
q266896
Database.getCache
test
public function getCache() { if (!isset($this->_cache) && isset($this->cacheComponent)) { if ($this->cacheComponent instanceof ExtendedCacheInterface) { $this->_cache = $this->cacheComponent; } else { $this->_cache = \Reaction::create($this->cacheComponent); } } return $this->_cache; }
php
{ "resource": "" }
q266897
Database.getQueryBuilder
test
public function getQueryBuilder() { if (!isset($this->_queryBuilder)) { /** @var QueryBuilderInterface $queryBuilder */ $queryBuilder = $this->createComponent(QueryBuilderInterface::class); $this->_queryBuilder = $queryBuilder; } return $this->_queryBuilder; }
php
{ "resource": "" }
q266898
Database.createComponent
test
protected function createComponent($interface, $config = [], $injectDb = true) { if (!isset($this->componentsConfig[$interface])) { $message = sprintf('Suitable component for interface "%s" not configured in "%s"', $interface, __CLASS__); throw new InvalidConfigException($message); } $className = $this->componentsConfig[$interface]; $_config = is_array($className) ? $className : ['class' => $className]; $_config = ArrayHelper::merge($_config, $config); if ($injectDb) { $_config = ArrayHelper::merge(['db' => $this], $_config); } return \Reaction::create($_config); }
php
{ "resource": "" }
q266899
Tokenizer.getStatedClassNameToken
test
public function getStatedClassNameToken(string $statedClassName, $removeProxyName = false): string { $statedClassNamePart = \explode('\\', $statedClassName); if (true === $removeProxyName) { \array_pop($statedClassNamePart); } return \strtolower(\implode('_', $statedClassNamePart)); }
php
{ "resource": "" }