repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
FriendsOfCake/search | src/Model/Filter/Base.php | Base.skip | public function skip()
{
return !$this->present() ||
($this->filterEmpty() &&
empty($this->_args[$this->name()]) &&
!is_numeric($this->_args[$this->name()])
);
} | php | public function skip()
{
return !$this->present() ||
($this->filterEmpty() &&
empty($this->_args[$this->name()]) &&
!is_numeric($this->_args[$this->name()])
);
} | [
"public",
"function",
"skip",
"(",
")",
"{",
"return",
"!",
"$",
"this",
"->",
"present",
"(",
")",
"||",
"(",
"$",
"this",
"->",
"filterEmpty",
"(",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"_args",
"[",
"$",
"this",
"->",
"name",
"(",
")",
... | Checks whether this finder should be skipped.
@return bool | [
"Checks",
"whether",
"this",
"finder",
"should",
"be",
"skipped",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Base.php#L177-L184 |
FriendsOfCake/search | src/Model/Filter/Base.php | Base.value | public function value()
{
$value = $this->_config['defaultValue'];
$passedValue = $this->passedValue();
if ($passedValue === null) {
return $value;
}
return $passedValue;
} | php | public function value()
{
$value = $this->_config['defaultValue'];
$passedValue = $this->passedValue();
if ($passedValue === null) {
return $value;
}
return $passedValue;
} | [
"public",
"function",
"value",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"_config",
"[",
"'defaultValue'",
"]",
";",
"$",
"passedValue",
"=",
"$",
"this",
"->",
"passedValue",
"(",
")",
";",
"if",
"(",
"$",
"passedValue",
"===",
"null",
")... | Get the value of the "name" from HTTP GET arguments.
@return mixed | [
"Get",
"the",
"value",
"of",
"the",
"name",
"from",
"HTTP",
"GET",
"arguments",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Base.php#L191-L201 |
FriendsOfCake/search | src/Model/Filter/Base.php | Base.validate | public function validate(array $value = null)
{
if ($value === null) {
return $this->getConfig('validate');
}
$this->setConfig('validate', $value);
} | php | public function validate(array $value = null)
{
if ($value === null) {
return $this->getConfig('validate');
}
$this->setConfig('validate', $value);
} | [
"public",
"function",
"validate",
"(",
"array",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getConfig",
"(",
"'validate'",
")",
";",
"}",
"$",
"this",
"->",
"setConfig",
"(",
... | Get / Set the validation rules.
@param array|null $value Value.
@return array|null
@codeCoverageIgnore
@internal | [
"Get",
"/",
"Set",
"the",
"validation",
"rules",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Base.php#L255-L262 |
FriendsOfCake/search | src/Model/Filter/Value.php | Value.process | public function process()
{
$value = $this->value();
if ($value === null) {
return false;
}
$isMultiValue = is_array($value);
if ($isMultiValue &&
empty($value)
) {
return false;
}
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field => $value,
]);
}
return true;
}
$expressions = [];
foreach ($this->fields() as $field) {
$expressions[] = function (QueryExpression $e) use ($field, $value, $isMultiValue) {
if ($isMultiValue) {
return $e->in($field, $value);
}
return $e->eq($field, $value);
};
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $expressions]);
return true;
} | php | public function process()
{
$value = $this->value();
if ($value === null) {
return false;
}
$isMultiValue = is_array($value);
if ($isMultiValue &&
empty($value)
) {
return false;
}
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field => $value,
]);
}
return true;
}
$expressions = [];
foreach ($this->fields() as $field) {
$expressions[] = function (QueryExpression $e) use ($field, $value, $isMultiValue) {
if ($isMultiValue) {
return $e->in($field, $value);
}
return $e->eq($field, $value);
};
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $expressions]);
return true;
} | [
"public",
"function",
"process",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
"(",
")",
";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"$",
"isMultiValue",
"=",
"is_array",
"(",
"$",
"value",
... | Process a value condition ($x == $y).
@return bool | [
"Process",
"a",
"value",
"condition",
"(",
"$x",
"==",
"$y",
")",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Value.php#L24-L62 |
FriendsOfCake/search | src/Model/Filter/Exists.php | Exists.process | public function process()
{
$value = $this->value();
if (!is_scalar($value) || $value === '') {
return false;
}
$bool = (bool)$value;
$nullValue = $this->getConfig('nullValue');
$comparison = ' !=';
if (!$bool) {
$comparison = '';
}
if ($nullValue === null) {
$comparison = ' IS NOT';
if (!$bool) {
$comparison = ' IS';
}
}
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field . $comparison => $nullValue,
]);
}
return true;
}
$conditions = [];
foreach ($this->fields() as $field) {
$conditions[] = [$field . $comparison => $nullValue];
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]);
return true;
} | php | public function process()
{
$value = $this->value();
if (!is_scalar($value) || $value === '') {
return false;
}
$bool = (bool)$value;
$nullValue = $this->getConfig('nullValue');
$comparison = ' !=';
if (!$bool) {
$comparison = '';
}
if ($nullValue === null) {
$comparison = ' IS NOT';
if (!$bool) {
$comparison = ' IS';
}
}
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field . $comparison => $nullValue,
]);
}
return true;
}
$conditions = [];
foreach ($this->fields() as $field) {
$conditions[] = [$field . $comparison => $nullValue];
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]);
return true;
} | [
"public",
"function",
"process",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
"(",
")",
";",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"===",
"''",
")",
"{",
"return",
"false",
";",
"}",
"$",
"boo... | Check if a value is truthy/falsy and pass as condition aware of NULLable.
@return bool | [
"Check",
"if",
"a",
"value",
"is",
"truthy",
"/",
"falsy",
"and",
"pass",
"as",
"condition",
"aware",
"of",
"NULLable",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Exists.php#L23-L62 |
FriendsOfCake/search | src/Model/Filter/Boolean.php | Boolean.process | public function process()
{
$value = $this->value();
if (!is_scalar($value)) {
return false;
}
if (is_string($value)) {
$value = strtolower($value);
}
$bool = null;
if (in_array($value, $this->getConfig('truthy'), true)) {
$bool = true;
} elseif (in_array($value, $this->getConfig('falsy'), true)) {
$bool = false;
}
if ($bool !== null) {
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field => $bool,
]);
}
return true;
}
$conditions = [];
foreach ($this->fields() as $field) {
$conditions[] = [$field => $bool];
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]);
}
return false;
} | php | public function process()
{
$value = $this->value();
if (!is_scalar($value)) {
return false;
}
if (is_string($value)) {
$value = strtolower($value);
}
$bool = null;
if (in_array($value, $this->getConfig('truthy'), true)) {
$bool = true;
} elseif (in_array($value, $this->getConfig('falsy'), true)) {
$bool = false;
}
if ($bool !== null) {
if (!$this->manager()->getRepository() instanceof Table) {
foreach ($this->fields() as $field) {
$this->getQuery()->where([
$field => $bool,
]);
}
return true;
}
$conditions = [];
foreach ($this->fields() as $field) {
$conditions[] = [$field => $bool];
}
$this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]);
}
return false;
} | [
"public",
"function",
"process",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
"(",
")",
";",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"value",
... | Check if a value is truthy/falsy and pass as condition.
@return bool | [
"Check",
"if",
"a",
"value",
"is",
"truthy",
"/",
"falsy",
"and",
"pass",
"as",
"condition",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Boolean.php#L25-L63 |
FriendsOfCake/search | src/Model/Filter/FilterCollection.php | FilterCollection.add | public function add($name, $filter, array $options = [])
{
$this->_filters[$name] = $this->_loadFilter($name, $filter, $options);
return $this;
} | php | public function add($name, $filter, array $options = [])
{
$this->_filters[$name] = $this->_loadFilter($name, $filter, $options);
return $this;
} | [
"public",
"function",
"add",
"(",
"$",
"name",
",",
"$",
"filter",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"_filters",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"->",
"_loadFilter",
"(",
"$",
"name",
",",
"$",
"... | Adds filter to the collection.
@param string $name Filter name.
@param string $filter Filter class name in short form like "Search.Value" or FQCN.
@param array $options Filter options.
@return $this | [
"Adds",
"filter",
"to",
"the",
"collection",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/FilterCollection.php#L58-L63 |
FriendsOfCake/search | src/Model/Filter/FilterCollection.php | FilterCollection._loadFilter | protected function _loadFilter($name, $filter, array $options = [])
{
if (empty($options['className'])) {
$class = $filter;
} else {
$class = $options['className'];
unset($options['className']);
}
$className = App::className($class, 'Model/Filter');
if (!$className) {
throw new InvalidArgumentException(sprintf('Search filter "%s" was not found.', $class));
}
return new $className($name, $this->_manager, $options);
} | php | protected function _loadFilter($name, $filter, array $options = [])
{
if (empty($options['className'])) {
$class = $filter;
} else {
$class = $options['className'];
unset($options['className']);
}
$className = App::className($class, 'Model/Filter');
if (!$className) {
throw new InvalidArgumentException(sprintf('Search filter "%s" was not found.', $class));
}
return new $className($name, $this->_manager, $options);
} | [
"protected",
"function",
"_loadFilter",
"(",
"$",
"name",
",",
"$",
"filter",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"'className'",
"]",
")",
")",
"{",
"$",
"class",
"=",
"$",
"filter",
... | Loads a search filter.
@param string $name Filter name.
@param string $filter Filter class name in short form like "Search.Value" or FQCN.
@param array $options Filter options.
@return \Search\Model\Filter\Base
@throws \InvalidArgumentException When no filter was found. | [
"Loads",
"a",
"search",
"filter",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/FilterCollection.php#L74-L89 |
FriendsOfCake/search | src/Model/Behavior/SearchBehavior.php | SearchBehavior.initialize | public function initialize(array $config)
{
parent::initialize($config);
if (isset($config['emptyValues'])) {
$this->setConfig('emptyValues', $config['emptyValues'], false);
}
$collectionClass = $this->getConfig('collectionClass');
if ($collectionClass) {
$this->_collectionClass = $collectionClass;
return;
}
$defaultCollectionClass = sprintf(
'%s\Model\Filter\%sCollection',
Configure::read('App.namespace'),
$this->getTable()->getAlias()
);
if (class_exists($defaultCollectionClass)) {
$this->_collectionClass = $defaultCollectionClass;
}
} | php | public function initialize(array $config)
{
parent::initialize($config);
if (isset($config['emptyValues'])) {
$this->setConfig('emptyValues', $config['emptyValues'], false);
}
$collectionClass = $this->getConfig('collectionClass');
if ($collectionClass) {
$this->_collectionClass = $collectionClass;
return;
}
$defaultCollectionClass = sprintf(
'%s\Model\Filter\%sCollection',
Configure::read('App.namespace'),
$this->getTable()->getAlias()
);
if (class_exists($defaultCollectionClass)) {
$this->_collectionClass = $defaultCollectionClass;
}
} | [
"public",
"function",
"initialize",
"(",
"array",
"$",
"config",
")",
"{",
"parent",
"::",
"initialize",
"(",
"$",
"config",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'emptyValues'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"setConfig",
"... | Overwrite emptyValues config value
@param array $config Config
@return void | [
"Overwrite",
"emptyValues",
"config",
"value"
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Behavior/SearchBehavior.php#L41-L64 |
FriendsOfCake/search | src/Controller/Component/PrgComponent.php | PrgComponent.startup | public function startup()
{
if (!$this->request->is('post') || !$this->_actionCheck()) {
return null;
}
list($url) = explode('?', $this->request->getRequestTarget());
$params = $this->_filterParams();
if ($params) {
$url .= '?' . http_build_query($params);
}
return $this->_registry->getController()->redirect($url);
} | php | public function startup()
{
if (!$this->request->is('post') || !$this->_actionCheck()) {
return null;
}
list($url) = explode('?', $this->request->getRequestTarget());
$params = $this->_filterParams();
if ($params) {
$url .= '?' . http_build_query($params);
}
return $this->_registry->getController()->redirect($url);
} | [
"public",
"function",
"startup",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
"->",
"is",
"(",
"'post'",
")",
"||",
"!",
"$",
"this",
"->",
"_actionCheck",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"list",
"(",
"$",
"url",
... | Checks if the current request has posted data and redirects the users
to the same action after converting the post data into GET params
@return \Cake\Http\Response|null | [
"Checks",
"if",
"the",
"current",
"request",
"has",
"posted",
"data",
"and",
"redirects",
"the",
"users",
"to",
"the",
"same",
"action",
"after",
"converting",
"the",
"post",
"data",
"into",
"GET",
"params"
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Controller/Component/PrgComponent.php#L58-L72 |
FriendsOfCake/search | src/Controller/Component/PrgComponent.php | PrgComponent.beforeRender | public function beforeRender()
{
if (!$this->_actionCheck()) {
return null;
}
$controller = $this->_registry->getController();
$modelClass = $this->getConfig('modelClass', $controller->modelClass);
if (!$modelClass) {
return null;
}
list (, $modelName) = pluginSplit($modelClass);
if (!isset($controller->{$modelName})) {
return null;
}
/* @var \Cake\ORM\Table|\Search\Model\Behavior\SearchBehavior $model */
$model = $controller->{$modelName};
if (!$model->behaviors()->has('Search')) {
return null;
}
$controller->set('_isSearch', $model->isSearch());
$controller->set('_searchParams', $model->searchParams());
} | php | public function beforeRender()
{
if (!$this->_actionCheck()) {
return null;
}
$controller = $this->_registry->getController();
$modelClass = $this->getConfig('modelClass', $controller->modelClass);
if (!$modelClass) {
return null;
}
list (, $modelName) = pluginSplit($modelClass);
if (!isset($controller->{$modelName})) {
return null;
}
/* @var \Cake\ORM\Table|\Search\Model\Behavior\SearchBehavior $model */
$model = $controller->{$modelName};
if (!$model->behaviors()->has('Search')) {
return null;
}
$controller->set('_isSearch', $model->isSearch());
$controller->set('_searchParams', $model->searchParams());
} | [
"public",
"function",
"beforeRender",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_actionCheck",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"controller",
"=",
"$",
"this",
"->",
"_registry",
"->",
"getController",
"(",
")",
";",
"$",... | Populates the $_isSearch view variable based on the current request.
You need to configure the modelClass config if you are not using the controller's
default modelClass property.
@return \Cake\Http\Response|null | [
"Populates",
"the",
"$_isSearch",
"view",
"variable",
"based",
"on",
"the",
"current",
"request",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Controller/Component/PrgComponent.php#L82-L107 |
FriendsOfCake/search | src/Controller/Component/PrgComponent.php | PrgComponent._actionCheck | protected function _actionCheck()
{
$actions = $this->getConfig('actions');
if (is_bool($actions)) {
return $actions;
}
return in_array($this->request->getParam('action'), (array)$actions, true);
} | php | protected function _actionCheck()
{
$actions = $this->getConfig('actions');
if (is_bool($actions)) {
return $actions;
}
return in_array($this->request->getParam('action'), (array)$actions, true);
} | [
"protected",
"function",
"_actionCheck",
"(",
")",
"{",
"$",
"actions",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'actions'",
")",
";",
"if",
"(",
"is_bool",
"(",
"$",
"actions",
")",
")",
"{",
"return",
"$",
"actions",
";",
"}",
"return",
"in_array",... | Checks if the action should be processed by the component.
@return bool | [
"Checks",
"if",
"the",
"action",
"should",
"be",
"processed",
"by",
"the",
"component",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Controller/Component/PrgComponent.php#L114-L122 |
FriendsOfCake/search | src/Controller/Component/PrgComponent.php | PrgComponent._filterParams | protected function _filterParams()
{
$params = Hash::filter((array)$this->request->getData());
foreach ((array)$this->getConfig('queryStringBlacklist') as $field) {
unset($params[$field]);
}
foreach ((array)$this->getConfig('emptyValues') as $field => $value) {
if (!isset($params[$field])) {
continue;
}
if ($params[$field] === (string)$value) {
unset($params[$field]);
}
}
foreach ((array)$this->getConfig('queryStringWhitelist') as $field) {
$value = $this->request->getQuery($field);
if ($value !== null && !isset($params[$field])) {
$params[$field] = $value;
}
}
return $params;
} | php | protected function _filterParams()
{
$params = Hash::filter((array)$this->request->getData());
foreach ((array)$this->getConfig('queryStringBlacklist') as $field) {
unset($params[$field]);
}
foreach ((array)$this->getConfig('emptyValues') as $field => $value) {
if (!isset($params[$field])) {
continue;
}
if ($params[$field] === (string)$value) {
unset($params[$field]);
}
}
foreach ((array)$this->getConfig('queryStringWhitelist') as $field) {
$value = $this->request->getQuery($field);
if ($value !== null && !isset($params[$field])) {
$params[$field] = $value;
}
}
return $params;
} | [
"protected",
"function",
"_filterParams",
"(",
")",
"{",
"$",
"params",
"=",
"Hash",
"::",
"filter",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"request",
"->",
"getData",
"(",
")",
")",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"g... | Filters the params from POST data and merges in the whitelisted query string ones.
@return array | [
"Filters",
"the",
"params",
"from",
"POST",
"data",
"and",
"merges",
"in",
"the",
"whitelisted",
"query",
"string",
"ones",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Controller/Component/PrgComponent.php#L129-L155 |
FriendsOfCake/search | src/Model/Filter/Callback.php | Callback.process | public function process()
{
$ret = call_user_func(
$this->getConfig('callback'),
$this->getQuery(),
$this->getArgs(),
$this
);
if ($ret === null) {
return true;
}
return $ret;
} | php | public function process()
{
$ret = call_user_func(
$this->getConfig('callback'),
$this->getQuery(),
$this->getArgs(),
$this
);
if ($ret === null) {
return true;
}
return $ret;
} | [
"public",
"function",
"process",
"(",
")",
"{",
"$",
"ret",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'callback'",
")",
",",
"$",
"this",
"->",
"getQuery",
"(",
")",
",",
"$",
"this",
"->",
"getArgs",
"(",
")",
",",
"$",
"th... | Modify query using callback.
@return bool | [
"Modify",
"query",
"using",
"callback",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Callback.php#L12-L25 |
FriendsOfCake/search | src/View/Helper/SearchHelper.php | SearchHelper.resetLink | public function resetLink($label, array $options = [])
{
return $this->Html->link($label, $this->resetUrl(), $options);
} | php | public function resetLink($label, array $options = [])
{
return $this->Html->link($label, $this->resetUrl(), $options);
} | [
"public",
"function",
"resetLink",
"(",
"$",
"label",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"Html",
"->",
"link",
"(",
"$",
"label",
",",
"$",
"this",
"->",
"resetUrl",
"(",
")",
",",
"$",
"options",
... | Returns a reset link for the search form.
@param string $label Label text.
@param array $options Array of options and HTML attributes.
@return string HTML. | [
"Returns",
"a",
"reset",
"link",
"for",
"the",
"search",
"form",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/View/Helper/SearchHelper.php#L77-L80 |
FriendsOfCake/search | src/View/Helper/SearchHelper.php | SearchHelper.resetUrl | public function resetUrl()
{
$query = $this->request->getQuery();
$searchParams = (array)$this->_View->get('_searchParams');
$query = array_diff_key($query, $searchParams);
$additionalBlacklist = (array)$this->getConfig('additionalBlacklist');
foreach ($additionalBlacklist as $param) {
unset($query[$param]);
}
return [
'?' => $query,
];
} | php | public function resetUrl()
{
$query = $this->request->getQuery();
$searchParams = (array)$this->_View->get('_searchParams');
$query = array_diff_key($query, $searchParams);
$additionalBlacklist = (array)$this->getConfig('additionalBlacklist');
foreach ($additionalBlacklist as $param) {
unset($query[$param]);
}
return [
'?' => $query,
];
} | [
"public",
"function",
"resetUrl",
"(",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
")",
";",
"$",
"searchParams",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"_View",
"->",
"get",
"(",
"'_searchParams'",
")",
";",... | Returns the cleaned URL.
@return array URL with cleaned Query string. | [
"Returns",
"the",
"cleaned",
"URL",
"."
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/View/Helper/SearchHelper.php#L87-L102 |
FriendsOfCake/search | src/Model/Filter/Escaper/DefaultEscaper.php | DefaultEscaper.formatWildcards | public function formatWildcards($value)
{
$from = $to = $substFrom = $substTo = [];
if ($this->getConfig('wildcardAny') !== '%') {
$from[] = $this->getConfig('fromWildCardAny');
$to[] = $this->getConfig('toWildCardAny');
$substFrom[] = $this->getConfig('wildcardAny');
$substTo[] = '%';
}
if ($this->getConfig('wildcardOne') !== '_') {
$from[] = $this->getConfig('fromWildCardOne');
$to[] = $this->getConfig('toWildCardOne');
$substFrom[] = $this->getConfig('wildcardOne');
$substTo[] = '_';
}
if ($from) {
// Escape first
$value = str_replace($from, $to, $value);
// Replace wildcards
$value = str_replace($substFrom, $substTo, $value);
}
return $value;
} | php | public function formatWildcards($value)
{
$from = $to = $substFrom = $substTo = [];
if ($this->getConfig('wildcardAny') !== '%') {
$from[] = $this->getConfig('fromWildCardAny');
$to[] = $this->getConfig('toWildCardAny');
$substFrom[] = $this->getConfig('wildcardAny');
$substTo[] = '%';
}
if ($this->getConfig('wildcardOne') !== '_') {
$from[] = $this->getConfig('fromWildCardOne');
$to[] = $this->getConfig('toWildCardOne');
$substFrom[] = $this->getConfig('wildcardOne');
$substTo[] = '_';
}
if ($from) {
// Escape first
$value = str_replace($from, $to, $value);
// Replace wildcards
$value = str_replace($substFrom, $substTo, $value);
}
return $value;
} | [
"public",
"function",
"formatWildcards",
"(",
"$",
"value",
")",
"{",
"$",
"from",
"=",
"$",
"to",
"=",
"$",
"substFrom",
"=",
"$",
"substTo",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'wildcardAny'",
")",
"!==",
"'%'",
"... | Replace substitutions with original wildcards
but first, escape the original wildcards in the text to use them as normal search text
@param string $value Value.
@return string Value | [
"Replace",
"substitutions",
"with",
"original",
"wildcards",
"but",
"first",
"escape",
"the",
"original",
"wildcards",
"in",
"the",
"text",
"to",
"use",
"them",
"as",
"normal",
"search",
"text"
] | train | https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Escaper/DefaultEscaper.php#L39-L62 |
UnionOfRAD/lithium | net/Socket.php | Socket.send | public function send($message = null, array $options = []) {
$defaults = ['response' => $this->_classes['response']];
$options += $defaults;
if ($this->write($message)) {
$config = ['message' => $this->read()] + $this->_config;
return $this->_instance($options['response'], $config);
}
} | php | public function send($message = null, array $options = []) {
$defaults = ['response' => $this->_classes['response']];
$options += $defaults;
if ($this->write($message)) {
$config = ['message' => $this->read()] + $this->_config;
return $this->_instance($options['response'], $config);
}
} | [
"public",
"function",
"send",
"(",
"$",
"message",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'response'",
"=>",
"$",
"this",
"->",
"_classes",
"[",
"'response'",
"]",
"]",
";",
"$",
"options",
"... | Aggregates read and write methods into a coherent request response
@param \lithium\net\Message $message
@param array $options
- '`response`': a fully-namespaced string for the response object
@return object a response object based on `\lithium\net\Message` | [
"Aggregates",
"read",
"and",
"write",
"methods",
"into",
"a",
"coherent",
"request",
"response"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/Socket.php#L143-L151 |
UnionOfRAD/lithium | net/HostString.php | HostString.parse | public static function parse($host) {
if ($host[0] === ':') {
return ['port' => (integer) substr($host, 1)];
}
if ($host[0] === '[') {
if (($close = strpos($host, ']')) === false) {
throw new LogicException("Failed to parse host string `{$host}`.");
}
if (strlen($host) > $close + 1) {
if ($host[$close + 1] !== ':') {
throw new LogicException("Failed to parse host string `{$host}`.");
}
return [
'host' => substr($host, 1, $close - 1),
'port' => (integer) substr($host, $close + 2)
];
}
return ['host' => substr($host, 1, -1)];
}
if (($colon = strpos($host, ':')) !== false) {
return [
'host' => substr($host, 0, $colon),
'port' => (integer) substr($host, $colon + 1)
];
}
return ['host' => $host];
} | php | public static function parse($host) {
if ($host[0] === ':') {
return ['port' => (integer) substr($host, 1)];
}
if ($host[0] === '[') {
if (($close = strpos($host, ']')) === false) {
throw new LogicException("Failed to parse host string `{$host}`.");
}
if (strlen($host) > $close + 1) {
if ($host[$close + 1] !== ':') {
throw new LogicException("Failed to parse host string `{$host}`.");
}
return [
'host' => substr($host, 1, $close - 1),
'port' => (integer) substr($host, $close + 2)
];
}
return ['host' => substr($host, 1, -1)];
}
if (($colon = strpos($host, ':')) !== false) {
return [
'host' => substr($host, 0, $colon),
'port' => (integer) substr($host, $colon + 1)
];
}
return ['host' => $host];
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"host",
")",
"{",
"if",
"(",
"$",
"host",
"[",
"0",
"]",
"===",
"':'",
")",
"{",
"return",
"[",
"'port'",
"=>",
"(",
"integer",
")",
"substr",
"(",
"$",
"host",
",",
"1",
")",
"]",
";",
"}",
... | Parses host string that can either hold just the host name (i.e. `localhost`), a
host/port combination (i.e. `localhost:8080`) or just the port prefixed with a
colon (i.e. `:8080`). Also works with IPv4 and IPv6 addresses.
Note: IPv6 addresses must be enclosed in square brackets `'[::1]:80'`.
@param string $host The host string with host, host/port or just port.
@return array An associative array containing parsed `'host'`, `'port'` or both. | [
"Parses",
"host",
"string",
"that",
"can",
"either",
"hold",
"just",
"the",
"host",
"name",
"(",
"i",
".",
"e",
".",
"localhost",
")",
"a",
"host",
"/",
"port",
"combination",
"(",
"i",
".",
"e",
".",
"localhost",
":",
"8080",
")",
"or",
"just",
"t... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/HostString.php#L30-L56 |
UnionOfRAD/lithium | core/Object.php | Object._init | protected function _init() {
foreach ($this->_autoConfig as $key => $flag) {
if (!isset($this->_config[$key]) && !isset($this->_config[$flag])) {
continue;
}
if ($flag === 'merge') {
$this->{"_{$key}"} = $this->_config[$key] + $this->{"_{$key}"};
} else {
$this->{"_$flag"} = $this->_config[$flag];
}
}
} | php | protected function _init() {
foreach ($this->_autoConfig as $key => $flag) {
if (!isset($this->_config[$key]) && !isset($this->_config[$flag])) {
continue;
}
if ($flag === 'merge') {
$this->{"_{$key}"} = $this->_config[$key] + $this->{"_{$key}"};
} else {
$this->{"_$flag"} = $this->_config[$flag];
}
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"_autoConfig",
"as",
"$",
"key",
"=>",
"$",
"flag",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_config",
"[",
"$",
"key",
"]",
")",
"&&",
"!",
... | Initializer function called by the constructor unless the constructor `'init'` flag is set
to `false`. May be used for testing purposes, where objects need to be manipulated in an
un-initialized state, or for high-overhead operations that require more control than the
constructor provides. Additionally, this method iterates over the `$_autoConfig` property
to automatically assign configuration settings to their corresponding properties.
For example, given the following:
```
class Bar extends \lithium\core\Object {
protected $_autoConfig = ['foo'];
protected $_foo;
}
$instance = new Bar(['foo' => 'value']);
```
The `$_foo` property of `$instance` would automatically be set to `'value'`. If `$_foo` was
an array, `$_autoConfig` could be set to `array('foo' => 'merge')`, and the constructor value
of `'foo'` would be merged with the default value of `$_foo` and assigned to it.
@see lithium\core\Object::$_autoConfig
@return void | [
"Initializer",
"function",
"called",
"by",
"the",
"constructor",
"unless",
"the",
"constructor",
"init",
"flag",
"is",
"set",
"to",
"false",
".",
"May",
"be",
"used",
"for",
"testing",
"purposes",
"where",
"objects",
"need",
"to",
"be",
"manipulated",
"in",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Object.php#L112-L124 |
UnionOfRAD/lithium | core/Object.php | Object.invokeMethod | public function invokeMethod($method, $params = []) {
switch (count($params)) {
case 0:
return $this->{$method}();
case 1:
return $this->{$method}($params[0]);
case 2:
return $this->{$method}($params[0], $params[1]);
case 3:
return $this->{$method}($params[0], $params[1], $params[2]);
case 4:
return $this->{$method}($params[0], $params[1], $params[2], $params[3]);
case 5:
return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array([&$this, $method], $params);
}
} | php | public function invokeMethod($method, $params = []) {
switch (count($params)) {
case 0:
return $this->{$method}();
case 1:
return $this->{$method}($params[0]);
case 2:
return $this->{$method}($params[0], $params[1]);
case 3:
return $this->{$method}($params[0], $params[1], $params[2]);
case 4:
return $this->{$method}($params[0], $params[1], $params[2], $params[3]);
case 5:
return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array([&$this, $method], $params);
}
} | [
"public",
"function",
"invokeMethod",
"(",
"$",
"method",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"switch",
"(",
"count",
"(",
"$",
"params",
")",
")",
"{",
"case",
"0",
":",
"return",
"$",
"this",
"->",
"{",
"$",
"method",
"}",
"(",
")",
... | Calls a method on this object with the given parameters. Provides an OO wrapper
for call_user_func_array, and improves performance by using straight method calls
in most cases.
@param string $method Name of the method to call
@param array $params Parameter list to use when calling $method
@return mixed Returns the result of the method call | [
"Calls",
"a",
"method",
"on",
"this",
"object",
"with",
"the",
"given",
"parameters",
".",
"Provides",
"an",
"OO",
"wrapper",
"for",
"call_user_func_array",
"and",
"improves",
"performance",
"by",
"using",
"straight",
"method",
"calls",
"in",
"most",
"cases",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Object.php#L135-L152 |
UnionOfRAD/lithium | core/Object.php | Object._filter | protected function _filter($method, $params, $callback, $filters = []) {
$message = '`' . __METHOD__ . '()` has been deprecated in favor of ';
$message .= '`\lithium\aop\Filters::run()` and `::apply()`.';
trigger_error($message, E_USER_DEPRECATED);
list(, $method) = explode('::', $method);
foreach ($filters as $filter) {
Filters::apply($this, $method, $filter);
}
return Filters::run($this, $method, $params, $callback);
} | php | protected function _filter($method, $params, $callback, $filters = []) {
$message = '`' . __METHOD__ . '()` has been deprecated in favor of ';
$message .= '`\lithium\aop\Filters::run()` and `::apply()`.';
trigger_error($message, E_USER_DEPRECATED);
list(, $method) = explode('::', $method);
foreach ($filters as $filter) {
Filters::apply($this, $method, $filter);
}
return Filters::run($this, $method, $params, $callback);
} | [
"protected",
"function",
"_filter",
"(",
"$",
"method",
",",
"$",
"params",
",",
"$",
"callback",
",",
"$",
"filters",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"'`'",
".",
"__METHOD__",
".",
"'()` has been deprecated in favor of '",
";",
"$",
"message... | Executes a set of filters against a method by taking a method's main implementation as a
callback, and iteratively wrapping the filters around it. This, along with the `Filters`
class, is the core of Lithium's filters system. This system allows you to "reach into" an
object's methods which are marked as _filterable_, and intercept calls to those methods,
optionally modifying parameters or return values.
@deprecated Replaced by `\lithium\aop\Filters::run()`.
@see lithium\core\Object::applyFilter()
@see lithium\util\collection\Filters
@param string $method The name of the method being executed, usually the value of
`__METHOD__`.
@param array $params An associative array containing all the parameters passed into
the method.
@param \Closure $callback The method's implementation, wrapped in a closure.
@param array $filters Additional filters to apply to the method for this call only.
@return mixed Returns the return value of `$callback`, modified by any filters passed in
`$filters` or applied with `applyFilter()`. | [
"Executes",
"a",
"set",
"of",
"filters",
"against",
"a",
"method",
"by",
"taking",
"a",
"method",
"s",
"main",
"implementation",
"as",
"a",
"callback",
"and",
"iteratively",
"wrapping",
"the",
"filters",
"around",
"it",
".",
"This",
"along",
"with",
"the",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Object.php#L289-L300 |
UnionOfRAD/lithium | analysis/Logger.php | Logger.write | public static function write($priority, $message, array $options = []) {
$defaults = ['name' => null];
$options += $defaults;
$result = true;
if (isset(static::$_configurations[$options['name']])) {
$name = $options['name'];
$methods = [$name => static::adapter($name)->write($priority, $message, $options)];
} elseif (!isset(static::$_priorities[$priority])) {
$message = "Attempted to write log message with invalid priority `{$priority}`.";
throw new UnexpectedValueException($message);
} else {
$methods = static::_configsByPriority($priority, $message, $options);
}
foreach ($methods as $name => $method) {
$params = compact('priority', 'message', 'options');
$config = static::_config($name);
if (!empty($config['filters'])) {
$message = 'Per adapter filters have been deprecated. Please ';
$message .= "filter the manager class' static methods instead.";
trigger_error($message, E_USER_DEPRECATED);
$r = Filters::bcRun(
get_called_class(), __FUNCTION__, $params, $method, $config['filters']
);
} else {
$r = Filters::run(get_called_class(), __FUNCTION__, $params, $method);
}
if (!$r) {
$result = false;
}
}
return $methods ? $result : false;
} | php | public static function write($priority, $message, array $options = []) {
$defaults = ['name' => null];
$options += $defaults;
$result = true;
if (isset(static::$_configurations[$options['name']])) {
$name = $options['name'];
$methods = [$name => static::adapter($name)->write($priority, $message, $options)];
} elseif (!isset(static::$_priorities[$priority])) {
$message = "Attempted to write log message with invalid priority `{$priority}`.";
throw new UnexpectedValueException($message);
} else {
$methods = static::_configsByPriority($priority, $message, $options);
}
foreach ($methods as $name => $method) {
$params = compact('priority', 'message', 'options');
$config = static::_config($name);
if (!empty($config['filters'])) {
$message = 'Per adapter filters have been deprecated. Please ';
$message .= "filter the manager class' static methods instead.";
trigger_error($message, E_USER_DEPRECATED);
$r = Filters::bcRun(
get_called_class(), __FUNCTION__, $params, $method, $config['filters']
);
} else {
$r = Filters::run(get_called_class(), __FUNCTION__, $params, $method);
}
if (!$r) {
$result = false;
}
}
return $methods ? $result : false;
} | [
"public",
"static",
"function",
"write",
"(",
"$",
"priority",
",",
"$",
"message",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'name'",
"=>",
"null",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",... | Writes a message to one or more log adapters, where the adapters that are written to are the
ones that respond to the given priority level.
@param string $priority The priority of the log message to be written.
@param string $message The message to be written.
@param array $options An array of adapter-specific options that may be passed when writing
log messages. Some options are also handled by `Logger` itself:
- `'name'` _string_: This option can be specified if you wish to write to a
specific adapter configuration, instead of writing to the adapter(s) that
respond to the given priority.
@return boolean Returns `true` if all log writes succeeded, or `false` if _any or all_ writes
failed.
@throws UnexpectedValueException If the value of `$priority` is not a defined priority value,
an `UnexpectedValueException` will be thrown.
@filter | [
"Writes",
"a",
"message",
"to",
"one",
"or",
"more",
"log",
"adapters",
"where",
"the",
"adapters",
"that",
"are",
"written",
"to",
"are",
"the",
"ones",
"that",
"respond",
"to",
"the",
"given",
"priority",
"level",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Logger.php#L105-L140 |
UnionOfRAD/lithium | analysis/Logger.php | Logger.respondsTo | public static function respondsTo($method, $internal = false) {
return isset(static::$_priorities[$method]) || parent::respondsTo($method, $internal);
} | php | public static function respondsTo($method, $internal = false) {
return isset(static::$_priorities[$method]) || parent::respondsTo($method, $internal);
} | [
"public",
"static",
"function",
"respondsTo",
"(",
"$",
"method",
",",
"$",
"internal",
"=",
"false",
")",
"{",
"return",
"isset",
"(",
"static",
"::",
"$",
"_priorities",
"[",
"$",
"method",
"]",
")",
"||",
"parent",
"::",
"respondsTo",
"(",
"$",
"met... | Determines if a given method can be called.
@param string $method Name of the method.
@param boolean $internal Provide `true` to perform check from inside the
class/object. When `false` checks also for public visibility;
defaults to `false`.
@return boolean Returns `true` if the method can be called, `false` otherwise. | [
"Determines",
"if",
"a",
"given",
"method",
"can",
"be",
"called",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Logger.php#L169-L171 |
UnionOfRAD/lithium | analysis/Logger.php | Logger._initConfig | protected static function _initConfig($name, $config) {
$defaults = ['priority' => true];
return parent::_initConfig($name, $config) + $defaults;
} | php | protected static function _initConfig($name, $config) {
$defaults = ['priority' => true];
return parent::_initConfig($name, $config) + $defaults;
} | [
"protected",
"static",
"function",
"_initConfig",
"(",
"$",
"name",
",",
"$",
"config",
")",
"{",
"$",
"defaults",
"=",
"[",
"'priority'",
"=>",
"true",
"]",
";",
"return",
"parent",
"::",
"_initConfig",
"(",
"$",
"name",
",",
"$",
"config",
")",
"+",
... | This method is called automatically to initialize the default configuration of a log adapter,
such that the adapter defaults to accepting log messages of any priority (i.e. the
`'priority'` key is set to `true`).
@param string $name The name of the logger configuration.
@param array $config The logger configuration as specified in application code.
@return array Returns an array of configuration data, merged with default values. | [
"This",
"method",
"is",
"called",
"automatically",
"to",
"initialize",
"the",
"default",
"configuration",
"of",
"a",
"log",
"adapter",
"such",
"that",
"the",
"adapter",
"defaults",
"to",
"accepting",
"log",
"messages",
"of",
"any",
"priority",
"(",
"i",
".",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Logger.php#L182-L185 |
UnionOfRAD/lithium | analysis/Logger.php | Logger._configsByPriority | protected static function _configsByPriority($priority, $message, array $options = []) {
$configs = [];
$key = 'priority';
foreach (array_keys(static::$_configurations) as $name) {
$config = static::config($name);
$nameMatch = ($config[$key] === true || $config[$key] === $priority);
$arrayMatch = (is_array($config[$key]) && in_array($priority, $config[$key]));
if ($nameMatch || $arrayMatch) {
$method = static::adapter($name)->write($priority, $message, $options);
$method ? $configs[$name] = $method : null;
}
}
return $configs;
} | php | protected static function _configsByPriority($priority, $message, array $options = []) {
$configs = [];
$key = 'priority';
foreach (array_keys(static::$_configurations) as $name) {
$config = static::config($name);
$nameMatch = ($config[$key] === true || $config[$key] === $priority);
$arrayMatch = (is_array($config[$key]) && in_array($priority, $config[$key]));
if ($nameMatch || $arrayMatch) {
$method = static::adapter($name)->write($priority, $message, $options);
$method ? $configs[$name] = $method : null;
}
}
return $configs;
} | [
"protected",
"static",
"function",
"_configsByPriority",
"(",
"$",
"priority",
",",
"$",
"message",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"configs",
"=",
"[",
"]",
";",
"$",
"key",
"=",
"'priority'",
";",
"foreach",
"(",
"array_ke... | Gets the names of the adapter configurations that respond to a specific priority. The list
of adapter configurations returned will be used to write a message with the given priority.
@param string $priority The priority level of a message to be written.
@param string $message The message to write to the adapter.
@param array $options Adapter-specific options.
@return array Returns an array of names of configurations which are set up to respond to the
message priority specified in `$priority`, or configured to respond to _all_ message
priorities. | [
"Gets",
"the",
"names",
"of",
"the",
"adapter",
"configurations",
"that",
"respond",
"to",
"a",
"specific",
"priority",
".",
"The",
"list",
"of",
"adapter",
"configurations",
"returned",
"will",
"be",
"used",
"to",
"write",
"a",
"message",
"with",
"the",
"gi... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Logger.php#L198-L213 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship._init | protected function _init() {
parent::_init();
$config =& $this->_config;
if (!$config['to']) {
$assoc = preg_replace("/\\w+$/", "", $config['from']) . $config['name'];
$config['to'] = Libraries::locate('models', $assoc);
} elseif (!strpos($config['to'], '\\')) {
$config['to'] = preg_replace("/\\w+$/", "", $config['from']) . $config['to'];
}
if (!$config['key'] || !is_array($config['key'])) {
$config['key'] = $this->_keys($config['key']);
}
if ($config['strategy']) {
$config = (array) $config['strategy']($this) + $config;
unset($this->_config['strategy']);
}
} | php | protected function _init() {
parent::_init();
$config =& $this->_config;
if (!$config['to']) {
$assoc = preg_replace("/\\w+$/", "", $config['from']) . $config['name'];
$config['to'] = Libraries::locate('models', $assoc);
} elseif (!strpos($config['to'], '\\')) {
$config['to'] = preg_replace("/\\w+$/", "", $config['from']) . $config['to'];
}
if (!$config['key'] || !is_array($config['key'])) {
$config['key'] = $this->_keys($config['key']);
}
if ($config['strategy']) {
$config = (array) $config['strategy']($this) + $config;
unset($this->_config['strategy']);
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"parent",
"::",
"_init",
"(",
")",
";",
"$",
"config",
"=",
"&",
"$",
"this",
"->",
"_config",
";",
"if",
"(",
"!",
"$",
"config",
"[",
"'to'",
"]",
")",
"{",
"$",
"assoc",
"=",
"preg_replace",
"("... | Initializes the `Relationship` object by attempting to automatically generate any values
that were not provided in the constructor configuration. | [
"Initializes",
"the",
"Relationship",
"object",
"by",
"attempting",
"to",
"automatically",
"generate",
"any",
"values",
"that",
"were",
"not",
"provided",
"in",
"the",
"constructor",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L137-L155 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship.data | public function data($key = null) {
if (!$key) {
return $this->_config;
}
return isset($this->_config[$key]) ? $this->_config[$key] : null;
} | php | public function data($key = null) {
if (!$key) {
return $this->_config;
}
return isset($this->_config[$key]) ? $this->_config[$key] : null;
} | [
"public",
"function",
"data",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"->",
"_config",
";",
"}",
"return",
"isset",
"(",
"$",
"this",
"->",
"_config",
"[",
"$",
"key",
"]",
")",
"?",
... | Returns the named configuration item, or all configuration data, if no parameter is given.
@param string $key The name of the configuration item to return, or `null` to return all
items.
@return mixed Returns a single configuration item (mixed), or an array of all items. | [
"Returns",
"the",
"named",
"configuration",
"item",
"or",
"all",
"configuration",
"data",
"if",
"no",
"parameter",
"is",
"given",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L164-L169 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship.get | public function get($object, array $options = []) {
$link = $this->link();
$strategies = $this->_strategies();
if (!isset($strategies[$link]) || !is_callable($strategies[$link])) {
$msg = "Attempted to get object for invalid relationship link type `{$link}`.";
throw new ConfigException($msg);
}
return $strategies[$link]($object, $this, $options);
} | php | public function get($object, array $options = []) {
$link = $this->link();
$strategies = $this->_strategies();
if (!isset($strategies[$link]) || !is_callable($strategies[$link])) {
$msg = "Attempted to get object for invalid relationship link type `{$link}`.";
throw new ConfigException($msg);
}
return $strategies[$link]($object, $this, $options);
} | [
"public",
"function",
"get",
"(",
"$",
"object",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"link",
"=",
"$",
"this",
"->",
"link",
"(",
")",
";",
"$",
"strategies",
"=",
"$",
"this",
"->",
"_strategies",
"(",
")",
";",
"if",
"... | Gets a related object (or objects) for the given object connected to it by this relationship.
@param object $object The object to get the related data for.
@param array $options Additional options to merge into the query to be performed, where
applicable.
@return object Returns the object(s) for this relationship. | [
"Gets",
"a",
"related",
"object",
"(",
"or",
"objects",
")",
"for",
"the",
"given",
"object",
"connected",
"to",
"it",
"by",
"this",
"relationship",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L190-L199 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship.query | public function query($object) {
$conditions = (array) $this->constraints();
foreach ($this->key() as $from => $to) {
if (!isset($object->{$from})) {
return null;
}
$conditions[$to] = $object->{$from};
if (is_object($conditions[$to]) && $conditions[$to] instanceof Countable) {
$conditions[$to] = iterator_to_array($conditions[$to]);
}
}
$fields = $this->fields();
$fields = $fields === true ? null : $fields;
return compact('conditions', 'fields');
} | php | public function query($object) {
$conditions = (array) $this->constraints();
foreach ($this->key() as $from => $to) {
if (!isset($object->{$from})) {
return null;
}
$conditions[$to] = $object->{$from};
if (is_object($conditions[$to]) && $conditions[$to] instanceof Countable) {
$conditions[$to] = iterator_to_array($conditions[$to]);
}
}
$fields = $this->fields();
$fields = $fields === true ? null : $fields;
return compact('conditions', 'fields');
} | [
"public",
"function",
"query",
"(",
"$",
"object",
")",
"{",
"$",
"conditions",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"constraints",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"key",
"(",
")",
"as",
"$",
"from",
"=>",
"$",
"to",
")",
... | Generates query parameters for a related object (or objects) for the given object
connected to it by this relationship.
@param object $object The object to get the related data for.
@return object Returns the object(s) for this relationship. | [
"Generates",
"query",
"parameters",
"for",
"a",
"related",
"object",
"(",
"or",
"objects",
")",
"for",
"the",
"given",
"object",
"connected",
"to",
"it",
"by",
"this",
"relationship",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L208-L224 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship.foreignKey | public function foreignKey($primaryKey) {
$result = [];
$entity = $this->_classes['entity'];
$keys = ($this->type() === 'belongsTo') ? array_flip($this->key()) : $this->key();
$primaryKey = ($primaryKey instanceof $entity) ? $primaryKey->to('array') : $primaryKey;
foreach ($keys as $key => $foreignKey) {
$result[$foreignKey] = $primaryKey[$key];
}
return $result;
} | php | public function foreignKey($primaryKey) {
$result = [];
$entity = $this->_classes['entity'];
$keys = ($this->type() === 'belongsTo') ? array_flip($this->key()) : $this->key();
$primaryKey = ($primaryKey instanceof $entity) ? $primaryKey->to('array') : $primaryKey;
foreach ($keys as $key => $foreignKey) {
$result[$foreignKey] = $primaryKey[$key];
}
return $result;
} | [
"public",
"function",
"foreignKey",
"(",
"$",
"primaryKey",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"_classes",
"[",
"'entity'",
"]",
";",
"$",
"keys",
"=",
"(",
"$",
"this",
"->",
"type",
"(",
")",
"==... | Build foreign keys from primary keys array.
@param $primaryKey An array where keys are primary keys and values are
the associated values of primary keys.
@return array An array where keys are foreign keys and values are
the associated values of foreign keys. | [
"Build",
"foreign",
"keys",
"from",
"primary",
"keys",
"array",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L234-L244 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship._keys | protected function _keys($keys) {
if (!$keys) {
return [];
}
$config = $this->_config;
$hasType = ($config['type'] === 'hasOne' || $config['type'] === 'hasMany');
$related = Libraries::locate('models', $config[$hasType ? 'from' : 'to']);
if (!class_exists($related)) {
throw new ClassNotFoundException("Related model class '{$related}' not found.");
}
if (!$related::key()) {
throw new ConfigException("No key defined for related model `{$related}`.");
}
$keys = (array) $keys;
$related = (array) $related::key();
if (count($keys) !== count($related)) {
$msg = "Unmatched keys in relationship `{$config['name']}` between models ";
$msg .= "`{$config['from']}` and `{$config['to']}`.";
throw new ConfigException($msg);
}
return $hasType ? array_combine($related, $keys) : array_combine($keys, $related);
} | php | protected function _keys($keys) {
if (!$keys) {
return [];
}
$config = $this->_config;
$hasType = ($config['type'] === 'hasOne' || $config['type'] === 'hasMany');
$related = Libraries::locate('models', $config[$hasType ? 'from' : 'to']);
if (!class_exists($related)) {
throw new ClassNotFoundException("Related model class '{$related}' not found.");
}
if (!$related::key()) {
throw new ConfigException("No key defined for related model `{$related}`.");
}
$keys = (array) $keys;
$related = (array) $related::key();
if (count($keys) !== count($related)) {
$msg = "Unmatched keys in relationship `{$config['name']}` between models ";
$msg .= "`{$config['from']}` and `{$config['to']}`.";
throw new ConfigException($msg);
}
return $hasType ? array_combine($related, $keys) : array_combine($keys, $related);
} | [
"protected",
"function",
"_keys",
"(",
"$",
"keys",
")",
"{",
"if",
"(",
"!",
"$",
"keys",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"config",
"=",
"$",
"this",
"->",
"_config",
";",
"$",
"hasType",
"=",
"(",
"$",
"config",
"[",
"'type'",
"]... | Generates an array of relationship key pairs, where the keys are fields on the origin model,
and values are fields on the lniked model. | [
"Generates",
"an",
"array",
"of",
"relationship",
"key",
"pairs",
"where",
"the",
"keys",
"are",
"fields",
"on",
"the",
"origin",
"model",
"and",
"values",
"are",
"fields",
"on",
"the",
"lniked",
"model",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L263-L286 |
UnionOfRAD/lithium | data/model/Relationship.php | Relationship._strategies | protected function _strategies() {
return [
static::LINK_EMBEDDED => function($object, $relationship) {
$fieldName = $relationship->fieldName();
return $object->{$fieldName};
},
static::LINK_CONTAINED => function($object, $relationship) {
$isArray = ($relationship->type() === "hasMany");
return $isArray ? $object->parent()->parent() : $object->parent();
},
static::LINK_KEY => function($object, $relationship, $options) {
$model = $relationship->to();
if (!$query = $relationship->query($object)) {
return;
}
$method = ($relationship->type() === "hasMany") ? 'all' : 'first';
return $model::$method(Set::merge((array) $query, (array) $options));
},
static::LINK_KEY_LIST => function($object, $relationship, $options) {
$model = $relationship->to();
$query = $relationship->query($object);
return $model::all(Set::merge($query, $options));
}
];
} | php | protected function _strategies() {
return [
static::LINK_EMBEDDED => function($object, $relationship) {
$fieldName = $relationship->fieldName();
return $object->{$fieldName};
},
static::LINK_CONTAINED => function($object, $relationship) {
$isArray = ($relationship->type() === "hasMany");
return $isArray ? $object->parent()->parent() : $object->parent();
},
static::LINK_KEY => function($object, $relationship, $options) {
$model = $relationship->to();
if (!$query = $relationship->query($object)) {
return;
}
$method = ($relationship->type() === "hasMany") ? 'all' : 'first';
return $model::$method(Set::merge((array) $query, (array) $options));
},
static::LINK_KEY_LIST => function($object, $relationship, $options) {
$model = $relationship->to();
$query = $relationship->query($object);
return $model::all(Set::merge($query, $options));
}
];
} | [
"protected",
"function",
"_strategies",
"(",
")",
"{",
"return",
"[",
"static",
"::",
"LINK_EMBEDDED",
"=>",
"function",
"(",
"$",
"object",
",",
"$",
"relationship",
")",
"{",
"$",
"fieldName",
"=",
"$",
"relationship",
"->",
"fieldName",
"(",
")",
";",
... | Strategies used to query related objects, indexed by key. | [
"Strategies",
"used",
"to",
"query",
"related",
"objects",
"indexed",
"by",
"key",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/model/Relationship.php#L291-L315 |
UnionOfRAD/lithium | console/Command.php | Command._init | protected function _init() {
parent::_init();
$this->request = $this->_config['request'];
if (!is_object($this->request) || !$this->request->params) {
return;
}
$default = ['command' => null, 'action' => null, 'args' => null];
$params = array_diff_key((array) $this->request->params, $default);
foreach ($params as $key => $param) {
$this->{$key} = $param;
}
$this->response = $this->_config['response'];
if (!is_object($this->response)) {
$this->response = $this->_instance('response', $this->response + [
'plain' => $this->plain
]);
}
} | php | protected function _init() {
parent::_init();
$this->request = $this->_config['request'];
if (!is_object($this->request) || !$this->request->params) {
return;
}
$default = ['command' => null, 'action' => null, 'args' => null];
$params = array_diff_key((array) $this->request->params, $default);
foreach ($params as $key => $param) {
$this->{$key} = $param;
}
$this->response = $this->_config['response'];
if (!is_object($this->response)) {
$this->response = $this->_instance('response', $this->response + [
'plain' => $this->plain
]);
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"parent",
"::",
"_init",
"(",
")",
";",
"$",
"this",
"->",
"request",
"=",
"$",
"this",
"->",
"_config",
"[",
"'request'",
"]",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"this",
"->",
"request",
")... | Command Initializer.
Populates the `$response` property with a new instance of the `Response` class passing it
configuration and assigns the values from named parameters of the request (if applicable) to
properties of the command.
@return void | [
"Command",
"Initializer",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L105-L125 |
UnionOfRAD/lithium | console/Command.php | Command._help | protected function _help() {
$help = new Help([
'request' => $this->request,
'response' => $this->response,
'classes' => $this->_classes
]);
return $help->run(get_class($this));
} | php | protected function _help() {
$help = new Help([
'request' => $this->request,
'response' => $this->response,
'classes' => $this->_classes
]);
return $help->run(get_class($this));
} | [
"protected",
"function",
"_help",
"(",
")",
"{",
"$",
"help",
"=",
"new",
"Help",
"(",
"[",
"'request'",
"=>",
"$",
"this",
"->",
"request",
",",
"'response'",
"=>",
"$",
"this",
"->",
"response",
",",
"'classes'",
"=>",
"$",
"this",
"->",
"_classes",
... | Invokes the `Help` command.
The invoked Help command will take over request and response objects of
the originally invoked command. Thus the response of the Help command
becomes the response of the original one.
@return boolean | [
"Invokes",
"the",
"Help",
"command",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L162-L169 |
UnionOfRAD/lithium | console/Command.php | Command.out | public function out($output = null, $options = ['nl' => 1]) {
if ($this->silent) {
return;
}
return $this->_response('output', $output, $options);
} | php | public function out($output = null, $options = ['nl' => 1]) {
if ($this->silent) {
return;
}
return $this->_response('output', $output, $options);
} | [
"public",
"function",
"out",
"(",
"$",
"output",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"'nl'",
"=>",
"1",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"silent",
")",
"{",
"return",
";",
"}",
"return",
"$",
"this",
"->",
"_response",
"(",
... | Writes a string to the output stream.
@param string|array $output The string or an array of strings to write.
@param mixed $options When passed an integer or boolean it is used as the number of
of new lines, when passed a string it is interpreted as style
to use otherwise when an array following options are available:
- `'nl'` _integer|boolean_: number of new lines to add at the
end. `false` to disable adding a newline.
- `'style'` _string_: the style name to wrap around the output.
@return integer | [
"Writes",
"a",
"string",
"to",
"the",
"output",
"stream",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L183-L188 |
UnionOfRAD/lithium | console/Command.php | Command.in | public function in($prompt = null, array $options = []) {
$defaults = ['choices' => null, 'default' => null, 'quit' => 'q'];
$options += $defaults;
$choices = null;
if (is_array($options['choices'])) {
$choices = '(' . implode('/', $options['choices']) . ')';
}
$default = $options['default'] ? "[{$options['default']}] " : '';
do {
$this->out("{$prompt} {$choices} \n {$default}> ", 0);
$result = trim($this->request->input());
} while (
!empty($options['choices']) &&
!in_array($result, $options['choices'], true) &&
(empty($options['quit']) || $result !== $options['quit']) &&
(!$options['default'] || $result !== '')
);
if ($result == $options['quit']) {
return false;
}
if ($options['default'] !== null && $result == '') {
return $options['default'];
}
return $result;
} | php | public function in($prompt = null, array $options = []) {
$defaults = ['choices' => null, 'default' => null, 'quit' => 'q'];
$options += $defaults;
$choices = null;
if (is_array($options['choices'])) {
$choices = '(' . implode('/', $options['choices']) . ')';
}
$default = $options['default'] ? "[{$options['default']}] " : '';
do {
$this->out("{$prompt} {$choices} \n {$default}> ", 0);
$result = trim($this->request->input());
} while (
!empty($options['choices']) &&
!in_array($result, $options['choices'], true) &&
(empty($options['quit']) || $result !== $options['quit']) &&
(!$options['default'] || $result !== '')
);
if ($result == $options['quit']) {
return false;
}
if ($options['default'] !== null && $result == '') {
return $options['default'];
}
return $result;
} | [
"public",
"function",
"in",
"(",
"$",
"prompt",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'choices'",
"=>",
"null",
",",
"'default'",
"=>",
"null",
",",
"'quit'",
"=>",
"'q'",
"]",
";",
"$",
"... | Handles input. Will continue to loop until `$options['quit']` or
result is part of `$options['choices']`.
@param string $prompt
@param array $options
@return string|boolean Returns the result of the input data. If the input is
equal to the `quit` option boolean `false` is returned. | [
"Handles",
"input",
".",
"Will",
"continue",
"to",
"loop",
"until",
"$options",
"[",
"quit",
"]",
"or",
"result",
"is",
"part",
"of",
"$options",
"[",
"choices",
"]",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L215-L243 |
UnionOfRAD/lithium | console/Command.php | Command.header | public function header($text, $line = null) {
if (!$line) {
$line = strlen($text);
}
$this->hr($line);
$this->out($text, 'heading');
$this->hr($line);
} | php | public function header($text, $line = null) {
if (!$line) {
$line = strlen($text);
}
$this->hr($line);
$this->out($text, 'heading');
$this->hr($line);
} | [
"public",
"function",
"header",
"(",
"$",
"text",
",",
"$",
"line",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"line",
")",
"{",
"$",
"line",
"=",
"strlen",
"(",
"$",
"text",
")",
";",
"}",
"$",
"this",
"->",
"hr",
"(",
"$",
"line",
")",
"... | Writes a header to the output stream. In addition to the actual text,
horizontal lines before and afterwards are written. The lines will have
the same length as the text. This behavior can be modified by providing
the length of lines as a second paramerter.
Given the text `'Lithium'` this generates following output:
```
-------
Lithium
-------
```
@param string $text The heading text.
@param integer $line The length of the line. Defaults to the length of text.
@return void | [
"Writes",
"a",
"header",
"to",
"the",
"output",
"stream",
".",
"In",
"addition",
"to",
"the",
"actual",
"text",
"horizontal",
"lines",
"before",
"and",
"afterwards",
"are",
"written",
".",
"The",
"lines",
"will",
"have",
"the",
"same",
"length",
"as",
"the... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L263-L270 |
UnionOfRAD/lithium | console/Command.php | Command.columns | public function columns($rows, $options = []) {
$defaults = ['separator' => "\t", "error" => false];
$options += $defaults;
$lengths = array_reduce($rows, function($columns, $row) {
foreach ((array) $row as $key => $val) {
if (!isset($columns[$key]) || strlen($val) > $columns[$key]) {
$columns[$key] = strlen($val);
}
}
return $columns;
});
$rows = array_reduce($rows, function($rows, $row) use ($lengths, $options) {
$text = '';
foreach ((array) $row as $key => $val) {
$text = $text . str_pad($val, $lengths[$key]) . $options['separator'];
}
$rows[] = $text;
return $rows;
});
if ($options['error']) {
$this->error($rows, $options);
return;
}
$this->out($rows, $options);
} | php | public function columns($rows, $options = []) {
$defaults = ['separator' => "\t", "error" => false];
$options += $defaults;
$lengths = array_reduce($rows, function($columns, $row) {
foreach ((array) $row as $key => $val) {
if (!isset($columns[$key]) || strlen($val) > $columns[$key]) {
$columns[$key] = strlen($val);
}
}
return $columns;
});
$rows = array_reduce($rows, function($rows, $row) use ($lengths, $options) {
$text = '';
foreach ((array) $row as $key => $val) {
$text = $text . str_pad($val, $lengths[$key]) . $options['separator'];
}
$rows[] = $text;
return $rows;
});
if ($options['error']) {
$this->error($rows, $options);
return;
}
$this->out($rows, $options);
} | [
"public",
"function",
"columns",
"(",
"$",
"rows",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'separator'",
"=>",
"\"\\t\"",
",",
"\"error\"",
"=>",
"false",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
... | Writes rows of columns.
This method expects asceding integer values as the keys, which map to the appropriate
columns. Currently, there is no special "header" option, but you can define them for your
own.
Example Usage:
```
$output = [
['Name', 'Age'],
['----', '---'],
];
foreach($users as $user) {
$output[] = [$user->name, $user->age];
}
$this->columns($output);
```
Would render something similar to:
```
Name Age
---- ---
Jane Doe 22
Foo Bar 18
```
This method also calculates the needed space between the columns. All option params given
also get passed down to the `out()` method, which allow custom formatting. Passing something
like `$this->columns($output, ['style' => 'red]` would print the table in red.
@see lithium\console\Response::styles()
@param array $rows The rows to print, with each column as an array element.
@param array $options Optional params:
- separator : Different column separator, defaults to `\t`
- style : the style name to wrap around the columns output
@return void | [
"Writes",
"rows",
"of",
"columns",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L312-L336 |
UnionOfRAD/lithium | console/Command.php | Command.stop | public function stop($status = 0, $message = null) {
if ($message) {
($status == 0) ? $this->out($message) : $this->error($message);
}
exit($status);
} | php | public function stop($status = 0, $message = null) {
if ($message) {
($status == 0) ? $this->out($message) : $this->error($message);
}
exit($status);
} | [
"public",
"function",
"stop",
"(",
"$",
"status",
"=",
"0",
",",
"$",
"message",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"message",
")",
"{",
"(",
"$",
"status",
"==",
"0",
")",
"?",
"$",
"this",
"->",
"out",
"(",
"$",
"message",
")",
":",
"$"... | Stop execution, by exiting the script.
@param integer $status Numeric value that will be used on `exit()`.
@param string|null $message An optional message that will be written to the stream.
@return void | [
"Stop",
"execution",
"by",
"exiting",
"the",
"script",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L375-L380 |
UnionOfRAD/lithium | console/Command.php | Command._response | protected function _response($type, $string, $options) {
$defaults = ['nl' => 1, 'style' => null];
if (!is_array($options)) {
if (is_bool($options)) {
$options = ['nl' => (integer) $options];
} elseif (is_int($options)) {
$options = ['nl' => $options];
} elseif (is_string($options)) {
$options = ['style' => $options];
} else {
$options = [];
}
}
$options += $defaults;
if (is_array($string)) {
$method = ($type == 'error' ? $type : 'out');
foreach ($string as $out) {
$this->{$method}($out, $options);
}
return;
}
if ($options['style'] !== null) {
$string = "{:{$options['style']}}{$string}{:end}";
}
if ($options['nl']) {
$string = $string . $this->nl((integer) $options['nl']);
}
return $this->response->{$type}($string);
} | php | protected function _response($type, $string, $options) {
$defaults = ['nl' => 1, 'style' => null];
if (!is_array($options)) {
if (is_bool($options)) {
$options = ['nl' => (integer) $options];
} elseif (is_int($options)) {
$options = ['nl' => $options];
} elseif (is_string($options)) {
$options = ['style' => $options];
} else {
$options = [];
}
}
$options += $defaults;
if (is_array($string)) {
$method = ($type == 'error' ? $type : 'out');
foreach ($string as $out) {
$this->{$method}($out, $options);
}
return;
}
if ($options['style'] !== null) {
$string = "{:{$options['style']}}{$string}{:end}";
}
if ($options['nl']) {
$string = $string . $this->nl((integer) $options['nl']);
}
return $this->response->{$type}($string);
} | [
"protected",
"function",
"_response",
"(",
"$",
"type",
",",
"$",
"string",
",",
"$",
"options",
")",
"{",
"$",
"defaults",
"=",
"[",
"'nl'",
"=>",
"1",
",",
"'style'",
"=>",
"null",
"]",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"options",
")",
... | Handles the response that is sent to the stream.
@param string $type The stream either output or error.
@param string|array $string The message to render.
@param mixed $options When passed an integer or boolean it is used as the number of
of new lines, when passed a string it is interpreted as style
to use otherwise when an array following options are available:
- `'nl'` _integer|boolean_: number of new lines to add at the
end. `false` to disable adding a newline.
- `'style'` _string_: the style name to wrap around the output.
@return void | [
"Handles",
"the",
"response",
"that",
"is",
"sent",
"to",
"the",
"stream",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Command.php#L395-L425 |
UnionOfRAD/lithium | action/Response.php | Response._init | protected function _init() {
parent::_init();
$router = $this->_classes['router'];
if ($this->_config['location']) {
$location = $router::match($this->_config['location'], $this->_config['request']);
$this->headers('Location', $location);
}
} | php | protected function _init() {
parent::_init();
$router = $this->_classes['router'];
if ($this->_config['location']) {
$location = $router::match($this->_config['location'], $this->_config['request']);
$this->headers('Location', $location);
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"parent",
"::",
"_init",
"(",
")",
";",
"$",
"router",
"=",
"$",
"this",
"->",
"_classes",
"[",
"'router'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"_config",
"[",
"'location'",
"]",
")",
"{",
"$",
... | Sets the Location header using `$config['location']` and `$config['request']` passed in
through the constructor if provided.
@return void | [
"Sets",
"the",
"Location",
"header",
"using",
"$config",
"[",
"location",
"]",
"and",
"$config",
"[",
"request",
"]",
"passed",
"in",
"through",
"the",
"constructor",
"if",
"provided",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L76-L84 |
UnionOfRAD/lithium | action/Response.php | Response.cache | public function cache($expires) {
if ($expires === false) {
$headers = [
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Cache-Control' => [
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0'
],
'Pragma' => 'no-cache'
];
} else {
$expires = is_int($expires) ? $expires : strtotime($expires);
$headers = [
'Expires' => gmdate('D, d M Y H:i:s', $expires) . ' GMT',
'Cache-Control' => 'max-age=' . ($expires - time()),
'Pragma' => 'cache'
];
}
$this->headers($headers);
} | php | public function cache($expires) {
if ($expires === false) {
$headers = [
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Cache-Control' => [
'no-store, no-cache, must-revalidate',
'post-check=0, pre-check=0',
'max-age=0'
],
'Pragma' => 'no-cache'
];
} else {
$expires = is_int($expires) ? $expires : strtotime($expires);
$headers = [
'Expires' => gmdate('D, d M Y H:i:s', $expires) . ' GMT',
'Cache-Control' => 'max-age=' . ($expires - time()),
'Pragma' => 'cache'
];
}
$this->headers($headers);
} | [
"public",
"function",
"cache",
"(",
"$",
"expires",
")",
"{",
"if",
"(",
"$",
"expires",
"===",
"false",
")",
"{",
"$",
"headers",
"=",
"[",
"'Expires'",
"=>",
"'Mon, 26 Jul 1997 05:00:00 GMT'",
",",
"'Cache-Control'",
"=>",
"[",
"'no-store, no-cache, must-reval... | Controls how or whether the client browser and web proxies should cache this response.
@param mixed $expires This can be a Unix timestamp indicating when the page expires, or a
string indicating the relative time offset that a page should expire, i.e. `"+5 hours".
Finally, `$expires` can be set to `false` to completely disable browser or proxy
caching.
@return void | [
"Controls",
"how",
"or",
"whether",
"the",
"client",
"browser",
"and",
"web",
"proxies",
"should",
"cache",
"this",
"response",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L95-L116 |
UnionOfRAD/lithium | action/Response.php | Response.type | public function type($type = null) {
if ($type === null && $this->_type === null) {
$type = 'html';
}
return parent::type($type);
} | php | public function type($type = null) {
if ($type === null && $this->_type === null) {
$type = 'html';
}
return parent::type($type);
} | [
"public",
"function",
"type",
"(",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"null",
"&&",
"$",
"this",
"->",
"_type",
"===",
"null",
")",
"{",
"$",
"type",
"=",
"'html'",
";",
"}",
"return",
"parent",
"::",
"type",
"(",
... | Sets/Gets the content type. If `'type'` is null, the method will attempt to determine the
type from the params, then from the environment setting
@param string $type a full content type i.e. `'application/json'` or simple name `'json'`
@return string A simple content type name, i.e. `'html'`, `'xml'`, `'json'`, etc., depending
on the content type of the request. | [
"Sets",
"/",
"Gets",
"the",
"content",
"type",
".",
"If",
"type",
"is",
"null",
"the",
"method",
"will",
"attempt",
"to",
"determine",
"the",
"type",
"from",
"the",
"params",
"then",
"from",
"the",
"environment",
"setting"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L126-L131 |
UnionOfRAD/lithium | action/Response.php | Response.render | public function render() {
$code = null;
if (isset($this->headers['location']) || isset($this->headers['Location'])) {
if ($this->status['code'] === 200) {
$this->status(302);
}
$code = $this->status['code'];
}
if ($cookies = $this->_cookies()) {
$this->headers('Set-Cookie', $cookies);
}
$this->_writeHeaders($this->status() ?: $this->status(500));
$this->_writeHeaders($this->headers(), $code);
if ($this->status['code'] === 302 || $this->status['code'] === 204) {
return;
}
foreach ($this->body(null, $this->_config) as $chunk) {
echo $chunk;
}
} | php | public function render() {
$code = null;
if (isset($this->headers['location']) || isset($this->headers['Location'])) {
if ($this->status['code'] === 200) {
$this->status(302);
}
$code = $this->status['code'];
}
if ($cookies = $this->_cookies()) {
$this->headers('Set-Cookie', $cookies);
}
$this->_writeHeaders($this->status() ?: $this->status(500));
$this->_writeHeaders($this->headers(), $code);
if ($this->status['code'] === 302 || $this->status['code'] === 204) {
return;
}
foreach ($this->body(null, $this->_config) as $chunk) {
echo $chunk;
}
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"code",
"=",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"headers",
"[",
"'location'",
"]",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"headers",
"[",
"'Location'",
"]",
")",
")",
... | Render a response by writing headers and output. Output is echoed in
chunks because of an issue where `echo` time increases exponentially
on long message bodies.
Reponses which have a `Location` header set are indicating a
redirect, will get their status code automatically adjusted to `302`
(Found/Moved Temporarily) in case the status code before was `200`
(OK). This is to allow easy redirects by setting just the `Location`
header and is assumed to be the original intent of the user.
On responses with status codes `204` (No Content) and `302` (Found)
a message body - even if one is set - will never be send. These
status codes either don't have a message body as per their nature or
they are ignored and can thus be omitted for performance reasons.
@return void | [
"Render",
"a",
"response",
"by",
"writing",
"headers",
"and",
"output",
".",
"Output",
"is",
"echoed",
"in",
"chunks",
"because",
"of",
"an",
"issue",
"where",
"echo",
"time",
"increases",
"exponentially",
"on",
"long",
"message",
"bodies",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L151-L172 |
UnionOfRAD/lithium | action/Response.php | Response._writeHeaders | protected function _writeHeaders($headers, $code = null) {
foreach ((array) $headers as $header) {
$code ? header($header, false, $code) : header($header, false);
}
} | php | protected function _writeHeaders($headers, $code = null) {
foreach ((array) $headers as $header) {
$code ? header($header, false, $code) : header($header, false);
}
} | [
"protected",
"function",
"_writeHeaders",
"(",
"$",
"headers",
",",
"$",
"code",
"=",
"null",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"headers",
"as",
"$",
"header",
")",
"{",
"$",
"code",
"?",
"header",
"(",
"$",
"header",
",",
"false",
... | Writes raw headers to output.
@param string|array $headers Either a raw header string, or an array of header strings. Use
an array if a single header must be written multiple times with different values.
Otherwise, additional values for duplicate headers will overwrite previous values.
@param integer $code Optional. If present, forces a specific HTTP response code. Used
primarily in conjunction with the 'Location' header.
@return void | [
"Writes",
"raw",
"headers",
"to",
"output",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L195-L199 |
UnionOfRAD/lithium | action/Response.php | Response.headers | public function headers($key = null, $value = null, $replace = true) {
if ($key === 'download' || $key === 'Download') {
$message = "Shorthand header `Download` with `<FILENAME>` has been deprecated ";
$message .= "because it's too magic. Please use `Content-Disposition` ";
$message .= "with `attachment; filename=\"<FILENAME>\"` instead.";
trigger_error($message, E_USER_DEPRECATED);
$key = 'Content-Disposition';
$value = 'attachment; filename="' . $value . '"';
}
return parent::headers($key, $value, $replace);
} | php | public function headers($key = null, $value = null, $replace = true) {
if ($key === 'download' || $key === 'Download') {
$message = "Shorthand header `Download` with `<FILENAME>` has been deprecated ";
$message .= "because it's too magic. Please use `Content-Disposition` ";
$message .= "with `attachment; filename=\"<FILENAME>\"` instead.";
trigger_error($message, E_USER_DEPRECATED);
$key = 'Content-Disposition';
$value = 'attachment; filename="' . $value . '"';
}
return parent::headers($key, $value, $replace);
} | [
"public",
"function",
"headers",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"value",
"=",
"null",
",",
"$",
"replace",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"key",
"===",
"'download'",
"||",
"$",
"key",
"===",
"'Download'",
")",
"{",
"$",
"message",
... | Expands on `\net\http\Message::headers()` with some magic conversions for shorthand headers.
@deprecated This method will be removed in a future version. Note that the parent `header()`
wil continue to exist.
@param string|array $key
@param mixed $value
@param boolean $replace
@return mixed | [
"Expands",
"on",
"\\",
"net",
"\\",
"http",
"\\",
"Message",
"::",
"headers",
"()",
"with",
"some",
"magic",
"conversions",
"for",
"shorthand",
"headers",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Response.php#L213-L224 |
UnionOfRAD/lithium | data/Schema.php | Schema.is | public function is($condition, $field) {
if (!isset($this->_fields[$field])) {
return null;
}
return isset($this->_fields[$field][$condition]) && $this->_fields[$field][$condition];
} | php | public function is($condition, $field) {
if (!isset($this->_fields[$field])) {
return null;
}
return isset($this->_fields[$field][$condition]) && $this->_fields[$field][$condition];
} | [
"public",
"function",
"is",
"(",
"$",
"condition",
",",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_fields",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"isset",
"(",
"$",
"this",
... | Detects properties of a field, i.e. if it supports arrays.
@param string $condition
@param string $field
@return boolean | [
"Detects",
"properties",
"of",
"a",
"field",
"i",
".",
"e",
".",
"if",
"it",
"supports",
"arrays",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Schema.php#L113-L118 |
UnionOfRAD/lithium | analysis/logger/adapter/Syslog.php | Syslog.write | public function write($priority, $message) {
$config = $this->_config;
if (!$this->_isConnected) {
closelog();
openlog($config['identity'], $config['options'], $config['facility']);
$this->_isConnected = true;
}
return function($params) {
$priority = $this->_priorities[$params['priority']];
return syslog($priority, $params['message']);
};
} | php | public function write($priority, $message) {
$config = $this->_config;
if (!$this->_isConnected) {
closelog();
openlog($config['identity'], $config['options'], $config['facility']);
$this->_isConnected = true;
}
return function($params) {
$priority = $this->_priorities[$params['priority']];
return syslog($priority, $params['message']);
};
} | [
"public",
"function",
"write",
"(",
"$",
"priority",
",",
"$",
"message",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"_config",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"_isConnected",
")",
"{",
"closelog",
"(",
")",
";",
"openlog",
"(",
"$",
... | Appends `$message` to the system log.
@param string $priority The message priority string. Maps to a `syslogd` priority constant.
@param string $message The message to write.
@return \Closure Function returning boolean `true` on successful write, `false` otherwise. | [
"Appends",
"$message",
"to",
"the",
"system",
"log",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/logger/adapter/Syslog.php#L71-L84 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.paths | public static function paths($path = null) {
if (empty($path)) {
return static::$_paths;
}
if (is_string($path)) {
return isset(static::$_paths[$path]) ? static::$_paths[$path] : null;
}
static::$_paths = array_filter(array_merge(static::$_paths, (array) $path));
} | php | public static function paths($path = null) {
if (empty($path)) {
return static::$_paths;
}
if (is_string($path)) {
return isset(static::$_paths[$path]) ? static::$_paths[$path] : null;
}
static::$_paths = array_filter(array_merge(static::$_paths, (array) $path));
} | [
"public",
"static",
"function",
"paths",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"return",
"static",
"::",
"$",
"_paths",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"... | Accessor method for the class path templates which `Libraries` uses to look up and load
classes. Using this method, you can define your own types of classes, or modify the default
organization of built-in class types.
For example, in a queuing application, you can define a class type called `'job'`:
```
Libraries::paths(['job' => '{:library}\extensions\job\{:name}']);
```
Then, any classes you add to the `extensions/job` directory in your application will be
automatically detected when calling `Libraries::locate('job')`. Additionally, any matching
classes in the `extensions/job` directory of any plugin or vendor library you add to your
application will also be detected.
Supposing you wanted to have the option of further organizing jobs by class type (some jobs
are related to updating caches, others to sending notifications, etc.), you can specify
multiple paths per class type, with varying levels of specificity:
```
Libraries::paths(['job' => [
'{:library}\extensions\job\{:class}\{:name}',
'{:library}\extensions\job\{:name}'
]]);
```
This allows you to, for example, have two different classes called `Cleanup`. One may be
located in `app\extensions\job\Cleanup`, while the other is in
`app\extensions\job\cache\Cleanup`. Calling: `Libraries::locate('job');` will find
both classes, while `Libraries::locate('job.cache');` will only find the second. You can
also find individual jobs by name: `Libraries::locate('job', 'Cleanup');`
See `Libraries::locate()` for more information on using built-in and user-defined paths to
look up classes.
In addition to adding custom class types, `paths()` allows you to redefine the naming and
organization of existing types. For example, if you wished to reference your model classes
as `app\models\PostModel` instead of `app\models\Post`, you can do the following:
```
Libraries::paths(['models' => '{:library}\models\{:name}Model']);
```
Note, however, that this is a destructive, not an additive operation, and will
replace any existing paths defined for that type. If you wish to add a search path
for an existing type, you must do the following:
```
$existing = Libraries::paths('controllers');
Libraries::paths(['controller' => array_merge(
['{:library}\extensions\controllers\{:name}Controller'], (array) $existing
)]);
```
@see lithium\core\Libraries::locate()
@see lithium\core\Libraries::$_paths
@param mixed $path If `$path` is a string, returns the path(s) associated with that path
type, or `null` if no paths are defined for that type.
@return mixed | [
"Accessor",
"method",
"for",
"the",
"class",
"path",
"templates",
"which",
"Libraries",
"uses",
"to",
"look",
"up",
"and",
"load",
"classes",
".",
"Using",
"this",
"method",
"you",
"can",
"define",
"your",
"own",
"types",
"of",
"classes",
"or",
"modify",
"... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L216-L224 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.add | public static function add($name, array $config = []) {
$defaults = [
'name' => $name,
'path' => null,
'prefix' => $name . "\\",
'suffix' => '.php',
'loader' => null,
'includePath' => false,
'transform' => null,
'bootstrap' => true,
'defer' => false,
'default' => false
];
if ($name === 'lithium') {
$defaults['defer'] = true;
$defaults['bootstrap'] = false;
$defaults['path'] = dirname(__DIR__);
$defaults['loader'] = 'lithium\core\Libraries::load';
}
if (isset($config['default']) && $config['default']) {
static::$_default = $name;
$defaults['path'] = LITHIUM_APP_PATH;
$defaults['bootstrap'] = false;
$defaults['resources'] = LITHIUM_APP_PATH . '/resources';
}
$config += $defaults;
if (!$config['path']) {
if (!$config['path'] = static::_locatePath('libraries', compact('name'))) {
throw new ConfigException("Library `{$name}` not found.");
}
}
$config['path'] = str_replace('\\', '/', $config['path']);
static::_configure(static::$_configurations[$name] = $config);
return $config;
} | php | public static function add($name, array $config = []) {
$defaults = [
'name' => $name,
'path' => null,
'prefix' => $name . "\\",
'suffix' => '.php',
'loader' => null,
'includePath' => false,
'transform' => null,
'bootstrap' => true,
'defer' => false,
'default' => false
];
if ($name === 'lithium') {
$defaults['defer'] = true;
$defaults['bootstrap'] = false;
$defaults['path'] = dirname(__DIR__);
$defaults['loader'] = 'lithium\core\Libraries::load';
}
if (isset($config['default']) && $config['default']) {
static::$_default = $name;
$defaults['path'] = LITHIUM_APP_PATH;
$defaults['bootstrap'] = false;
$defaults['resources'] = LITHIUM_APP_PATH . '/resources';
}
$config += $defaults;
if (!$config['path']) {
if (!$config['path'] = static::_locatePath('libraries', compact('name'))) {
throw new ConfigException("Library `{$name}` not found.");
}
}
$config['path'] = str_replace('\\', '/', $config['path']);
static::_configure(static::$_configurations[$name] = $config);
return $config;
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"name",
",",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'name'",
"=>",
"$",
"name",
",",
"'path'",
"=>",
"null",
",",
"'prefix'",
"=>",
"$",
"name",
".",
"\"\\\\\"",... | Adds a class library from which files can be loaded.
The `add()` method registers a named library configuration to your application, and is used
to allow the framework to auto-load classes on an as-needed basis.
### Adding libraries to your application
In Lithium, libraries represent the broadest unit of class organization in an application,
and _everything_ is a library; this includes your application, and the Lithium framework
itself. Libraries can also be other frameworks, like Solar, Zend Framework or PEAR, or
Lithium plugins, which are simply libraries that follow the same organizational standards
as Lithium applications.
By convention, libraries are placed in the `libraries` directory inside your application, or
the root `libraries` directory at the top level of the default distribution (i.e. the one
that contains the `lithium` directory), however, you can change this on a case-by-case basis
using the `'path'` key to specify an absolute path to the library's directory.
@param string $name Library name, i.e. `'app'`, `'lithium'`, `'pear'` or `'aura'`.
@param array $config Specifies where the library is in the filesystem, and how classes
should be loaded from it. Allowed keys are:
- `'bootstrap'` _mixed_: A file path (relative to `'path'`) to a bootstrap script that
should be run when the library is added, or `true` to use the default bootstrap
path, i.e. `config/bootstrap.php`.
- `'defer'` _boolean_: If `true`, indicates that, when locating classes, this library
should defer to other libraries in order of preference.
- `'includePath'` _mixed_: If `true`, appends the absolutely-resolved value of
`'path'` to the PHP include path. If a string, the value is appended to PHP's.
- `'loader'`: An auto-loader method associated with the library, if any.
- `'path'`: The directory containing the library.
- `'prefix'` _string_: The class prefix this library uses, i.e. `'lithium\'`,
`'Zend_'` or `'Solar_'`. If the library has no global prefix, set to `false`.
- `'suffix'` _string_: Gets appended to the end of the file name. For example, most
libraries end classes in `'.php'`, but some use `'.class.php'`, or `'.inc.php'`.
- `'transform'` _\Closure_: Defines a custom way to transform a class name into its
corresponding file path. Accepts either an array of two strings which are
interpreted as the pattern and replacement for a regex, or an anonymous function,
which receives the class name and library configuration arrays as parameters, and
returns the full physical file path as output.
- `'resources'` _string_: If this is the default library, this maybe set to the
absolute path to the write-enabled application resources directory, which is used
for caching, log files, uploads, etc.
@return array Returns the resulting set of options created for this library. | [
"Adds",
"a",
"class",
"library",
"from",
"which",
"files",
"can",
"be",
"loaded",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L271-L306 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._configure | protected static function _configure($config) {
if ($config['includePath']) {
$path = ($config['includePath'] === true) ? $config['path'] : $config['includePath'];
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
}
if ($config['bootstrap'] === true) {
$path = "{$config['path']}/config/bootstrap.php";
$config['bootstrap'] = file_exists($path) ? 'config/bootstrap.php' : false;
}
if ($config['bootstrap']) {
require "{$config['path']}/{$config['bootstrap']}";
}
if (!empty($config['loader'])) {
spl_autoload_register($config['loader']);
}
} | php | protected static function _configure($config) {
if ($config['includePath']) {
$path = ($config['includePath'] === true) ? $config['path'] : $config['includePath'];
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
}
if ($config['bootstrap'] === true) {
$path = "{$config['path']}/config/bootstrap.php";
$config['bootstrap'] = file_exists($path) ? 'config/bootstrap.php' : false;
}
if ($config['bootstrap']) {
require "{$config['path']}/{$config['bootstrap']}";
}
if (!empty($config['loader'])) {
spl_autoload_register($config['loader']);
}
} | [
"protected",
"static",
"function",
"_configure",
"(",
"$",
"config",
")",
"{",
"if",
"(",
"$",
"config",
"[",
"'includePath'",
"]",
")",
"{",
"$",
"path",
"=",
"(",
"$",
"config",
"[",
"'includePath'",
"]",
"===",
"true",
")",
"?",
"$",
"config",
"["... | Configures the application environment based on a library's settings, including appending to
the include path, loading a bootstrap file, and registering a loader with SPL's autoloading
system.
@param array $config The new library's configuration array.
@return void | [
"Configures",
"the",
"application",
"environment",
"based",
"on",
"a",
"library",
"s",
"settings",
"including",
"appending",
"to",
"the",
"include",
"path",
"loading",
"a",
"bootstrap",
"file",
"and",
"registering",
"a",
"loader",
"with",
"SPL",
"s",
"autoloadin... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L316-L331 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.get | public static function get($name = null, $key = null) {
$configs = static::$_configurations;
if (!$name && !$key) {
return $configs;
}
if ($name === true) {
$name = static::$_default;
}
if (is_array($name) || (!$name && $key)) {
$name = $name ?: array_keys(static::$_configurations);
$call = [get_called_class(), 'get'];
return array_combine($name, array_map($call, $name, array_fill(0, count($name), $key)));
}
$config = isset($configs[$name]) ? $configs[$name] : null;
if ($key) {
return isset($config[$key]) ? $config[$key] : null;
}
if (strpos($name, '\\') === false) {
return $config;
}
foreach (static::$_configurations as $library => $config) {
if ($config['prefix'] && strpos($name, $config['prefix']) === 0) {
return $library;
}
}
} | php | public static function get($name = null, $key = null) {
$configs = static::$_configurations;
if (!$name && !$key) {
return $configs;
}
if ($name === true) {
$name = static::$_default;
}
if (is_array($name) || (!$name && $key)) {
$name = $name ?: array_keys(static::$_configurations);
$call = [get_called_class(), 'get'];
return array_combine($name, array_map($call, $name, array_fill(0, count($name), $key)));
}
$config = isset($configs[$name]) ? $configs[$name] : null;
if ($key) {
return isset($config[$key]) ? $config[$key] : null;
}
if (strpos($name, '\\') === false) {
return $config;
}
foreach (static::$_configurations as $library => $config) {
if ($config['prefix'] && strpos($name, $config['prefix']) === 0) {
return $library;
}
}
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"configs",
"=",
"static",
"::",
"$",
"_configurations",
";",
"if",
"(",
"!",
"$",
"name",
"&&",
"!",
"$",
"key",
")",
"{",
"return"... | Allows library information to be retrieved in various ways, including:
By name:
``` embed:lithium\tests\cases\core\LibrariesTest::testLibraryConfigAccess(1-1) ```
With no parameters, to return all configuration for all libraries:
``` embed:lithium\tests\cases\core\LibrariesTest::testLibraryConfigAccess(22-22) ```
By list of names with a key to extract:
``` embed:lithium\tests\cases\core\LibrariesTest::testLibraryConfigAccess(34-34) ```
With no name, and a key to extract, to return a key/value array, where the library name is
the key, and the `$key` value is the value:
``` embed:lithium\tests\cases\core\LibrariesTest::testLibraryConfigAccess(37-37) ```
By containing class name:
``` embed:lithium\tests\cases\core\LibrariesTest::testLibraryConfigAccess(45-45) ```
@param mixed $name Either the name of a library added in `Libraries::add()`, an array of
library names, or a fully-namespaced class name (see usage examples above).
@param string $key Optional key name. If `$name` is set and is the name of a valid library
(or an array of valid libraries), returns the given named configuration key,
i.e. `'path'`, `'webroot'` or `'resources'`.
@return mixed A configuation array for one or more libraries, or a string value if `$key` is
specified and `$name` is a string, or a library name (string) if `$name` is a
fully-namespaced class name. | [
"Allows",
"library",
"information",
"to",
"be",
"retrieved",
"in",
"various",
"ways",
"including",
":"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L361-L388 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.remove | public static function remove($name) {
foreach ((array) $name as $library) {
if (isset(static::$_configurations[$library])) {
if (static::$_configurations[$library]['loader']) {
spl_autoload_unregister(static::$_configurations[$library]['loader']);
}
unset(static::$_configurations[$library]);
}
}
} | php | public static function remove($name) {
foreach ((array) $name as $library) {
if (isset(static::$_configurations[$library])) {
if (static::$_configurations[$library]['loader']) {
spl_autoload_unregister(static::$_configurations[$library]['loader']);
}
unset(static::$_configurations[$library]);
}
}
} | [
"public",
"static",
"function",
"remove",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"name",
"as",
"$",
"library",
")",
"{",
"if",
"(",
"isset",
"(",
"static",
"::",
"$",
"_configurations",
"[",
"$",
"library",
"]",
")",
")... | Removes a registered library, and unregister's the library's autoloader, if it has one.
@param mixed $name A string or array of library names indicating the libraries you wish to
remove, i.e. `'app'` or `'lithium'`. This can also be used to unload plugins by name. | [
"Removes",
"a",
"registered",
"library",
"and",
"unregister",
"s",
"the",
"library",
"s",
"autoloader",
"if",
"it",
"has",
"one",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L396-L405 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.find | public static function find($library, array $options = []) {
$format = function($file, $config) {
$trim = [strlen($config['path']) + 1, strlen($config['suffix'])];
$rTrim = strpos($file, $config['suffix']) !== false ? -$trim[1] : 9999;
$file = preg_split('/[\/\\\\]/', substr($file, $trim[0], $rTrim));
return $config['prefix'] . join('\\', $file);
};
$defaults = compact('format') + [
'path' => '',
'recursive' => false,
'filter' => '/^(\w+)?(\\\\[a-z0-9_]+)+\\\\[A-Z][a-zA-Z0-9]+$/',
'exclude' => '',
'namespaces' => false
];
$options += $defaults;
$libs = [];
if ($options['namespaces'] && $options['filter'] === $defaults['filter']) {
$options['format'] = function($class, $config) use ($format, $defaults) {
if (is_dir($class)) {
return $format($class, $config);
}
if (preg_match($defaults['filter'], $class = $format($class, $config))) {
return $class;
}
};
$options['filter'] = false;
}
if ($library === true) {
foreach (static::$_configurations as $library => $config) {
$libs = array_merge($libs, static::find($library, $options));
}
return $libs;
}
if (!isset(static::$_configurations[$library])) {
return null;
}
$config = static::$_configurations[$library];
$options['path'] = "{$config['path']}{$options['path']}/*";
$libs = static::_search($config, $options);
return array_values(array_filter($libs));
} | php | public static function find($library, array $options = []) {
$format = function($file, $config) {
$trim = [strlen($config['path']) + 1, strlen($config['suffix'])];
$rTrim = strpos($file, $config['suffix']) !== false ? -$trim[1] : 9999;
$file = preg_split('/[\/\\\\]/', substr($file, $trim[0], $rTrim));
return $config['prefix'] . join('\\', $file);
};
$defaults = compact('format') + [
'path' => '',
'recursive' => false,
'filter' => '/^(\w+)?(\\\\[a-z0-9_]+)+\\\\[A-Z][a-zA-Z0-9]+$/',
'exclude' => '',
'namespaces' => false
];
$options += $defaults;
$libs = [];
if ($options['namespaces'] && $options['filter'] === $defaults['filter']) {
$options['format'] = function($class, $config) use ($format, $defaults) {
if (is_dir($class)) {
return $format($class, $config);
}
if (preg_match($defaults['filter'], $class = $format($class, $config))) {
return $class;
}
};
$options['filter'] = false;
}
if ($library === true) {
foreach (static::$_configurations as $library => $config) {
$libs = array_merge($libs, static::find($library, $options));
}
return $libs;
}
if (!isset(static::$_configurations[$library])) {
return null;
}
$config = static::$_configurations[$library];
$options['path'] = "{$config['path']}{$options['path']}/*";
$libs = static::_search($config, $options);
return array_values(array_filter($libs));
} | [
"public",
"static",
"function",
"find",
"(",
"$",
"library",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"format",
"=",
"function",
"(",
"$",
"file",
",",
"$",
"config",
")",
"{",
"$",
"trim",
"=",
"[",
"strlen",
"(",
"$",
"config... | Finds the classes or namespaces belonging to a particular library. _Note_: This method
assumes loaded class libraries use a consistent class-to-file naming convention.
@param mixed $library The name of a library added to the application with `Libraries::add()`,
or `true` to search all libraries.
@param array $options The options this method accepts:
- `'path'` _string_: A physical filesystem path relative to the directory of the
library being searched. If provided, only the classes or namespaces within
this path will be returned.
- `'recursive'` _boolean_: If `true`, recursively searches all directories
(namespaces) in the given library. If `false` (the default), only searches the
top level of the given path.
- `'filter'` _string_: A regular expression applied to a class after it is
transformed into a fully-namespaced class name. The default regular expression
filters class names based on the
[PSR-0](http://groups.google.com/group/php-standards/web/psr-0-final-proposal)
PHP 5.3 naming standard.
- `'exclude'` _mixed_: Can be either a regular expression of classes/namespaces
to exclude, or a PHP callable to be used with `array_filter()`.
- `'namespaces'` _boolean_: Indicates whether namespaces should be included in
the search results. If `false` (the default), only classes are returned.
@return array Returns an array of fully-namespaced class names found in the given library or
libraries.
@todo Patch this to skip paths belonging to nested libraries in recursive searches. | [
"Finds",
"the",
"classes",
"or",
"namespaces",
"belonging",
"to",
"a",
"particular",
"library",
".",
"_Note_",
":",
"This",
"method",
"assumes",
"loaded",
"class",
"libraries",
"use",
"a",
"consistent",
"class",
"-",
"to",
"-",
"file",
"naming",
"convention",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L433-L476 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.load | public static function load($class, $require = false) {
$path = isset(static::$_cachedPaths[$class]) ? static::$_cachedPaths[$class] : null;
$path = $path ?: static::path($class);
if ($path && include $path) {
static::$_cachedPaths[$class] = $path;
if (method_exists($class, '__init')) {
$message = "Support for automatic initialization of static classes has been ";
$message .= "removed. `{$class}::__init()` exists, please remove it to get rid ";
$message .= "of this message. Static classes must now be initialized manually. ";
$message .= "i.e. by creating an `init()` method and calling it at the end of ";
$message .= "the file and outside of the class.";
throw new RuntimeException($message);
}
} elseif ($require) {
throw new RuntimeException("Failed to load class `{$class}` from path `{$path}`.");
}
} | php | public static function load($class, $require = false) {
$path = isset(static::$_cachedPaths[$class]) ? static::$_cachedPaths[$class] : null;
$path = $path ?: static::path($class);
if ($path && include $path) {
static::$_cachedPaths[$class] = $path;
if (method_exists($class, '__init')) {
$message = "Support for automatic initialization of static classes has been ";
$message .= "removed. `{$class}::__init()` exists, please remove it to get rid ";
$message .= "of this message. Static classes must now be initialized manually. ";
$message .= "i.e. by creating an `init()` method and calling it at the end of ";
$message .= "the file and outside of the class.";
throw new RuntimeException($message);
}
} elseif ($require) {
throw new RuntimeException("Failed to load class `{$class}` from path `{$path}`.");
}
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"class",
",",
"$",
"require",
"=",
"false",
")",
"{",
"$",
"path",
"=",
"isset",
"(",
"static",
"::",
"$",
"_cachedPaths",
"[",
"$",
"class",
"]",
")",
"?",
"static",
"::",
"$",
"_cachedPaths",
"[",
... | Loads the class definition specified by `$class`. Looks through the list of libraries
defined in `$_configurations`, which are added through `lithium\core\Libraries::add()`.
@see lithium\core\Libraries::add()
@see lithium\core\Libraries::path()
@param string $class The fully-namespaced (where applicable) name of the class to load.
@param boolean $require Specifies whether the class must be loaded or considered an
exception. Defaults to `false`.
@return void | [
"Loads",
"the",
"class",
"definition",
"specified",
"by",
"$class",
".",
"Looks",
"through",
"the",
"list",
"of",
"libraries",
"defined",
"in",
"$_configurations",
"which",
"are",
"added",
"through",
"lithium",
"\\",
"core",
"\\",
"Libraries",
"::",
"add",
"()... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L489-L507 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.map | public static function map(array $classes) {
foreach ($classes as $key => $value) {
unset(static::$_cachedPaths[$key]);
}
static::$_map = array_merge(static::$_map, $classes);
} | php | public static function map(array $classes) {
foreach ($classes as $key => $value) {
unset(static::$_cachedPaths[$key]);
}
static::$_map = array_merge(static::$_map, $classes);
} | [
"public",
"static",
"function",
"map",
"(",
"array",
"$",
"classes",
")",
"{",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"unset",
"(",
"static",
"::",
"$",
"_cachedPaths",
"[",
"$",
"key",
"]",
")",
";",
"}",
... | Associtates fully-namespaced class names to their corresponding paths on
the file system.
Once a class is associtated to a path using `lithium\core\Libraries::map()`
the PSR-0 loader or custom class loader setted using the `transform` or `loader`
option of `lithium\core\Libraries::add()` are ignored and the associtated path
is used instead.
@param array $classes An array of fully-namespaced class names (as keys) and
their correponding file's paths (as values).
@return void | [
"Associtates",
"fully",
"-",
"namespaced",
"class",
"names",
"to",
"their",
"corresponding",
"paths",
"on",
"the",
"file",
"system",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L522-L527 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.unmap | public static function unmap($classes) {
if (!is_array($classes)) {
$classes = [$classes];
}
foreach ($classes as $value) {
unset(static::$_map[$value]);
}
} | php | public static function unmap($classes) {
if (!is_array($classes)) {
$classes = [$classes];
}
foreach ($classes as $value) {
unset(static::$_map[$value]);
}
} | [
"public",
"static",
"function",
"unmap",
"(",
"$",
"classes",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"classes",
")",
")",
"{",
"$",
"classes",
"=",
"[",
"$",
"classes",
"]",
";",
"}",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"value",
"... | Unmap fully-namespaced class names mapped using `lithium\core\Libraries::map()`.
@see lithium\core\Libraries::map()
@param mixed $classes An array of fully-namespaced class names or
a string with a fully-namespaced class name. | [
"Unmap",
"fully",
"-",
"namespaced",
"class",
"names",
"mapped",
"using",
"lithium",
"\\",
"core",
"\\",
"Libraries",
"::",
"map",
"()",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L536-L543 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.path | public static function path($class, array $options = []) {
$defaults = ['dirs' => false];
$options += $defaults;
$class = ltrim($class, '\\');
if (isset(static::$_cachedPaths[$class]) && !$options['dirs']) {
return static::$_cachedPaths[$class];
}
if (isset(static::$_map[$class]) && !$options['dirs']) {
return static::$_map[$class];
}
foreach (static::$_configurations as $name => $config) {
$params = $options + $config;
$suffix = $params['suffix'];
if ($params['prefix'] && strpos($class, $params['prefix']) !== 0) {
continue;
}
if ($transform = $params['transform']) {
if ($file = static::_transformPath($transform, $class, $params)) {
return $file;
}
continue;
}
$path = str_replace("\\", '/', substr($class, strlen($params['prefix'])));
$fullPath = "{$params['path']}/{$path}";
if (!$options['dirs']) {
return static::$_cachedPaths[$class] = static::realPath($fullPath . $suffix);
}
$list = glob(dirname($fullPath) . '/*');
$list = array_map(function($i) { return str_replace('\\', '/', $i); }, $list);
if (in_array($fullPath . $suffix, $list)) {
return static::$_cachedPaths[$class] = static::realPath($fullPath . $suffix);
}
return is_dir($fullPath) ? static::realPath($fullPath) : null;
}
} | php | public static function path($class, array $options = []) {
$defaults = ['dirs' => false];
$options += $defaults;
$class = ltrim($class, '\\');
if (isset(static::$_cachedPaths[$class]) && !$options['dirs']) {
return static::$_cachedPaths[$class];
}
if (isset(static::$_map[$class]) && !$options['dirs']) {
return static::$_map[$class];
}
foreach (static::$_configurations as $name => $config) {
$params = $options + $config;
$suffix = $params['suffix'];
if ($params['prefix'] && strpos($class, $params['prefix']) !== 0) {
continue;
}
if ($transform = $params['transform']) {
if ($file = static::_transformPath($transform, $class, $params)) {
return $file;
}
continue;
}
$path = str_replace("\\", '/', substr($class, strlen($params['prefix'])));
$fullPath = "{$params['path']}/{$path}";
if (!$options['dirs']) {
return static::$_cachedPaths[$class] = static::realPath($fullPath . $suffix);
}
$list = glob(dirname($fullPath) . '/*');
$list = array_map(function($i) { return str_replace('\\', '/', $i); }, $list);
if (in_array($fullPath . $suffix, $list)) {
return static::$_cachedPaths[$class] = static::realPath($fullPath . $suffix);
}
return is_dir($fullPath) ? static::realPath($fullPath) : null;
}
} | [
"public",
"static",
"function",
"path",
"(",
"$",
"class",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'dirs'",
"=>",
"false",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
"class",
"=",
"ltrim",
... | Get the corresponding physical file path for a class or namespace name.
@param string $class The class name to locate the physical file for. If `$options['dirs']` is
set to `true`, `$class` may also be a namespace name, in which case the corresponding
directory will be located.
@param array $options Options for converting `$class` to a physical path:
- `'dirs'`: Defaults to `false`. If `true`, will attempt to case-sensitively look up
directories in addition to files (in which case `$class` is assumed to actually be a
namespace).
@return string Returns the absolute path to the file containing `$class`, or `null` if the
file cannot be found. | [
"Get",
"the",
"corresponding",
"physical",
"file",
"path",
"for",
"a",
"class",
"or",
"namespace",
"name",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L558-L596 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.realPath | public static function realPath($path) {
if (($absolutePath = realpath($path)) !== false) {
return $absolutePath;
}
if (!preg_match('%^phar://([^.]+\.phar(?:\.gz)?)(.+)%', $path, $pathComponents)) {
return;
}
list(, $relativePath, $pharPath) = $pathComponents;
$pharPath = implode('/', array_reduce(explode('/', $pharPath), function ($parts, $value) {
if ($value === '..') {
array_pop($parts);
} elseif ($value !== '.') {
$parts[] = $value;
}
return $parts;
}));
if (($resolvedPath = realpath($relativePath)) !== false) {
if (file_exists($absolutePath = "phar://{$resolvedPath}{$pharPath}")) {
return $absolutePath;
}
}
} | php | public static function realPath($path) {
if (($absolutePath = realpath($path)) !== false) {
return $absolutePath;
}
if (!preg_match('%^phar://([^.]+\.phar(?:\.gz)?)(.+)%', $path, $pathComponents)) {
return;
}
list(, $relativePath, $pharPath) = $pathComponents;
$pharPath = implode('/', array_reduce(explode('/', $pharPath), function ($parts, $value) {
if ($value === '..') {
array_pop($parts);
} elseif ($value !== '.') {
$parts[] = $value;
}
return $parts;
}));
if (($resolvedPath = realpath($relativePath)) !== false) {
if (file_exists($absolutePath = "phar://{$resolvedPath}{$pharPath}")) {
return $absolutePath;
}
}
} | [
"public",
"static",
"function",
"realPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"(",
"$",
"absolutePath",
"=",
"realpath",
"(",
"$",
"path",
")",
")",
"!==",
"false",
")",
"{",
"return",
"$",
"absolutePath",
";",
"}",
"if",
"(",
"!",
"preg_match",... | Wraps the PHP `realpath()` function to add support for finding paths to files inside Phar
archives.
@param string $path An unresolved path to a file inside a Phar archive which may or may not
exist.
@return string If `$path` is a valid path to a file inside a Phar archive, returns a string
in the format `'phar://<path-to-phar>/<path-to-file>'`. Otherwise returns
`null`. | [
"Wraps",
"the",
"PHP",
"realpath",
"()",
"function",
"to",
"add",
"support",
"for",
"finding",
"paths",
"to",
"files",
"inside",
"Phar",
"archives",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L608-L631 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._transformPath | protected static function _transformPath($transform, $class, array $options = []) {
if ((is_callable($transform)) && $file = $transform($class, $options)) {
return $file;
}
if (is_array($transform)) {
list($match, $replace) = $transform;
return preg_replace($match, $replace, $class) ?: null;
}
} | php | protected static function _transformPath($transform, $class, array $options = []) {
if ((is_callable($transform)) && $file = $transform($class, $options)) {
return $file;
}
if (is_array($transform)) {
list($match, $replace) = $transform;
return preg_replace($match, $replace, $class) ?: null;
}
} | [
"protected",
"static",
"function",
"_transformPath",
"(",
"$",
"transform",
",",
"$",
"class",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"(",
"is_callable",
"(",
"$",
"transform",
")",
")",
"&&",
"$",
"file",
"=",
"$",
"transf... | Handles the conversion of a class name to a file name using a custom transformation typically
defined in the `'transform'` key of a configuration defined through `Libraries::add()`.
The transformation can either be a closure which receives two parameters (the class name
as a string, and the library configuration as an array), or an array with two values (one
being the pattern to match, the other being the replacement).
@see lithium\core\Libraries::add()
@see lithium\core\Libraries::path()
@param mixed $transform Either a closure or an array containing a regular expression match
and replacement. If the closure returns an empty value, or the regular
expression fails to match, will return `null`.
@param string $class The class name which is attempting to be mapped to a file.
@param array $options The configuration of the library as passed to `Libraries::add()`, along
with any options specified in the call to `Libraries::path()`.
@return string Returns transformed path of a class to a file, or `null` if the transformation
did not match. | [
"Handles",
"the",
"conversion",
"of",
"a",
"class",
"name",
"to",
"a",
"file",
"name",
"using",
"a",
"custom",
"transformation",
"typically",
"defined",
"in",
"the",
"transform",
"key",
"of",
"a",
"configuration",
"defined",
"through",
"Libraries",
"::",
"add"... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L652-L660 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.instance | public static function instance($type, $name, array $options = []) {
$params = compact('type', 'name', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$name = $params['name'];
$type = $params['type'];
if (!$name && !$type) {
$message = "Invalid class lookup: `\$name` and `\$type` are empty.";
throw new ClassNotFoundException($message);
}
if (!is_string($type) && $type !== null && !isset(static::$_paths[$type])) {
throw new ClassNotFoundException("Invalid class type `{$type}`.");
}
if (!$class = static::locate($type, $name)) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not found.");
}
if (is_object($class)) {
return $class;
}
if (!(is_string($class) && class_exists($class))) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not defined.");
}
return new $class($params['options']);
});
} | php | public static function instance($type, $name, array $options = []) {
$params = compact('type', 'name', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$name = $params['name'];
$type = $params['type'];
if (!$name && !$type) {
$message = "Invalid class lookup: `\$name` and `\$type` are empty.";
throw new ClassNotFoundException($message);
}
if (!is_string($type) && $type !== null && !isset(static::$_paths[$type])) {
throw new ClassNotFoundException("Invalid class type `{$type}`.");
}
if (!$class = static::locate($type, $name)) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not found.");
}
if (is_object($class)) {
return $class;
}
if (!(is_string($class) && class_exists($class))) {
throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not defined.");
}
return new $class($params['options']);
});
} | [
"public",
"static",
"function",
"instance",
"(",
"$",
"type",
",",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'type'",
",",
"'name'",
",",
"'options'",
")",
";",
"return",
"Filters",
"::",... | Uses service location (i.e. `Libraries::locate()`) to look up a named class of a particular
type, and creates an instance of it, and passes an array of parameters to the constructor.
If the given class can't be found, an exception is thrown.
@param string $type The type of class as defined by `Libraries::$_paths`.
@param string $name The un-namespaced name of the class to instantiate.
@param array $options An array of constructor parameters to pass to the class.
@return object If the class is found, returns an instance of it, otherwise throws an
exception.
@throws lithium\core\ClassNotFoundException Throws an exception if the class can't be found.
@filter | [
"Uses",
"service",
"location",
"(",
"i",
".",
"e",
".",
"Libraries",
"::",
"locate",
"()",
")",
"to",
"look",
"up",
"a",
"named",
"class",
"of",
"a",
"particular",
"type",
"and",
"creates",
"an",
"instance",
"of",
"it",
"and",
"passes",
"an",
"array",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L676-L701 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.locate | public static function locate($type, $name = null, array $options = []) {
if (is_object($name) || strpos($name, '\\') !== false) {
return $name;
}
$ident = $name ? ($type . '.' . $name) : ($type . '.*');
$ident .= $options ? '.' . md5(serialize($options)) : null;
if (isset(static::$_cachedPaths[$ident])) {
return static::$_cachedPaths[$ident];
}
$params = static::_params($type, $name);
$defaults = [
'type' => 'class',
'library' => $params['library'] !== '*' ? $params['library'] : null
];
$options += $defaults;
unset($params['library']);
$paths = static::paths($params['type']);
if (!isset($paths)) {
return null;
}
if ($params['name'] === '*') {
$result = static::_locateAll($params, $options);
return (static::$_cachedPaths[$ident] = $result);
}
if ($options['library']) {
$result = static::_locateDeferred(null, $paths, $params, $options);
return static::$_cachedPaths[$ident] = $result;
}
foreach ([false, true] as $defer) {
if ($result = static::_locateDeferred($defer, $paths, $params, $options)) {
return (static::$_cachedPaths[$ident] = $result);
}
}
} | php | public static function locate($type, $name = null, array $options = []) {
if (is_object($name) || strpos($name, '\\') !== false) {
return $name;
}
$ident = $name ? ($type . '.' . $name) : ($type . '.*');
$ident .= $options ? '.' . md5(serialize($options)) : null;
if (isset(static::$_cachedPaths[$ident])) {
return static::$_cachedPaths[$ident];
}
$params = static::_params($type, $name);
$defaults = [
'type' => 'class',
'library' => $params['library'] !== '*' ? $params['library'] : null
];
$options += $defaults;
unset($params['library']);
$paths = static::paths($params['type']);
if (!isset($paths)) {
return null;
}
if ($params['name'] === '*') {
$result = static::_locateAll($params, $options);
return (static::$_cachedPaths[$ident] = $result);
}
if ($options['library']) {
$result = static::_locateDeferred(null, $paths, $params, $options);
return static::$_cachedPaths[$ident] = $result;
}
foreach ([false, true] as $defer) {
if ($result = static::_locateDeferred($defer, $paths, $params, $options)) {
return (static::$_cachedPaths[$ident] = $result);
}
}
} | [
"public",
"static",
"function",
"locate",
"(",
"$",
"type",
",",
"$",
"name",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"name",
")",
"||",
"strpos",
"(",
"$",
"name",
",",
"'\\\\'",
")",... | Performs service location for an object of a specific type. If `$name` is a string, finds the
first instance of a class with the given name in any registered library (i.e. apps, plugins
or vendor libraries registered via `Libraries::add()`), based on each library's order of
precedence. For example, this will find the first model called `File` in any plugin or class
library loaded into an application, including the application itself.
```
Libraries::locate('models', 'File');
```
Order of precedence is usually based on the order in which the library was registered (via
`Libraries::add()`), unless the library was registered with the `'defer'` option set to
`true`. All libraries with the `'defer'` option set will be searched in
registration-order **after** searching all libraries **without** `'defer'` set. This means
that in the above example, if an app and a plugin both have a model named `File`, then the
model from the app will be returned first, assuming the app was registered first (and
assuming the default settings).
If `$name` is not specified, `locate()` returns an array with all classes of the specified
type which can be found. By default, `locate()` searches all registered libraries.
```
Libraries::locate('models');
```
For example, the above will return an array of all model classes in all registered plugins
and libraries (including the app itself).
To learn more about adding and modifying the class paths used with `locate()`, see the
documentation for the `paths()` method.
@see lithium\core\Libraries::paths()
@see lithium\core\Libraries::add()
@see lithium\core\Libraries::_locateDeferred()
@param string $type The type of class to search for. Typically follows the name of the
directory in which the class is stored, i.e. `'models'`, `'controllers'` or
`'adapter'`. Some classes types, such as adapters, will require a greater
degree of specificity when looking up the desired class. In this case, the dot
syntax is used, as in this example when looking up cache adapters:
`'adapter.storage.cache'`, or this example, when looking up authentication
adapters: `'adapter.security.auth'`.
@param string $name The base name (without namespace) of the class you wish to locate. If
unspecified, `locate()` will attempt to find all classes of the type specified
in `$type`. If you only wish to search for classes within a single plugin or
library, you may use the dot syntax to prefix the class name with the library
name, i.e. `'app.Post'`, which will only look for a `Post` model within the
app itself.
@param array $options The options to use when searching and returning class names.
- `'type'` _string_: Defaults to `'class'`. If set to `'file'`, returns file
names instead of class names.
- `'library'` _string_: When specified, only the given library/plugin name will
be searched.
@return mixed If `$name` is specified, returns the name of the first class found that matches
`$name` and `$type`, or returns `null` if no matching classes were found in any
registered library. If `$name` is not specified, returns an array of all classes
found which match `$type`. | [
"Performs",
"service",
"location",
"for",
"an",
"object",
"of",
"a",
"specific",
"type",
".",
"If",
"$name",
"is",
"a",
"string",
"finds",
"the",
"first",
"instance",
"of",
"a",
"class",
"with",
"the",
"given",
"name",
"in",
"any",
"registered",
"library",... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L761-L796 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.cache | public static function cache($cache = null) {
if ($cache === false) {
static::$_cachedPaths = [];
}
if (is_array($cache)) {
static::$_cachedPaths += $cache;
}
return static::$_cachedPaths;
} | php | public static function cache($cache = null) {
if ($cache === false) {
static::$_cachedPaths = [];
}
if (is_array($cache)) {
static::$_cachedPaths += $cache;
}
return static::$_cachedPaths;
} | [
"public",
"static",
"function",
"cache",
"(",
"$",
"cache",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"cache",
"===",
"false",
")",
"{",
"static",
"::",
"$",
"_cachedPaths",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"cache",
")",
")"... | Returns or sets the the class path cache used for mapping class names to file paths, or
locating classes using `Libraries::locate()`.
@param array $cache An array of keys and values to use when pre-populating the cache. Keys
are either class names (which match to file paths as values), or dot-separated
lookup paths used by `locate()` (which matches to either a single class or an
array of classes). If `false`, the cache is cleared.
@return array Returns an array of cached class lookups, formatted per the description for
`$cache`. | [
"Returns",
"or",
"sets",
"the",
"the",
"class",
"path",
"cache",
"used",
"for",
"mapping",
"class",
"names",
"to",
"file",
"paths",
"or",
"locating",
"classes",
"using",
"Libraries",
"::",
"locate",
"()",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L809-L817 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._locateDeferred | protected static function _locateDeferred($defer, $paths, $params, array $options = []) {
$libraries = static::$_configurations;
if (isset($options['library'])) {
$libraries = static::get((array) $options['library']);
}
foreach ($libraries as $library => $config) {
if ($config['defer'] !== $defer && $defer !== null) {
continue;
}
foreach (static::_searchPaths($paths, $library) as $tpl) {
$params['library'] = rtrim($config['prefix'], '\\');
$class = str_replace('\\*', '', Text::insert($tpl, $params));
if (file_exists($file = Libraries::path($class, $options))) {
return ($options['type'] === 'file') ? $file : $class;
}
}
}
} | php | protected static function _locateDeferred($defer, $paths, $params, array $options = []) {
$libraries = static::$_configurations;
if (isset($options['library'])) {
$libraries = static::get((array) $options['library']);
}
foreach ($libraries as $library => $config) {
if ($config['defer'] !== $defer && $defer !== null) {
continue;
}
foreach (static::_searchPaths($paths, $library) as $tpl) {
$params['library'] = rtrim($config['prefix'], '\\');
$class = str_replace('\\*', '', Text::insert($tpl, $params));
if (file_exists($file = Libraries::path($class, $options))) {
return ($options['type'] === 'file') ? $file : $class;
}
}
}
} | [
"protected",
"static",
"function",
"_locateDeferred",
"(",
"$",
"defer",
",",
"$",
"paths",
",",
"$",
"params",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"libraries",
"=",
"static",
"::",
"$",
"_configurations",
";",
"if",
"(",
"isset... | Performs service location lookups by library, based on the library's `'defer'` flag.
Libraries with `'defer'` set to `true` will be searched last when looking up services.
@see lithium\core\Libraries::$_paths
@see lithium\core\Libraries::locate()
@param boolean|null $defer A boolean flag indicating which libraries to search, either
the ones with the `'defer'` flag set, or the ones without. Providing `null`
will cause the method to ignore the `'defer'` flag set on any library and
perform a complete lookup.
@param array $paths List of paths to be searched for the given service (class). These are
defined in `lithium\core\Libraries::$_paths`, and are organized by class type.
@param array $params The list of insert parameters to be injected into each path format
string when searching for classes.
@param array $options
@return string Returns a class path as a string if a given class is found, or null if no
class in any path matching any of the parameters is located. | [
"Performs",
"service",
"location",
"lookups",
"by",
"library",
"based",
"on",
"the",
"library",
"s",
"defer",
"flag",
".",
"Libraries",
"with",
"defer",
"set",
"to",
"true",
"will",
"be",
"searched",
"last",
"when",
"looking",
"up",
"services",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L837-L857 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._searchPaths | protected static function _searchPaths($paths, $library) {
$result = [];
foreach ($paths as $tpl => $opts) {
if (is_int($tpl)) {
$tpl = $opts;
$opts = [];
}
if (isset($opts['libraries']) && !in_array($library, (array) $opts['libraries'])) {
continue;
}
$result[] = $tpl;
}
return $result;
} | php | protected static function _searchPaths($paths, $library) {
$result = [];
foreach ($paths as $tpl => $opts) {
if (is_int($tpl)) {
$tpl = $opts;
$opts = [];
}
if (isset($opts['libraries']) && !in_array($library, (array) $opts['libraries'])) {
continue;
}
$result[] = $tpl;
}
return $result;
} | [
"protected",
"static",
"function",
"_searchPaths",
"(",
"$",
"paths",
",",
"$",
"library",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"tpl",
"=>",
"$",
"opts",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"t... | Returns the list of valid search path templates for the given service location lookup.
@see lithium\core\Libraries::$_paths
@see lithium\core\Libraries::_search()
@param array $paths The list of all possible path templates from `Libraries::$_paths`.
@param string $library The name of the library being searched.
@return array Returns an array of valid path template strings. | [
"Returns",
"the",
"list",
"of",
"valid",
"search",
"path",
"templates",
"for",
"the",
"given",
"service",
"location",
"lookup",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L868-L882 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._locateAll | protected static function _locateAll(array $params, array $options = []) {
$defaults = ['libraries' => null, 'recursive' => true, 'namespaces' => false];
$options += $defaults;
$paths = (array) static::$_paths[$params['type']];
$libraries = $options['library'] ? $options['library'] : $options['libraries'];
$libraries = static::get((array) $libraries);
$flags = ['escape' => '/'];
$classes = [];
foreach ($libraries as $library => $config) {
$params['library'] = $config['path'];
foreach (static::_searchPaths($paths, $library) as $tpl) {
$options['path'] = str_replace('\\', '/', Text::insert($tpl, $params, $flags));
$options['path'] = str_replace('*/', '', $options['path']);
$classes = array_merge($classes, static::_search($config, $options));
}
}
return array_unique($classes);
} | php | protected static function _locateAll(array $params, array $options = []) {
$defaults = ['libraries' => null, 'recursive' => true, 'namespaces' => false];
$options += $defaults;
$paths = (array) static::$_paths[$params['type']];
$libraries = $options['library'] ? $options['library'] : $options['libraries'];
$libraries = static::get((array) $libraries);
$flags = ['escape' => '/'];
$classes = [];
foreach ($libraries as $library => $config) {
$params['library'] = $config['path'];
foreach (static::_searchPaths($paths, $library) as $tpl) {
$options['path'] = str_replace('\\', '/', Text::insert($tpl, $params, $flags));
$options['path'] = str_replace('*/', '', $options['path']);
$classes = array_merge($classes, static::_search($config, $options));
}
}
return array_unique($classes);
} | [
"protected",
"static",
"function",
"_locateAll",
"(",
"array",
"$",
"params",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'libraries'",
"=>",
"null",
",",
"'recursive'",
"=>",
"true",
",",
"'namespaces'",
"=>",
"fal... | Locates all possible classes for given set of parameters.
@param array $params
@param array $options
@return array | [
"Locates",
"all",
"possible",
"classes",
"for",
"given",
"set",
"of",
"parameters",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L891-L911 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._locatePath | protected static function _locatePath($type, $params) {
if (!isset(static::$_paths[$type])) {
return null;
}
$params += ['app' => LITHIUM_APP_PATH, 'root' => LITHIUM_LIBRARY_PATH];
foreach (static::$_paths[$type] as $path) {
if (is_dir($path = str_replace('\\', '/', Text::insert($path, $params)))) {
return $path;
}
}
} | php | protected static function _locatePath($type, $params) {
if (!isset(static::$_paths[$type])) {
return null;
}
$params += ['app' => LITHIUM_APP_PATH, 'root' => LITHIUM_LIBRARY_PATH];
foreach (static::$_paths[$type] as $path) {
if (is_dir($path = str_replace('\\', '/', Text::insert($path, $params)))) {
return $path;
}
}
} | [
"protected",
"static",
"function",
"_locatePath",
"(",
"$",
"type",
",",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"static",
"::",
"$",
"_paths",
"[",
"$",
"type",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"params",
"+=",
... | Helper function for returning known paths given a certain type.
@see lithium\core\Libraries::$_paths
@param string $type Path type (specified in `Libraries::$_paths`).
@param array $params Path parameters.
@return string|null Valid path name or `null` when no of path of given tpe is set. | [
"Helper",
"function",
"for",
"returning",
"known",
"paths",
"given",
"a",
"certain",
"type",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L921-L932 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._search | protected static function _search($config, $options, $name = null) {
$defaults = [
'path' => null,
'suffix' => null,
'namespaces' => false,
'recursive' => false,
'preFilter' => '/[A-Z][A-Za-z0-9]+\./',
'filter' => false,
'exclude' => false,
'format' => function ($file, $config) {
$trim = [strlen($config['path']) + 1, strlen($config['suffix'])];
$file = substr($file, $trim[0], -$trim[1]);
return $config['prefix'] . str_replace('/', '\\', $file);
}
];
$options += $defaults;
$path = $options['path'];
$suffix = $options['namespaces'] ? '' : $config['suffix'];
$suffix = ($options['suffix'] === null) ? $suffix : $options['suffix'];
$dFlags = GLOB_ONLYDIR;
$zFlags = 0;
if (strpos($path, '{') !== false) {
$message = "Search path `{$path}` relies on brace globbing. ";
$message .= 'Support for brace globbing in search paths has been deprecated.';
trigger_error($message, E_USER_DEPRECATED);
$dFlags |= GLOB_BRACE;
$zFlags |= GLOB_BRACE;
}
$libs = (array) glob($path . $suffix, $options['namespaces'] ? $dFlags : $zFlags);
if ($options['recursive']) {
list($current, $match) = explode('/*', $path, 2);
$queue = array_diff((array) glob($current . '/*', $dFlags), $libs);
$match = str_replace('##', '.+', preg_quote(str_replace('*', '##', $match), '/'));
$match = '/' . $match . preg_quote($suffix, '/') . '$/';
while ($queue) {
if (!is_dir($dir = array_pop($queue))) {
continue;
}
$libs = array_merge($libs, (array) glob("{$dir}/*{$suffix}"));
$queue = array_merge($queue, array_diff((array) glob("{$dir}/*", $dFlags), $libs));
}
$libs = preg_grep($match, $libs);
}
if ($suffix) {
$libs = $options['preFilter'] ? preg_grep($options['preFilter'], $libs) : $libs;
}
return static::_filter($libs, (array) $config, $options + compact('name'));
} | php | protected static function _search($config, $options, $name = null) {
$defaults = [
'path' => null,
'suffix' => null,
'namespaces' => false,
'recursive' => false,
'preFilter' => '/[A-Z][A-Za-z0-9]+\./',
'filter' => false,
'exclude' => false,
'format' => function ($file, $config) {
$trim = [strlen($config['path']) + 1, strlen($config['suffix'])];
$file = substr($file, $trim[0], -$trim[1]);
return $config['prefix'] . str_replace('/', '\\', $file);
}
];
$options += $defaults;
$path = $options['path'];
$suffix = $options['namespaces'] ? '' : $config['suffix'];
$suffix = ($options['suffix'] === null) ? $suffix : $options['suffix'];
$dFlags = GLOB_ONLYDIR;
$zFlags = 0;
if (strpos($path, '{') !== false) {
$message = "Search path `{$path}` relies on brace globbing. ";
$message .= 'Support for brace globbing in search paths has been deprecated.';
trigger_error($message, E_USER_DEPRECATED);
$dFlags |= GLOB_BRACE;
$zFlags |= GLOB_BRACE;
}
$libs = (array) glob($path . $suffix, $options['namespaces'] ? $dFlags : $zFlags);
if ($options['recursive']) {
list($current, $match) = explode('/*', $path, 2);
$queue = array_diff((array) glob($current . '/*', $dFlags), $libs);
$match = str_replace('##', '.+', preg_quote(str_replace('*', '##', $match), '/'));
$match = '/' . $match . preg_quote($suffix, '/') . '$/';
while ($queue) {
if (!is_dir($dir = array_pop($queue))) {
continue;
}
$libs = array_merge($libs, (array) glob("{$dir}/*{$suffix}"));
$queue = array_merge($queue, array_diff((array) glob("{$dir}/*", $dFlags), $libs));
}
$libs = preg_grep($match, $libs);
}
if ($suffix) {
$libs = $options['preFilter'] ? preg_grep($options['preFilter'], $libs) : $libs;
}
return static::_filter($libs, (array) $config, $options + compact('name'));
} | [
"protected",
"static",
"function",
"_search",
"(",
"$",
"config",
",",
"$",
"options",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"defaults",
"=",
"[",
"'path'",
"=>",
"null",
",",
"'suffix'",
"=>",
"null",
",",
"'namespaces'",
"=>",
"false",
",",
... | Search file system.
@param string $config
@param array $options
@param string $name
@return array | [
"Search",
"file",
"system",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L942-L994 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._filter | protected static function _filter($libs, array $config, array $options = []) {
if (is_callable($options['format'])) {
foreach ($libs as $i => $file) {
$libs[$i] = $options['format']($file, $config);
}
$libs = $options['name'] ? preg_grep("/{$options['name']}$/", $libs) : $libs;
}
if ($exclude = $options['exclude']) {
if (is_string($exclude)) {
$libs = preg_grep($exclude, $libs, PREG_GREP_INVERT);
} elseif (is_callable($exclude)) {
$libs = array_values(array_filter($libs, $exclude));
}
}
if ($filter = $options['filter']) {
if (is_string($filter)) {
$libs = preg_grep($filter, $libs) ;
} elseif (is_callable($filter)) {
$libs = array_filter(array_map($filter, $libs));
}
}
return $libs;
} | php | protected static function _filter($libs, array $config, array $options = []) {
if (is_callable($options['format'])) {
foreach ($libs as $i => $file) {
$libs[$i] = $options['format']($file, $config);
}
$libs = $options['name'] ? preg_grep("/{$options['name']}$/", $libs) : $libs;
}
if ($exclude = $options['exclude']) {
if (is_string($exclude)) {
$libs = preg_grep($exclude, $libs, PREG_GREP_INVERT);
} elseif (is_callable($exclude)) {
$libs = array_values(array_filter($libs, $exclude));
}
}
if ($filter = $options['filter']) {
if (is_string($filter)) {
$libs = preg_grep($filter, $libs) ;
} elseif (is_callable($filter)) {
$libs = array_filter(array_map($filter, $libs));
}
}
return $libs;
} | [
"protected",
"static",
"function",
"_filter",
"(",
"$",
"libs",
",",
"array",
"$",
"config",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"options",
"[",
"'format'",
"]",
")",
")",
"{",
"foreach",
"(",
... | Filters a list of library search results by the given set of options.
@param array $libs List of found libraries.
@param array $config The configuration of the library currently being searched within.
@param array $options The options used to filter/format `$libs`.
@return array Returns a copy of `$libs`, filtered and transformed based on the configuration
provided in `$options`. | [
"Filters",
"a",
"list",
"of",
"library",
"search",
"results",
"by",
"the",
"given",
"set",
"of",
"options",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L1005-L1027 |
UnionOfRAD/lithium | core/Libraries.php | Libraries._params | protected static function _params($type, $name = "*") {
if (!$name) {
$name = '*';
}
$library = $namespace = $class = '*';
if (strpos($type, '.') !== false) {
$parts = explode('.', $type);
$type = array_shift($parts);
switch (count($parts)) {
case 1:
list($class) = $parts;
break;
case 2:
list($namespace, $class) = $parts;
break;
default:
$class = array_pop($parts);
$namespace = join('\\', $parts);
break;
}
}
if (strpos($name, '.') !== false) {
$parts = explode('.', $name);
$library = array_shift($parts);
$name = array_pop($parts);
$namespace = $parts ? join('\\', $parts) : "*";
}
return compact('library', 'namespace', 'type', 'class', 'name');
} | php | protected static function _params($type, $name = "*") {
if (!$name) {
$name = '*';
}
$library = $namespace = $class = '*';
if (strpos($type, '.') !== false) {
$parts = explode('.', $type);
$type = array_shift($parts);
switch (count($parts)) {
case 1:
list($class) = $parts;
break;
case 2:
list($namespace, $class) = $parts;
break;
default:
$class = array_pop($parts);
$namespace = join('\\', $parts);
break;
}
}
if (strpos($name, '.') !== false) {
$parts = explode('.', $name);
$library = array_shift($parts);
$name = array_pop($parts);
$namespace = $parts ? join('\\', $parts) : "*";
}
return compact('library', 'namespace', 'type', 'class', 'name');
} | [
"protected",
"static",
"function",
"_params",
"(",
"$",
"type",
",",
"$",
"name",
"=",
"\"*\"",
")",
"{",
"if",
"(",
"!",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"'*'",
";",
"}",
"$",
"library",
"=",
"$",
"namespace",
"=",
"$",
"class",
"=",
"... | Get params from type.
@param string $type
@param string $name default: '*'
@return array type, namespace, class, name | [
"Get",
"params",
"from",
"type",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L1036-L1066 |
UnionOfRAD/lithium | core/Libraries.php | Libraries.applyFilter | public static function applyFilter($method, $filter = null) {
$message = '`' . __METHOD__ . '()` has been deprecated in favor of ';
$message .= '`\lithium\aop\Filters::apply()` and `::clear()`.';
trigger_error($message, E_USER_DEPRECATED);
$class = get_called_class();
if ($method === false) {
Filters::clear($class);
return;
}
foreach ((array) $method as $m) {
if ($filter === false) {
Filters::clear($class, $m);
} else {
Filters::apply($class, $m, $filter);
}
}
} | php | public static function applyFilter($method, $filter = null) {
$message = '`' . __METHOD__ . '()` has been deprecated in favor of ';
$message .= '`\lithium\aop\Filters::apply()` and `::clear()`.';
trigger_error($message, E_USER_DEPRECATED);
$class = get_called_class();
if ($method === false) {
Filters::clear($class);
return;
}
foreach ((array) $method as $m) {
if ($filter === false) {
Filters::clear($class, $m);
} else {
Filters::apply($class, $m, $filter);
}
}
} | [
"public",
"static",
"function",
"applyFilter",
"(",
"$",
"method",
",",
"$",
"filter",
"=",
"null",
")",
"{",
"$",
"message",
"=",
"'`'",
".",
"__METHOD__",
".",
"'()` has been deprecated in favor of '",
";",
"$",
"message",
".=",
"'`\\lithium\\aop\\Filters::apply... | Apply a closure to a method in `Libraries`.
@deprecated Replaced by `\lithium\aop\Filters::apply()` and `::clear()`.
@see lithium\util\collection\Filters
@param string $method The name of the method to apply the closure to.
@param Closure $filter The closure that is used to filter the method.
@return void | [
"Apply",
"a",
"closure",
"to",
"a",
"method",
"in",
"Libraries",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Libraries.php#L1087-L1105 |
UnionOfRAD/lithium | util/Validator.php | Validator.reset | public static function reset() {
$alnum = '[A-Fa-f0-9]';
$class = get_called_class();
Filters::clear($class);
static::$_rules = [
'alphaNumeric' => '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/mu',
'blank' => '/[^\\s]/',
'creditCard' => [
'amex' => '/^3[4|7]\\d{13}$/',
'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
'disc' => '/^(?:6011|650\\d)\\d{12}$/',
'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
'enroute' => '/^2(?:014|149)\\d{11}$/',
'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
'mc' => '/^5[1-5]\\d{14}$/',
'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})' .
'\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4]' .
'[0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
'visa' => '/^4\\d{12}(\\d{3})?$/',
'voyager' => '/^8699[0-9]{11}$/',
'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3' .
'(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
],
'date' => [
'dmy' => '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
'(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?' .
'\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' .
'(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' .
'00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|' .
'(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%',
'mdy' => '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|' .
'1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d' .
'{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' .
'(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' .
'00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1' .
'\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%',
'ymd' => '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579]' .
'[26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)' .
'(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|' .
'\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])' .
'\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]' .
'))))$%',
'dMy' => '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)' .
'(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ ' .
'(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' .
'[048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|' .
'Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|' .
'Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]' .
'\\d)\\d{2})$/',
'Mdy' => '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?' .
'|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)' .
'|(ne?))|Aug(ust)?|Oct(ober)?|(Sept|Nov|Dec)(ember)?)\\ (0?[1-9]' .
'|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ' .
'((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' .
'[048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/',
'My' => '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|' .
'Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]' .
'|[2-9]\\d)\\d{2})$%',
'my' => '%^(0?[1-9]|1[012])([- /.])((1[6-9])|([2-9]\\d)\\d{2})$%'
],
'ip' => function($value, $format = null, array $options = []) {
$options += ['flags' => []];
return (boolean) filter_var($value, FILTER_VALIDATE_IP, $options);
},
'money' => [
'right' => '/^(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))' .
'((?!\1)[,.]\d{2})?(?<!\x{00a2})\p{Sc}?$/u',
'left' => '/^(?!\x{00a2})\p{Sc}?(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?' .
'(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{2})?$/u'
],
'notEmpty' => '/[^\s]+/m',
'phone' => '/^\+?[0-9\(\)\-]{10,20}$/',
'postalCode' => '/(^|\A\b)[A-Z0-9\s\-]{5,}($|\b\z)/i',
'regex' => '/^(?:([^[:alpha:]\\\\{<\[\(])(.+)(?:\1))|(?:{(.+)})|(?:<(.+)>)|' .
'(?:\[(.+)\])|(?:\((.+)\))[gimsxu]*$/',
'time' => '%^((0?[1-9]|1[012])(:[0-5]\d){0,2}([AP]M|[ap]m))$|^([01]\d|2[0-3])' .
'(:[0-5]\d){0,2}$%',
'boolean' => function($value) {
$bool = is_bool($value);
$filter = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return ($bool || $filter !== null || empty($value));
},
'decimal' => function($value, $format = null, array $options = []) {
if (isset($options['precision'])) {
$precision = strlen($value) - strrpos($value, '.') - 1;
if ($precision !== (int) $options['precision']) {
return false;
}
}
return (filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) !== null);
},
'inList' => function($value, $format, $options) {
$options += ['list' => []];
$strict = is_bool($value) || $value === '';
return in_array($value, $options['list'], $strict);
},
'lengthBetween' => function($value, $format, $options) {
$length = strlen($value);
$options += ['min' => 1, 'max' => 255];
return ($length >= $options['min'] && $length <= $options['max']);
},
'luhn' => function($value) {
if (empty($value) || !is_string($value)) {
return false;
}
$sum = 0;
$length = strlen($value);
for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
$sum += $value[$position];
}
for ($position = ($length % 2); $position < $length; $position += 2) {
$number = $value[$position] * 2;
$sum += ($number < 10) ? $number : $number - 9;
}
return ($sum % 10 === 0);
},
'numeric' => function($value) {
return is_numeric($value);
},
'inRange' => function($value, $format, $options) {
$defaults = ['upper' => null, 'lower' => null];
$options += $defaults;
if (!is_numeric($value)) {
return false;
}
switch (true) {
case ($options['upper'] !== null && $options['lower'] !== null):
return ($value >= $options['lower'] && $value <= $options['upper']);
case ($options['upper'] !== null):
return ($value <= $options['upper']);
case ($options['lower'] !== null):
return ($value >= $options['lower']);
}
return is_finite($value);
},
'uuid' => "/^{$alnum}{8}-{$alnum}{4}-{$alnum}{4}-{$alnum}{4}-{$alnum}{12}$/",
'email' => function($value) {
return filter_var($value, FILTER_VALIDATE_EMAIL);
},
'url' => function($value, $format = null, array $options = []) {
$options += ['flags' => []];
return (boolean) filter_var($value, FILTER_VALIDATE_URL, $options);
}
];
$isEmpty = function($params, $next) {
extract($params);
return (empty($value) && $value !== '0') ? false : $next($params);
};
Filters::apply($class, 'alphaNumeric', $isEmpty);
Filters::apply($class, 'notEmpty', $isEmpty);
Filters::apply($class, 'creditCard', function($params, $next) {
extract($params);
$options += ['deep' => false];
if (strlen($value = str_replace(['-', ' '], '', $value)) < 13) {
return false;
}
$params['value'] = $value;
if (!$next($params)) {
return false;
}
return $options['deep'] ? Validator::isLuhn($value) : true;
});
Filters::apply($class, 'email', function($params, $next) {
extract($params);
$defaults = ['deep' => false];
$options += $defaults;
if (!$next($params)) {
return false;
}
if (!$options['deep']) {
return true;
}
list($prefix, $host) = explode('@', $params['value']);
$mxhosts = [];
if (getmxrr($host, $mxhosts)) {
return is_array($mxhosts);
}
return false;
});
} | php | public static function reset() {
$alnum = '[A-Fa-f0-9]';
$class = get_called_class();
Filters::clear($class);
static::$_rules = [
'alphaNumeric' => '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/mu',
'blank' => '/[^\\s]/',
'creditCard' => [
'amex' => '/^3[4|7]\\d{13}$/',
'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
'disc' => '/^(?:6011|650\\d)\\d{12}$/',
'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
'enroute' => '/^2(?:014|149)\\d{11}$/',
'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
'mc' => '/^5[1-5]\\d{14}$/',
'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})' .
'\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4]' .
'[0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
'visa' => '/^4\\d{12}(\\d{3})?$/',
'voyager' => '/^8699[0-9]{11}$/',
'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3' .
'(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
],
'date' => [
'dmy' => '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
'(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?' .
'\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' .
'(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' .
'00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|' .
'(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%',
'mdy' => '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|' .
'1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d' .
'{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?' .
'(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])' .
'00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1' .
'\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%',
'ymd' => '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579]' .
'[26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)' .
'(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|' .
'\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])' .
'\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]' .
'))))$%',
'dMy' => '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)' .
'(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ ' .
'(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' .
'[048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|' .
'Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|' .
'Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]' .
'\\d)\\d{2})$/',
'Mdy' => '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?' .
'|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)' .
'|(ne?))|Aug(ust)?|Oct(ober)?|(Sept|Nov|Dec)(ember)?)\\ (0?[1-9]' .
'|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ' .
'((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468]' .
'[048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/',
'My' => '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|' .
'Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]' .
'|[2-9]\\d)\\d{2})$%',
'my' => '%^(0?[1-9]|1[012])([- /.])((1[6-9])|([2-9]\\d)\\d{2})$%'
],
'ip' => function($value, $format = null, array $options = []) {
$options += ['flags' => []];
return (boolean) filter_var($value, FILTER_VALIDATE_IP, $options);
},
'money' => [
'right' => '/^(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))' .
'((?!\1)[,.]\d{2})?(?<!\x{00a2})\p{Sc}?$/u',
'left' => '/^(?!\x{00a2})\p{Sc}?(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?' .
'(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{2})?$/u'
],
'notEmpty' => '/[^\s]+/m',
'phone' => '/^\+?[0-9\(\)\-]{10,20}$/',
'postalCode' => '/(^|\A\b)[A-Z0-9\s\-]{5,}($|\b\z)/i',
'regex' => '/^(?:([^[:alpha:]\\\\{<\[\(])(.+)(?:\1))|(?:{(.+)})|(?:<(.+)>)|' .
'(?:\[(.+)\])|(?:\((.+)\))[gimsxu]*$/',
'time' => '%^((0?[1-9]|1[012])(:[0-5]\d){0,2}([AP]M|[ap]m))$|^([01]\d|2[0-3])' .
'(:[0-5]\d){0,2}$%',
'boolean' => function($value) {
$bool = is_bool($value);
$filter = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return ($bool || $filter !== null || empty($value));
},
'decimal' => function($value, $format = null, array $options = []) {
if (isset($options['precision'])) {
$precision = strlen($value) - strrpos($value, '.') - 1;
if ($precision !== (int) $options['precision']) {
return false;
}
}
return (filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE) !== null);
},
'inList' => function($value, $format, $options) {
$options += ['list' => []];
$strict = is_bool($value) || $value === '';
return in_array($value, $options['list'], $strict);
},
'lengthBetween' => function($value, $format, $options) {
$length = strlen($value);
$options += ['min' => 1, 'max' => 255];
return ($length >= $options['min'] && $length <= $options['max']);
},
'luhn' => function($value) {
if (empty($value) || !is_string($value)) {
return false;
}
$sum = 0;
$length = strlen($value);
for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
$sum += $value[$position];
}
for ($position = ($length % 2); $position < $length; $position += 2) {
$number = $value[$position] * 2;
$sum += ($number < 10) ? $number : $number - 9;
}
return ($sum % 10 === 0);
},
'numeric' => function($value) {
return is_numeric($value);
},
'inRange' => function($value, $format, $options) {
$defaults = ['upper' => null, 'lower' => null];
$options += $defaults;
if (!is_numeric($value)) {
return false;
}
switch (true) {
case ($options['upper'] !== null && $options['lower'] !== null):
return ($value >= $options['lower'] && $value <= $options['upper']);
case ($options['upper'] !== null):
return ($value <= $options['upper']);
case ($options['lower'] !== null):
return ($value >= $options['lower']);
}
return is_finite($value);
},
'uuid' => "/^{$alnum}{8}-{$alnum}{4}-{$alnum}{4}-{$alnum}{4}-{$alnum}{12}$/",
'email' => function($value) {
return filter_var($value, FILTER_VALIDATE_EMAIL);
},
'url' => function($value, $format = null, array $options = []) {
$options += ['flags' => []];
return (boolean) filter_var($value, FILTER_VALIDATE_URL, $options);
}
];
$isEmpty = function($params, $next) {
extract($params);
return (empty($value) && $value !== '0') ? false : $next($params);
};
Filters::apply($class, 'alphaNumeric', $isEmpty);
Filters::apply($class, 'notEmpty', $isEmpty);
Filters::apply($class, 'creditCard', function($params, $next) {
extract($params);
$options += ['deep' => false];
if (strlen($value = str_replace(['-', ' '], '', $value)) < 13) {
return false;
}
$params['value'] = $value;
if (!$next($params)) {
return false;
}
return $options['deep'] ? Validator::isLuhn($value) : true;
});
Filters::apply($class, 'email', function($params, $next) {
extract($params);
$defaults = ['deep' => false];
$options += $defaults;
if (!$next($params)) {
return false;
}
if (!$options['deep']) {
return true;
}
list($prefix, $host) = explode('@', $params['value']);
$mxhosts = [];
if (getmxrr($host, $mxhosts)) {
return is_array($mxhosts);
}
return false;
});
} | [
"public",
"static",
"function",
"reset",
"(",
")",
"{",
"$",
"alnum",
"=",
"'[A-Fa-f0-9]'",
";",
"$",
"class",
"=",
"get_called_class",
"(",
")",
";",
"Filters",
"::",
"clear",
"(",
"$",
"class",
")",
";",
"static",
"::",
"$",
"_rules",
"=",
"[",
"'a... | Initializes the list of default validation rules. | [
"Initializes",
"the",
"list",
"of",
"default",
"validation",
"rules",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L177-L372 |
UnionOfRAD/lithium | util/Validator.php | Validator.respondsTo | public static function respondsTo($method, $internal = false) {
$rule = preg_replace("/^is([A-Z][A-Za-z0-9]+)$/", '$1', $method);
$rule[0] = strtolower($rule[0]);
return isset(static::$_rules[$rule]) || parent::respondsTo($method, $internal);
} | php | public static function respondsTo($method, $internal = false) {
$rule = preg_replace("/^is([A-Z][A-Za-z0-9]+)$/", '$1', $method);
$rule[0] = strtolower($rule[0]);
return isset(static::$_rules[$rule]) || parent::respondsTo($method, $internal);
} | [
"public",
"static",
"function",
"respondsTo",
"(",
"$",
"method",
",",
"$",
"internal",
"=",
"false",
")",
"{",
"$",
"rule",
"=",
"preg_replace",
"(",
"\"/^is([A-Z][A-Za-z0-9]+)$/\"",
",",
"'$1'",
",",
"$",
"method",
")",
";",
"$",
"rule",
"[",
"0",
"]",... | Determines if a given method can be called.
@param string $method Name of the method.
@param boolean $internal Provide `true` to perform check from inside the
class/object. When `false` checks also for public visibility;
defaults to `false`.
@return boolean Returns `true` if the method can be called, `false` otherwise. | [
"Determines",
"if",
"a",
"given",
"method",
"can",
"be",
"called",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L402-L406 |
UnionOfRAD/lithium | util/Validator.php | Validator.check | public static function check(array $values, array $rules, array $options = []) {
$defaults = [
'notEmpty',
'message' => null,
'required' => true,
'skipEmpty' => false,
'format' => 'any',
'on' => null,
'last' => false
];
$options += $defaults;
$params = compact('values', 'rules', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$values = $params['values'];
$rules = $params['rules'];
$options = $params['options'];
$errors = [];
$events = (array) (isset($options['events']) ? $options['events'] : null);
$values = array_merge($values, Set::flatten($values));
foreach ($rules as $field => $rules) {
$rules = is_string($rules) ? ['message' => $rules] : $rules;
$rules = is_array(current($rules)) ? $rules : [$rules];
$errors[$field] = [];
$options['field'] = $field;
foreach ($rules as $key => $rule) {
if (array_key_exists('required', $rule) && $rule['required'] === null) {
unset($rule['required']);
}
$rule += $options + compact('values');
list($name) = $rule;
if ($events && $rule['on'] && !array_intersect($events, (array) $rule['on'])) {
continue;
}
if (!array_key_exists($field, $values)) {
if ($rule['required']) {
$errors[$field][$key] = $rule['message'] ?: $key;
}
if ($rule['last']) {
break;
}
continue;
}
if (empty($values[$field]) && $rule['skipEmpty']) {
continue;
}
if (!static::rule($name, $values[$field], $rule['format'], $rule + $options)) {
$errors[$field][$key] = $rule['message'] ?: $key;
if ($rule['last']) {
break;
}
}
}
}
return array_filter($errors);
});
} | php | public static function check(array $values, array $rules, array $options = []) {
$defaults = [
'notEmpty',
'message' => null,
'required' => true,
'skipEmpty' => false,
'format' => 'any',
'on' => null,
'last' => false
];
$options += $defaults;
$params = compact('values', 'rules', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$values = $params['values'];
$rules = $params['rules'];
$options = $params['options'];
$errors = [];
$events = (array) (isset($options['events']) ? $options['events'] : null);
$values = array_merge($values, Set::flatten($values));
foreach ($rules as $field => $rules) {
$rules = is_string($rules) ? ['message' => $rules] : $rules;
$rules = is_array(current($rules)) ? $rules : [$rules];
$errors[$field] = [];
$options['field'] = $field;
foreach ($rules as $key => $rule) {
if (array_key_exists('required', $rule) && $rule['required'] === null) {
unset($rule['required']);
}
$rule += $options + compact('values');
list($name) = $rule;
if ($events && $rule['on'] && !array_intersect($events, (array) $rule['on'])) {
continue;
}
if (!array_key_exists($field, $values)) {
if ($rule['required']) {
$errors[$field][$key] = $rule['message'] ?: $key;
}
if ($rule['last']) {
break;
}
continue;
}
if (empty($values[$field]) && $rule['skipEmpty']) {
continue;
}
if (!static::rule($name, $values[$field], $rule['format'], $rule + $options)) {
$errors[$field][$key] = $rule['message'] ?: $key;
if ($rule['last']) {
break;
}
}
}
}
return array_filter($errors);
});
} | [
"public",
"static",
"function",
"check",
"(",
"array",
"$",
"values",
",",
"array",
"$",
"rules",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'notEmpty'",
",",
"'message'",
"=>",
"null",
",",
"'required'",
"=>",
... | Checks a set of values against a specified rules list. This method may be used to validate
any arbitrary array of data against a set of validation rules.
@param array $values An array of key/value pairs, where the values are to be checked.
@param array $rules An array of rules to check the values in `$values` against. Each key in
`$rules` should match a key contained in `$values`, and each value should be a
validation rule in one of the allowable formats. For example, if you are
validating a data set containing a `'credit_card'` key, possible values for
`$rules` would be as follows:
- `array('credit_card' => 'You must include a credit card number')`: This is the
simplest form of validation rule, in which the value is simply a message to
display if the rule fails. Using this format, all other validation settings
inherit from the defaults, including the validation rule itself, which only
checks to see that the corresponding key in `$values` is present and contains
a value that is not empty. _Please note when globalizing validation messages:_
When specifying messages, it may be preferable to use a code string (i.e.
`'ERR_NO_TITLE'`) instead of the full text of the validation error. These code
strings may then be translated by the appropriate tools in the templating layer.
- `array('credit_card' => ['creditCard', 'message' => 'Invalid CC #'])`:
In the second format, the validation rule (in this case `creditCard`) and
associated configuration are specified as an array, where the rule to use is
the first value in the array (no key), and additional settings are specified
as other keys in the array. Please see the list below for more information on
allowed keys.
- The final format allows you to apply multiple validation rules to a single
value, and it is specified as follows:
`array('credit_card' => [
['notEmpty', 'message' => 'You must include credit card number'],
['creditCard', 'message' => 'Your credit card number must be valid']
]);`
@param array $options Validator-specific options.
Each rule defined as an array can contain any of the following settings
(in addition to the first value, which represents the rule to be used):
- `'message'` _string_: The error message to be returned if the validation
rule fails. See the note above regarding globalization of error messages.
- `'required`' _boolean_: Represents whether the value is required to be
present in `$values`. If `'required'` is set to `false`, the validation rule
will be skipped if the corresponding key is not present. Defaults to `true`.
- `'skipEmpty'` _boolean_: Similar to `'required'`, this setting (if `true`)
will cause the validation rule to be skipped if the corresponding value
is empty (an empty string or `null`). Defaults to `false`.
- `'format'` _string_: If the validation rule has multiple format definitions
(see the `add()` or `init()` methods), the name of the format to be used
can be specified here. Additionally, two special values can be used:
either `'any'`, which means that all formats will be checked and the rule
will pass if any format passes, or `'all'`, which requires all formats to
pass in order for the rule check to succeed.
@return array Returns an array containing all validation failures for data in `$values`,
where each key matches a key in `$values`, and each value is an array of
that element's validation errors.
@filter | [
"Checks",
"a",
"set",
"of",
"values",
"against",
"a",
"specified",
"rules",
"list",
".",
"This",
"method",
"may",
"be",
"used",
"to",
"validate",
"any",
"arbitrary",
"array",
"of",
"data",
"against",
"a",
"set",
"of",
"validation",
"rules",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L461-L524 |
UnionOfRAD/lithium | util/Validator.php | Validator.add | public static function add($name, $rule = null, array $options = []) {
if (!is_array($name)) {
$name = [$name => $rule];
}
static::$_rules = Set::merge(static::$_rules, $name);
if (!empty($options)) {
$options = array_combine(array_keys($name), array_fill(0, count($name), $options));
static::$_options = Set::merge(static::$_options, $options);
}
} | php | public static function add($name, $rule = null, array $options = []) {
if (!is_array($name)) {
$name = [$name => $rule];
}
static::$_rules = Set::merge(static::$_rules, $name);
if (!empty($options)) {
$options = array_combine(array_keys($name), array_fill(0, count($name), $options));
static::$_options = Set::merge(static::$_options, $options);
}
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"name",
",",
"$",
"rule",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"[",
"$",
"name",
"=... | Adds to or replaces built-in validation rules specified in `Validator::$_rules`. Any new
validation rules created are automatically callable as validation methods.
For example:
```
Validator::add('zeroToNine', '/^[0-9]$/');
$isValid = Validator::isZeroToNine("5"); // true
$isValid = Validator::isZeroToNine("20"); // false
```
Alternatively, the first parameter may be an array of rules expressed as key/value pairs,
as in the following:
```
Validator::add([
'zeroToNine' => '/^[0-9]$/',
'tenToNineteen' => '/^1[0-9]$/',
]);
```
In addition to regular expressions, validation rules can also be defined as full anonymous
functions:
```
use app\models\Account;
Validator::add('accountActive', function($value) {
$value = is_int($value) ? Account::find($value) : $value;
return (boolean) $value->is_active;
});
$testAccount = Account::create(['is_active' => false]);
Validator::isAccountActive($testAccount); // returns false
```
These functions can take up to 3 parameters:
- `$value` _mixed_: This is the actual value to be validated (as in the above example).
- `$format` _string_: Often, validation rules come in multiple "formats", for example:
postal codes, which vary by country or region. Defining multiple formats allows you to
retain flexibility in how you validate data. In cases where a user's country of origin
is known, the appropriate validation rule may be selected. In cases where it is not
known, the value of `$format` may be `'any'`, which should pass if any format matches.
In cases where validation rule formats are not mutually exclusive, the value may be
`'all'`, in which case all must match.
- `$options` _array_: This parameter allows a validation rule to implement custom
options.
@see lithium\util\Validator::$_rules
@param mixed $name The name of the validation rule (string), or an array of key/value pairs
of names and rules.
@param string $rule If $name is a string, this should be a string regular expression, or a
closure that returns a boolean indicating success. Should be left blank if
`$name` is an array.
@param array $options The default options for validating this rule. An option which applies
to all regular expression rules is `'contains'` which, if set to true, allows
validated values to simply _contain_ a match to a rule, rather than exactly
matching it in whole. | [
"Adds",
"to",
"or",
"replaces",
"built",
"-",
"in",
"validation",
"rules",
"specified",
"in",
"Validator",
"::",
"$_rules",
".",
"Any",
"new",
"validation",
"rules",
"created",
"are",
"automatically",
"callable",
"as",
"validation",
"methods",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L583-L593 |
UnionOfRAD/lithium | util/Validator.php | Validator.rule | public static function rule($rule, $value, $format = 'any', array $options = []) {
if (!isset(static::$_rules[$rule])) {
throw new InvalidArgumentException("Rule `{$rule}` is not a validation rule.");
}
$defaults = isset(static::$_options[$rule]) ? static::$_options[$rule] : [];
$options = (array) $options + $defaults + static::$_options['defaults'];
$ruleCheck = static::$_rules[$rule];
$ruleCheck = is_array($ruleCheck) ? $ruleCheck : [$ruleCheck];
if (!$options['contains'] && !empty($ruleCheck)) {
foreach ($ruleCheck as $key => $item) {
$ruleCheck[$key] = is_string($item) ? "/^{$item}$/" : $item;
}
}
$params = compact('value', 'format', 'options');
return Filters::run(get_called_class(), $rule, $params, static::_checkFormats($ruleCheck));
} | php | public static function rule($rule, $value, $format = 'any', array $options = []) {
if (!isset(static::$_rules[$rule])) {
throw new InvalidArgumentException("Rule `{$rule}` is not a validation rule.");
}
$defaults = isset(static::$_options[$rule]) ? static::$_options[$rule] : [];
$options = (array) $options + $defaults + static::$_options['defaults'];
$ruleCheck = static::$_rules[$rule];
$ruleCheck = is_array($ruleCheck) ? $ruleCheck : [$ruleCheck];
if (!$options['contains'] && !empty($ruleCheck)) {
foreach ($ruleCheck as $key => $item) {
$ruleCheck[$key] = is_string($item) ? "/^{$item}$/" : $item;
}
}
$params = compact('value', 'format', 'options');
return Filters::run(get_called_class(), $rule, $params, static::_checkFormats($ruleCheck));
} | [
"public",
"static",
"function",
"rule",
"(",
"$",
"rule",
",",
"$",
"value",
",",
"$",
"format",
"=",
"'any'",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"static",
"::",
"$",
"_rules",
"[",
"$",
"rule",
... | Checks a single value against a single validation rule in one or more formats.
@param string $rule
@param mixed $value
@param string $format
@param array $options
@return boolean Returns `true` or `false` indicating whether the validation rule check
succeeded or failed.
@filter | [
"Checks",
"a",
"single",
"value",
"against",
"a",
"single",
"validation",
"rule",
"in",
"one",
"or",
"more",
"formats",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L606-L624 |
UnionOfRAD/lithium | util/Validator.php | Validator.rules | public static function rules($name = null) {
if (!$name) {
return array_keys(static::$_rules);
}
return isset(static::$_rules[$name]) ? static::$_rules[$name] : null;
} | php | public static function rules($name = null) {
if (!$name) {
return array_keys(static::$_rules);
}
return isset(static::$_rules[$name]) ? static::$_rules[$name] : null;
} | [
"public",
"static",
"function",
"rules",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"name",
")",
"{",
"return",
"array_keys",
"(",
"static",
"::",
"$",
"_rules",
")",
";",
"}",
"return",
"isset",
"(",
"static",
"::",
"$",
"_rules... | Returns a list of available validation rules, or the configuration details of a single rule.
@param string $name Optional name of a rule to get the details of. If not specified, an array
of all available rule names is returned. Otherwise, returns the details of a
single rule. This can be a regular expression string, a closure object, or an
array of available rule formats made up of string regular expressions,
closures, or both.
@return mixed Returns either an single array of rule names, or the details of a single rule. | [
"Returns",
"a",
"list",
"of",
"available",
"validation",
"rules",
"or",
"the",
"configuration",
"details",
"of",
"a",
"single",
"rule",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L636-L641 |
UnionOfRAD/lithium | util/Validator.php | Validator._checkFormats | protected static function _checkFormats($rules) {
return function($params) use ($rules) {
$value = $params['value'];
$format = $params['format'];
$options = $params['options'];
$defaults = ['all' => true];
$options += $defaults;
$formats = (array) $format;
$options['all'] = ($format === 'any');
foreach ($rules as $index => $check) {
if (!$options['all'] && !(in_array($index, $formats) || isset($formats[$index]))) {
continue;
}
$regexPassed = (is_string($check) && preg_match($check, $value));
$closurePassed = (is_object($check) && $check($value, $format, $options));
if ($regexPassed || $closurePassed) {
return true;
}
}
return false;
};
} | php | protected static function _checkFormats($rules) {
return function($params) use ($rules) {
$value = $params['value'];
$format = $params['format'];
$options = $params['options'];
$defaults = ['all' => true];
$options += $defaults;
$formats = (array) $format;
$options['all'] = ($format === 'any');
foreach ($rules as $index => $check) {
if (!$options['all'] && !(in_array($index, $formats) || isset($formats[$index]))) {
continue;
}
$regexPassed = (is_string($check) && preg_match($check, $value));
$closurePassed = (is_object($check) && $check($value, $format, $options));
if ($regexPassed || $closurePassed) {
return true;
}
}
return false;
};
} | [
"protected",
"static",
"function",
"_checkFormats",
"(",
"$",
"rules",
")",
"{",
"return",
"function",
"(",
"$",
"params",
")",
"use",
"(",
"$",
"rules",
")",
"{",
"$",
"value",
"=",
"$",
"params",
"[",
"'value'",
"]",
";",
"$",
"format",
"=",
"$",
... | Perform validation checks against a value using an array of all possible formats for a rule,
and an array specifying which formats within the rule to use.
@param array $rules All available rules.
@return \Closure Function returning boolean `true` if validation succeeded, `false` otherwise. | [
"Perform",
"validation",
"checks",
"against",
"a",
"value",
"using",
"an",
"array",
"of",
"all",
"possible",
"formats",
"for",
"a",
"rule",
"and",
"an",
"array",
"specifying",
"which",
"formats",
"within",
"the",
"rule",
"to",
"use",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Validator.php#L650-L676 |
UnionOfRAD/lithium | storage/cache/adapter/Redis.php | Redis._init | protected function _init() {
if (!$this->connection) {
$this->connection = new RedisCore();
}
$method = $this->_config['persistent'] ? 'pconnect' : 'connect';
if (HostString::isSocket($this->_config['host'])) {
$this->connection->{$method}($this->_config['host']);
} else {
$host = HostString::parse($this->_config['host']) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$this->connection->{$method}($host['host'], $host['port']);
}
if ($this->_config['scope']) {
$this->connection->setOption(RedisCore::OPT_PREFIX, "{$this->_config['scope']}:");
}
} | php | protected function _init() {
if (!$this->connection) {
$this->connection = new RedisCore();
}
$method = $this->_config['persistent'] ? 'pconnect' : 'connect';
if (HostString::isSocket($this->_config['host'])) {
$this->connection->{$method}($this->_config['host']);
} else {
$host = HostString::parse($this->_config['host']) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$this->connection->{$method}($host['host'], $host['port']);
}
if ($this->_config['scope']) {
$this->connection->setOption(RedisCore::OPT_PREFIX, "{$this->_config['scope']}:");
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"connection",
")",
"{",
"$",
"this",
"->",
"connection",
"=",
"new",
"RedisCore",
"(",
")",
";",
"}",
"$",
"method",
"=",
"$",
"this",
"->",
"_config",
"[",
"'persi... | Initialize the Redis connection object, connect to the Redis server and sets
prefix using the scope if provided.
@return void | [
"Initialize",
"the",
"Redis",
"connection",
"object",
"connect",
"to",
"the",
"Redis",
"server",
"and",
"sets",
"prefix",
"using",
"the",
"scope",
"if",
"provided",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Redis.php#L111-L130 |
UnionOfRAD/lithium | storage/cache/adapter/Redis.php | Redis.write | public function write(array $keys, $expiry = null) {
$expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry'];
if (!$expiry || $expiry === Cache::PERSIST) {
$ttl = null;
} elseif (is_int($expiry)) {
$ttl = $expiry;
} else {
$ttl = strtotime($expiry) - time();
}
if (count($keys) > 1) {
if (!$ttl) {
return $this->connection->mset($keys);
}
$transaction = $this->connection->multi();
foreach ($keys as $key => $value) {
if (!$this->connection->setex($key, $ttl, $value)) {
$transaction->discard();
return false;
}
}
return $transaction->exec() === array_fill(0, count($keys), true);
}
$key = key($keys);
$value = current($keys);
if (!$ttl) {
return $this->connection->set($key, $value);
}
return $this->connection->setex($key, $ttl, $value);
} | php | public function write(array $keys, $expiry = null) {
$expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry'];
if (!$expiry || $expiry === Cache::PERSIST) {
$ttl = null;
} elseif (is_int($expiry)) {
$ttl = $expiry;
} else {
$ttl = strtotime($expiry) - time();
}
if (count($keys) > 1) {
if (!$ttl) {
return $this->connection->mset($keys);
}
$transaction = $this->connection->multi();
foreach ($keys as $key => $value) {
if (!$this->connection->setex($key, $ttl, $value)) {
$transaction->discard();
return false;
}
}
return $transaction->exec() === array_fill(0, count($keys), true);
}
$key = key($keys);
$value = current($keys);
if (!$ttl) {
return $this->connection->set($key, $value);
}
return $this->connection->setex($key, $ttl, $value);
} | [
"public",
"function",
"write",
"(",
"array",
"$",
"keys",
",",
"$",
"expiry",
"=",
"null",
")",
"{",
"$",
"expiry",
"=",
"$",
"expiry",
"||",
"$",
"expiry",
"===",
"Cache",
"::",
"PERSIST",
"?",
"$",
"expiry",
":",
"$",
"this",
"->",
"_config",
"["... | Write values to the cache. All items to be cached will receive an
expiration time of `$expiry`.
@param array $keys Key/value pairs with keys to uniquely identify the to-be-cached item.
@param string|integer $expiry A `strtotime()` compatible cache time or TTL in seconds.
To persist an item use `\lithium\storage\Cache::PERSIST`.
@return boolean `true` on successful write, `false` otherwise. | [
"Write",
"values",
"to",
"the",
"cache",
".",
"All",
"items",
"to",
"be",
"cached",
"will",
"receive",
"an",
"expiration",
"time",
"of",
"$expiry",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Redis.php#L181-L213 |
UnionOfRAD/lithium | storage/cache/adapter/Redis.php | Redis.read | public function read(array $keys) {
if (count($keys) > 1) {
$results = [];
$data = $this->connection->mGet($keys);
foreach ($data as $key => $item) {
$key = $keys[$key];
if ($item === false && !$connection->exists($key)) {
continue;
}
$results[$key] = $item;
}
return $results;
}
$result = $this->connection->get($key = current($keys));
return $result === false ? [] : [$key => $result];
} | php | public function read(array $keys) {
if (count($keys) > 1) {
$results = [];
$data = $this->connection->mGet($keys);
foreach ($data as $key => $item) {
$key = $keys[$key];
if ($item === false && !$connection->exists($key)) {
continue;
}
$results[$key] = $item;
}
return $results;
}
$result = $this->connection->get($key = current($keys));
return $result === false ? [] : [$key => $result];
} | [
"public",
"function",
"read",
"(",
"array",
"$",
"keys",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"keys",
")",
">",
"1",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"connection",
"->",
"mGet",
"(",
"$",
"... | Read values from the cache. Will attempt to return an array of data
containing key/value pairs of the requested data.
@param array $keys Keys to uniquely identify the cached items.
@return array Cached values keyed by cache keys on successful read,
keys which could not be read will not be included in
the results array. | [
"Read",
"values",
"from",
"the",
"cache",
".",
"Will",
"attempt",
"to",
"return",
"an",
"array",
"of",
"data",
"containing",
"key",
"/",
"value",
"pairs",
"of",
"the",
"requested",
"data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Redis.php#L224-L241 |
UnionOfRAD/lithium | g11n/catalog/Adapter.php | Adapter._merge | protected function _merge(array $data, array $item) {
if (!isset($item['id'])) {
return $data;
}
$id = $item['id'];
$defaults = [
'ids' => [],
'translated' => null,
'flags' => [],
'comments' => [],
'occurrences' => []
];
$item += $defaults;
if (isset($item['context']) && $item['context']) {
$id .= '|' . $item['context'];
}
if (!isset($data[$id])) {
$data[$id] = $item;
return $data;
}
foreach (['ids', 'flags', 'comments', 'occurrences'] as $field) {
$data[$id][$field] = array_merge($data[$id][$field], $item[$field]);
}
if (!isset($data[$id]['translated'])) {
$data[$id]['translated'] = $item['translated'];
} elseif (is_array($item['translated'])) {
$data[$id]['translated'] = (array) $data[$id]['translated'] + $item['translated'];
}
return $data;
} | php | protected function _merge(array $data, array $item) {
if (!isset($item['id'])) {
return $data;
}
$id = $item['id'];
$defaults = [
'ids' => [],
'translated' => null,
'flags' => [],
'comments' => [],
'occurrences' => []
];
$item += $defaults;
if (isset($item['context']) && $item['context']) {
$id .= '|' . $item['context'];
}
if (!isset($data[$id])) {
$data[$id] = $item;
return $data;
}
foreach (['ids', 'flags', 'comments', 'occurrences'] as $field) {
$data[$id][$field] = array_merge($data[$id][$field], $item[$field]);
}
if (!isset($data[$id]['translated'])) {
$data[$id]['translated'] = $item['translated'];
} elseif (is_array($item['translated'])) {
$data[$id]['translated'] = (array) $data[$id]['translated'] + $item['translated'];
}
return $data;
} | [
"protected",
"function",
"_merge",
"(",
"array",
"$",
"data",
",",
"array",
"$",
"item",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"item",
"[",
"'id'",
"]",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"$",
"id",
"=",
"$",
"item",
"[",
... | Merges an item into given data.
@param array $data Data to merge item into.
@param array $item Item to merge into $data. The item must have an `'id'` key.
@return array The merged data. | [
"Merges",
"an",
"item",
"into",
"given",
"data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/Adapter.php#L72-L104 |
UnionOfRAD/lithium | template/view/Compiler.php | Compiler.template | public static function template($file, array $options = []) {
$cachePath = Libraries::get(true, 'resources') . '/tmp/cache/templates';
$defaults = ['path' => $cachePath, 'fallback' => false];
$options += $defaults;
$stats = stat($file);
$oname = basename(dirname($file)) . '_' . basename($file, '.php');
$oname .= '_' . ($stats['ino'] ?: hash('md5', $file));
$template = "template_{$oname}_{$stats['mtime']}_{$stats['size']}.php";
$template = "{$options['path']}/{$template}";
if (file_exists($template)) {
return $template;
}
$compiled = static::compile(file_get_contents($file));
if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) {
foreach (glob("{$options['path']}/template_{$oname}_*.php", GLOB_NOSORT) as $expired) {
if ($expired !== $template) {
unlink($expired);
}
}
return $template;
}
if ($options['fallback']) {
return $file;
}
throw new TemplateException("Could not write compiled template `{$template}` to cache.");
} | php | public static function template($file, array $options = []) {
$cachePath = Libraries::get(true, 'resources') . '/tmp/cache/templates';
$defaults = ['path' => $cachePath, 'fallback' => false];
$options += $defaults;
$stats = stat($file);
$oname = basename(dirname($file)) . '_' . basename($file, '.php');
$oname .= '_' . ($stats['ino'] ?: hash('md5', $file));
$template = "template_{$oname}_{$stats['mtime']}_{$stats['size']}.php";
$template = "{$options['path']}/{$template}";
if (file_exists($template)) {
return $template;
}
$compiled = static::compile(file_get_contents($file));
if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) {
foreach (glob("{$options['path']}/template_{$oname}_*.php", GLOB_NOSORT) as $expired) {
if ($expired !== $template) {
unlink($expired);
}
}
return $template;
}
if ($options['fallback']) {
return $file;
}
throw new TemplateException("Could not write compiled template `{$template}` to cache.");
} | [
"public",
"static",
"function",
"template",
"(",
"$",
"file",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"cachePath",
"=",
"Libraries",
"::",
"get",
"(",
"true",
",",
"'resources'",
")",
".",
"'/tmp/cache/templates'",
";",
"$",
"defaults... | Compiles a template and writes it to a cache file, which is used for inclusion.
@param string $file The full path to the template that will be compiled.
@param array $options Options for compilation include:
- `path`: Path where the compiled template should be written.
- `fallback`: Boolean indicating that if the compilation failed for some
reason (e.g. `path` is not writable), that the compiled template
should still be returned and no exception be thrown.
@return string The compiled template. | [
"Compiles",
"a",
"template",
"and",
"writes",
"it",
"to",
"a",
"cache",
"file",
"which",
"is",
"used",
"for",
"inclusion",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Compiler.php#L55-L85 |
UnionOfRAD/lithium | template/view/Compiler.php | Compiler.compile | public static function compile($string) {
$patterns = static::$_processors;
return preg_replace(array_keys($patterns), array_values($patterns), $string);
} | php | public static function compile($string) {
$patterns = static::$_processors;
return preg_replace(array_keys($patterns), array_values($patterns), $string);
} | [
"public",
"static",
"function",
"compile",
"(",
"$",
"string",
")",
"{",
"$",
"patterns",
"=",
"static",
"::",
"$",
"_processors",
";",
"return",
"preg_replace",
"(",
"array_keys",
"(",
"$",
"patterns",
")",
",",
"array_values",
"(",
"$",
"patterns",
")",
... | Preprocess the passed `$string` (usually a PHP template) for syntax replacements
using sets of regular expressions.
@see lithium\template\view\Compiler::$_processors
@param string $string The string to be preprocessed.
@return string Processed string. | [
"Preprocess",
"the",
"passed",
"$string",
"(",
"usually",
"a",
"PHP",
"template",
")",
"for",
"syntax",
"replacements",
"using",
"sets",
"of",
"regular",
"expressions",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Compiler.php#L95-L98 |
UnionOfRAD/lithium | template/Helper.php | Helper._init | protected function _init() {
parent::_init();
if (!$this->_context) {
return;
}
$this->_context->strings($this->_strings);
if ($this->_config['handlers']) {
$this->_context->handlers($this->_config['handlers']);
}
} | php | protected function _init() {
parent::_init();
if (!$this->_context) {
return;
}
$this->_context->strings($this->_strings);
if ($this->_config['handlers']) {
$this->_context->handlers($this->_config['handlers']);
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"parent",
"::",
"_init",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"_context",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"_context",
"->",
"strings",
"(",
"$",
"this",
"->",
"_strings"... | Imports local string definitions into rendering context.
@return void | [
"Imports",
"local",
"string",
"definitions",
"into",
"rendering",
"context",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L85-L96 |
UnionOfRAD/lithium | template/Helper.php | Helper.escape | public function escape($value, $method = null, array $options = []) {
$defaults = ['escape' => true];
$options += $defaults;
if ($options['escape'] === false) {
return $value;
}
if (is_array($value)) {
return array_map([$this, __FUNCTION__], $value);
}
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
} | php | public function escape($value, $method = null, array $options = []) {
$defaults = ['escape' => true];
$options += $defaults;
if ($options['escape'] === false) {
return $value;
}
if (is_array($value)) {
return array_map([$this, __FUNCTION__], $value);
}
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
} | [
"public",
"function",
"escape",
"(",
"$",
"value",
",",
"$",
"method",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'escape'",
"=>",
"true",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
... | Escapes values according to the output type of the rendering context. Helpers that output to
non-HTML/XML contexts should override this method accordingly.
@param string $value
@param mixed $method
@param array $options
@return mixed | [
"Escapes",
"values",
"according",
"to",
"the",
"output",
"type",
"of",
"the",
"rendering",
"context",
".",
"Helpers",
"that",
"output",
"to",
"non",
"-",
"HTML",
"/",
"XML",
"contexts",
"should",
"override",
"this",
"method",
"accordingly",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L107-L118 |
UnionOfRAD/lithium | template/Helper.php | Helper._options | protected function _options(array $defaults, array $scope) {
$scope += $defaults;
$options = array_diff_key($scope, $defaults);
return [$scope, $options];
} | php | protected function _options(array $defaults, array $scope) {
$scope += $defaults;
$options = array_diff_key($scope, $defaults);
return [$scope, $options];
} | [
"protected",
"function",
"_options",
"(",
"array",
"$",
"defaults",
",",
"array",
"$",
"scope",
")",
"{",
"$",
"scope",
"+=",
"$",
"defaults",
";",
"$",
"options",
"=",
"array_diff_key",
"(",
"$",
"scope",
",",
"$",
"defaults",
")",
";",
"return",
"[",... | Takes the defaults and current options, merges them and returns options which have
the default keys removed and full set of options as the scope.
@param array $defaults
@param array $scope the complete set of options
@return array $scope, $options | [
"Takes",
"the",
"defaults",
"and",
"current",
"options",
"merges",
"them",
"and",
"returns",
"options",
"which",
"have",
"the",
"default",
"keys",
"removed",
"and",
"full",
"set",
"of",
"options",
"as",
"the",
"scope",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L128-L132 |
UnionOfRAD/lithium | template/Helper.php | Helper._render | protected function _render($method, $string, $params, array $options = []) {
$strings = $this->_strings;
if (isset($params['options']['scope'])) {
$options['scope'] = $params['options']['scope'];
unset($params['options']['scope']);
}
if ($this->_context) {
foreach ($params as $key => $value) {
$handler = isset($options['handlers'][$key]) ? $options['handlers'][$key] : $key;
$params[$key] = $this->_context->applyHandler(
$this, $method, $handler, $value, $options
);
}
$strings = $this->_context->strings();
}
return Text::insert(isset($strings[$string]) ? $strings[$string] : $string, $params);
} | php | protected function _render($method, $string, $params, array $options = []) {
$strings = $this->_strings;
if (isset($params['options']['scope'])) {
$options['scope'] = $params['options']['scope'];
unset($params['options']['scope']);
}
if ($this->_context) {
foreach ($params as $key => $value) {
$handler = isset($options['handlers'][$key]) ? $options['handlers'][$key] : $key;
$params[$key] = $this->_context->applyHandler(
$this, $method, $handler, $value, $options
);
}
$strings = $this->_context->strings();
}
return Text::insert(isset($strings[$string]) ? $strings[$string] : $string, $params);
} | [
"protected",
"function",
"_render",
"(",
"$",
"method",
",",
"$",
"string",
",",
"$",
"params",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"strings",
"=",
"$",
"this",
"->",
"_strings",
";",
"if",
"(",
"isset",
"(",
"$",
"params",
... | Render a string template after applying context filters
Use examples in the Html::link() method:
`return $this->_render(__METHOD__, 'link', compact('title', 'url', 'options'), $scope);`
@param string $method name of method that is calling the render (for context filters)
@param string $string template key (in Helper::_strings) to render
@param array $params associated array of template inserts {:key} will be replaced by value
@param array $options Available options:
- `'handlers'` _array_: Before inserting `$params` inside the string template,
`$this->_context`'s handlers are applied to each value of `$params` according
to the key (e.g `$params['url']`, which is processed by the `'url'` handler
via `$this->_context->applyHandler()`).
The `'handlers'` option allow to set custom mapping beetween `$params`'s key and
`$this->_context`'s handlers. e.g. the following handler:
`'handlers' => ['url' => 'path']` will make `$params['url']` to be
processed by the `'path'` handler instead of the `'url'` one.
@return string Rendered HTML | [
"Render",
"a",
"string",
"template",
"after",
"applying",
"context",
"filters",
"Use",
"examples",
"in",
"the",
"Html",
"::",
"link",
"()",
"method",
":",
"return",
"$this",
"-",
">",
"_render",
"(",
"__METHOD__",
"link",
"compact",
"(",
"title",
"url",
"o... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L153-L171 |
UnionOfRAD/lithium | template/Helper.php | Helper._attributes | protected function _attributes($params, $method = null, array $options = []) {
$defaults = ['escape' => true, 'prepend' => ' ', 'append' => ''];
$options += $defaults;
$result = [];
if (!is_array($params)) {
return !$params ? '' : $options['prepend'] . $params;
}
foreach ($params as $key => $value) {
if ($next = $this->_attribute($key, $value, $options)) {
$result[] = $next;
}
}
return $result ? $options['prepend'] . implode(' ', $result) . $options['append'] : '';
} | php | protected function _attributes($params, $method = null, array $options = []) {
$defaults = ['escape' => true, 'prepend' => ' ', 'append' => ''];
$options += $defaults;
$result = [];
if (!is_array($params)) {
return !$params ? '' : $options['prepend'] . $params;
}
foreach ($params as $key => $value) {
if ($next = $this->_attribute($key, $value, $options)) {
$result[] = $next;
}
}
return $result ? $options['prepend'] . implode(' ', $result) . $options['append'] : '';
} | [
"protected",
"function",
"_attributes",
"(",
"$",
"params",
",",
"$",
"method",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'escape'",
"=>",
"true",
",",
"'prepend'",
"=>",
"' '",
",",
"'append'",
"... | Converts a set of parameters to HTML attributes into a string.
@see lithium\template\view\Renderer::__call()
@param array|string $params The parameters where key is the attribute name and
the value the attribute value. When string will simply prepend with the
prepend-string (by default `' '`) unless $params is falsey in which case
an empty string is returned. This alternative syntax is used by the method
internally.
@param string $method When used as a context handler, the method the handler
was called for I.e. `'wrap'`. Currently not used by the method.
@param array $options Available options are:
- `'escape'` _boolean_: Indicates whether the output should be HTML-escaped.
Defaults to `true`.
- `'prepend'` _string_: String to prepend to each attribute pair and the final
result. Defaults to `' '`.
- `'append'` _string_: String to append to result. Defaults to `''`.
@return string Attribute string. | [
"Converts",
"a",
"set",
"of",
"parameters",
"to",
"HTML",
"attributes",
"into",
"a",
"string",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L192-L206 |
UnionOfRAD/lithium | template/Helper.php | Helper._attribute | protected function _attribute($key, $value, array $options = []) {
$defaults = ['escape' => true, 'format' => '%s="%s"'];
$options += $defaults;
if (in_array($key, $this->_minimized)) {
$isMini = ($value === 1 || $value === true || $value === $key);
if (!($value = $isMini ? $key : $value)) {
return null;
}
}
$value = (string) $value;
if ($options['escape']) {
return sprintf($options['format'], $this->escape($key), $this->escape($value));
}
return sprintf($options['format'], $key, $value);
} | php | protected function _attribute($key, $value, array $options = []) {
$defaults = ['escape' => true, 'format' => '%s="%s"'];
$options += $defaults;
if (in_array($key, $this->_minimized)) {
$isMini = ($value === 1 || $value === true || $value === $key);
if (!($value = $isMini ? $key : $value)) {
return null;
}
}
$value = (string) $value;
if ($options['escape']) {
return sprintf($options['format'], $this->escape($key), $this->escape($value));
}
return sprintf($options['format'], $key, $value);
} | [
"protected",
"function",
"_attribute",
"(",
"$",
"key",
",",
"$",
"value",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'escape'",
"=>",
"true",
",",
"'format'",
"=>",
"'%s=\"%s\"'",
"]",
";",
"$",
"options",
"+=... | Convert a key/value pair to a valid HTML attribute.
@param string $key The key name of the HTML attribute.
@param mixed $value The HTML attribute value.
@param array $options The options used when converting the key/value pair to attributes:
- `'escape'` _boolean_: Indicates whether `$key` and `$value` should be
HTML-escaped. Defaults to `true`.
- `'format'` _string_: The format string. Defaults to `'%s="%s"'`.
@return string Returns an HTML attribute/value pair, in the form of `'$key="$value"'`. | [
"Convert",
"a",
"key",
"/",
"value",
"pair",
"to",
"a",
"valid",
"HTML",
"attribute",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/Helper.php#L219-L235 |
UnionOfRAD/lithium | action/Dispatcher.php | Dispatcher.run | public static function run($request, array $options = []) {
$params = compact('request', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$router = static::$_classes['router'];
$request = $params['request'];
$options = $params['options'];
if (($result = $router::process($request)) instanceof Response) {
return $result;
}
$params = static::applyRules($result->params);
if (!$params) {
throw new DispatchException('Could not route request.');
}
$callable = static::_callable($result, $params, $options);
return static::_call($callable, $result, $params);
});
} | php | public static function run($request, array $options = []) {
$params = compact('request', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$router = static::$_classes['router'];
$request = $params['request'];
$options = $params['options'];
if (($result = $router::process($request)) instanceof Response) {
return $result;
}
$params = static::applyRules($result->params);
if (!$params) {
throw new DispatchException('Could not route request.');
}
$callable = static::_callable($result, $params, $options);
return static::_call($callable, $result, $params);
});
} | [
"public",
"static",
"function",
"run",
"(",
"$",
"request",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'request'",
",",
"'options'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"get_called_class",
"... | Dispatches a request based on a request object (an instance or subclass of
`lithium\net\http\Request`).
@see lithium\action\Request
@see lithium\action\Response
@param object $request An instance of a request object (usually `lithium\action\Request`)
with HTTP request information.
@param array $options
@return mixed Returns the value returned from the callable object retrieved from
`Dispatcher::_callable()`, which is either a string or an instance of
`lithium\action\Response`.
@filter Allows to perform actions very early or late in the request. | [
"Dispatches",
"a",
"request",
"based",
"on",
"a",
"request",
"object",
"(",
"an",
"instance",
"or",
"subclass",
"of",
"lithium",
"\\",
"net",
"\\",
"http",
"\\",
"Request",
")",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Dispatcher.php#L151-L171 |
UnionOfRAD/lithium | action/Dispatcher.php | Dispatcher.applyRules | public static function applyRules(&$params) {
$values = [];
$rules = static::$_rules;
if (!$params) {
return false;
}
if (isset($params['controller']) && is_string($params['controller'])) {
$controller = $params['controller'];
if (strpos($controller, '.') !== false) {
list($library, $controller) = explode('.', $controller);
$controller = $library . '.' . Inflector::camelize($controller);
$params += compact('library');
} elseif (strpos($controller, '\\') === false) {
$controller = Inflector::camelize($controller);
if (isset($params['library'])) {
$controller = "{$params['library']}.{$controller}";
}
}
$values = compact('controller');
}
$values += $params;
if (is_callable($rules)) {
$rules = $rules($params);
}
foreach ($rules as $rule => $value) {
if (!isset($values[$rule])) {
continue;
}
foreach ($value as $k => $v) {
if (is_callable($v)) {
$values[$k] = $v($values);
continue;
}
$match = preg_replace('/\{:\w+\}/', '@', $v);
$match = preg_replace('/@/', '.+', preg_quote($match, '/'));
if (preg_match('/' . $match . '/i', $values[$k])) {
continue;
}
$values[$k] = Text::insert($v, $values);
}
}
return $values;
} | php | public static function applyRules(&$params) {
$values = [];
$rules = static::$_rules;
if (!$params) {
return false;
}
if (isset($params['controller']) && is_string($params['controller'])) {
$controller = $params['controller'];
if (strpos($controller, '.') !== false) {
list($library, $controller) = explode('.', $controller);
$controller = $library . '.' . Inflector::camelize($controller);
$params += compact('library');
} elseif (strpos($controller, '\\') === false) {
$controller = Inflector::camelize($controller);
if (isset($params['library'])) {
$controller = "{$params['library']}.{$controller}";
}
}
$values = compact('controller');
}
$values += $params;
if (is_callable($rules)) {
$rules = $rules($params);
}
foreach ($rules as $rule => $value) {
if (!isset($values[$rule])) {
continue;
}
foreach ($value as $k => $v) {
if (is_callable($v)) {
$values[$k] = $v($values);
continue;
}
$match = preg_replace('/\{:\w+\}/', '@', $v);
$match = preg_replace('/@/', '.+', preg_quote($match, '/'));
if (preg_match('/' . $match . '/i', $values[$k])) {
continue;
}
$values[$k] = Text::insert($v, $values);
}
}
return $values;
} | [
"public",
"static",
"function",
"applyRules",
"(",
"&",
"$",
"params",
")",
"{",
"$",
"values",
"=",
"[",
"]",
";",
"$",
"rules",
"=",
"static",
"::",
"$",
"_rules",
";",
"if",
"(",
"!",
"$",
"params",
")",
"{",
"return",
"false",
";",
"}",
"if",... | Attempts to apply a set of formatting rules from `$_rules` to a `$params` array, where each
formatting rule is applied if the key of the rule in `$_rules` is present and not empty in
`$params`. Also performs sanity checking against `$params` to ensure that no value
matching a rule is present unless the rule check passes.
@param array $params An array of route parameters to which rules will be applied.
@return array Returns the `$params` array with formatting rules applied to array values. | [
"Attempts",
"to",
"apply",
"a",
"set",
"of",
"formatting",
"rules",
"from",
"$_rules",
"to",
"a",
"$params",
"array",
"where",
"each",
"formatting",
"rule",
"is",
"applied",
"if",
"the",
"key",
"of",
"the",
"rule",
"in",
"$_rules",
"is",
"present",
"and",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Dispatcher.php#L182-L230 |
UnionOfRAD/lithium | action/Dispatcher.php | Dispatcher._callable | protected static function _callable($request, $params, $options) {
$params = compact('request', 'params', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$options = ['request' => $params['request']] + $params['options'];
$controller = $params['params']['controller'];
try {
return Libraries::instance('controllers', $controller, $options);
} catch (ClassNotFoundException $e) {
throw new DispatchException("Controller `{$controller}` not found.", null, $e);
}
});
} | php | protected static function _callable($request, $params, $options) {
$params = compact('request', 'params', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$options = ['request' => $params['request']] + $params['options'];
$controller = $params['params']['controller'];
try {
return Libraries::instance('controllers', $controller, $options);
} catch (ClassNotFoundException $e) {
throw new DispatchException("Controller `{$controller}` not found.", null, $e);
}
});
} | [
"protected",
"static",
"function",
"_callable",
"(",
"$",
"request",
",",
"$",
"params",
",",
"$",
"options",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'request'",
",",
"'params'",
",",
"'options'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
... | Accepts parameters generated by the `Router` class in `Dispatcher::run()`, and produces a
callable controller object. By default, this method uses the `'controller'` path lookup
configuration in `Libraries::locate()` to return a callable object.
@param object $request The instance of the `Request` class either passed into or generated by
`Dispatcher::run()`.
@param array $params The parameter array generated by routing the request.
@param array $options Not currently implemented.
@return object Returns a callable object which the request will be routed to.
@filter | [
"Accepts",
"parameters",
"generated",
"by",
"the",
"Router",
"class",
"in",
"Dispatcher",
"::",
"run",
"()",
"and",
"produces",
"a",
"callable",
"controller",
"object",
".",
"By",
"default",
"this",
"method",
"uses",
"the",
"controller",
"path",
"lookup",
"con... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Dispatcher.php#L244-L257 |
UnionOfRAD/lithium | action/Dispatcher.php | Dispatcher._call | protected static function _call($callable, $request, $params) {
$params = compact('callable', 'request', 'params');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
if (is_callable($callable = $params['callable'])) {
return $callable($params['request'], $params['params']);
}
throw new DispatchException('Result not callable.');
});
} | php | protected static function _call($callable, $request, $params) {
$params = compact('callable', 'request', 'params');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
if (is_callable($callable = $params['callable'])) {
return $callable($params['request'], $params['params']);
}
throw new DispatchException('Result not callable.');
});
} | [
"protected",
"static",
"function",
"_call",
"(",
"$",
"callable",
",",
"$",
"request",
",",
"$",
"params",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'callable'",
",",
"'request'",
",",
"'params'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"... | Invokes the callable object returned by `_callable()`, and returns the results, usually a
`Response` object instance.
@see lithium\action
@param object $callable Typically a closure or instance of `lithium\action\Controller`.
@param object $request An instance of `lithium\action\Request`.
@param array $params An array of parameters to pass to `$callable`, along with `$request`.
@return mixed Returns the return value of `$callable`, usually an instance of
`lithium\action\Response`.
@throws lithium\action\DispatchException Throws an exception if `$callable` is not a
`Closure`, or does not declare the PHP magic `__invoke()` method.
@filter | [
"Invokes",
"the",
"callable",
"object",
"returned",
"by",
"_callable",
"()",
"and",
"returns",
"the",
"results",
"usually",
"a",
"Response",
"object",
"instance",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Dispatcher.php#L273-L281 |
UnionOfRAD/lithium | data/source/Http.php | Http.respondsTo | public function respondsTo($method, $internal = false) {
return isset($this->_methods[$method]) || parent::respondsTo($method, $internal);
} | php | public function respondsTo($method, $internal = false) {
return isset($this->_methods[$method]) || parent::respondsTo($method, $internal);
} | [
"public",
"function",
"respondsTo",
"(",
"$",
"method",
",",
"$",
"internal",
"=",
"false",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"_methods",
"[",
"$",
"method",
"]",
")",
"||",
"parent",
"::",
"respondsTo",
"(",
"$",
"method",
",",
"$... | Determines if a given method can be called.
@param string $method Name of the method.
@param boolean $internal Provide `true` to perform check from inside the
class/object. When `false` checks also for public visibility;
defaults to `false`.
@return boolean Returns `true` if the method can be called, `false` otherwise. | [
"Determines",
"if",
"a",
"given",
"method",
"can",
"be",
"called",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Http.php#L153-L155 |
UnionOfRAD/lithium | data/source/Http.php | Http.send | public function send($query = null, array $options = []) {
$query = !is_object($query) ? new Query((array) $query) : $query;
$method = $query->method() ?: "get";
$path = $query->path();
$data = $query->data();
$insert = (array) $options + $data + $query->export($this);
if (preg_match_all('/\{:(\w+)\}/', $path, $matches)) {
$data = array_diff_key($data, array_flip($matches[1]));
}
return $this->connection->{$method}(
Text::insert($path, $insert, ['clean' => true]),
$data + (array) $query->conditions() + ['limit' => $query->limit()],
(array) $options
);
} | php | public function send($query = null, array $options = []) {
$query = !is_object($query) ? new Query((array) $query) : $query;
$method = $query->method() ?: "get";
$path = $query->path();
$data = $query->data();
$insert = (array) $options + $data + $query->export($this);
if (preg_match_all('/\{:(\w+)\}/', $path, $matches)) {
$data = array_diff_key($data, array_flip($matches[1]));
}
return $this->connection->{$method}(
Text::insert($path, $insert, ['clean' => true]),
$data + (array) $query->conditions() + ['limit' => $query->limit()],
(array) $options
);
} | [
"public",
"function",
"send",
"(",
"$",
"query",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"!",
"is_object",
"(",
"$",
"query",
")",
"?",
"new",
"Query",
"(",
"(",
"array",
")",
"$",
"query",
")",
":... | Method to send to a specific resource.
@param array $query a query object
@param array $options array.
@return mixed | [
"Method",
"to",
"send",
"to",
"a",
"specific",
"resource",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Http.php#L164-L179 |
UnionOfRAD/lithium | data/source/Http.php | Http.disconnect | public function disconnect() {
if ($this->_isConnected && $this->connection !== null) {
$this->_isConnected = false;
}
return !$this->_isConnected;
} | php | public function disconnect() {
if ($this->_isConnected && $this->connection !== null) {
$this->_isConnected = false;
}
return !$this->_isConnected;
} | [
"public",
"function",
"disconnect",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_isConnected",
"&&",
"$",
"this",
"->",
"connection",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"_isConnected",
"=",
"false",
";",
"}",
"return",
"!",
"$",
"this",
"-... | Disconnect from socket.
@return boolean | [
"Disconnect",
"from",
"socket",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Http.php#L198-L203 |
UnionOfRAD/lithium | data/source/Http.php | Http.read | public function read($query, array $options = []) {
$query = !is_object($query) ? new Query() : $query;
$query->method() ?: $query->method("get");
$query->path() ?: $query->path("/{:source}");
$params = [$query, $options];
return Filters::run($this, __FUNCTION__, $params, function($params) {
list($query, $options) = $params;
return $this->send($query, $options);
});
} | php | public function read($query, array $options = []) {
$query = !is_object($query) ? new Query() : $query;
$query->method() ?: $query->method("get");
$query->path() ?: $query->path("/{:source}");
$params = [$query, $options];
return Filters::run($this, __FUNCTION__, $params, function($params) {
list($query, $options) = $params;
return $this->send($query, $options);
});
} | [
"public",
"function",
"read",
"(",
"$",
"query",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"!",
"is_object",
"(",
"$",
"query",
")",
"?",
"new",
"Query",
"(",
")",
":",
"$",
"query",
";",
"$",
"query",
"->",
"met... | Read used by model to GET.
@param object $query
@param array $options
@return string
@filter | [
"Read",
"used",
"by",
"model",
"to",
"GET",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Http.php#L256-L267 |
UnionOfRAD/lithium | data/source/Http.php | Http.relationship | public function relationship($class, $type, $name, array $options = []) {
if (isset($this->_classes['relationship'])) {
return $this->_instance('relationship', compact('type', 'name') + $options);
}
return null;
} | php | public function relationship($class, $type, $name, array $options = []) {
if (isset($this->_classes['relationship'])) {
return $this->_instance('relationship', compact('type', 'name') + $options);
}
return null;
} | [
"public",
"function",
"relationship",
"(",
"$",
"class",
",",
"$",
"type",
",",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_classes",
"[",
"'relationship'",
"]",
")",
")",
"{",
... | Defines or modifies the default settings of a relationship between two models.
@param string $class
@param string $type
@param string $name
@param array $options
@return array Returns an array containing the configuration for a model relationship. | [
"Defines",
"or",
"modifies",
"the",
"default",
"settings",
"of",
"a",
"relationship",
"between",
"two",
"models",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Http.php#L320-L325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.