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 |
|---|---|---|---|---|---|---|---|---|---|---|
UnionOfRAD/lithium | g11n/catalog/adapter/Php.php | Php.read | public function read($category, $locale, $scope) {
$path = $this->_config['path'];
$file = $this->_file($category, $locale, $scope);
$data = [];
if (file_exists($file)) {
foreach (require $file as $id => $translated) {
if (strpos($id, '|') !== false) {
list($id, $context) = explode('|', $id);
}
$data = $this->_merge($data, compact('id', 'translated', 'context'));
}
}
return $data;
} | php | public function read($category, $locale, $scope) {
$path = $this->_config['path'];
$file = $this->_file($category, $locale, $scope);
$data = [];
if (file_exists($file)) {
foreach (require $file as $id => $translated) {
if (strpos($id, '|') !== false) {
list($id, $context) = explode('|', $id);
}
$data = $this->_merge($data, compact('id', 'translated', 'context'));
}
}
return $data;
} | [
"public",
"function",
"read",
"(",
"$",
"category",
",",
"$",
"locale",
",",
"$",
"scope",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"_config",
"[",
"'path'",
"]",
";",
"$",
"file",
"=",
"$",
"this",
"->",
"_file",
"(",
"$",
"category",
",",... | Reads data.
@param string $category A category.
@param string $locale A locale identifier.
@param string $scope The scope for the current operation.
@return array | [
"Reads",
"data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Php.php#L90-L104 |
UnionOfRAD/lithium | g11n/catalog/adapter/Php.php | Php._file | protected function _file($category, $locale, $scope) {
$path = $this->_config['path'];
$scope = $scope ?: 'default';
if (($pos = strpos($category, 'Template')) !== false) {
$category = substr($category, 0, $pos);
return "{$path}/{$category}_{$scope}.php";
}
return "{$path}/{$locale}/{$category}/{$scope}.php";
} | php | protected function _file($category, $locale, $scope) {
$path = $this->_config['path'];
$scope = $scope ?: 'default';
if (($pos = strpos($category, 'Template')) !== false) {
$category = substr($category, 0, $pos);
return "{$path}/{$category}_{$scope}.php";
}
return "{$path}/{$locale}/{$category}/{$scope}.php";
} | [
"protected",
"function",
"_file",
"(",
"$",
"category",
",",
"$",
"locale",
",",
"$",
"scope",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"_config",
"[",
"'path'",
"]",
";",
"$",
"scope",
"=",
"$",
"scope",
"?",
":",
"'default'",
";",
"if",
"... | Helper method for transforming a category, locale and scope into a filename.
@param string $category Category name.
@param string $locale Locale identifier.
@param string $scope Current operation scope.
@return string Filename. | [
"Helper",
"method",
"for",
"transforming",
"a",
"category",
"locale",
"and",
"scope",
"into",
"a",
"filename",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Php.php#L114-L123 |
UnionOfRAD/lithium | storage/cache/adapter/Memcache.php | Memcache._init | protected function _init() {
$this->connection = $this->connection ?: new Memcached();
$this->connection->addServers($this->_formatHostList($this->_config['host']));
if ($this->_config['scope']) {
$this->connection->setOption(Memcached::OPT_PREFIX_KEY, "{$this->_config['scope']}:");
}
} | php | protected function _init() {
$this->connection = $this->connection ?: new Memcached();
$this->connection->addServers($this->_formatHostList($this->_config['host']));
if ($this->_config['scope']) {
$this->connection->setOption(Memcached::OPT_PREFIX_KEY, "{$this->_config['scope']}:");
}
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"$",
"this",
"->",
"connection",
"=",
"$",
"this",
"->",
"connection",
"?",
":",
"new",
"Memcached",
"(",
")",
";",
"$",
"this",
"->",
"connection",
"->",
"addServers",
"(",
"$",
"this",
"->",
"_formatHo... | Handles the actual `Memcached` connection and server connection
adding for the adapter constructor and sets prefix using the scope
if provided.
@return void | [
"Handles",
"the",
"actual",
"Memcached",
"connection",
"and",
"server",
"connection",
"adding",
"for",
"the",
"adapter",
"constructor",
"and",
"sets",
"prefix",
"using",
"the",
"scope",
"if",
"provided",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memcache.php#L108-L115 |
UnionOfRAD/lithium | storage/cache/adapter/Memcache.php | Memcache._formatHostList | protected function _formatHostList($host) {
$hosts = [];
foreach ((array) $this->_config['host'] as $host => $weight) {
$host = HostString::parse(($hasWeight = is_integer($weight)) ? $host : $weight) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$host = [$host['host'], $host['port']];
if ($hasWeight) {
$host[] = $weight;
}
$hosts[] = $host;
}
return $hosts;
} | php | protected function _formatHostList($host) {
$hosts = [];
foreach ((array) $this->_config['host'] as $host => $weight) {
$host = HostString::parse(($hasWeight = is_integer($weight)) ? $host : $weight) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$host = [$host['host'], $host['port']];
if ($hasWeight) {
$host[] = $weight;
}
$hosts[] = $host;
}
return $hosts;
} | [
"protected",
"function",
"_formatHostList",
"(",
"$",
"host",
")",
"{",
"$",
"hosts",
"=",
"[",
"]",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"_config",
"[",
"'host'",
"]",
"as",
"$",
"host",
"=>",
"$",
"weight",
")",
"{",
"$",
... | Formats standard `'host:port'` strings into arrays used by `Memcached`.
@param mixed $host A host string in `'host:port'` format, or an array of host strings
optionally paired with relative selection weight values.
@return array Returns an array of `Memcached` server definitions. | [
"Formats",
"standard",
"host",
":",
"port",
"strings",
"into",
"arrays",
"used",
"by",
"Memcached",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memcache.php#L158-L174 |
UnionOfRAD/lithium | storage/cache/adapter/Memcache.php | Memcache.write | public function write(array $keys, $expiry = null) {
$expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry'];
if (!$expiry || $expiry === Cache::PERSIST) {
$expires = 0;
} elseif (is_int($expiry)) {
$expires = $expiry + time();
} else {
$expires = strtotime($expiry);
}
if (count($keys) > 1) {
return $this->connection->setMulti($keys, $expires);
}
return $this->connection->set(key($keys), current($keys), $expires);
} | php | public function write(array $keys, $expiry = null) {
$expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry'];
if (!$expiry || $expiry === Cache::PERSIST) {
$expires = 0;
} elseif (is_int($expiry)) {
$expires = $expiry + time();
} else {
$expires = strtotime($expiry);
}
if (count($keys) > 1) {
return $this->connection->setMulti($keys, $expires);
}
return $this->connection->set(key($keys), current($keys), $expires);
} | [
"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`.
Expiration is always based off the current unix time in order to gurantee we never
exceed the TTL limit of 30 days when specifying the TTL directly.
@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/Memcache.php#L188-L202 |
UnionOfRAD/lithium | storage/cache/adapter/Memcache.php | Memcache.read | public function read(array $keys) {
if (count($keys) > 1) {
if (!$results = $this->connection->getMulti($keys)) {
return [];
}
} else {
$result = $this->connection->get($key = current($keys));
if ($result === false && $this->connection->getResultCode() === Memcached::RES_NOTFOUND) {
return [];
}
$results = [$key => $result];
}
return $results;
} | php | public function read(array $keys) {
if (count($keys) > 1) {
if (!$results = $this->connection->getMulti($keys)) {
return [];
}
} else {
$result = $this->connection->get($key = current($keys));
if ($result === false && $this->connection->getResultCode() === Memcached::RES_NOTFOUND) {
return [];
}
$results = [$key => $result];
}
return $results;
} | [
"public",
"function",
"read",
"(",
"array",
"$",
"keys",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"keys",
")",
">",
"1",
")",
"{",
"if",
"(",
"!",
"$",
"results",
"=",
"$",
"this",
"->",
"connection",
"->",
"getMulti",
"(",
"$",
"keys",
")",
")"... | 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/Memcache.php#L213-L227 |
UnionOfRAD/lithium | storage/cache/adapter/Memcache.php | Memcache.delete | public function delete(array $keys) {
if (count($keys) > 1) {
return $this->connection->deleteMulti($keys);
}
return $this->connection->delete(current($keys));
} | php | public function delete(array $keys) {
if (count($keys) > 1) {
return $this->connection->deleteMulti($keys);
}
return $this->connection->delete(current($keys));
} | [
"public",
"function",
"delete",
"(",
"array",
"$",
"keys",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"keys",
")",
">",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"deleteMulti",
"(",
"$",
"keys",
")",
";",
"}",
"return",
"$",
"t... | Will attempt to remove specified keys from the user space cache.
@param array $keys Keys to uniquely identify the cached items.
@return boolean `true` on successful delete, `false` otherwise. | [
"Will",
"attempt",
"to",
"remove",
"specified",
"keys",
"from",
"the",
"user",
"space",
"cache",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memcache.php#L235-L240 |
UnionOfRAD/lithium | security/validation/RequestToken.php | RequestToken.config | public static function config(array $config = []) {
if (!$config) {
return ['classes' => static::$_classes];
}
foreach ($config as $key => $val) {
$key = "_{$key}";
if (isset(static::${$key})) {
static::${$key} = $val + static::${$key};
}
}
} | php | public static function config(array $config = []) {
if (!$config) {
return ['classes' => static::$_classes];
}
foreach ($config as $key => $val) {
$key = "_{$key}";
if (isset(static::${$key})) {
static::${$key} = $val + static::${$key};
}
}
} | [
"public",
"static",
"function",
"config",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"config",
")",
"{",
"return",
"[",
"'classes'",
"=>",
"static",
"::",
"$",
"_classes",
"]",
";",
"}",
"foreach",
"(",
"$",
"config"... | Used to get or reconfigure dependencies with custom classes.
@param array $config When assigning new configuration, should be an array containing a
`'classes'` key.
@return array If `$config` is empty, returns an array with a `'classes'` key containing class
dependencies. Otherwise returns `null`. | [
"Used",
"to",
"get",
"or",
"reconfigure",
"dependencies",
"with",
"custom",
"classes",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/RequestToken.php#L72-L84 |
UnionOfRAD/lithium | security/validation/RequestToken.php | RequestToken.get | public static function get(array $options = []) {
$defaults = [
'regenerate' => false,
'sessionKey' => 'security.token',
'salt' => null,
'type' => 'sha512'
];
$options += $defaults;
$session = static::$_classes['session'];
if ($options['regenerate'] || !($token = $session::read($options['sessionKey']))) {
$token = Hash::calculate(uniqid(microtime(true)), $options);
$session::write($options['sessionKey'], $token);
}
return $token;
} | php | public static function get(array $options = []) {
$defaults = [
'regenerate' => false,
'sessionKey' => 'security.token',
'salt' => null,
'type' => 'sha512'
];
$options += $defaults;
$session = static::$_classes['session'];
if ($options['regenerate'] || !($token = $session::read($options['sessionKey']))) {
$token = Hash::calculate(uniqid(microtime(true)), $options);
$session::write($options['sessionKey'], $token);
}
return $token;
} | [
"public",
"static",
"function",
"get",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'regenerate'",
"=>",
"false",
",",
"'sessionKey'",
"=>",
"'security.token'",
",",
"'salt'",
"=>",
"null",
",",
"'type'",
"=>",
"'sha... | Generates (or regenerates) a cryptographically-secure token to be used for the life of the
client session, and stores the token using the `Session` class.
@see lithium\security\Hash::calculate()
@param array $options An array of options to be used when generating or storing the token:
- `'regenerate'` _boolean_: If `true`, will force the regeneration of a the
token, even if one is already available in the session. Defaults to `false`.
- `'sessionKey'` _string_: The key used for session storage and retrieval.
Defaults to `'security.token'`.
- `'salt'` _string_: If the token is being generated (or regenerated), sets a
custom salt value to be used by `Hash::calculate()`.
- `'type'` _string_: The hashing algorithm used by `Hash::calculate()` when
generating the token. Defaults to `'sha512'`.
@return string Returns a cryptographically-secure client session token. | [
"Generates",
"(",
"or",
"regenerates",
")",
"a",
"cryptographically",
"-",
"secure",
"token",
"to",
"be",
"used",
"for",
"the",
"life",
"of",
"the",
"client",
"session",
"and",
"stores",
"the",
"token",
"using",
"the",
"Session",
"class",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/RequestToken.php#L102-L117 |
UnionOfRAD/lithium | security/validation/RequestToken.php | RequestToken.check | public static function check($key, array $options = []) {
$defaults = ['sessionKey' => 'security.token'];
$options += $defaults;
$session = static::$_classes['session'];
if (is_object($key) && isset($key->data)) {
$result = Set::extract($key->data, '/security/token');
$key = $result ? $result[0] : null;
}
return Password::check($session::read($options['sessionKey']), (string) $key);
} | php | public static function check($key, array $options = []) {
$defaults = ['sessionKey' => 'security.token'];
$options += $defaults;
$session = static::$_classes['session'];
if (is_object($key) && isset($key->data)) {
$result = Set::extract($key->data, '/security/token');
$key = $result ? $result[0] : null;
}
return Password::check($session::read($options['sessionKey']), (string) $key);
} | [
"public",
"static",
"function",
"check",
"(",
"$",
"key",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'sessionKey'",
"=>",
"'security.token'",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
"session",
... | Checks a single-use hash key against the session token that generated it, using
a cryptographically-secure verification method. Accepts either the request key as a string,
or a `Request` object with a `$data` property containing a `['security']['token']` key.
For example, the following two controller code samples are equivalent:
```
$key = $this->request->data['security']['token'];
if (!RequestToken::check($key)) {
// Handle invalid request...
}
```
```
if (!RequestToken::check($this->request)) {
// Handle invalid request...
}
```
@param mixed $key Either the actual key as a string, or a `Request` object containing the
key.
@param array $options The options to use when matching the key to the token:
- `'sessionKey'` _string_: The key used when reading the token from the session.
@return boolean Returns `true` if the hash key is a cryptographic match to the stored
session token. Returns `false` on failure, which indicates a forged request attempt. | [
"Checks",
"a",
"single",
"-",
"use",
"hash",
"key",
"against",
"the",
"session",
"token",
"that",
"generated",
"it",
"using",
"a",
"cryptographically",
"-",
"secure",
"verification",
"method",
".",
"Accepts",
"either",
"the",
"request",
"key",
"as",
"a",
"st... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/RequestToken.php#L160-L170 |
UnionOfRAD/lithium | action/Controller.php | Controller._init | protected function _init() {
parent::_init();
foreach (static::_parents() as $parent) {
$inherit = get_class_vars($parent);
if (isset($inherit['_render'])) {
$this->_render += $inherit['_render'];
}
if ($parent === __CLASS__) {
break;
}
}
$this->request = $this->request ?: $this->_config['request'];
$this->response = $this->_instance('response', $this->_config['response']);
if (!$this->request || $this->_render['type']) {
return;
}
if ($this->_render['negotiate']) {
$this->_render['type'] = $this->request->accepts();
return;
}
$this->_render['type'] = $this->request->get('params:type') ?: 'html';
} | php | protected function _init() {
parent::_init();
foreach (static::_parents() as $parent) {
$inherit = get_class_vars($parent);
if (isset($inherit['_render'])) {
$this->_render += $inherit['_render'];
}
if ($parent === __CLASS__) {
break;
}
}
$this->request = $this->request ?: $this->_config['request'];
$this->response = $this->_instance('response', $this->_config['response']);
if (!$this->request || $this->_render['type']) {
return;
}
if ($this->_render['negotiate']) {
$this->_render['type'] = $this->request->accepts();
return;
}
$this->_render['type'] = $this->request->get('params:type') ?: 'html';
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"parent",
"::",
"_init",
"(",
")",
";",
"foreach",
"(",
"static",
"::",
"_parents",
"(",
")",
"as",
"$",
"parent",
")",
"{",
"$",
"inherit",
"=",
"get_class_vars",
"(",
"$",
"parent",
")",
";",
"if",
... | Populates the `$response` property with a new instance of the `Response` class passing it
configuration, and sets some rendering options, depending on the incoming request.
@return void | [
"Populates",
"the",
"$response",
"property",
"with",
"a",
"new",
"instance",
"of",
"the",
"Response",
"class",
"passing",
"it",
"configuration",
"and",
"sets",
"some",
"rendering",
"options",
"depending",
"on",
"the",
"incoming",
"request",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Controller.php#L158-L183 |
UnionOfRAD/lithium | action/Controller.php | Controller.render | public function render(array $options = []) {
$media = $this->_classes['media'];
$class = get_class($this);
$name = preg_replace('/Controller$/', '', substr($class, strrpos($class, '\\') + 1));
$key = key($options);
if (isset($options['data'])) {
$this->set($options['data']);
unset($options['data']);
}
$defaults = [
'status' => null,
'location' => false,
'data' => null,
'head' => false,
'controller' => Inflector::underscore($name),
'library' => Libraries::get($class)
];
$options += $this->_render + $defaults;
if ($key && $media::type($key)) {
$options['type'] = $key;
$this->set($options[$key]);
unset($options[$key]);
}
$this->_render['hasRendered'] = true;
$this->response->type($options['type']);
$this->response->status($options['status']);
$this->response->headers('Location', $options['location']);
if ($options['head']) {
return;
}
$response = $media::render($this->response, $this->_render['data'], $options + [
'request' => $this->request
]);
return ($this->response = $response ?: $this->response);
} | php | public function render(array $options = []) {
$media = $this->_classes['media'];
$class = get_class($this);
$name = preg_replace('/Controller$/', '', substr($class, strrpos($class, '\\') + 1));
$key = key($options);
if (isset($options['data'])) {
$this->set($options['data']);
unset($options['data']);
}
$defaults = [
'status' => null,
'location' => false,
'data' => null,
'head' => false,
'controller' => Inflector::underscore($name),
'library' => Libraries::get($class)
];
$options += $this->_render + $defaults;
if ($key && $media::type($key)) {
$options['type'] = $key;
$this->set($options[$key]);
unset($options[$key]);
}
$this->_render['hasRendered'] = true;
$this->response->type($options['type']);
$this->response->status($options['status']);
$this->response->headers('Location', $options['location']);
if ($options['head']) {
return;
}
$response = $media::render($this->response, $this->_render['data'], $options + [
'request' => $this->request
]);
return ($this->response = $response ?: $this->response);
} | [
"public",
"function",
"render",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"media",
"=",
"$",
"this",
"->",
"_classes",
"[",
"'media'",
"]",
";",
"$",
"class",
"=",
"get_class",
"(",
"$",
"this",
")",
";",
"$",
"name",
"=",
"preg... | Uses results (typically coming from a controller action) to generate content and headers for
a `Response` object.
@see lithium\action\Controller::$_render
@param array $options An array of options, as follows:
- `'data'`: An associative array of variables to be assigned to the template. These
are merged on top of any variables set in `Controller::set()`.
- `'head'`: If true, only renders the headers of the response, not the body. Defaults
to `false`.
- `'template'`: The name of a template, which usually matches the name of the action.
By default, this template is looked for in the views directory of the current
controller, i.e. given a `PostsController` object, if template is set to `'view'`,
the template path would be `views/posts/view.html.php`. Defaults to the name of the
action being rendered.
The options specified here are merged with the values in the `Controller::$_render`
property. You may refer to it for other options accepted by this method.
@return object Returns the `Response` object associated with this `Controller` instance. | [
"Uses",
"results",
"(",
"typically",
"coming",
"from",
"a",
"controller",
"action",
")",
"to",
"generate",
"content",
"and",
"headers",
"for",
"a",
"Response",
"object",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Controller.php#L259-L298 |
UnionOfRAD/lithium | action/Controller.php | Controller.redirect | public function redirect($url, array $options = []) {
$defaults = ['location' => null, 'status' => 302, 'head' => true, 'exit' => false];
$options += $defaults;
$params = compact('url', 'options');
Filters::run($this, __FUNCTION__, $params, function($params) {
$router = $this->_classes['router'];
$options = $params['options'];
$location = $options['location'] ?: $router::match($params['url'], $this->request);
$this->render(compact('location') + $options);
});
if ($options['exit']) {
$this->response->render();
$this->_stop();
}
return $this->response;
} | php | public function redirect($url, array $options = []) {
$defaults = ['location' => null, 'status' => 302, 'head' => true, 'exit' => false];
$options += $defaults;
$params = compact('url', 'options');
Filters::run($this, __FUNCTION__, $params, function($params) {
$router = $this->_classes['router'];
$options = $params['options'];
$location = $options['location'] ?: $router::match($params['url'], $this->request);
$this->render(compact('location') + $options);
});
if ($options['exit']) {
$this->response->render();
$this->_stop();
}
return $this->response;
} | [
"public",
"function",
"redirect",
"(",
"$",
"url",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'location'",
"=>",
"null",
",",
"'status'",
"=>",
"302",
",",
"'head'",
"=>",
"true",
",",
"'exit'",
"=>",
"false",
... | Creates a redirect response by calling `render()` and providing a `'location'` parameter.
@see lithium\net\http\Router::match()
@see lithium\action\Controller::$response
@param mixed $url The location to redirect to, provided as a string relative to the root of
the application, a fully-qualified URL, or an array of routing parameters to be
resolved to a URL. Post-processed by `Router::match()`.
@param array $options Options when performing the redirect. Available options include:
- `'status'` _integer_: The HTTP status code associated with the redirect.
Defaults to `302`.
- `'head'` _boolean_: Determines whether only headers are returned with the
response. Defaults to `true`, in which case only headers and no body are
returned. Set to `false` to render a body as well.
- `'exit'` _boolean_: Exit immediately after rendering. Defaults to `false`.
Because `redirect()` does not exit by default, you should always prefix calls
with a `return` statement, so that the action is always immediately exited.
@return object Returns the instance of the `Response` object associated with this controller.
@filter Allows to intercept redirects, either stopping them completely i.e. during debugging
or for logging purposes. | [
"Creates",
"a",
"redirect",
"response",
"by",
"calling",
"render",
"()",
"and",
"providing",
"a",
"location",
"parameter",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Controller.php#L321-L339 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature.config | public static function config(array $config = []) {
if (!$config) {
return [
'classes' => static::$_classes,
'secret' => static::$_secret
];
}
if (isset($config['classes'])) {
static::$_classes = $config['classes'] + static::$_classes;
}
if (isset($config['secret'])) {
static::$_secret = $config['secret'];
}
} | php | public static function config(array $config = []) {
if (!$config) {
return [
'classes' => static::$_classes,
'secret' => static::$_secret
];
}
if (isset($config['classes'])) {
static::$_classes = $config['classes'] + static::$_classes;
}
if (isset($config['secret'])) {
static::$_secret = $config['secret'];
}
} | [
"public",
"static",
"function",
"config",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"config",
")",
"{",
"return",
"[",
"'classes'",
"=>",
"static",
"::",
"$",
"_classes",
",",
"'secret'",
"=>",
"static",
"::",
"$",
... | Configures the class or retrieves current class configuration.
@param array $config Available configuration options are:
- `'classes'` _array_: May be used to inject dependencies.
- `'secret'` _string_: *Must* be provided.
@return array|void If `$config` is empty, returns an array with the current configurations. | [
"Configures",
"the",
"class",
"or",
"retrieves",
"current",
"class",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L57-L70 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature.key | public static function key(array $data) {
$data += [
'fields' => [],
'locked' => [],
'excluded' => []
];
return static::_compile(
array_keys(Set::flatten($data['fields'])),
$data['locked'],
array_keys($data['excluded'])
);
} | php | public static function key(array $data) {
$data += [
'fields' => [],
'locked' => [],
'excluded' => []
];
return static::_compile(
array_keys(Set::flatten($data['fields'])),
$data['locked'],
array_keys($data['excluded'])
);
} | [
"public",
"static",
"function",
"key",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"data",
"+=",
"[",
"'fields'",
"=>",
"[",
"]",
",",
"'locked'",
"=>",
"[",
"]",
",",
"'excluded'",
"=>",
"[",
"]",
"]",
";",
"return",
"static",
"::",
"_compile",
"(",... | Generates form signature string from form data.
@param array $data An array of fields, locked fields and excluded fields.
@return string The form signature string. | [
"Generates",
"form",
"signature",
"string",
"from",
"form",
"data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L78-L89 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature.check | public static function check($data) {
if (is_object($data) && isset($data->data)) {
$data = $data->data;
}
if (!isset($data['security']['signature'])) {
throw new Exception('Unable to check form signature. Cannot find signature in data.');
}
$signature = $data['security']['signature'];
unset($data['security']);
$parsed = static::_parse($signature);
$data = Set::flatten($data);
if (array_intersect_assoc($data, $parsed['locked']) != $parsed['locked']) {
return false;
}
$fields = array_diff(
array_keys($data),
array_keys($parsed['locked']),
$parsed['excluded']
);
return $signature === static::_compile($fields, $parsed['locked'], $parsed['excluded']);
} | php | public static function check($data) {
if (is_object($data) && isset($data->data)) {
$data = $data->data;
}
if (!isset($data['security']['signature'])) {
throw new Exception('Unable to check form signature. Cannot find signature in data.');
}
$signature = $data['security']['signature'];
unset($data['security']);
$parsed = static::_parse($signature);
$data = Set::flatten($data);
if (array_intersect_assoc($data, $parsed['locked']) != $parsed['locked']) {
return false;
}
$fields = array_diff(
array_keys($data),
array_keys($parsed['locked']),
$parsed['excluded']
);
return $signature === static::_compile($fields, $parsed['locked'], $parsed['excluded']);
} | [
"public",
"static",
"function",
"check",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"data",
")",
"&&",
"isset",
"(",
"$",
"data",
"->",
"data",
")",
")",
"{",
"$",
"data",
"=",
"$",
"data",
"->",
"data",
";",
"}",
"if",
"(",
... | Validates form data using an embedded form signature string. The form signature string
must be embedded in `security.signature` alongside the other data to check against.
Note: Will ignore any other data inside `security.*`.
@param array|object $data The form data as an array or an
object with the data inside the `data` property.
@return boolean `true` if the form data is valid, `false` if not. | [
"Validates",
"form",
"data",
"using",
"an",
"embedded",
"form",
"signature",
"string",
".",
"The",
"form",
"signature",
"string",
"must",
"be",
"embedded",
"in",
"security",
".",
"signature",
"alongside",
"the",
"other",
"data",
"to",
"check",
"against",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L101-L123 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature._compile | protected static function _compile(array $fields, array $locked, array $excluded) {
$hash = static::$_classes['hash'];
sort($fields, SORT_STRING);
ksort($locked, SORT_STRING);
sort($excluded, SORT_STRING);
foreach (['fields', 'excluded', 'locked'] as $list) {
${$list} = urlencode(serialize(${$list}));
}
$hash = $hash::calculate($fields);
$signature = static::_signature("{$locked}::{$excluded}::{$hash}");
return "{$locked}::{$excluded}::{$signature}";
} | php | protected static function _compile(array $fields, array $locked, array $excluded) {
$hash = static::$_classes['hash'];
sort($fields, SORT_STRING);
ksort($locked, SORT_STRING);
sort($excluded, SORT_STRING);
foreach (['fields', 'excluded', 'locked'] as $list) {
${$list} = urlencode(serialize(${$list}));
}
$hash = $hash::calculate($fields);
$signature = static::_signature("{$locked}::{$excluded}::{$hash}");
return "{$locked}::{$excluded}::{$signature}";
} | [
"protected",
"static",
"function",
"_compile",
"(",
"array",
"$",
"fields",
",",
"array",
"$",
"locked",
",",
"array",
"$",
"excluded",
")",
"{",
"$",
"hash",
"=",
"static",
"::",
"$",
"_classes",
"[",
"'hash'",
"]",
";",
"sort",
"(",
"$",
"fields",
... | Compiles form signature string. Will normalize input data and `urlencode()` it.
The signature is calculated over locked and exclude fields as well as a hash
of $fields. The $fields data will not become part of the final form signature
string. The $fields hash is not signed itself as the hash will become part
of the form signature string which is already signed.
@param array $fields
@param array $locked
@param array $excluded
@return string The compiled form signature string that should be submitted
with the form data in the form of:
`<serialized locked>::<serialized excluded>::<signature>`. | [
"Compiles",
"form",
"signature",
"string",
".",
"Will",
"normalize",
"input",
"data",
"and",
"urlencode",
"()",
"it",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L140-L154 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature._signature | protected static function _signature($data) {
$hash = static::$_classes['hash'];
if (empty(static::$_secret)) {
$message = 'Form signature requires a secret key. ';
$message .= 'Please see documentation on how to configure a key.';
throw new ConfigException($message);
}
$key = 'li3,1' . static::$_secret;
$key = $hash::calculate(date('YMD'), ['key' => $key, 'raw' => true]);
$key = $hash::calculate('li3,1_form', ['key' => $key, 'raw' => true]);
return $hash::calculate($data, ['key' => $key]);
} | php | protected static function _signature($data) {
$hash = static::$_classes['hash'];
if (empty(static::$_secret)) {
$message = 'Form signature requires a secret key. ';
$message .= 'Please see documentation on how to configure a key.';
throw new ConfigException($message);
}
$key = 'li3,1' . static::$_secret;
$key = $hash::calculate(date('YMD'), ['key' => $key, 'raw' => true]);
$key = $hash::calculate('li3,1_form', ['key' => $key, 'raw' => true]);
return $hash::calculate($data, ['key' => $key]);
} | [
"protected",
"static",
"function",
"_signature",
"(",
"$",
"data",
")",
"{",
"$",
"hash",
"=",
"static",
"::",
"$",
"_classes",
"[",
"'hash'",
"]",
";",
"if",
"(",
"empty",
"(",
"static",
"::",
"$",
"_secret",
")",
")",
"{",
"$",
"message",
"=",
"'... | Calculates signature over given data.
Will first derive a signing key from the secret key and current date, then
calculate the HMAC over given data. This process is modelled after Amazon's
_Message Signature Version 4_ but uses less key derivations as we don't have
more information at our hands.
During key derivation the strings `li3,1` and `li3,1_form` are inserted. `1`
denotes the version of our signature algorithm and should be raised when the
algorithm is changed. Derivation is needed to not reveal the secret key.
Note: As the current date (year, month, day) is used to increase key security by
limiting its lifetime, a possible sideeffect is that a signature doen't verify if it is
generated on day N and verified on day N+1.
@link http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
@param string $data The data to calculate the signature for.
@return string The signature. | [
"Calculates",
"signature",
"over",
"given",
"data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L176-L189 |
UnionOfRAD/lithium | security/validation/FormSignature.php | FormSignature._parse | protected static function _parse($string) {
if (substr_count($string, '::') !== 2) {
throw new Exception('Possible data tampering: form signature string has wrong format.');
}
list($locked, $excluded) = explode('::', $string, 3);
return [
'locked' => unserialize(urldecode($locked)),
'excluded' => unserialize(urldecode($excluded))
];
} | php | protected static function _parse($string) {
if (substr_count($string, '::') !== 2) {
throw new Exception('Possible data tampering: form signature string has wrong format.');
}
list($locked, $excluded) = explode('::', $string, 3);
return [
'locked' => unserialize(urldecode($locked)),
'excluded' => unserialize(urldecode($excluded))
];
} | [
"protected",
"static",
"function",
"_parse",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"substr_count",
"(",
"$",
"string",
",",
"'::'",
")",
"!==",
"2",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Possible data tampering: form signature string has wrong format.'"... | Parses form signature string.
Note: The parsed signature is not returned as it's not needed. The signature
is verified by re-compiling the form signature string with the retrieved
signature.
@param string $string
@return array | [
"Parses",
"form",
"signature",
"string",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/validation/FormSignature.php#L201-L211 |
UnionOfRAD/lithium | analysis/Debugger.php | Debugger.trace | public static function trace(array $options = []) {
$defaults = [
'depth' => 999,
'format' => null,
'args' => false,
'start' => 0,
'scope' => [],
'trace' => [],
'includeScope' => true,
'closures' => true
];
$options += $defaults;
$backtrace = $options['trace'] ?: debug_backtrace();
$scope = $options['scope'];
$count = count($backtrace);
$back = [];
$traceDefault = [
'line' => '??', 'file' => '[internal]', 'class' => null, 'function' => '[main]'
];
for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
$trace = array_merge(['file' => '[internal]', 'line' => '??'], $backtrace[$i]);
$function = '[main]';
if (isset($backtrace[$i + 1])) {
$next = $backtrace[$i + 1] + $traceDefault;
$function = $next['function'];
if (!empty($next['class'])) {
$function = $next['class'] . '::' . $function . '(';
if ($options['args'] && isset($next['args'])) {
$args = array_map(['static', 'export'], $next['args']);
$function .= join(', ', $args);
}
$function .= ')';
}
}
if ($options['closures'] && strpos($function, '{closure}') !== false) {
$function = static::_closureDef($backtrace[$i], $function);
}
if (in_array($function, ['call_user_func_array', 'trigger_error'])) {
continue;
}
$trace['functionRef'] = $function;
if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
$back[] = ['file' => $trace['file'], 'line' => $trace['line']];
} elseif (is_string($options['format']) && $options['format'] !== 'array') {
$back[] = Text::insert($options['format'], array_map(
function($data) { return is_object($data) ? get_class($data) : $data; },
$trace
));
} elseif (empty($options['format'])) {
$back[] = $function . ' - ' . $trace['file'] . ', line ' . $trace['line'];
} else {
$back[] = $trace;
}
if (!empty($scope) && array_intersect_assoc($scope, $trace) == $scope) {
if (!$options['includeScope']) {
$back = array_slice($back, 0, count($back) - 1);
}
break;
}
}
if ($options['format'] === 'array' || $options['format'] === 'points') {
return $back;
}
return join("\n", $back);
} | php | public static function trace(array $options = []) {
$defaults = [
'depth' => 999,
'format' => null,
'args' => false,
'start' => 0,
'scope' => [],
'trace' => [],
'includeScope' => true,
'closures' => true
];
$options += $defaults;
$backtrace = $options['trace'] ?: debug_backtrace();
$scope = $options['scope'];
$count = count($backtrace);
$back = [];
$traceDefault = [
'line' => '??', 'file' => '[internal]', 'class' => null, 'function' => '[main]'
];
for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
$trace = array_merge(['file' => '[internal]', 'line' => '??'], $backtrace[$i]);
$function = '[main]';
if (isset($backtrace[$i + 1])) {
$next = $backtrace[$i + 1] + $traceDefault;
$function = $next['function'];
if (!empty($next['class'])) {
$function = $next['class'] . '::' . $function . '(';
if ($options['args'] && isset($next['args'])) {
$args = array_map(['static', 'export'], $next['args']);
$function .= join(', ', $args);
}
$function .= ')';
}
}
if ($options['closures'] && strpos($function, '{closure}') !== false) {
$function = static::_closureDef($backtrace[$i], $function);
}
if (in_array($function, ['call_user_func_array', 'trigger_error'])) {
continue;
}
$trace['functionRef'] = $function;
if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
$back[] = ['file' => $trace['file'], 'line' => $trace['line']];
} elseif (is_string($options['format']) && $options['format'] !== 'array') {
$back[] = Text::insert($options['format'], array_map(
function($data) { return is_object($data) ? get_class($data) : $data; },
$trace
));
} elseif (empty($options['format'])) {
$back[] = $function . ' - ' . $trace['file'] . ', line ' . $trace['line'];
} else {
$back[] = $trace;
}
if (!empty($scope) && array_intersect_assoc($scope, $trace) == $scope) {
if (!$options['includeScope']) {
$back = array_slice($back, 0, count($back) - 1);
}
break;
}
}
if ($options['format'] === 'array' || $options['format'] === 'points') {
return $back;
}
return join("\n", $back);
} | [
"public",
"static",
"function",
"trace",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'depth'",
"=>",
"999",
",",
"'format'",
"=>",
"null",
",",
"'args'",
"=>",
"false",
",",
"'start'",
"=>",
"0",
",",
"'scope'",... | Outputs a stack trace based on the supplied options.
@param array $options Format for outputting stack trace. Available options are:
- `'args'`: A boolean indicating if arguments should be included.
- `'depth'`: The maximum depth of the trace.
- `'format'`: Either `null`, `'points'` or `'array'`.
- `'includeScope'`: A boolean indicating if items within scope
should be included.
- `'scope'`: Scope for items to include.
- `'start'`: The depth to start with.
- `'trace'`: A trace to use instead of generating one.
@return string|array|null Stack trace formatted according to `'format'` option. | [
"Outputs",
"a",
"stack",
"trace",
"based",
"on",
"the",
"supplied",
"options",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Debugger.php#L44-L116 |
UnionOfRAD/lithium | analysis/Debugger.php | Debugger.export | public static function export($var) {
$export = var_export($var, true);
if (is_array($var)) {
$replace = [" (", " )", " ", " )", "=> \n\t"];
$with = ["(", ")", "\t", "\t)", "=> "];
$export = str_replace($replace, $with, $export);
}
return $export;
} | php | public static function export($var) {
$export = var_export($var, true);
if (is_array($var)) {
$replace = [" (", " )", " ", " )", "=> \n\t"];
$with = ["(", ")", "\t", "\t)", "=> "];
$export = str_replace($replace, $with, $export);
}
return $export;
} | [
"public",
"static",
"function",
"export",
"(",
"$",
"var",
")",
"{",
"$",
"export",
"=",
"var_export",
"(",
"$",
"var",
",",
"true",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"var",
")",
")",
"{",
"$",
"replace",
"=",
"[",
"\" (\"",
",",
"\" )\"... | Returns a parseable string representation of a variable.
@param mixed $var The variable to export.
@return string The exported contents. | [
"Returns",
"a",
"parseable",
"string",
"representation",
"of",
"a",
"variable",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Debugger.php#L124-L133 |
UnionOfRAD/lithium | analysis/Debugger.php | Debugger._definition | protected static function _definition($reference, $callLine) {
if (file_exists($reference)) {
foreach (array_reverse(token_get_all(file_get_contents($reference))) as $token) {
if (!is_array($token) || $token[2] > $callLine) {
continue;
}
if ($token[0] === T_FUNCTION) {
return $token[2];
}
}
return;
}
list($class,) = explode('::', $reference);
if (!class_exists($class)) {
return;
}
$classRef = new ReflectionClass($class);
$methodInfo = Inspector::info($reference);
$methodDef = join("\n", Inspector::lines($classRef->getFileName(), range(
$methodInfo['start'] + 1, $methodInfo['end'] - 1
)));
foreach (array_reverse(token_get_all("<?php {$methodDef} ?>")) as $token) {
if (!is_array($token) || $token[2] > $callLine) {
continue;
}
if ($token[0] === T_FUNCTION) {
return $token[2] + $methodInfo['start'];
}
}
} | php | protected static function _definition($reference, $callLine) {
if (file_exists($reference)) {
foreach (array_reverse(token_get_all(file_get_contents($reference))) as $token) {
if (!is_array($token) || $token[2] > $callLine) {
continue;
}
if ($token[0] === T_FUNCTION) {
return $token[2];
}
}
return;
}
list($class,) = explode('::', $reference);
if (!class_exists($class)) {
return;
}
$classRef = new ReflectionClass($class);
$methodInfo = Inspector::info($reference);
$methodDef = join("\n", Inspector::lines($classRef->getFileName(), range(
$methodInfo['start'] + 1, $methodInfo['end'] - 1
)));
foreach (array_reverse(token_get_all("<?php {$methodDef} ?>")) as $token) {
if (!is_array($token) || $token[2] > $callLine) {
continue;
}
if ($token[0] === T_FUNCTION) {
return $token[2] + $methodInfo['start'];
}
}
} | [
"protected",
"static",
"function",
"_definition",
"(",
"$",
"reference",
",",
"$",
"callLine",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"reference",
")",
")",
"{",
"foreach",
"(",
"array_reverse",
"(",
"token_get_all",
"(",
"file_get_contents",
"(",
"$"... | Locates original location of closures.
@param mixed $reference File or class name to inspect.
@param integer $callLine Line number of class reference.
@return mixed Returns the line number where the method called is defined. | [
"Locates",
"original",
"location",
"of",
"closures",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Debugger.php#L142-L174 |
UnionOfRAD/lithium | analysis/Debugger.php | Debugger._closureDef | protected static function _closureDef($frame, $function) {
$reference = '::';
$frame += ['file' => '??', 'line' => '??'];
$cacheKey = "{$frame['file']}@{$frame['line']}";
if (isset(static::$_closureCache[$cacheKey])) {
return static::$_closureCache[$cacheKey];
}
if ($class = Inspector::classes(['file' => $frame['file']])) {
foreach (Inspector::methods(key($class), 'extents') as $method => $extents) {
$line = $frame['line'];
if (!($extents[0] <= $line && $line <= $extents[1])) {
continue;
}
$class = key($class);
$reference = "{$class}::{$method}";
$function = "{$reference}()::{closure}";
break;
}
} else {
$reference = $frame['file'];
$function = "{$reference}::{closure}";
}
$line = static::_definition($reference, $frame['line']) ?: '?';
$function .= " @ {$line}";
return static::$_closureCache[$cacheKey] = $function;
} | php | protected static function _closureDef($frame, $function) {
$reference = '::';
$frame += ['file' => '??', 'line' => '??'];
$cacheKey = "{$frame['file']}@{$frame['line']}";
if (isset(static::$_closureCache[$cacheKey])) {
return static::$_closureCache[$cacheKey];
}
if ($class = Inspector::classes(['file' => $frame['file']])) {
foreach (Inspector::methods(key($class), 'extents') as $method => $extents) {
$line = $frame['line'];
if (!($extents[0] <= $line && $line <= $extents[1])) {
continue;
}
$class = key($class);
$reference = "{$class}::{$method}";
$function = "{$reference}()::{closure}";
break;
}
} else {
$reference = $frame['file'];
$function = "{$reference}::{closure}";
}
$line = static::_definition($reference, $frame['line']) ?: '?';
$function .= " @ {$line}";
return static::$_closureCache[$cacheKey] = $function;
} | [
"protected",
"static",
"function",
"_closureDef",
"(",
"$",
"frame",
",",
"$",
"function",
")",
"{",
"$",
"reference",
"=",
"'::'",
";",
"$",
"frame",
"+=",
"[",
"'file'",
"=>",
"'??'",
",",
"'line'",
"=>",
"'??'",
"]",
";",
"$",
"cacheKey",
"=",
"\"... | Helper method for caching closure function references to help the process of building the
stack trace.
@param array $frame Backtrace information.
@param callable|string $function The method related to $frame information.
@return string Returns either the cached or the fetched closure function reference while
writing its reference to the cache array `$_closureCache`. | [
"Helper",
"method",
"for",
"caching",
"closure",
"function",
"references",
"to",
"help",
"the",
"process",
"of",
"building",
"the",
"stack",
"trace",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Debugger.php#L185-L213 |
UnionOfRAD/lithium | security/Password.php | Password.salt | public static function salt($type = null, $count = null) {
switch (true) {
case CRYPT_BLOWFISH === 1 && (!$type || $type === 'bf'):
return static::_generateSaltBf($count);
case CRYPT_EXT_DES === 1 && (!$type || $type === 'xdes'):
return static::_generateSaltXdes($count);
default:
return static::_generateSaltMd5();
}
} | php | public static function salt($type = null, $count = null) {
switch (true) {
case CRYPT_BLOWFISH === 1 && (!$type || $type === 'bf'):
return static::_generateSaltBf($count);
case CRYPT_EXT_DES === 1 && (!$type || $type === 'xdes'):
return static::_generateSaltXdes($count);
default:
return static::_generateSaltMd5();
}
} | [
"public",
"static",
"function",
"salt",
"(",
"$",
"type",
"=",
"null",
",",
"$",
"count",
"=",
"null",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"CRYPT_BLOWFISH",
"===",
"1",
"&&",
"(",
"!",
"$",
"type",
"||",
"$",
"type",
"===",
"'bf'",
... | Generates a cryptographically strong salt, using the best available
method (tries Blowfish, then XDES, and fallbacks to MD5), for use in
`Password::hash()`.
Blowfish and XDES are adaptive hashing algorithms. MD5 is not. Adaptive
hashing algorithms are designed in such a way that when computers get
faster, you can tune the algorithm to be slower by increasing the number
of hash iterations, without introducing incompatibility with existing
passwords.
To pick an appropriate iteration count for adaptive algorithms, consider
that the original DES crypt was designed to have the speed of 4 hashes
per second on the hardware of that time. Slower than 4 hashes per second
would probably dampen usability. Faster than 100 hashes per second is
probably too fast. The defaults generate about 10 hashes per second
using a dual-core 2.2GHz CPU.
_Note 1_: this salt generator is different from naive salt implementations
(e.g. `md5(microtime())`) in that it uses all of the available bits of
entropy for the supplied salt method.
_Note2_: this method should not be use to generate custom salts. Indeed,
the resulting salts are prefixed with information expected by PHP's
`crypt()`. To get an arbitrarily long, cryptographically strong salt
consisting in random sequences of alpha numeric characters, use
`lithium\security\Random::generate()` instead.
@link http://php.net/function.crypt.php
@link http://www.postgresql.org/docs/9.0/static/pgcrypto.html
@see lithium\security\Password::hash()
@see lithium\security\Password::check()
@see lithium\security\Random::generate()
@param string $type The hash type. Optional. Defaults to the best
available option. Supported values, along with their maximum
password lengths, include:
- `'bf'`: Blowfish (128 salt bits, max 72 chars)
- `'xdes'`: XDES (24 salt bits, max 8 chars)
- `'md5'`: MD5 (48 salt bits, unlimited length)
@param integer $count Optional. The base-2 logarithm of the iteration
count, for adaptive algorithms. Defaults to:
- `10` for Blowfish
- `18` for XDES
@return string The salt string. | [
"Generates",
"a",
"cryptographically",
"strong",
"salt",
"using",
"the",
"best",
"available",
"method",
"(",
"tries",
"Blowfish",
"then",
"XDES",
"and",
"fallbacks",
"to",
"MD5",
")",
"for",
"use",
"in",
"Password",
"::",
"hash",
"()",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Password.php#L148-L157 |
UnionOfRAD/lithium | security/Password.php | Password._generateSaltBf | protected static function _generateSaltBf($count = null) {
$count = (integer) $count;
$count = ($count < 4 || $count > 31) ? static::BF : $count;
$base64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$i = 0;
$input = Random::generate(16);
$output = '';
do {
$c1 = ord($input[$i++]);
$output .= $base64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $base64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $base64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $base64[$c1];
$output .= $base64[$c2 & 0x3f];
} while (1);
$result = '$2a$';
$result .= chr(ord('0') + $count / static::BF);
$result .= chr(ord('0') + $count % static::BF);
$result .= '$' . $output;
return $result;
} | php | protected static function _generateSaltBf($count = null) {
$count = (integer) $count;
$count = ($count < 4 || $count > 31) ? static::BF : $count;
$base64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$i = 0;
$input = Random::generate(16);
$output = '';
do {
$c1 = ord($input[$i++]);
$output .= $base64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $base64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $base64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $base64[$c1];
$output .= $base64[$c2 & 0x3f];
} while (1);
$result = '$2a$';
$result .= chr(ord('0') + $count / static::BF);
$result .= chr(ord('0') + $count % static::BF);
$result .= '$' . $output;
return $result;
} | [
"protected",
"static",
"function",
"_generateSaltBf",
"(",
"$",
"count",
"=",
"null",
")",
"{",
"$",
"count",
"=",
"(",
"integer",
")",
"$",
"count",
";",
"$",
"count",
"=",
"(",
"$",
"count",
"<",
"4",
"||",
"$",
"count",
">",
"31",
")",
"?",
"s... | Generates a Blowfish salt for use in `lithium\security\Password::hash()`. _Note_: Does not
use the `'encode'` option of `Random::generate()` because it could result in 2 bits less of
entropy depending on the last character.
@param integer $count The base-2 logarithm of the iteration count.
Defaults to `10`. Can be `4` to `31`.
@return string The Blowfish salt. | [
"Generates",
"a",
"Blowfish",
"salt",
"for",
"use",
"in",
"lithium",
"\\",
"security",
"\\",
"Password",
"::",
"hash",
"()",
".",
"_Note_",
":",
"Does",
"not",
"use",
"the",
"encode",
"option",
"of",
"Random",
"::",
"generate",
"()",
"because",
"it",
"co... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Password.php#L168-L204 |
UnionOfRAD/lithium | security/Password.php | Password._generateSaltXdes | protected static function _generateSaltXdes($count = null) {
$count = (integer) $count;
$count = ($count < 1 || $count > 24) ? static::XDES : $count;
$count = (1 << $count) - 1;
$base64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$output = '_' . $base64[$count & 0x3f] . $base64[($count >> 6) & 0x3f];
$output .= $base64[($count >> 12) & 0x3f] . $base64[($count >> 18) & 0x3f];
$output .= Random::generate(3, ['encode' => Random::ENCODE_BASE_64]);
return $output;
} | php | protected static function _generateSaltXdes($count = null) {
$count = (integer) $count;
$count = ($count < 1 || $count > 24) ? static::XDES : $count;
$count = (1 << $count) - 1;
$base64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$output = '_' . $base64[$count & 0x3f] . $base64[($count >> 6) & 0x3f];
$output .= $base64[($count >> 12) & 0x3f] . $base64[($count >> 18) & 0x3f];
$output .= Random::generate(3, ['encode' => Random::ENCODE_BASE_64]);
return $output;
} | [
"protected",
"static",
"function",
"_generateSaltXdes",
"(",
"$",
"count",
"=",
"null",
")",
"{",
"$",
"count",
"=",
"(",
"integer",
")",
"$",
"count",
";",
"$",
"count",
"=",
"(",
"$",
"count",
"<",
"1",
"||",
"$",
"count",
">",
"24",
")",
"?",
... | Generates an Extended DES salt for use in `lithium\security\Password::hash()`.
@param integer $count The base-2 logarithm of the iteration count. Defaults to `18`. Can be
`1` to `24`. 1 will be stripped from the non-log value, e.g. 2^18 - 1, to
ensure we don't use a weak DES key.
@return string The XDES salt. | [
"Generates",
"an",
"Extended",
"DES",
"salt",
"for",
"use",
"in",
"lithium",
"\\",
"security",
"\\",
"Password",
"::",
"hash",
"()",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Password.php#L214-L226 |
UnionOfRAD/lithium | aop/Filters.php | Filters.apply | public static function apply($class, $method, $filter) {
list($id,) = static::_ids($class, $method);
if (!isset(static::$_filters[$id])) {
static::$_filters[$id] = [];
}
static::$_filters[$id][] = $filter;
if (isset(static::$_chains[$id])) {
unset(static::$_chains[$id]);
}
} | php | public static function apply($class, $method, $filter) {
list($id,) = static::_ids($class, $method);
if (!isset(static::$_filters[$id])) {
static::$_filters[$id] = [];
}
static::$_filters[$id][] = $filter;
if (isset(static::$_chains[$id])) {
unset(static::$_chains[$id]);
}
} | [
"public",
"static",
"function",
"apply",
"(",
"$",
"class",
",",
"$",
"method",
",",
"$",
"filter",
")",
"{",
"list",
"(",
"$",
"id",
",",
")",
"=",
"static",
"::",
"_ids",
"(",
"$",
"class",
",",
"$",
"method",
")",
";",
"if",
"(",
"!",
"isset... | Lazily applies a filter to a method.
Classes aliased via `class_alias()` are treated as entirely separate from
their original class.
When calling apply after previous runs (rarely happens), this method will
invalidate the chain cache.
Multiple applications of a filter will add the filter multiple times to
the chain. It is up to the user to keep the list of filters unique.
This method intentionally does not establish class context for closures
by binding them to the instance or statically to the class. Closures can
originate from static and instance methods and PHP does not allow to
rebind a closure from a static method to an instance.
@param string|object $class The fully namespaced name of a static class or
an instance of a concrete class to which the filter will be applied.
Passing a class name for a concrete class will apply the filter to all
instances of that class.
@param string $method The method name to which the filter will be applied i.e. `'bar'`.
@param callable $filter The filter to apply to the class method. Can be anykind of
a callable, most often this is a closure.
@return void | [
"Lazily",
"applies",
"a",
"filter",
"to",
"a",
"method",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L150-L161 |
UnionOfRAD/lithium | aop/Filters.php | Filters.hasApplied | public static function hasApplied($class, $method) {
foreach (static::_ids($class, $method) as $id) {
if (isset(static::$_filters[$id])) {
return true;
}
}
return false;
} | php | public static function hasApplied($class, $method) {
foreach (static::_ids($class, $method) as $id) {
if (isset(static::$_filters[$id])) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"hasApplied",
"(",
"$",
"class",
",",
"$",
"method",
")",
"{",
"foreach",
"(",
"static",
"::",
"_ids",
"(",
"$",
"class",
",",
"$",
"method",
")",
"as",
"$",
"id",
")",
"{",
"if",
"(",
"isset",
"(",
"static",
"::",
... | Checks to see if the given class/method has any filters applied.
@param string|object $class Fully namespaced class name or an instance of a class.
@param string $method The method name i.e. `'bar'`.
@return boolean | [
"Checks",
"to",
"see",
"if",
"the",
"given",
"class",
"/",
"method",
"has",
"any",
"filters",
"applied",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L170-L177 |
UnionOfRAD/lithium | aop/Filters.php | Filters.run | public static function run($class, $method, array $params, $implementation) {
$implementation = static::_bcImplementation($class, $method, $params, $implementation);
if (!static::hasApplied($class, $method)) {
return $implementation($params);
}
return static::_chain($class, $method)->run($params, $implementation);
} | php | public static function run($class, $method, array $params, $implementation) {
$implementation = static::_bcImplementation($class, $method, $params, $implementation);
if (!static::hasApplied($class, $method)) {
return $implementation($params);
}
return static::_chain($class, $method)->run($params, $implementation);
} | [
"public",
"static",
"function",
"run",
"(",
"$",
"class",
",",
"$",
"method",
",",
"array",
"$",
"params",
",",
"$",
"implementation",
")",
"{",
"$",
"implementation",
"=",
"static",
"::",
"_bcImplementation",
"(",
"$",
"class",
",",
"$",
"method",
",",
... | Runs the chain and returns its result value. This method is used to make
a method filterable.
All filters in the run will have access to given parameters. The
implementation will be placed as the last item in the chain, so
that effectively filters for the implementation wrap arround its
implementation.
Creates `Chain` objects lazily, caches and reuses them with differing
parameters for best of both worlds: lazy object construction to save
upfront memory as well as quick re-execution. This method may be called
quite often when filtered methods are executed inside a loop. Thus it
tries to reduce overhead as much as possible. Optimized for the common
case that no filters for a filtered method are present.
An example implementation function:
```
function($params) {
$params['foo'] = 'bar';
return $params['foo'];
}
```
Two examples to make a method filterable.
```
// Inside a static method.
Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
return 'implementation';
});
// Inside an instance method.
Filters::run($this, __FUNCTION__, $params, function($params) {
return 'implementation';
});
```
@see lithium\aop\Chain
@see lithium\aop\Chain::run()
@param string|object $class The fully namespaced name of a static class or
an instance of a concrete class. Do not pass a class name for
concrete classes. For instances will use a set of merged filters.
First class filter, then instance filters.
@param string $method The method name i.e. `'bar'`.
@param array $params
@param callable $implementation
@return mixed The result of running the chain. | [
"Runs",
"the",
"chain",
"and",
"returns",
"its",
"result",
"value",
".",
"This",
"method",
"is",
"used",
"to",
"make",
"a",
"method",
"filterable",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L227-L234 |
UnionOfRAD/lithium | aop/Filters.php | Filters.clear | public static function clear($class = null, $method = null) {
if ($class === null && $method === null) {
static::$_filters = static::$_chains = [];
return;
}
if (is_string($class)) {
$regex = '^<' . str_replace('\\', '\\\\', ltrim($class, '\\')) . '.*>';
} else {
$regex = '^<.*#' . spl_object_hash($class) . '>';
}
if ($method) {
$regex .= "::{$method}$";
}
foreach (preg_grep("/{$regex}/", array_keys(static::$_filters)) as $id) {
unset(static::$_filters[$id]);
}
foreach (preg_grep("/{$regex}/", array_keys(static::$_chains)) as $id) {
unset(static::$_chains[$id]);
}
} | php | public static function clear($class = null, $method = null) {
if ($class === null && $method === null) {
static::$_filters = static::$_chains = [];
return;
}
if (is_string($class)) {
$regex = '^<' . str_replace('\\', '\\\\', ltrim($class, '\\')) . '.*>';
} else {
$regex = '^<.*#' . spl_object_hash($class) . '>';
}
if ($method) {
$regex .= "::{$method}$";
}
foreach (preg_grep("/{$regex}/", array_keys(static::$_filters)) as $id) {
unset(static::$_filters[$id]);
}
foreach (preg_grep("/{$regex}/", array_keys(static::$_chains)) as $id) {
unset(static::$_chains[$id]);
}
} | [
"public",
"static",
"function",
"clear",
"(",
"$",
"class",
"=",
"null",
",",
"$",
"method",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"class",
"===",
"null",
"&&",
"$",
"method",
"===",
"null",
")",
"{",
"static",
"::",
"$",
"_filters",
"=",
"static"... | Clears filters optionally constrained by class or class and method combination.
To clear filters for all methods of static class:
```
Filters::clear('Foo');
```
To clear instance and class filters for all methods of concrete class,
or to clear just the instance filters for all methods:
```
Filters::clear('Bar');
Filters::clear($instance);
```
This method involves some overhead. This is neglectable as it isn't commonly
called in hot code paths.
@param string|object $class Fully namespaced class name or an instance of a class.
@param string $method The method name i.e. `'bar'`.
@return void | [
"Clears",
"filters",
"optionally",
"constrained",
"by",
"class",
"or",
"class",
"and",
"method",
"combination",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L258-L278 |
UnionOfRAD/lithium | aop/Filters.php | Filters._chain | protected static function _chain($class, $method) {
$ids = static::_ids($class, $method);
if (isset(static::$_chains[$ids[0]])) {
return static::$_chains[$ids[0]];
}
$filters = [];
foreach ($ids as $id) {
if (isset(static::$_filters[$id])) {
$filters = array_merge(static::$_filters[$id], $filters);
}
}
return static::$_chains[$ids[0]] = new Chain(compact('class', 'method', 'filters'));
} | php | protected static function _chain($class, $method) {
$ids = static::_ids($class, $method);
if (isset(static::$_chains[$ids[0]])) {
return static::$_chains[$ids[0]];
}
$filters = [];
foreach ($ids as $id) {
if (isset(static::$_filters[$id])) {
$filters = array_merge(static::$_filters[$id], $filters);
}
}
return static::$_chains[$ids[0]] = new Chain(compact('class', 'method', 'filters'));
} | [
"protected",
"static",
"function",
"_chain",
"(",
"$",
"class",
",",
"$",
"method",
")",
"{",
"$",
"ids",
"=",
"static",
"::",
"_ids",
"(",
"$",
"class",
",",
"$",
"method",
")",
";",
"if",
"(",
"isset",
"(",
"static",
"::",
"$",
"_chains",
"[",
... | Creates a chain for given class/method combination or retrieves it from
cache. Will implictly do a reverse merge to put static filters first before
instance filters.
@see lithium\aop\Chain
@param string|object $class Fully namespaced class name or an instance of a class.
@param string $method The method name i.e. `'bar'`.
@return \lithium\aop\Chain | [
"Creates",
"a",
"chain",
"for",
"given",
"class",
"/",
"method",
"combination",
"or",
"retrieves",
"it",
"from",
"cache",
".",
"Will",
"implictly",
"do",
"a",
"reverse",
"merge",
"to",
"put",
"static",
"filters",
"first",
"before",
"instance",
"filters",
"."... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L317-L331 |
UnionOfRAD/lithium | aop/Filters.php | Filters.bcRun | public static function bcRun($class, $method, array $params, $implementation, array $filters) {
$implementation = static::_bcImplementation($class, $method, $params, $implementation);
$ids = static::_ids($class, $method);
foreach ($ids as $id) {
if (isset(static::$_filters[$id])) {
$filters = array_merge(static::$_filters[$id], $filters);
}
}
return new Chain(compact('class', 'method', 'filters'));
} | php | public static function bcRun($class, $method, array $params, $implementation, array $filters) {
$implementation = static::_bcImplementation($class, $method, $params, $implementation);
$ids = static::_ids($class, $method);
foreach ($ids as $id) {
if (isset(static::$_filters[$id])) {
$filters = array_merge(static::$_filters[$id], $filters);
}
}
return new Chain(compact('class', 'method', 'filters'));
} | [
"public",
"static",
"function",
"bcRun",
"(",
"$",
"class",
",",
"$",
"method",
",",
"array",
"$",
"params",
",",
"$",
"implementation",
",",
"array",
"$",
"filters",
")",
"{",
"$",
"implementation",
"=",
"static",
"::",
"_bcImplementation",
"(",
"$",
"c... | /* Deprecated / BC | [
"/",
"*",
"Deprecated",
"/",
"BC"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Filters.php#L335-L345 |
UnionOfRAD/lithium | storage/Cache.php | Cache.write | public static function write($name, $key, $data = null, $expiry = null, array $options = []) {
$options += ['conditions' => null, 'strategies' => true];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key, $data);
if (is_array($key)) {
$keys = $key;
$expiry = $data;
} else {
$keys = [$key => $data];
}
if ($options['strategies']) {
foreach ($keys as $key => &$value) {
$value = static::applyStrategies(__FUNCTION__, $name, $value, [
'key' => $key, 'class' => __CLASS__
]);
}
}
$params = compact('keys', 'expiry');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->write($params['keys'], $params['expiry']);
});
} | php | public static function write($name, $key, $data = null, $expiry = null, array $options = []) {
$options += ['conditions' => null, 'strategies' => true];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key, $data);
if (is_array($key)) {
$keys = $key;
$expiry = $data;
} else {
$keys = [$key => $data];
}
if ($options['strategies']) {
foreach ($keys as $key => &$value) {
$value = static::applyStrategies(__FUNCTION__, $name, $value, [
'key' => $key, 'class' => __CLASS__
]);
}
}
$params = compact('keys', 'expiry');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->write($params['keys'], $params['expiry']);
});
} | [
"public",
"static",
"function",
"write",
"(",
"$",
"name",
",",
"$",
"key",
",",
"$",
"data",
"=",
"null",
",",
"$",
"expiry",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'conditions'",
"=>",
"n... | Writes to the specified cache configuration.
Can handle single- and multi-key writes.
This method has two valid syntaxes depending on if you're storing
data using a single key or multiple keys as outlined below.
```
// To write data to a single-key use the following syntax.
Cache::write('default', 'foo', 'bar', '+1 minute');
// For multi-key writes the $data parameter's role becomes
// the one of the $expiry parameter.
Cache::write('default', ['foo' => 'bar', ... ], '+1 minute');
```
These two calls are synonymical and demonstrate the two
possible ways to specify the expiration time.
```
Cache::write('default', 'foo', 'bar', '+1 minute');
Cache::write('default', 'foo', 'bar', 60);
```
@param string $name Configuration to be used for writing.
@param mixed $key Key to uniquely identify the cache entry or an array of key/value pairs
for multi-key writes mapping cache keys to the data to be cached.
@param mixed $data Data to be cached.
@param string|integer $expiry A `strtotime()` compatible cache time. Alternatively an integer
denoting the seconds until the item expires (TTL). If no expiry time is
set, then the default cache expiration time set with the cache adapter
configuration will be used. To persist an item use `Cache::PERSIST`.
@param array $options Options for the method and strategies.
- `'strategies'` _boolean_: Indicates if strategies should be used,
defaults to `true`.
- `'conditions'` _mixed_: A function or item that must return or
evaluate to `true` in order to continue write operation.
@return boolean `true` on successful cache write, `false` otherwise. When writing
multiple items and an error occurs writing any of the items the
whole operation fails and this method will return `false`.
@filter | [
"Writes",
"to",
"the",
"specified",
"cache",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/Cache.php#L154-L186 |
UnionOfRAD/lithium | storage/Cache.php | Cache.read | public static function read($name, $key, array $options = []) {
$options += ['conditions' => null, 'strategies' => true, 'write' => null];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
if ($isMulti = is_array($key)) {
$keys = $key;
} else {
$keys = [$key];
}
$params = compact('keys');
$results = Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->read($params['keys']);
});
if ($write = $options['write']) {
$isEvaluated = false;
foreach ($keys as $key) {
if (isset($results[$key])) {
continue;
}
if (!$isEvaluated) {
$write = is_callable($write) ? $write() : $write;
$expiry = key($write);
$value = current($write);
$value = is_callable($value) ? $value() : $value;
$isEvaluated = true;
}
if (!static::write($name, $key, $value, $expiry)) {
return false;
}
$results[$key] = static::applyStrategies('write', $name, $value, [
'key' => $key, 'mode' => 'LIFO', 'class' => __CLASS__
]);
}
}
if ($options['strategies']) {
foreach ($results as $key => &$result) {
$result = static::applyStrategies(__FUNCTION__, $name, $result, [
'key' => $key, 'mode' => 'LIFO', 'class' => __CLASS__
]);
}
}
return $isMulti ? $results : ($results ? reset($results) : null);
} | php | public static function read($name, $key, array $options = []) {
$options += ['conditions' => null, 'strategies' => true, 'write' => null];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
if ($isMulti = is_array($key)) {
$keys = $key;
} else {
$keys = [$key];
}
$params = compact('keys');
$results = Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->read($params['keys']);
});
if ($write = $options['write']) {
$isEvaluated = false;
foreach ($keys as $key) {
if (isset($results[$key])) {
continue;
}
if (!$isEvaluated) {
$write = is_callable($write) ? $write() : $write;
$expiry = key($write);
$value = current($write);
$value = is_callable($value) ? $value() : $value;
$isEvaluated = true;
}
if (!static::write($name, $key, $value, $expiry)) {
return false;
}
$results[$key] = static::applyStrategies('write', $name, $value, [
'key' => $key, 'mode' => 'LIFO', 'class' => __CLASS__
]);
}
}
if ($options['strategies']) {
foreach ($results as $key => &$result) {
$result = static::applyStrategies(__FUNCTION__, $name, $result, [
'key' => $key, 'mode' => 'LIFO', 'class' => __CLASS__
]);
}
}
return $isMulti ? $results : ($results ? reset($results) : null);
} | [
"public",
"static",
"function",
"read",
"(",
"$",
"name",
",",
"$",
"key",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'conditions'",
"=>",
"null",
",",
"'strategies'",
"=>",
"true",
",",
"'write'",
"=>",
"null"... | Reads from the specified cache configuration.
Can handle single- and multi-key reads.
Read-through caching can be used by passing expiry and the to-be-cached value
in the `write` option. Following three ways to achieve this.
```
Cache::read('default', 'foo', [
'write' => ['+5 days' => 'bar']
]); // returns `'bar'`
Cache::read('default', 'foo', [
'write' => ['+5 days' => function() { return 'bar'; }]
]);
Cache::read('default', 'foo', [
'write' => function() { return ['+5 days' => 'bar']; }
]);
```
@param string $name Configuration to be used for reading.
@param mixed $key Key to uniquely identify the cache entry or an array of keys
for multikey-reads.
@param array $options Options for the method and strategies.
- `'write'`: Allows for read-through caching see description for usage.
- `'strategies'` _boolean_: Indicates if strategies should be used,
defaults to `true`.
- `'conditions'` _mixed_: A function or item that must return or
evaluate to `true` in order to continue write operation.
@return mixed For single-key reads will return the result if the cache
key has been found otherwise returns `null`. When reading
multiple keys a results array is returned mapping keys to
retrieved values. Keys where the value couldn't successfully
been read will not be contained in the results array.
@filter | [
"Reads",
"from",
"the",
"specified",
"cache",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/Cache.php#L225-L281 |
UnionOfRAD/lithium | storage/Cache.php | Cache.delete | public static function delete($name, $key, array $options = []) {
$options += ['conditions' => null, 'strategies' => true];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
if (is_array($key)) {
$keys = $key;
} else {
$keys = [$key];
}
$params = compact('keys');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->delete($params['keys']);
});
} | php | public static function delete($name, $key, array $options = []) {
$options += ['conditions' => null, 'strategies' => true];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
if (is_array($key)) {
$keys = $key;
} else {
$keys = [$key];
}
$params = compact('keys');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->delete($params['keys']);
});
} | [
"public",
"static",
"function",
"delete",
"(",
"$",
"name",
",",
"$",
"key",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'conditions'",
"=>",
"null",
",",
"'strategies'",
"=>",
"true",
"]",
";",
"if",
"(",
"is... | Deletes using the specified cache configuration.
Can handle single- and multi-key deletes.
@param string $name The cache configuration to delete from.
@param mixed $key Key to be deleted or an array of keys to delete.
@param array $options Options for the method and strategies.
- `'conditions'` _mixed_: A function or item that must return or
evaluate to `true` in order to continue write operation.
@return boolean `true` on successful cache delete, `false` otherwise. When deleting
multiple items and an error occurs deleting any of the items the
whole operation fails and this method will return `false`.
@filter | [
"Deletes",
"using",
"the",
"specified",
"cache",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/Cache.php#L298-L321 |
UnionOfRAD/lithium | storage/Cache.php | Cache.increment | public static function increment($name, $key, $offset = 1, array $options = []) {
$options += ['conditions' => null];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
$params = compact('key', 'offset');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->increment($params['key'], $params['offset']);
});
} | php | public static function increment($name, $key, $offset = 1, array $options = []) {
$options += ['conditions' => null];
if (is_callable($options['conditions']) && !$options['conditions']()) {
return false;
}
try {
$adapter = static::adapter($name);
} catch (ConfigException $e) {
return false;
}
$key = static::key($key);
$params = compact('key', 'offset');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) use ($adapter) {
return $adapter->increment($params['key'], $params['offset']);
});
} | [
"public",
"static",
"function",
"increment",
"(",
"$",
"name",
",",
"$",
"key",
",",
"$",
"offset",
"=",
"1",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'conditions'",
"=>",
"null",
"]",
";",
"if",
"(",
"is... | Performs a increment operation on specified numeric cache item
from the given cache configuration.
@param string $name Name of the cache configuration to use.
@param string $key Key of numeric cache item to increment
@param integer $offset Offset to increment - defaults to 1.
@param array $options Options for this method.
- `'conditions'`: A function or item that must return or evaluate to
`true` in order to continue operation.
@return integer|boolean Item's new value on successful increment, false otherwise.
@filter | [
"Performs",
"a",
"increment",
"operation",
"on",
"specified",
"numeric",
"cache",
"item",
"from",
"the",
"given",
"cache",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/Cache.php#L336-L353 |
UnionOfRAD/lithium | data/source/Result.php | Result.next | public function next() {
if ($this->_buffer) {
list($this->_key, $this->_current) = array_shift($this->_buffer);
return $this->_current;
}
if (!$next = $this->_fetch()) {
$this->_key = null;
$this->_current = null;
$this->_valid = false;
return null;
} else {
list($this->_key, $this->_current) = $next;
$this->_valid = true;
}
return $this->_current;
} | php | public function next() {
if ($this->_buffer) {
list($this->_key, $this->_current) = array_shift($this->_buffer);
return $this->_current;
}
if (!$next = $this->_fetch()) {
$this->_key = null;
$this->_current = null;
$this->_valid = false;
return null;
} else {
list($this->_key, $this->_current) = $next;
$this->_valid = true;
}
return $this->_current;
} | [
"public",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_buffer",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"_key",
",",
"$",
"this",
"->",
"_current",
")",
"=",
"array_shift",
"(",
"$",
"this",
"->",
"_buffer",
")",
";",
"ret... | Fetches the next element from the resource.
@return mixed The next result (or `null` if there is none). | [
"Fetches",
"the",
"next",
"element",
"from",
"the",
"resource",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Result.php#L135-L152 |
UnionOfRAD/lithium | data/source/Result.php | Result.peek | public function peek() {
if ($this->_buffer) {
return reset($this->_buffer);
}
if (!$next = $this->_fetch()) {
return null;
}
$this->_buffer[] = $next;
$first = reset($this->_buffer);
return end($first);
} | php | public function peek() {
if ($this->_buffer) {
return reset($this->_buffer);
}
if (!$next = $this->_fetch()) {
return null;
}
$this->_buffer[] = $next;
$first = reset($this->_buffer);
return end($first);
} | [
"public",
"function",
"peek",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_buffer",
")",
"{",
"return",
"reset",
"(",
"$",
"this",
"->",
"_buffer",
")",
";",
"}",
"if",
"(",
"!",
"$",
"next",
"=",
"$",
"this",
"->",
"_fetch",
"(",
")",
")",
... | Peeks at the next element in the resource without advancing `Result`'s cursor.
@return mixed The next result (or `null` if there is none). | [
"Peeks",
"at",
"the",
"next",
"element",
"in",
"the",
"resource",
"without",
"advancing",
"Result",
"s",
"cursor",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Result.php#L159-L169 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql._init | protected function _init() {
if (!$this->_config['host'] && $this->_config['host'] !== false) {
throw new ConfigException('No host configured.');
}
if ($this->_config['host'] === false) {
$this->_config['dsn'] = sprintf(
'pgsql:dbname=%s',
$this->_config['database']
);
} else {
$host = HostString::parse($this->_config['host']) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$this->_config['dsn'] = sprintf(
'pgsql:host=%s;port=%s;dbname=%s',
$host['host'],
$host['port'],
$this->_config['database']
);
}
parent::_init();
} | php | protected function _init() {
if (!$this->_config['host'] && $this->_config['host'] !== false) {
throw new ConfigException('No host configured.');
}
if ($this->_config['host'] === false) {
$this->_config['dsn'] = sprintf(
'pgsql:dbname=%s',
$this->_config['database']
);
} else {
$host = HostString::parse($this->_config['host']) + [
'host' => static::DEFAULT_HOST,
'port' => static::DEFAULT_PORT
];
$this->_config['dsn'] = sprintf(
'pgsql:host=%s;port=%s;dbname=%s',
$host['host'],
$host['port'],
$this->_config['database']
);
}
parent::_init();
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_config",
"[",
"'host'",
"]",
"&&",
"$",
"this",
"->",
"_config",
"[",
"'host'",
"]",
"!==",
"false",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
"'No host confi... | Initializer. Constructs a DSN from configuration.
@return void | [
"Initializer",
".",
"Constructs",
"a",
"DSN",
"from",
"configuration",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L154-L177 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.connect | public function connect() {
if (!parent::connect()) {
return false;
}
if ($this->_config['schema']) {
$this->searchPath($this->_config['schema']);
}
if ($this->_config['timezone']) {
$this->timezone($this->_config['timezone']);
}
return true;
} | php | public function connect() {
if (!parent::connect()) {
return false;
}
if ($this->_config['schema']) {
$this->searchPath($this->_config['schema']);
}
if ($this->_config['timezone']) {
$this->timezone($this->_config['timezone']);
}
return true;
} | [
"public",
"function",
"connect",
"(",
")",
"{",
"if",
"(",
"!",
"parent",
"::",
"connect",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"_config",
"[",
"'schema'",
"]",
")",
"{",
"$",
"this",
"->",
"searchPath",
... | Connects to the database by creating a PDO intance using the constructed DSN string.
Will set specific options on the connection as provided (timezone, schema).
@see lithium\data\source\database\adapter\PostgreSql::timezone()
@return boolean Returns `true` if a database connection could be established,
otherwise `false`. | [
"Connects",
"to",
"the",
"database",
"by",
"creating",
"a",
"PDO",
"intance",
"using",
"the",
"constructed",
"DSN",
"string",
".",
"Will",
"set",
"specific",
"options",
"on",
"the",
"connection",
"as",
"provided",
"(",
"timezone",
"schema",
")",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L187-L198 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.sources | public function sources($model = null) {
$params = compact('model');
return Filters::run($this, __FUNCTION__, $params, function($params) {
$schema = $this->connection->quote($this->_config['schema']);
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables";
$sql .= " WHERE table_schema = {$schema}";
if (!$result = $this->_execute($sql)) {
return null;
}
$sources = [];
foreach ($result as $row) {
$sources[] = $row[0];
}
return $sources;
});
} | php | public function sources($model = null) {
$params = compact('model');
return Filters::run($this, __FUNCTION__, $params, function($params) {
$schema = $this->connection->quote($this->_config['schema']);
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables";
$sql .= " WHERE table_schema = {$schema}";
if (!$result = $this->_execute($sql)) {
return null;
}
$sources = [];
foreach ($result as $row) {
$sources[] = $row[0];
}
return $sources;
});
} | [
"public",
"function",
"sources",
"(",
"$",
"model",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'model'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"$",
"this",
",",
"__FUNCTION__",
",",
"$",
"params",
",",
"function",
"(",
"$"... | Returns the list of tables in the currently-connected database.
@param string $model The fully-name-spaced class name of the model object making the request.
@return array Returns an array of sources to which models can connect.
@filter | [
"Returns",
"the",
"list",
"of",
"tables",
"in",
"the",
"currently",
"-",
"connected",
"database",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L207-L226 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.describe | public function describe($entity, $fields = [], array $meta = []) {
$schema = $this->_config['schema'];
$params = compact('entity', 'meta', 'fields', 'schema');
return Filters::run($this, __FUNCTION__, $params, function($params) {
extract($params);
if ($fields) {
return $this->_instance('schema', compact('fields'));
}
$name = $this->connection->quote($this->_entityName($entity));
$schema = $this->connection->quote($schema);
$sql = 'SELECT "column_name" AS "field", "data_type" AS "type", ';
$sql .= '"is_nullable" AS "null", "column_default" AS "default", ';
$sql .= '"character_maximum_length" AS "char_length" ';
$sql .= 'FROM "information_schema"."columns" WHERE "table_name" = ' . $name;
$sql .= ' AND table_schema = ' . $schema . ' ORDER BY "ordinal_position"';
$columns = $this->connection->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$fields = [];
foreach ($columns as $column) {
$schema = $this->_column($column['type']);
$default = $column['default'];
if (preg_match("/^'(.*)'::/", $default, $match)) {
$default = $match[1];
} elseif ($default === 'true') {
$default = true;
} elseif ($default === 'false') {
$default = false;
} else {
$default = null;
}
$fields[$column['field']] = $schema + [
'null' => ($column['null'] === 'YES' ? true : false),
'default' => $default
];
if ($fields[$column['field']]['type'] === 'string') {
$fields[$column['field']]['length'] = $column['char_length'];
}
}
return $this->_instance('schema', compact('fields'));
});
} | php | public function describe($entity, $fields = [], array $meta = []) {
$schema = $this->_config['schema'];
$params = compact('entity', 'meta', 'fields', 'schema');
return Filters::run($this, __FUNCTION__, $params, function($params) {
extract($params);
if ($fields) {
return $this->_instance('schema', compact('fields'));
}
$name = $this->connection->quote($this->_entityName($entity));
$schema = $this->connection->quote($schema);
$sql = 'SELECT "column_name" AS "field", "data_type" AS "type", ';
$sql .= '"is_nullable" AS "null", "column_default" AS "default", ';
$sql .= '"character_maximum_length" AS "char_length" ';
$sql .= 'FROM "information_schema"."columns" WHERE "table_name" = ' . $name;
$sql .= ' AND table_schema = ' . $schema . ' ORDER BY "ordinal_position"';
$columns = $this->connection->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$fields = [];
foreach ($columns as $column) {
$schema = $this->_column($column['type']);
$default = $column['default'];
if (preg_match("/^'(.*)'::/", $default, $match)) {
$default = $match[1];
} elseif ($default === 'true') {
$default = true;
} elseif ($default === 'false') {
$default = false;
} else {
$default = null;
}
$fields[$column['field']] = $schema + [
'null' => ($column['null'] === 'YES' ? true : false),
'default' => $default
];
if ($fields[$column['field']]['type'] === 'string') {
$fields[$column['field']]['length'] = $column['char_length'];
}
}
return $this->_instance('schema', compact('fields'));
});
} | [
"public",
"function",
"describe",
"(",
"$",
"entity",
",",
"$",
"fields",
"=",
"[",
"]",
",",
"array",
"$",
"meta",
"=",
"[",
"]",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"_config",
"[",
"'schema'",
"]",
";",
"$",
"params",
"=",
"compact... | Gets the column schema for a given PostgreSQL table.
@param mixed $entity Specifies the table name for which the schema should be returned, or
the class name of the model object requesting the schema, in which case the model
class will be queried for the correct table name.
@param array $fields Any schema data pre-defined by the model.
@param array $meta
@return array Returns an associative array describing the given table's schema, where the
array keys are the available fields, and the values are arrays describing each
field, containing the following keys:
- `'type'`: The field type name
@filter | [
"Gets",
"the",
"column",
"schema",
"for",
"a",
"given",
"PostgreSQL",
"table",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L242-L287 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.searchPath | public function searchPath($searchPath = null) {
if ($searchPath === null) {
return explode(',', $this->connection->query('SHOW search_path')->fetchColumn(1));
}
return $this->connection->exec("SET search_path TO {$searchPath}") !== false;
} | php | public function searchPath($searchPath = null) {
if ($searchPath === null) {
return explode(',', $this->connection->query('SHOW search_path')->fetchColumn(1));
}
return $this->connection->exec("SET search_path TO {$searchPath}") !== false;
} | [
"public",
"function",
"searchPath",
"(",
"$",
"searchPath",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"searchPath",
"===",
"null",
")",
"{",
"return",
"explode",
"(",
"','",
",",
"$",
"this",
"->",
"connection",
"->",
"query",
"(",
"'SHOW search_path'",
")"... | Getter/Setter for the connection's search path.
@param null|string $searchPath Either `null` to retrieve the current one, or
a string to set the current one to.
@return string|boolean When $searchPath is `null` returns the current search path
in effect, otherwise a boolean indicating if setting the search path
succeeded or failed. | [
"Getter",
"/",
"Setter",
"for",
"the",
"connection",
"s",
"search",
"path",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L298-L303 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.timezone | public function timezone($timezone = null) {
if ($timezone === null) {
return $this->connection->query('SHOW TIME ZONE')->fetchColumn();
}
return $this->connection->exec("SET TIME ZONE '{$timezone}'") !== false;
} | php | public function timezone($timezone = null) {
if ($timezone === null) {
return $this->connection->query('SHOW TIME ZONE')->fetchColumn();
}
return $this->connection->exec("SET TIME ZONE '{$timezone}'") !== false;
} | [
"public",
"function",
"timezone",
"(",
"$",
"timezone",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"timezone",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"->",
"query",
"(",
"'SHOW TIME ZONE'",
")",
"->",
"fetchColumn",
"(",
")",
"... | Getter/Setter for the connection's timezone.
@param null|string $timezone Either `null` to retrieve the current TZ, or
a string to set the current TZ to.
@return string|boolean When $timezone is `null` returns the current TZ
in effect, otherwise a boolean indicating if setting the TZ
succeeded or failed. | [
"Getter",
"/",
"Setter",
"for",
"the",
"connection",
"s",
"timezone",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L314-L319 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.value | public function value($value, array $schema = []) {
if (($result = parent::value($value, $schema)) !== null) {
return $result;
}
return $this->connection->quote((string) $value);
} | php | public function value($value, array $schema = []) {
if (($result = parent::value($value, $schema)) !== null) {
return $result;
}
return $this->connection->quote((string) $value);
} | [
"public",
"function",
"value",
"(",
"$",
"value",
",",
"array",
"$",
"schema",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"(",
"$",
"result",
"=",
"parent",
"::",
"value",
"(",
"$",
"value",
",",
"$",
"schema",
")",
")",
"!==",
"null",
")",
"{",
"retu... | Converts a given value into the proper type based on a given schema definition.
@see lithium\data\source\Database::schema()
@param mixed $value The value to be converted. Arrays will be recursively converted.
@param array $schema Formatted array from `lithium\data\source\Database::schema()`
@return mixed Value with converted type. | [
"Converts",
"a",
"given",
"value",
"into",
"the",
"proper",
"type",
"based",
"on",
"a",
"given",
"schema",
"definition",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L358-L363 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql._execute | protected function _execute($sql, array $options = []) {
$params = compact('sql', 'options');
return Filters::run($this, __FUNCTION__, $params, function($params) {
try {
$resource = $this->connection->query($params['sql']);
} catch (PDOException $e) {
$this->_error($params['sql']);
};
return $this->_instance('result', compact('resource'));
});
} | php | protected function _execute($sql, array $options = []) {
$params = compact('sql', 'options');
return Filters::run($this, __FUNCTION__, $params, function($params) {
try {
$resource = $this->connection->query($params['sql']);
} catch (PDOException $e) {
$this->_error($params['sql']);
};
return $this->_instance('result', compact('resource'));
});
} | [
"protected",
"function",
"_execute",
"(",
"$",
"sql",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'sql'",
",",
"'options'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"$",
"this",
",",
"__FUNCTION... | Execute a given query.
@see lithium\data\source\Database::renderCommand()
@param string $sql The sql string to execute
@param array $options Available options:
@return \lithium\data\source\Result Returns a result object if the query was successful.
@filter | [
"Execute",
"a",
"given",
"query",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L405-L416 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql._insertId | protected function _insertId($query) {
$model = $query->model();
$field = $model::key();
$source = $model::meta('source');
$sequence = "{$source}_{$field}_seq";
$id = $this->connection->lastInsertId($sequence);
return ($id && $id !== '0') ? $id : null;
} | php | protected function _insertId($query) {
$model = $query->model();
$field = $model::key();
$source = $model::meta('source');
$sequence = "{$source}_{$field}_seq";
$id = $this->connection->lastInsertId($sequence);
return ($id && $id !== '0') ? $id : null;
} | [
"protected",
"function",
"_insertId",
"(",
"$",
"query",
")",
"{",
"$",
"model",
"=",
"$",
"query",
"->",
"model",
"(",
")",
";",
"$",
"field",
"=",
"$",
"model",
"::",
"key",
"(",
")",
";",
"$",
"source",
"=",
"$",
"model",
"::",
"meta",
"(",
... | Gets the last auto-generated ID from the query that inserted a new record.
@param object $query The `Query` object associated with the query which generated
@return mixed Returns the last inserted ID key for an auto-increment column or a column
bound to a sequence. | [
"Gets",
"the",
"last",
"auto",
"-",
"generated",
"ID",
"from",
"the",
"query",
"that",
"inserted",
"a",
"new",
"record",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L425-L432 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql._formatters | protected function _formatters() {
$datetime = $timestamp = function($format, $value) {
if ($format && (($time = strtotime($value)) !== false)) {
$val = date($format, $time);
if (!preg_match('/^' . preg_quote($val) . '\.\d+$/', $value)) {
$value = $val;
}
}
return $this->connection->quote($value);
};
return compact('datetime', 'timestamp') + [
'boolean' => function($value) {
return $this->connection->quote($value ? 't' : 'f');
}
] + parent::_formatters();
} | php | protected function _formatters() {
$datetime = $timestamp = function($format, $value) {
if ($format && (($time = strtotime($value)) !== false)) {
$val = date($format, $time);
if (!preg_match('/^' . preg_quote($val) . '\.\d+$/', $value)) {
$value = $val;
}
}
return $this->connection->quote($value);
};
return compact('datetime', 'timestamp') + [
'boolean' => function($value) {
return $this->connection->quote($value ? 't' : 'f');
}
] + parent::_formatters();
} | [
"protected",
"function",
"_formatters",
"(",
")",
"{",
"$",
"datetime",
"=",
"$",
"timestamp",
"=",
"function",
"(",
"$",
"format",
",",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"format",
"&&",
"(",
"(",
"$",
"time",
"=",
"strtotime",
"(",
"$",
"val... | Provide an associative array of Closures to be used as the "formatter" key inside of the
`Database::$_columns` specification.
@see lithium\data\source\Database::_formatters() | [
"Provide",
"an",
"associative",
"array",
"of",
"Closures",
"to",
"be",
"used",
"as",
"the",
"formatter",
"key",
"inside",
"of",
"the",
"Database",
"::",
"$_columns",
"specification",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L494-L510 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql._distinctExport | protected function _distinctExport($query) {
$model = $query->model();
$orders = $query->order();
$result = [
'fields' => [],
'orders' => [],
];
if (is_string($orders)) {
$direction = 'ASC';
if (preg_match('/^(.*?)\s+((?:A|DE)SC)$/i', $orders, $match)) {
$orders = $match[1];
$direction = $match[2];
}
$orders = [$orders => $direction];
}
if (!is_array($orders)) {
return array_values($result);
}
foreach ($orders as $column => $dir) {
if (is_int($column)) {
$column = $dir;
$dir = 'ASC';
}
if ($model && $model::schema($column)) {
$name = $this->name($query->alias()) . '.' . $this->name($column);
$alias = $this->name('_' . $query->alias() . '_' . $column . '_');
} else {
list($alias, $field) = $this->_splitFieldname($column);
$name = $this->name($column);
$alias = $this->name('_' . $alias . '_' . $field . '_');
}
$result['fields'][] = "{$name} AS {$alias}";
$result['orders'][] = "{$alias} {$dir}";
}
return array_values($result);
} | php | protected function _distinctExport($query) {
$model = $query->model();
$orders = $query->order();
$result = [
'fields' => [],
'orders' => [],
];
if (is_string($orders)) {
$direction = 'ASC';
if (preg_match('/^(.*?)\s+((?:A|DE)SC)$/i', $orders, $match)) {
$orders = $match[1];
$direction = $match[2];
}
$orders = [$orders => $direction];
}
if (!is_array($orders)) {
return array_values($result);
}
foreach ($orders as $column => $dir) {
if (is_int($column)) {
$column = $dir;
$dir = 'ASC';
}
if ($model && $model::schema($column)) {
$name = $this->name($query->alias()) . '.' . $this->name($column);
$alias = $this->name('_' . $query->alias() . '_' . $column . '_');
} else {
list($alias, $field) = $this->_splitFieldname($column);
$name = $this->name($column);
$alias = $this->name('_' . $alias . '_' . $field . '_');
}
$result['fields'][] = "{$name} AS {$alias}";
$result['orders'][] = "{$alias} {$dir}";
}
return array_values($result);
} | [
"protected",
"function",
"_distinctExport",
"(",
"$",
"query",
")",
"{",
"$",
"model",
"=",
"$",
"query",
"->",
"model",
"(",
")",
";",
"$",
"orders",
"=",
"$",
"query",
"->",
"order",
"(",
")",
";",
"$",
"result",
"=",
"[",
"'fields'",
"=>",
"[",
... | Helper method for `PostgreSql::_queryExport()` to export data
for use in distinct query.
@see lithium\data\source\PostgreSql::_queryExport()
@param object $query The query object.
@return array Returns an array with the fields as the first
value and the orders as the second value. | [
"Helper",
"method",
"for",
"PostgreSql",
"::",
"_queryExport",
"()",
"to",
"export",
"data",
"for",
"use",
"in",
"distinct",
"query",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L557-L597 |
UnionOfRAD/lithium | data/source/database/adapter/PostgreSql.php | PostgreSql.& | protected function &_queryExport($query) {
$data = $query->export($this);
if (!$query->limit() || !($model = $query->model())) {
return $data;
}
foreach ($query->relationships() as $relation) {
if ($relation['type'] !== 'hasMany') {
continue;
}
$pk = $this->name($model::meta('name') . '.' . $model::key());
if ($query->order()) {
list($fields, $orders) = $this->_distinctExport($query);
array_unshift($fields, "DISTINCT ON($pk) $pk AS _ID_");
$command = $this->renderCommand('read', [
'limit' => null, 'order' => null,
'fields' => implode(', ', $fields)
] + $data);
$command = rtrim($command, ';');
$command = $this->renderCommand('read', [
'source' => "( $command ) AS _TEMP_",
'fields' => '_ID_',
'order' => "ORDER BY " . implode(', ', $orders),
'limit' => $data['limit'],
]);
} else {
$command = $this->renderCommand('read', [
'fields' => "DISTINCT({$pk}) AS _ID_"
] + $data);
}
$result = $this->_execute($command);
$ids = [];
foreach ($result as $row) {
$ids[] = $row[0];
}
if (!$ids) {
$data = null;
break;
}
$conditions = [];
$relations = array_keys($query->relationships());
$pattern = '/^(' . implode('|', $relations) . ')\./';
foreach ($query->conditions() as $key => $value) {
if (preg_match($pattern, $key)) {
$conditions[$key] = $value;
}
}
$data['conditions'] = $this->conditions(
[$pk => $ids] + $conditions, $query
);
$data['limit'] = '';
break;
}
return $data;
} | php | protected function &_queryExport($query) {
$data = $query->export($this);
if (!$query->limit() || !($model = $query->model())) {
return $data;
}
foreach ($query->relationships() as $relation) {
if ($relation['type'] !== 'hasMany') {
continue;
}
$pk = $this->name($model::meta('name') . '.' . $model::key());
if ($query->order()) {
list($fields, $orders) = $this->_distinctExport($query);
array_unshift($fields, "DISTINCT ON($pk) $pk AS _ID_");
$command = $this->renderCommand('read', [
'limit' => null, 'order' => null,
'fields' => implode(', ', $fields)
] + $data);
$command = rtrim($command, ';');
$command = $this->renderCommand('read', [
'source' => "( $command ) AS _TEMP_",
'fields' => '_ID_',
'order' => "ORDER BY " . implode(', ', $orders),
'limit' => $data['limit'],
]);
} else {
$command = $this->renderCommand('read', [
'fields' => "DISTINCT({$pk}) AS _ID_"
] + $data);
}
$result = $this->_execute($command);
$ids = [];
foreach ($result as $row) {
$ids[] = $row[0];
}
if (!$ids) {
$data = null;
break;
}
$conditions = [];
$relations = array_keys($query->relationships());
$pattern = '/^(' . implode('|', $relations) . ')\./';
foreach ($query->conditions() as $key => $value) {
if (preg_match($pattern, $key)) {
$conditions[$key] = $value;
}
}
$data['conditions'] = $this->conditions(
[$pk => $ids] + $conditions, $query
);
$data['limit'] = '';
break;
}
return $data;
} | [
"protected",
"function",
"&",
"_queryExport",
"(",
"$",
"query",
")",
"{",
"$",
"data",
"=",
"$",
"query",
"->",
"export",
"(",
"$",
"this",
")",
";",
"if",
"(",
"!",
"$",
"query",
"->",
"limit",
"(",
")",
"||",
"!",
"(",
"$",
"model",
"=",
"$"... | Helper method for `Database::read()` to export query while handling additional joins
when using relationships and limited result sets. Filters conditions on subsequent
queries to just the ones applying to the relation.
@see lithium\data\source\Database::read()
@param object $query The query object.
@return array The exported query returned by reference. | [
"Helper",
"method",
"for",
"Database",
"::",
"read",
"()",
"to",
"export",
"query",
"while",
"handling",
"additional",
"joins",
"when",
"using",
"relationships",
"and",
"limited",
"result",
"sets",
".",
"Filters",
"conditions",
"on",
"subsequent",
"queries",
"to... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/PostgreSql.php#L608-L670 |
UnionOfRAD/lithium | net/http/Request.php | Request.body | public function body($data = null, $options = []) {
$defaults = ['encode' => true];
return parent::body($data, $options + $defaults);
} | php | public function body($data = null, $options = []) {
$defaults = ['encode' => true];
return parent::body($data, $options + $defaults);
} | [
"public",
"function",
"body",
"(",
"$",
"data",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'encode'",
"=>",
"true",
"]",
";",
"return",
"parent",
"::",
"body",
"(",
"$",
"data",
",",
"$",
"options",
"+"... | Compile the HTTP message body, optionally encoding its parts according to content type.
@see lithium\net\http\Message::body()
@see lithium\net\http\Message::_encode()
@param mixed $data
@param array $options
- `'buffer'` _integer_: split the body string
- `'encode'` _boolean_: encode the body based on the content type
- `'decode'` _boolean_: decode the body based on the content type
@return array | [
"Compile",
"the",
"HTTP",
"message",
"body",
"optionally",
"encoding",
"its",
"parts",
"according",
"to",
"content",
"type",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L154-L157 |
UnionOfRAD/lithium | net/http/Request.php | Request.cookies | public function cookies($key = null, $value = null) {
if (is_string($key)) {
if ($value === null) {
return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
}
if ($value === false) {
unset($this->cookies[$key]);
return $this->cookies;
}
}
if ($key) {
$cookies = is_array($key) ? $key : [$key => $value];
$this->cookies = $cookies + $this->cookies;
}
return $this->cookies;
} | php | public function cookies($key = null, $value = null) {
if (is_string($key)) {
if ($value === null) {
return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
}
if ($value === false) {
unset($this->cookies[$key]);
return $this->cookies;
}
}
if ($key) {
$cookies = is_array($key) ? $key : [$key => $value];
$this->cookies = $cookies + $this->cookies;
}
return $this->cookies;
} | [
"public",
"function",
"cookies",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"key",
")",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"thi... | Add a cookie to header output, or return a single cookie or full cookie list.
NOTE: Cookies values are expected to be scalar. This function will not serialize cookie values.
If you wish to store a non-scalar value, you must serialize the data first.
@param string $key
@param string $value
@return mixed | [
"Add",
"a",
"cookie",
"to",
"header",
"output",
"or",
"return",
"a",
"single",
"cookie",
"or",
"full",
"cookie",
"list",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L169-L184 |
UnionOfRAD/lithium | net/http/Request.php | Request._cookies | protected function _cookies() {
$cookies = $this->cookies;
$invalid = str_split(",; \+\t\r\n\013\014");
$replace = array_map('rawurlencode', $invalid);
foreach ($cookies as $key => &$value) {
if (!is_scalar($value)) {
$message = "Non-scalar value cannot be rendered for cookie `{$key}`";
throw new UnexpectedValueException($message);
}
$value = strtr($value, array_combine($invalid, $replace));
$value = "{$key}={$value}";
}
return implode('; ', $cookies);
} | php | protected function _cookies() {
$cookies = $this->cookies;
$invalid = str_split(",; \+\t\r\n\013\014");
$replace = array_map('rawurlencode', $invalid);
foreach ($cookies as $key => &$value) {
if (!is_scalar($value)) {
$message = "Non-scalar value cannot be rendered for cookie `{$key}`";
throw new UnexpectedValueException($message);
}
$value = strtr($value, array_combine($invalid, $replace));
$value = "{$key}={$value}";
}
return implode('; ', $cookies);
} | [
"protected",
"function",
"_cookies",
"(",
")",
"{",
"$",
"cookies",
"=",
"$",
"this",
"->",
"cookies",
";",
"$",
"invalid",
"=",
"str_split",
"(",
"\",; \\+\\t\\r\\n\\013\\014\"",
")",
";",
"$",
"replace",
"=",
"array_map",
"(",
"'rawurlencode'",
",",
"$",
... | Render `Cookie` header, urlencoding invalid characters.
NOTE: Technically '+' is a valid character, but many browsers erroneously convert these to
spaces, so we must escape this too.
@return string | [
"Render",
"Cookie",
"header",
"urlencoding",
"invalid",
"characters",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L194-L208 |
UnionOfRAD/lithium | net/http/Request.php | Request._parseCookies | protected function _parseCookies($header) {
$cookies = array_map('trim', array_filter(explode('; ', $header)));
foreach ($cookies as $cookie) {
list($name, $value) = array_map('urldecode', explode('=', $cookie, 2)) + ['',''];
$this->cookies($name, $value);
}
} | php | protected function _parseCookies($header) {
$cookies = array_map('trim', array_filter(explode('; ', $header)));
foreach ($cookies as $cookie) {
list($name, $value) = array_map('urldecode', explode('=', $cookie, 2)) + ['',''];
$this->cookies($name, $value);
}
} | [
"protected",
"function",
"_parseCookies",
"(",
"$",
"header",
")",
"{",
"$",
"cookies",
"=",
"array_map",
"(",
"'trim'",
",",
"array_filter",
"(",
"explode",
"(",
"'; '",
",",
"$",
"header",
")",
")",
")",
";",
"foreach",
"(",
"$",
"cookies",
"as",
"$"... | Parse `Cookie` header.
@param string $header `Cookie` header. | [
"Parse",
"Cookie",
"header",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L215-L221 |
UnionOfRAD/lithium | net/http/Request.php | Request.queryString | public function queryString($params = [], $format = null) {
$result = [];
$query = [];
foreach (array_filter([$this->query, $params]) as $querySet) {
if (is_string($querySet)) {
$result[] = $querySet;
continue;
}
$query = array_merge($query, $querySet);
}
$query = array_filter($query);
if ($format) {
$q = null;
foreach ($query as $key => $value) {
if (!is_array($value)) {
$q .= Text::insert($format, [
'key' => urlencode($key),
'value' => urlencode($value)
]);
continue;
}
foreach ($value as $val) {
$q .= Text::insert($format, [
'key' => urlencode("{$key}[]"),
'value' => urlencode($val)
]);
}
}
$result[] = substr($q, 0, -1);
} else {
$result[] = http_build_query($query);
}
$result = array_filter($result);
return $result ? "?" . join("&", $result) : null;
} | php | public function queryString($params = [], $format = null) {
$result = [];
$query = [];
foreach (array_filter([$this->query, $params]) as $querySet) {
if (is_string($querySet)) {
$result[] = $querySet;
continue;
}
$query = array_merge($query, $querySet);
}
$query = array_filter($query);
if ($format) {
$q = null;
foreach ($query as $key => $value) {
if (!is_array($value)) {
$q .= Text::insert($format, [
'key' => urlencode($key),
'value' => urlencode($value)
]);
continue;
}
foreach ($value as $val) {
$q .= Text::insert($format, [
'key' => urlencode("{$key}[]"),
'value' => urlencode($val)
]);
}
}
$result[] = substr($q, 0, -1);
} else {
$result[] = http_build_query($query);
}
$result = array_filter($result);
return $result ? "?" . join("&", $result) : null;
} | [
"public",
"function",
"queryString",
"(",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"format",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"query",
"=",
"[",
"]",
";",
"foreach",
"(",
"array_filter",
"(",
"[",
"$",
"this",
"->",
... | Get the full query string queryString.
@param array $params
@param string $format
@return string | [
"Get",
"the",
"full",
"query",
"string",
"queryString",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L230-L267 |
UnionOfRAD/lithium | net/http/Request.php | Request.to | public function to($format, array $options = []) {
$defaults = [
'method' => $this->method,
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port,
'path' => $this->path,
'query' => null,
'auth' => $this->auth,
'username' => $this->username,
'password' => $this->password,
'headers' => [],
'cookies' => [],
'proxy' => $this->_config['proxy'],
'body' => null,
'version' => $this->version,
'ignore_errors' => $this->_config['ignoreErrors'],
'follow_location' => $this->_config['followLocation'],
'request_fulluri' => (boolean) $this->_config['proxy']
];
$options += $defaults;
if (is_string($options['query'])) {
$options['query'] = "?" . $options['query'];
} elseif ($options['query']) {
$options['query'] = "?" . http_build_query($options['query']);
} elseif ($options['query'] === null) {
$options['query'] = $this->queryString();
}
if ($options['auth']) {
$data = [];
if (is_array($options['auth']) && !empty($options['auth']['nonce'])) {
$data = ['method' => $options['method'], 'uri' => $options['path']];
$data += $options['auth'];
}
$auth = $this->_classes['auth'];
$data = $auth::encode($options['username'], $options['password'], $data);
$this->headers('Authorization', $auth::header($data));
}
if ($this->cookies($options['cookies'])) {
$this->headers('Cookie', $this->_cookies());
}
$body = $this->body($options['body']);
if ($body || !in_array($options['method'], ['GET', 'HEAD', 'DELETE'])) {
$this->headers('Content-Length', strlen($body));
}
$conv = isset($this->_formats[$format]) ? $this->_formats[$format] : null;
return $conv ? $conv($this, $options, $defaults) : parent::to($format, $options);
} | php | public function to($format, array $options = []) {
$defaults = [
'method' => $this->method,
'scheme' => $this->scheme,
'host' => $this->host,
'port' => $this->port,
'path' => $this->path,
'query' => null,
'auth' => $this->auth,
'username' => $this->username,
'password' => $this->password,
'headers' => [],
'cookies' => [],
'proxy' => $this->_config['proxy'],
'body' => null,
'version' => $this->version,
'ignore_errors' => $this->_config['ignoreErrors'],
'follow_location' => $this->_config['followLocation'],
'request_fulluri' => (boolean) $this->_config['proxy']
];
$options += $defaults;
if (is_string($options['query'])) {
$options['query'] = "?" . $options['query'];
} elseif ($options['query']) {
$options['query'] = "?" . http_build_query($options['query']);
} elseif ($options['query'] === null) {
$options['query'] = $this->queryString();
}
if ($options['auth']) {
$data = [];
if (is_array($options['auth']) && !empty($options['auth']['nonce'])) {
$data = ['method' => $options['method'], 'uri' => $options['path']];
$data += $options['auth'];
}
$auth = $this->_classes['auth'];
$data = $auth::encode($options['username'], $options['password'], $data);
$this->headers('Authorization', $auth::header($data));
}
if ($this->cookies($options['cookies'])) {
$this->headers('Cookie', $this->_cookies());
}
$body = $this->body($options['body']);
if ($body || !in_array($options['method'], ['GET', 'HEAD', 'DELETE'])) {
$this->headers('Content-Length', strlen($body));
}
$conv = isset($this->_formats[$format]) ? $this->_formats[$format] : null;
return $conv ? $conv($this, $options, $defaults) : parent::to($format, $options);
} | [
"public",
"function",
"to",
"(",
"$",
"format",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'method'",
"=>",
"$",
"this",
"->",
"method",
",",
"'scheme'",
"=>",
"$",
"this",
"->",
"scheme",
",",
"'host'",
"=>"... | Converts the data in the record set to a different format, i.e. an array. Available
options: array, URL, stream context configuration, or string.
@see lithium\net\Message::to()
@param string $format Format to convert to. Should be either `'url'`, which returns a string
representation of the URL that this request points to, or `'context'`, which returns an
array usable with PHP's `stream_context_create()` function. For more available formats,
see the parent method, `lithium\net\Message::to()`.
@param array $options Allows overriding of specific portions of the URL, as follows. These
options should only be specified if you intend to replace the values that are already in
the `Request` object.
- `'scheme'` _string_: The protocol scheme of the URL.
- `'method'` _string_: If applicable, the HTTP method to use in the request. Mainly
applies to the `'context'` format.
- `'host'` _string_: The host name the request is pointing at.
- `'port'` _string_: The host port, if any.
- `'path'` _string_: The URL path.
- `'query'` _mixed_: The query string of the URL as a string or array.
- `'auth'` _string_: Authentication information. See the constructor for details.
- `'content'` _string_: The body of the request.
- `'headers'` _array_: The request headers.
- `'version'` _string_: The HTTP version of the request, where applicable.
@return mixed Varies; see the `$format` parameter for possible return values. | [
"Converts",
"the",
"data",
"in",
"the",
"record",
"set",
"to",
"a",
"different",
"format",
"i",
".",
"e",
".",
"an",
"array",
".",
"Available",
"options",
":",
"array",
"URL",
"stream",
"context",
"configuration",
"or",
"string",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Request.php#L294-L346 |
UnionOfRAD/lithium | core/ErrorHandler.php | ErrorHandler.run | public static function run(array $config = []) {
$defaults = ['trapErrors' => false, 'convertErrors' => true];
if (static::$_isRunning) {
return;
}
static::$_isRunning = true;
static::$_runOptions = $config + $defaults;
$trap = function($code, $message, $file, $line = 0, $context = null) {
$trace = debug_backtrace();
$trace = array_slice($trace, 1, count($trace));
static::handle(compact('type', 'code', 'message', 'file', 'line', 'trace', 'context'));
};
$convert = function($code, $message, $file, $line = 0, $context = null) {
throw new ErrorException($message, 500, $code, $file, $line);
};
if (static::$_runOptions['trapErrors']) {
set_error_handler($trap);
} elseif (static::$_runOptions['convertErrors']) {
set_error_handler($convert);
}
set_exception_handler(static::$_exceptionHandler);
} | php | public static function run(array $config = []) {
$defaults = ['trapErrors' => false, 'convertErrors' => true];
if (static::$_isRunning) {
return;
}
static::$_isRunning = true;
static::$_runOptions = $config + $defaults;
$trap = function($code, $message, $file, $line = 0, $context = null) {
$trace = debug_backtrace();
$trace = array_slice($trace, 1, count($trace));
static::handle(compact('type', 'code', 'message', 'file', 'line', 'trace', 'context'));
};
$convert = function($code, $message, $file, $line = 0, $context = null) {
throw new ErrorException($message, 500, $code, $file, $line);
};
if (static::$_runOptions['trapErrors']) {
set_error_handler($trap);
} elseif (static::$_runOptions['convertErrors']) {
set_error_handler($convert);
}
set_exception_handler(static::$_exceptionHandler);
} | [
"public",
"static",
"function",
"run",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'trapErrors'",
"=>",
"false",
",",
"'convertErrors'",
"=>",
"true",
"]",
";",
"if",
"(",
"static",
"::",
"$",
"_isRunning",
")",
... | Register error and exception handlers.
This method (`ErrorHandler::run()`) needs to be called as early as possible in the bootstrap
cycle; immediately after `require`-ing `bootstrap/libraries.php` is your best bet.
@param array $config The configuration with which to start the error handler. Available
options include:
- `'trapErrors'` _boolean_: Defaults to `false`. If set to `true`, PHP errors
will be caught by `ErrorHandler` and handled in-place. Execution will resume
in the same context in which the error occurred.
- `'convertErrors'` _boolean_: Defaults to `true`, and specifies that all PHP
errors should be converted to `ErrorException`s and thrown from the point
where the error occurred. The exception will be caught at the first point in
the stack trace inside a matching `try`/`catch` block, or that has a matching
error handler applied using the `apply()` method. | [
"Register",
"error",
"and",
"exception",
"handlers",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/ErrorHandler.php#L87-L112 |
UnionOfRAD/lithium | core/ErrorHandler.php | ErrorHandler.reset | public static function reset() {
static::$_config = [];
static::$_checks = [];
static::$_exceptionHandler = null;
static::$_checks = [
'type' => function($config, $info) {
return (boolean) array_filter((array) $config['type'], function($type) use ($info) {
return $type === $info['type'] || is_subclass_of($info['type'], $type);
});
},
'code' => function($config, $info) {
return ($config['code'] & $info['code']);
},
'stack' => function($config, $info) {
return (boolean) array_intersect((array) $config['stack'], $info['stack']);
},
'message' => function($config, $info) {
return preg_match($config['message'], $info['message']);
}
];
static::$_exceptionHandler = function($exception, $return = false) {
if (ob_get_length()) {
ob_end_clean();
}
$info = compact('exception') + [
'type' => get_class($exception),
'stack' => static::trace($exception->getTrace())
];
foreach (['message', 'file', 'line', 'trace'] as $key) {
$method = 'get' . ucfirst($key);
$info[$key] = $exception->{$method}();
}
return $return ? $info : static::handle($info);
};
} | php | public static function reset() {
static::$_config = [];
static::$_checks = [];
static::$_exceptionHandler = null;
static::$_checks = [
'type' => function($config, $info) {
return (boolean) array_filter((array) $config['type'], function($type) use ($info) {
return $type === $info['type'] || is_subclass_of($info['type'], $type);
});
},
'code' => function($config, $info) {
return ($config['code'] & $info['code']);
},
'stack' => function($config, $info) {
return (boolean) array_intersect((array) $config['stack'], $info['stack']);
},
'message' => function($config, $info) {
return preg_match($config['message'], $info['message']);
}
];
static::$_exceptionHandler = function($exception, $return = false) {
if (ob_get_length()) {
ob_end_clean();
}
$info = compact('exception') + [
'type' => get_class($exception),
'stack' => static::trace($exception->getTrace())
];
foreach (['message', 'file', 'line', 'trace'] as $key) {
$method = 'get' . ucfirst($key);
$info[$key] = $exception->{$method}();
}
return $return ? $info : static::handle($info);
};
} | [
"public",
"static",
"function",
"reset",
"(",
")",
"{",
"static",
"::",
"$",
"_config",
"=",
"[",
"]",
";",
"static",
"::",
"$",
"_checks",
"=",
"[",
"]",
";",
"static",
"::",
"$",
"_exceptionHandler",
"=",
"null",
";",
"static",
"::",
"$",
"_checks"... | Setup basic error handling checks/types, as well as register the error and exception
handlers and wipes out all configuration and resets the error handler to its initial state
when loaded. Mainly used for testing. | [
"Setup",
"basic",
"error",
"handling",
"checks",
"/",
"types",
"as",
"well",
"as",
"register",
"the",
"error",
"and",
"exception",
"handlers",
"and",
"wipes",
"out",
"all",
"configuration",
"and",
"resets",
"the",
"error",
"handler",
"to",
"its",
"initial",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/ErrorHandler.php#L138-L172 |
UnionOfRAD/lithium | core/ErrorHandler.php | ErrorHandler.handle | public static function handle($info, $scope = []) {
$checks = static::$_checks;
$rules = $scope ?: static::$_config;
$handler = static::$_exceptionHandler;
$info = is_object($info) ? $handler($info, true) : $info;
$defaults = [
'type' => null, 'code' => 0, 'message' => null, 'file' => null, 'line' => 0,
'trace' => [], 'context' => null, 'exception' => null
];
$info = (array) $info + $defaults;
$info['stack'] = static::trace($info['trace']);
$info['origin'] = static::_origin($info['trace']);
foreach ($rules as $config) {
foreach (array_keys($config) as $key) {
if ($key === 'conditions' || $key === 'scope' || $key === 'handler') {
continue;
}
if (!isset($info[$key]) || !isset($checks[$key])) {
continue 2;
}
if (($check = $checks[$key]) && !$check($config, $info)) {
continue 2;
}
}
if (!isset($config['handler'])) {
return false;
}
if ((isset($config['conditions']) && $call = $config['conditions']) && !$call($info)) {
return false;
}
if ((isset($config['scope'])) && static::handle($info, $config['scope']) !== false) {
return true;
}
$handler = $config['handler'];
return $handler($info) !== false;
}
return false;
} | php | public static function handle($info, $scope = []) {
$checks = static::$_checks;
$rules = $scope ?: static::$_config;
$handler = static::$_exceptionHandler;
$info = is_object($info) ? $handler($info, true) : $info;
$defaults = [
'type' => null, 'code' => 0, 'message' => null, 'file' => null, 'line' => 0,
'trace' => [], 'context' => null, 'exception' => null
];
$info = (array) $info + $defaults;
$info['stack'] = static::trace($info['trace']);
$info['origin'] = static::_origin($info['trace']);
foreach ($rules as $config) {
foreach (array_keys($config) as $key) {
if ($key === 'conditions' || $key === 'scope' || $key === 'handler') {
continue;
}
if (!isset($info[$key]) || !isset($checks[$key])) {
continue 2;
}
if (($check = $checks[$key]) && !$check($config, $info)) {
continue 2;
}
}
if (!isset($config['handler'])) {
return false;
}
if ((isset($config['conditions']) && $call = $config['conditions']) && !$call($info)) {
return false;
}
if ((isset($config['scope'])) && static::handle($info, $config['scope']) !== false) {
return true;
}
$handler = $config['handler'];
return $handler($info) !== false;
}
return false;
} | [
"public",
"static",
"function",
"handle",
"(",
"$",
"info",
",",
"$",
"scope",
"=",
"[",
"]",
")",
"{",
"$",
"checks",
"=",
"static",
"::",
"$",
"_checks",
";",
"$",
"rules",
"=",
"$",
"scope",
"?",
":",
"static",
"::",
"$",
"_config",
";",
"$",
... | Receives the handled errors and exceptions that have been caught, and processes them
in a normalized manner.
@param object|array $info
@param array $scope
@return boolean True if successfully handled, false otherwise. | [
"Receives",
"the",
"handled",
"errors",
"and",
"exceptions",
"that",
"have",
"been",
"caught",
"and",
"processes",
"them",
"in",
"a",
"normalized",
"manner",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/ErrorHandler.php#L182-L222 |
UnionOfRAD/lithium | core/ErrorHandler.php | ErrorHandler.trace | public static function trace(array $stack) {
$result = [];
foreach ($stack as $frame) {
if (isset($frame['function'])) {
if (isset($frame['class'])) {
$result[] = trim($frame['class'], '\\') . '::' . $frame['function'];
} else {
$result[] = $frame['function'];
}
}
}
return $result;
} | php | public static function trace(array $stack) {
$result = [];
foreach ($stack as $frame) {
if (isset($frame['function'])) {
if (isset($frame['class'])) {
$result[] = trim($frame['class'], '\\') . '::' . $frame['function'];
} else {
$result[] = $frame['function'];
}
}
}
return $result;
} | [
"public",
"static",
"function",
"trace",
"(",
"array",
"$",
"stack",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"stack",
"as",
"$",
"frame",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"frame",
"[",
"'function'",
"]",
")",
")",... | Trim down a typical stack trace to class & method calls.
@param array $stack A `debug_backtrace()`-compatible stack trace output.
@return array Returns a flat stack array containing class and method references. | [
"Trim",
"down",
"a",
"typical",
"stack",
"trace",
"to",
"class",
"&",
"method",
"calls",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/ErrorHandler.php#L284-L297 |
UnionOfRAD/lithium | console/command/create/Controller.php | Controller._use | protected function _use($request) {
$request->params['command'] = 'model';
return $this->_namespace($request) . '\\' . $this->_model($request);
} | php | protected function _use($request) {
$request->params['command'] = 'model';
return $this->_namespace($request) . '\\' . $this->_model($request);
} | [
"protected",
"function",
"_use",
"(",
"$",
"request",
")",
"{",
"$",
"request",
"->",
"params",
"[",
"'command'",
"]",
"=",
"'model'",
";",
"return",
"$",
"this",
"->",
"_namespace",
"(",
"$",
"request",
")",
".",
"'\\\\'",
".",
"$",
"this",
"->",
"_... | Get the fully-qualified model class that is used by the controller.
@param string $request
@return string | [
"Get",
"the",
"fully",
"-",
"qualified",
"model",
"class",
"that",
"is",
"used",
"by",
"the",
"controller",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/create/Controller.php#L29-L32 |
UnionOfRAD/lithium | net/Message.php | Message.body | public function body($data = null, $options = []) {
$default = ['buffer' => null];
$options += $default;
$this->body = array_merge((array) $this->body, (array) $data);
$body = join("\r\n", $this->body);
return ($options['buffer']) ? str_split($body, $options['buffer']) : $body;
} | php | public function body($data = null, $options = []) {
$default = ['buffer' => null];
$options += $default;
$this->body = array_merge((array) $this->body, (array) $data);
$body = join("\r\n", $this->body);
return ($options['buffer']) ? str_split($body, $options['buffer']) : $body;
} | [
"public",
"function",
"body",
"(",
"$",
"data",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"default",
"=",
"[",
"'buffer'",
"=>",
"null",
"]",
";",
"$",
"options",
"+=",
"$",
"default",
";",
"$",
"this",
"->",
"body",
"=",
... | Add body parts and compile the message body.
@param mixed $data
@param array $options
- `'buffer'` _integer_: split the body string
@return array | [
"Add",
"body",
"parts",
"and",
"compile",
"the",
"message",
"body",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/Message.php#L111-L117 |
UnionOfRAD/lithium | net/Message.php | Message.to | public function to($format, array $options = []) {
switch ($format) {
case 'array':
$array = [];
$class = new ReflectionClass(get_class($this));
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) {
$array[$prop->getName()] = $prop->getValue($this);
}
return $array;
case 'url':
$host = $this->host . ($this->port ? ":{$this->port}" : '');
return "{$this->scheme}://{$host}{$this->path}";
case 'context':
$defaults = ['content' => $this->body(), 'ignore_errors' => true];
return [$this->scheme => $options + $defaults];
case 'string':
default:
return (string) $this;
}
} | php | public function to($format, array $options = []) {
switch ($format) {
case 'array':
$array = [];
$class = new ReflectionClass(get_class($this));
foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) {
$array[$prop->getName()] = $prop->getValue($this);
}
return $array;
case 'url':
$host = $this->host . ($this->port ? ":{$this->port}" : '');
return "{$this->scheme}://{$host}{$this->path}";
case 'context':
$defaults = ['content' => $this->body(), 'ignore_errors' => true];
return [$this->scheme => $options + $defaults];
case 'string':
default:
return (string) $this;
}
} | [
"public",
"function",
"to",
"(",
"$",
"format",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"'array'",
":",
"$",
"array",
"=",
"[",
"]",
";",
"$",
"class",
"=",
"new",
"ReflectionClass",
... | Converts the data in the record set to a different format, i.e. an array. Available
options: array, url, context, or string.
@param string $format Format to convert to.
@param array $options
@return mixed | [
"Converts",
"the",
"data",
"in",
"the",
"record",
"set",
"to",
"a",
"different",
"format",
"i",
".",
"e",
".",
"an",
"array",
".",
"Available",
"options",
":",
"array",
"url",
"context",
"or",
"string",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/Message.php#L127-L147 |
UnionOfRAD/lithium | storage/session/strategy/Encrypt.php | Encrypt.read | public function read($data, array $options = []) {
$class = $options['class'];
$encrypted = $class::read(null, ['strategies' => false]);
$key = isset($options['key']) ? $options['key'] : null;
if (!isset($encrypted['__encrypted']) || !$encrypted['__encrypted']) {
return isset($encrypted[$key]) ? $encrypted[$key] : null;
}
$current = $this->_decrypt($encrypted['__encrypted']);
if ($key) {
return isset($current[$key]) ? $current[$key] : null;
} else {
return $current;
}
} | php | public function read($data, array $options = []) {
$class = $options['class'];
$encrypted = $class::read(null, ['strategies' => false]);
$key = isset($options['key']) ? $options['key'] : null;
if (!isset($encrypted['__encrypted']) || !$encrypted['__encrypted']) {
return isset($encrypted[$key]) ? $encrypted[$key] : null;
}
$current = $this->_decrypt($encrypted['__encrypted']);
if ($key) {
return isset($current[$key]) ? $current[$key] : null;
} else {
return $current;
}
} | [
"public",
"function",
"read",
"(",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"class",
"=",
"$",
"options",
"[",
"'class'",
"]",
";",
"$",
"encrypted",
"=",
"$",
"class",
"::",
"read",
"(",
"null",
",",
"[",
"'strate... | Read encryption method.
@param array $data the Data being read.
@param array $options Options for this method.
@return mixed Returns the decrypted key or the dataset. | [
"Read",
"encryption",
"method",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/strategy/Encrypt.php#L118-L135 |
UnionOfRAD/lithium | storage/session/strategy/Encrypt.php | Encrypt.write | public function write($data, array $options = []) {
$class = $options['class'];
$futureData = $this->read(null, ['key' => null] + $options) ?: [];
$futureData = [$options['key'] => $data] + $futureData;
$payload = empty($futureData) ? null : $this->_encrypt($futureData);
$class::write('__encrypted', $payload, ['strategies' => false] + $options);
return $payload;
} | php | public function write($data, array $options = []) {
$class = $options['class'];
$futureData = $this->read(null, ['key' => null] + $options) ?: [];
$futureData = [$options['key'] => $data] + $futureData;
$payload = empty($futureData) ? null : $this->_encrypt($futureData);
$class::write('__encrypted', $payload, ['strategies' => false] + $options);
return $payload;
} | [
"public",
"function",
"write",
"(",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"class",
"=",
"$",
"options",
"[",
"'class'",
"]",
";",
"$",
"futureData",
"=",
"$",
"this",
"->",
"read",
"(",
"null",
",",
"[",
"'key'"... | Write encryption method.
@param mixed $data The data to be encrypted.
@param array $options Options for this method.
@return string Returns the written data in cleartext. | [
"Write",
"encryption",
"method",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/strategy/Encrypt.php#L144-L154 |
UnionOfRAD/lithium | storage/session/strategy/Encrypt.php | Encrypt._encrypt | protected function _encrypt($decrypted = []) {
$vector = $this->_config['vector'];
$secret = $this->_hashSecret($this->_config['secret']);
mcrypt_generic_init(static::$_resource, $secret, $vector);
$encrypted = mcrypt_generic(static::$_resource, serialize($decrypted));
mcrypt_generic_deinit(static::$_resource);
return base64_encode($encrypted) . base64_encode($vector);
} | php | protected function _encrypt($decrypted = []) {
$vector = $this->_config['vector'];
$secret = $this->_hashSecret($this->_config['secret']);
mcrypt_generic_init(static::$_resource, $secret, $vector);
$encrypted = mcrypt_generic(static::$_resource, serialize($decrypted));
mcrypt_generic_deinit(static::$_resource);
return base64_encode($encrypted) . base64_encode($vector);
} | [
"protected",
"function",
"_encrypt",
"(",
"$",
"decrypted",
"=",
"[",
"]",
")",
"{",
"$",
"vector",
"=",
"$",
"this",
"->",
"_config",
"[",
"'vector'",
"]",
";",
"$",
"secret",
"=",
"$",
"this",
"->",
"_hashSecret",
"(",
"$",
"this",
"->",
"_config",... | Serialize and encrypt a given data array.
@param array $decrypted The cleartext data to be encrypted.
@return string A Base64 encoded and encrypted string. | [
"Serialize",
"and",
"encrypt",
"a",
"given",
"data",
"array",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/strategy/Encrypt.php#L181-L190 |
UnionOfRAD/lithium | storage/session/strategy/Encrypt.php | Encrypt._decrypt | protected function _decrypt($encrypted) {
$secret = $this->_hashSecret($this->_config['secret']);
$vectorSize = strlen(base64_encode(str_repeat(" ", static::_vectorSize())));
$vector = base64_decode(substr($encrypted, -$vectorSize));
$data = base64_decode(substr($encrypted, 0, -$vectorSize));
mcrypt_generic_init(static::$_resource, $secret, $vector);
$decrypted = mdecrypt_generic(static::$_resource, $data);
mcrypt_generic_deinit(static::$_resource);
return unserialize(trim($decrypted));
} | php | protected function _decrypt($encrypted) {
$secret = $this->_hashSecret($this->_config['secret']);
$vectorSize = strlen(base64_encode(str_repeat(" ", static::_vectorSize())));
$vector = base64_decode(substr($encrypted, -$vectorSize));
$data = base64_decode(substr($encrypted, 0, -$vectorSize));
mcrypt_generic_init(static::$_resource, $secret, $vector);
$decrypted = mdecrypt_generic(static::$_resource, $data);
mcrypt_generic_deinit(static::$_resource);
return unserialize(trim($decrypted));
} | [
"protected",
"function",
"_decrypt",
"(",
"$",
"encrypted",
")",
"{",
"$",
"secret",
"=",
"$",
"this",
"->",
"_hashSecret",
"(",
"$",
"this",
"->",
"_config",
"[",
"'secret'",
"]",
")",
";",
"$",
"vectorSize",
"=",
"strlen",
"(",
"base64_encode",
"(",
... | Decrypt and unserialize a previously encrypted string.
@param string $encrypted The base64 encoded and encrypted string.
@return array The cleartext data. | [
"Decrypt",
"and",
"unserialize",
"a",
"previously",
"encrypted",
"string",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/strategy/Encrypt.php#L198-L210 |
UnionOfRAD/lithium | storage/session/strategy/Encrypt.php | Encrypt._hashSecret | protected function _hashSecret($key) {
$size = mcrypt_enc_get_key_size(static::$_resource);
if (strlen($key) >= $size) {
return $key;
}
return substr(hash('sha256', $key, true), 0, $size);
} | php | protected function _hashSecret($key) {
$size = mcrypt_enc_get_key_size(static::$_resource);
if (strlen($key) >= $size) {
return $key;
}
return substr(hash('sha256', $key, true), 0, $size);
} | [
"protected",
"function",
"_hashSecret",
"(",
"$",
"key",
")",
"{",
"$",
"size",
"=",
"mcrypt_enc_get_key_size",
"(",
"static",
"::",
"$",
"_resource",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"key",
")",
">=",
"$",
"size",
")",
"{",
"return",
"$",
"k... | Hashes the given secret to make harder to detect.
This method figures out the appropriate key size for the chosen encryption algorithm and
then hashes the given key accordingly. Note that if the key has already the needed length,
it is considered to be hashed (secure) already and is therefore not hashed again. This lets
you change the hashing method in your own code if you like.
The default `MCRYPT_RIJNDAEL_128` key should be 32 byte long `sha256` is used as the hashing
algorithm. If the key size is shorter than the one generated by `sha256`, the first n bytes
will be used.
@link http://php.net/function.mcrypt-enc-get-key-size.php
@param string $key The possibly too weak key.
@return string The hashed (raw) key. | [
"Hashes",
"the",
"given",
"secret",
"to",
"make",
"harder",
"to",
"detect",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/strategy/Encrypt.php#L237-L245 |
UnionOfRAD/lithium | console/Request.php | Request._init | protected function _init() {
if ($this->_config['globals']) {
$this->_env += (array) $_SERVER + (array) $_ENV;
}
$this->_env['working'] = str_replace('\\', '/', getcwd()) ?: null;
$argv = (array) $this->env('argv');
$this->_env['script'] = array_shift($argv);
$this->_env['PLATFORM'] = 'CLI';
$this->argv += $argv + (array) $this->_config['args'];
$this->input = $this->_config['input'];
if (!is_resource($this->_config['input'])) {
$this->input = fopen('php://stdin', 'r');
}
parent::_init();
} | php | protected function _init() {
if ($this->_config['globals']) {
$this->_env += (array) $_SERVER + (array) $_ENV;
}
$this->_env['working'] = str_replace('\\', '/', getcwd()) ?: null;
$argv = (array) $this->env('argv');
$this->_env['script'] = array_shift($argv);
$this->_env['PLATFORM'] = 'CLI';
$this->argv += $argv + (array) $this->_config['args'];
$this->input = $this->_config['input'];
if (!is_resource($this->_config['input'])) {
$this->input = fopen('php://stdin', 'r');
}
parent::_init();
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_config",
"[",
"'globals'",
"]",
")",
"{",
"$",
"this",
"->",
"_env",
"+=",
"(",
"array",
")",
"$",
"_SERVER",
"+",
"(",
"array",
")",
"$",
"_ENV",
";",
"}",
"$",
"... | Initialize request object, pulling request data from superglobals.
Defines an artificial `'PLATFORM'` environment variable as `'CLI'` to
allow checking for the SAPI in a normalized way. This is also for
establishing consistency with this class' sister classes.
@see lithium\action\Request::_init()
@return void | [
"Initialize",
"request",
"object",
"pulling",
"request",
"data",
"from",
"superglobals",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Request.php#L95-L110 |
UnionOfRAD/lithium | console/Request.php | Request.args | public function args($key = 0) {
if (!empty($this->args[$key])) {
return $this->args[$key];
}
return null;
} | php | public function args($key = 0) {
if (!empty($this->args[$key])) {
return $this->args[$key];
}
return null;
} | [
"public",
"function",
"args",
"(",
"$",
"key",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"args",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"args",
"[",
"$",
"key",
"]",
";",
"}",
"return",
... | Get the value of a command line argument at a given key
@param integer $key
@return mixed returns null if key does not exist or the value of the key in the args array | [
"Get",
"the",
"value",
"of",
"a",
"command",
"line",
"argument",
"at",
"a",
"given",
"key"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Request.php#L136-L141 |
UnionOfRAD/lithium | console/Request.php | Request.env | public function env($key = null) {
if (!empty($this->_env[$key])) {
return $this->_env[$key];
}
if ($key === null) {
return $this->_env;
}
return null;
} | php | public function env($key = null) {
if (!empty($this->_env[$key])) {
return $this->_env[$key];
}
if ($key === null) {
return $this->_env;
}
return null;
} | [
"public",
"function",
"env",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"_env",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_env",
"[",
"$",
"key",
"]",
";",
"}",
"if",
"(... | Get environment variables.
@param string $key
@return mixed Returns the environment key related to the `$key` argument. If `$key` is equal
to null the result will be the entire environment array. If `$key` is set but not
available, `null` will be returned. | [
"Get",
"environment",
"variables",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Request.php#L151-L159 |
UnionOfRAD/lithium | console/Request.php | Request.shift | public function shift($num = 1) {
for ($i = $num; $i > 1; $i--) {
$this->shift(--$i);
}
$this->params['command'] = $this->params['action'];
if (isset($this->params['args'][0])) {
$this->params['action'] = array_shift($this->params['args']);
}
return $this;
} | php | public function shift($num = 1) {
for ($i = $num; $i > 1; $i--) {
$this->shift(--$i);
}
$this->params['command'] = $this->params['action'];
if (isset($this->params['args'][0])) {
$this->params['action'] = array_shift($this->params['args']);
}
return $this;
} | [
"public",
"function",
"shift",
"(",
"$",
"num",
"=",
"1",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"$",
"num",
";",
"$",
"i",
">",
"1",
";",
"$",
"i",
"--",
")",
"{",
"$",
"this",
"->",
"shift",
"(",
"--",
"$",
"i",
")",
";",
"}",
"$",
"thi... | Moves params up a level. Sets command to action, action to passed[0], and so on.
@param integer $num how many times to shift
@return self | [
"Moves",
"params",
"up",
"a",
"level",
".",
"Sets",
"command",
"to",
"action",
"action",
"to",
"passed",
"[",
"0",
"]",
"and",
"so",
"on",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Request.php#L167-L176 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.random | public static function random($bytes, array $options = []) {
$message = "lithium\util\String::random() has been deprecated in favor of ";
$message .= "lithium\security\Random::generate().";
trigger_error($message, E_USER_DEPRECATED);
return Random::generate($bytes, $options);
} | php | public static function random($bytes, array $options = []) {
$message = "lithium\util\String::random() has been deprecated in favor of ";
$message .= "lithium\security\Random::generate().";
trigger_error($message, E_USER_DEPRECATED);
return Random::generate($bytes, $options);
} | [
"public",
"static",
"function",
"random",
"(",
"$",
"bytes",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::random() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\security\\Random::ge... | Generates random bytes for use in UUIDs and password salts, using
(when available) a cryptographically strong random number generator.
@deprecated Replaced by `lithium\security\Random::generate()`.
@param integer $bytes The number of random bytes to generate.
@param array $options
@return string Returns a string of random bytes. | [
"Generates",
"random",
"bytes",
"for",
"use",
"in",
"UUIDs",
"and",
"password",
"salts",
"using",
"(",
"when",
"available",
")",
"a",
"cryptographically",
"strong",
"random",
"number",
"generator",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L78-L83 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.hash | public static function hash($string, array $options = []) {
$message = "lithium\util\String::hash() has been deprecated in favor of ";
$message .= "lithium\security\Hash::calculate().";
trigger_error($message, E_USER_DEPRECATED);
return Hash::calculate($string, $options);
} | php | public static function hash($string, array $options = []) {
$message = "lithium\util\String::hash() has been deprecated in favor of ";
$message .= "lithium\security\Hash::calculate().";
trigger_error($message, E_USER_DEPRECATED);
return Hash::calculate($string, $options);
} | [
"public",
"static",
"function",
"hash",
"(",
"$",
"string",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::hash() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\security\\Hash::calcula... | Uses PHP's hashing functions to create a hash of the string provided, using the options
specified. The default hash algorithm is SHA-512.
@deprecated Replaced by `lithium\security\Hash::calculate()`.
@link http://php.net/function.hash.php PHP Manual: `hash()`
@link http://php.net/function.hash-hmac.php PHP Manual: `hash_hmac()`
@link http://php.net/function.hash-algos.php PHP Manual: `hash_algos()`
@param string $string The string to hash.
@param array $options
@return string Returns a hashed string. | [
"Uses",
"PHP",
"s",
"hashing",
"functions",
"to",
"create",
"a",
"hash",
"of",
"the",
"string",
"provided",
"using",
"the",
"options",
"specified",
".",
"The",
"default",
"hash",
"algorithm",
"is",
"SHA",
"-",
"512",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L97-L103 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.compare | public static function compare($known, $user) {
$message = "lithium\util\String::compare() has been deprecated in favor of ";
$message .= "lithium\security\Hash::compare().";
trigger_error($message, E_USER_DEPRECATED);
return Hash::compare($known, $user);
} | php | public static function compare($known, $user) {
$message = "lithium\util\String::compare() has been deprecated in favor of ";
$message .= "lithium\security\Hash::compare().";
trigger_error($message, E_USER_DEPRECATED);
return Hash::compare($known, $user);
} | [
"public",
"static",
"function",
"compare",
"(",
"$",
"known",
",",
"$",
"user",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::compare() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\security\\Hash::compare().\"",
";",
"trigger_erro... | Compares two strings in constant time to prevent timing attacks.
@deprecated Replaced by `lithium\security\Hash::compare()`.
@param string $known The string of known length to compare against.
@param string $user The user-supplied string.
@return boolean Returns a boolean indicating whether the two strings are equal. | [
"Compares",
"two",
"strings",
"in",
"constant",
"time",
"to",
"prevent",
"timing",
"attacks",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L113-L119 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.insert | public static function insert($str, array $data, array $options = []) {
$message = "lithium\util\String::insert() has been deprecated in favor of ";
$message .= "lithium\util\Text::insert().";
trigger_error($message, E_USER_DEPRECATED);
return Text::insert($str, $data, $options);
} | php | public static function insert($str, array $data, array $options = []) {
$message = "lithium\util\String::insert() has been deprecated in favor of ";
$message .= "lithium\util\Text::insert().";
trigger_error($message, E_USER_DEPRECATED);
return Text::insert($str, $data, $options);
} | [
"public",
"static",
"function",
"insert",
"(",
"$",
"str",
",",
"array",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::insert() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
... | Replaces variable placeholders inside a string with any given data. Each key
in the `$data` array corresponds to a variable placeholder name in `$str`.
@deprecated Replaced by `lithium\util\Text::insert()`.
@param string $str A string containing variable place-holders.
@param array $data A key, value array where each key stands for a place-holder variable
name to be replaced with value.
@param array $options
@return string | [
"Replaces",
"variable",
"placeholders",
"inside",
"a",
"string",
"with",
"any",
"given",
"data",
".",
"Each",
"key",
"in",
"the",
"$data",
"array",
"corresponds",
"to",
"a",
"variable",
"placeholder",
"name",
"in",
"$str",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L147-L153 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.clean | public static function clean($str, array $options = []) {
$message = "lithium\util\String::clean() has been deprecated in favor of ";
$message .= "lithium\util\Text::clean().";
trigger_error($message, E_USER_DEPRECATED);
return Text::clean($str, $options);
} | php | public static function clean($str, array $options = []) {
$message = "lithium\util\String::clean() has been deprecated in favor of ";
$message .= "lithium\util\Text::clean().";
trigger_error($message, E_USER_DEPRECATED);
return Text::clean($str, $options);
} | [
"public",
"static",
"function",
"clean",
"(",
"$",
"str",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::clean() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\util\\Text::clean().\"",... | Cleans up a `String::insert()` formatted string with given `$options` depending
on the `'clean'` option. The goal of this function is to replace all whitespace
and unneeded mark-up around place-holders that did not get replaced by `String::insert()`.
@deprecated Replaced by `lithium\util\Text::clean()`.
@param string $str The string to clean.
@param array $options
@return string The cleaned string. | [
"Cleans",
"up",
"a",
"String",
"::",
"insert",
"()",
"formatted",
"string",
"with",
"given",
"$options",
"depending",
"on",
"the",
"clean",
"option",
".",
"The",
"goal",
"of",
"this",
"function",
"is",
"to",
"replace",
"all",
"whitespace",
"and",
"unneeded",... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L165-L171 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.extract | public static function extract($regex, $str, $index = 0) {
$message = "lithium\util\String::extract() has been deprecated in favor of ";
$message .= "lithium\util\Text::extract().";
trigger_error($message, E_USER_DEPRECATED);
return Text::extract($regex, $str, $index);
} | php | public static function extract($regex, $str, $index = 0) {
$message = "lithium\util\String::extract() has been deprecated in favor of ";
$message .= "lithium\util\Text::extract().";
trigger_error($message, E_USER_DEPRECATED);
return Text::extract($regex, $str, $index);
} | [
"public",
"static",
"function",
"extract",
"(",
"$",
"regex",
",",
"$",
"str",
",",
"$",
"index",
"=",
"0",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::extract() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\util\\Text::ext... | Extract a part of a string based on a regular expression `$regex`.
@deprecated Replaced by `lithium\util\Text::extract()`.
@param string $regex The regular expression to use.
@param string $str The string to run the extraction on.
@param integer $index The number of the part to return based on the regex.
@return mixed | [
"Extract",
"a",
"part",
"of",
"a",
"string",
"based",
"on",
"a",
"regular",
"expression",
"$regex",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L182-L188 |
UnionOfRAD/lithium | util/String.php | StringDeprecated.tokenize | public static function tokenize($data, array $options = []) {
$message = "lithium\util\String::tokenize() has been deprecated in favor of ";
$message .= "lithium\util\Text::tokenize().";
trigger_error($message, E_USER_DEPRECATED);
return Text::tokenize($data, $options);
} | php | public static function tokenize($data, array $options = []) {
$message = "lithium\util\String::tokenize() has been deprecated in favor of ";
$message .= "lithium\util\Text::tokenize().";
trigger_error($message, E_USER_DEPRECATED);
return Text::tokenize($data, $options);
} | [
"public",
"static",
"function",
"tokenize",
"(",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"\"lithium\\util\\String::tokenize() has been deprecated in favor of \"",
";",
"$",
"message",
".=",
"\"lithium\\util\\Text::token... | Tokenizes a string using `$options['separator']`, ignoring any instances of
`$options['separator']` that appear between `$options['leftBound']` and
`$options['rightBound']`.
@deprecated Replaced by `lithium\util\Text::tokenize()`.
@param string $data The data to tokenize.
@param array $options
@return array Returns an array of tokens. | [
"Tokenizes",
"a",
"string",
"using",
"$options",
"[",
"separator",
"]",
"ignoring",
"any",
"instances",
"of",
"$options",
"[",
"separator",
"]",
"that",
"appear",
"between",
"$options",
"[",
"leftBound",
"]",
"and",
"$options",
"[",
"rightBound",
"]",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/String.php#L200-L206 |
UnionOfRAD/lithium | security/Random.php | Random.generate | public static function generate($bytes, array $options = []) {
$defaults = ['encode' => null];
$options += $defaults;
$source = static::$_source ?: (static::$_source = static::_source());
$result = $source($bytes);
if ($options['encode'] !== static::ENCODE_BASE_64) {
return $result;
}
return strtr(rtrim(base64_encode($result), '='), '+', '.');
} | php | public static function generate($bytes, array $options = []) {
$defaults = ['encode' => null];
$options += $defaults;
$source = static::$_source ?: (static::$_source = static::_source());
$result = $source($bytes);
if ($options['encode'] !== static::ENCODE_BASE_64) {
return $result;
}
return strtr(rtrim(base64_encode($result), '='), '+', '.');
} | [
"public",
"static",
"function",
"generate",
"(",
"$",
"bytes",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'encode'",
"=>",
"null",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
"source",
"=",
"st... | Generates random bytes for use in UUIDs and password salts, using
a cryptographically strong random number generator source.
```
$bits = Random::generate(8); // 64 bits
$hex = bin2hex($bits); // [0-9a-f]+
```
Optionally base64-encodes the resulting random string per the following. The
alphabet used by `base64_encode()` is different than the one we should be using.
When considering the meaty part of the resulting string, however, a bijection
allows to go the from one to another. Given that we're working on random bytes, we
can use safely use `base64_encode()` without losing any entropy.
@param integer $bytes The number of random bytes to generate.
@param array $options The options used when generating random bytes:
- `'encode'` _integer_: If specified, and set to `Random::ENCODE_BASE_64`, the
resulting value will be base64-encoded, per the note above.
@return string Returns (an encoded) string of random bytes. | [
"Generates",
"random",
"bytes",
"for",
"use",
"in",
"UUIDs",
"and",
"password",
"salts",
"using",
"a",
"cryptographically",
"strong",
"random",
"number",
"generator",
"source",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Random.php#L60-L71 |
UnionOfRAD/lithium | security/Random.php | Random._source | protected static function _source() {
if (function_exists('random_bytes')) {
return function($bytes) {
return random_bytes($bytes);
};
}
if (function_exists('mcrypt_create_iv')) {
return function($bytes) {
return mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
};
}
if (is_readable('/dev/urandom')) {
return function($bytes) {
$stream = fopen('/dev/urandom', 'rb');
$result = fread($stream, $bytes);
fclose($stream);
return $result;
};
}
if (class_exists('COM', false)) {
$com = new COM('CAPICOM.Utilities.1');
return function($bytes) use ($com) {
return base64_decode($com->GetRandom($bytes, 0));
};
}
throw new LogicException('No suitable strong random number generator source found.');
} | php | protected static function _source() {
if (function_exists('random_bytes')) {
return function($bytes) {
return random_bytes($bytes);
};
}
if (function_exists('mcrypt_create_iv')) {
return function($bytes) {
return mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
};
}
if (is_readable('/dev/urandom')) {
return function($bytes) {
$stream = fopen('/dev/urandom', 'rb');
$result = fread($stream, $bytes);
fclose($stream);
return $result;
};
}
if (class_exists('COM', false)) {
$com = new COM('CAPICOM.Utilities.1');
return function($bytes) use ($com) {
return base64_decode($com->GetRandom($bytes, 0));
};
}
throw new LogicException('No suitable strong random number generator source found.');
} | [
"protected",
"static",
"function",
"_source",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'random_bytes'",
")",
")",
"{",
"return",
"function",
"(",
"$",
"bytes",
")",
"{",
"return",
"random_bytes",
"(",
"$",
"bytes",
")",
";",
"}",
";",
"}",
"i... | Returns the best available random number generator source.
The source of randomness used are as follows:
1. `random_bytes()`, available in PHP >=7.0
2. `mcrypt_create_iv()`, available if the mcrypt extensions is installed
3. `/dev/urandom`, available on *nix
4. `GetRandom()` through COM, available on Windows
Note: Users restricting path access through the `open_basedir` INI setting,
will need to include `/dev/urandom` into the list of allowed paths, as this
method might read from it.
The `openssl_random_pseudo_bytes()` function is not used, as it is not clear
under which circumstances it will not have a strong source available to it.
@link http://php.net/random_bytes
@link http://php.net/mcrypt_create_iv
@link http://msdn.microsoft.com/en-us/library/aa388182%28VS.85%29.aspx?ppud=4
@link http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
@see lithium\util\Random::$_source
@return callable Returns a closure containing a random number generator. | [
"Returns",
"the",
"best",
"available",
"random",
"number",
"generator",
"source",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Random.php#L97-L125 |
UnionOfRAD/lithium | util/collection/Filters.php | Filters.apply | public static function apply($class, $method, $filter) {
$message = '`\lithium\util\collection\Filters::apply()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Filters::apply()`';
trigger_error($message, E_USER_DEPRECATED);
NewFilters::apply($class, $method, $filter);
} | php | public static function apply($class, $method, $filter) {
$message = '`\lithium\util\collection\Filters::apply()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Filters::apply()`';
trigger_error($message, E_USER_DEPRECATED);
NewFilters::apply($class, $method, $filter);
} | [
"public",
"static",
"function",
"apply",
"(",
"$",
"class",
",",
"$",
"method",
",",
"$",
"filter",
")",
"{",
"$",
"message",
"=",
"'`\\lithium\\util\\collection\\Filters::apply()` has been deprecated '",
";",
"$",
"message",
".=",
"'in favor of `\\lithium\\aop\\Filters... | Lazily applies a filter to a method of a static class.
This method is useful if you want to apply a filter inside a global bootstrap file to a
static class which may or may not be loaded during every request, or which may be loaded
lazily elsewhere in your application. If the class is already loaded, the filter will be
applied immediately.
However, if the class has not been loaded, the filter will be stored and applied to the class
the first time the method specified in `$method` is called. This works for any class which
extends `StaticObject`.
@deprecated Forwards to new implementation.
@see lithium\core\StaticObject
@param string $class The fully namespaced name of a **static** class to which the filter will
be applied. The class name specified in `$class` **must** extend
`StaticObject`, or else statically implement the `applyFilter()` method.
@param string $method The method to which the filter will be applied.
@param \Closure $filter The filter to apply to the class method.
@return void | [
"Lazily",
"applies",
"a",
"filter",
"to",
"a",
"method",
"of",
"a",
"static",
"class",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/collection/Filters.php#L142-L148 |
UnionOfRAD/lithium | util/collection/Filters.php | Filters.run | public static function run($class, $params, array $options = []) {
$message = '`\lithium\util\collection\Filters::run()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Filters::run()`';
trigger_error($message, E_USER_DEPRECATED);
$defaults = ['class' => null, 'method' => null, 'data' => []];
$options += $defaults;
$callback = array_pop($options['data']);
foreach ($options['data'] as $filter) {
NewFilters::apply($class, $options['method'], $filter);
}
return NewFilters::run($class, $options['method'], $params, $callback);
} | php | public static function run($class, $params, array $options = []) {
$message = '`\lithium\util\collection\Filters::run()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Filters::run()`';
trigger_error($message, E_USER_DEPRECATED);
$defaults = ['class' => null, 'method' => null, 'data' => []];
$options += $defaults;
$callback = array_pop($options['data']);
foreach ($options['data'] as $filter) {
NewFilters::apply($class, $options['method'], $filter);
}
return NewFilters::run($class, $options['method'], $params, $callback);
} | [
"public",
"static",
"function",
"run",
"(",
"$",
"class",
",",
"$",
"params",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"message",
"=",
"'`\\lithium\\util\\collection\\Filters::run()` has been deprecated '",
";",
"$",
"message",
".=",
"'in favo... | Collects a set of filters to iterate. Creates a filter chain for the given class/method,
executes it, and returns the value.
@deprecated Forwards to new implementation.
@param mixed $class The class for which this filter chain is being created. If this is the
result of a static method call, `$class` should be a string. Otherwise, it should
be the instance of the object making the call.
@param array $params An associative array of the given method's parameters.
@param array $options The configuration options with which to create the filter chain.
Mainly, these options allow the `Filters` object to be queried for details such as
which class / method initiated it. Available keys:
- `'class'`: The name of the class that initiated the filter chain.
- `'method'`: The name of the method that initiated the filter chain.
- `'data'` _array_: An array of callable objects (usually closures) to be iterated
through. By default, execution will be nested such that the first item will be
executed first, and will be the last to return.
@return Returns the value returned by the first closure in `$options['data`]`. | [
"Collects",
"a",
"set",
"of",
"filters",
"to",
"iterate",
".",
"Creates",
"a",
"filter",
"chain",
"for",
"the",
"given",
"class",
"/",
"method",
"executes",
"it",
"and",
"returns",
"the",
"value",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/collection/Filters.php#L190-L204 |
UnionOfRAD/lithium | util/collection/Filters.php | Filters.next | public function next(/* $self, $params, $chain */) {
if (func_num_args() !== 3) {
trigger_error('Missing argument/s.', E_USER_WARNING);
return;
}
list($self, $params, $chain) = func_get_args();
$message = '`\lithium\util\collection\Filters::next()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Chain::next()`';
trigger_error($message, E_USER_DEPRECATED);
if (empty($self) || empty($chain)) {
return parent::next();
}
$next = parent::next();
return $next($self, $params, $chain);
} | php | public function next(/* $self, $params, $chain */) {
if (func_num_args() !== 3) {
trigger_error('Missing argument/s.', E_USER_WARNING);
return;
}
list($self, $params, $chain) = func_get_args();
$message = '`\lithium\util\collection\Filters::next()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Chain::next()`';
trigger_error($message, E_USER_DEPRECATED);
if (empty($self) || empty($chain)) {
return parent::next();
}
$next = parent::next();
return $next($self, $params, $chain);
} | [
"public",
"function",
"next",
"(",
"/* $self, $params, $chain */",
")",
"{",
"if",
"(",
"func_num_args",
"(",
")",
"!==",
"3",
")",
"{",
"trigger_error",
"(",
"'Missing argument/s.'",
",",
"E_USER_WARNING",
")",
";",
"return",
";",
"}",
"list",
"(",
"$",
"se... | Provides short-hand convenience syntax for filter chaining.
@deprecated Not used here anymore.
@see lithium\core\Object::applyFilter()
@see lithium\core\Object::_filter()
@param object $self The object instance that owns the filtered method.
@param array $params An associative array containing the parameters passed to the filtered
method.
@param array $chain The Filters object instance containing this chain of filters.
@return mixed Returns the return value of the next filter in the chain. | [
"Provides",
"short",
"-",
"hand",
"convenience",
"syntax",
"for",
"filter",
"chaining",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/collection/Filters.php#L218-L234 |
UnionOfRAD/lithium | util/collection/Filters.php | Filters.method | public function method($full = false) {
$message = '`\lithium\util\collection\Filters::method()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Chain::method()`';
trigger_error($message, E_USER_DEPRECATED);
return $full ? $this->_class . '::' . $this->_method : $this->_method;
} | php | public function method($full = false) {
$message = '`\lithium\util\collection\Filters::method()` has been deprecated ';
$message .= 'in favor of `\lithium\aop\Chain::method()`';
trigger_error($message, E_USER_DEPRECATED);
return $full ? $this->_class . '::' . $this->_method : $this->_method;
} | [
"public",
"function",
"method",
"(",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"message",
"=",
"'`\\lithium\\util\\collection\\Filters::method()` has been deprecated '",
";",
"$",
"message",
".=",
"'in favor of `\\lithium\\aop\\Chain::method()`'",
";",
"trigger_error",
"(",... | Gets the method name associated with this filter chain. This is the method being filtered.
@deprecated Not used here anymore.
@param boolean $full Whether to return the method name including the class name or not.
@return string | [
"Gets",
"the",
"method",
"name",
"associated",
"with",
"this",
"filter",
"chain",
".",
"This",
"is",
"the",
"method",
"being",
"filtered",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/collection/Filters.php#L243-L249 |
UnionOfRAD/lithium | template/view/adapter/Simple.php | Simple.render | public function render($template, $data = [], array $options = []) {
$defaults = ['context' => []];
$options += $defaults;
$context = [];
$this->_context = $options['context'] + $this->_context;
foreach (array_keys($this->_context) as $key) {
$context[$key] = $this->__get($key);
}
$data = array_merge($this->_toString($context), $this->_toString($data));
return Text::insert($template, $data, $options);
} | php | public function render($template, $data = [], array $options = []) {
$defaults = ['context' => []];
$options += $defaults;
$context = [];
$this->_context = $options['context'] + $this->_context;
foreach (array_keys($this->_context) as $key) {
$context[$key] = $this->__get($key);
}
$data = array_merge($this->_toString($context), $this->_toString($data));
return Text::insert($template, $data, $options);
} | [
"public",
"function",
"render",
"(",
"$",
"template",
",",
"$",
"data",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'context'",
"=>",
"[",
"]",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",... | Renders content from a template file provided by `template()`.
@param string $template
@param array $data
@param array $options
@return string | [
"Renders",
"content",
"from",
"a",
"template",
"file",
"provided",
"by",
"template",
"()",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/adapter/Simple.php#L31-L43 |
UnionOfRAD/lithium | template/view/adapter/Simple.php | Simple.template | public function template($type, $options) {
if (isset($options[$type])) {
return $options[$type];
}
return isset($options['template']) ? $options['template'] : '';
} | php | public function template($type, $options) {
if (isset($options[$type])) {
return $options[$type];
}
return isset($options['template']) ? $options['template'] : '';
} | [
"public",
"function",
"template",
"(",
"$",
"type",
",",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"type",
"]",
")",
")",
"{",
"return",
"$",
"options",
"[",
"$",
"type",
"]",
";",
"}",
"return",
"isset",
"(",
... | Returns a template string
@param string $type
@param array $options
@return string | [
"Returns",
"a",
"template",
"string"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/adapter/Simple.php#L52-L57 |
UnionOfRAD/lithium | template/view/adapter/Simple.php | Simple._toString | protected function _toString($data) {
foreach ($data as $key => $val) {
switch (true) {
case is_object($val) && !$val instanceof \Closure:
try {
$data[$key] = (string) $val;
} catch (Exception $e) {
$data[$key] = '';
}
break;
case is_array($val):
$data = array_merge($data, Set::flatten($val));
break;
}
}
return $data;
} | php | protected function _toString($data) {
foreach ($data as $key => $val) {
switch (true) {
case is_object($val) && !$val instanceof \Closure:
try {
$data[$key] = (string) $val;
} catch (Exception $e) {
$data[$key] = '';
}
break;
case is_array($val):
$data = array_merge($data, Set::flatten($val));
break;
}
}
return $data;
} | [
"protected",
"function",
"_toString",
"(",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"is_object",
"(",
"$",
"val",
")",
"&&",
"!",
"$",
"val",
"insta... | Renders `$data` into an easier to understand, or flat, array.
@param array $data Data to traverse.
@return array | [
"Renders",
"$data",
"into",
"an",
"easier",
"to",
"understand",
"or",
"flat",
"array",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/adapter/Simple.php#L65-L81 |
UnionOfRAD/lithium | data/Model.php | Model.config | public static function config(array $config = []) {
if (($class = get_called_class()) === __CLASS__) {
return;
}
if (!isset(static::$_instances[$class])) {
static::$_instances[$class] = new $class();
}
$self = static::$_instances[$class];
foreach ($self->_autoConfig as $key) {
if (isset($config[$key])) {
$_key = "_{$key}";
$val = $config[$key];
$self->$_key = is_array($val) ? $val + $self->$_key : $val;
}
}
static::$_initialized[$class] = false;
} | php | public static function config(array $config = []) {
if (($class = get_called_class()) === __CLASS__) {
return;
}
if (!isset(static::$_instances[$class])) {
static::$_instances[$class] = new $class();
}
$self = static::$_instances[$class];
foreach ($self->_autoConfig as $key) {
if (isset($config[$key])) {
$_key = "_{$key}";
$val = $config[$key];
$self->$_key = is_array($val) ? $val + $self->$_key : $val;
}
}
static::$_initialized[$class] = false;
} | [
"public",
"static",
"function",
"config",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"(",
"$",
"class",
"=",
"get_called_class",
"(",
")",
")",
"===",
"__CLASS__",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
... | Configures the model for use. This method will set the `Model::$_schema`, `Model::$_meta`,
`Model::$_finders` class attributes, as well as obtain a handle to the configured
persistent storage connection.
@param array $config Possible options are:
- `meta`: Meta-information for this model, such as the connection.
- `finders`: Custom finders for this model.
- `query`: Default query parameters.
- `schema`: A `Schema` instance for this model.
- `classes`: Classes used by this model. | [
"Configures",
"the",
"model",
"for",
"use",
".",
"This",
"method",
"will",
"set",
"the",
"Model",
"::",
"$_schema",
"Model",
"::",
"$_meta",
"Model",
"::",
"$_finders",
"class",
"attributes",
"as",
"well",
"as",
"obtain",
"a",
"handle",
"to",
"the",
"confi... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L325-L344 |
UnionOfRAD/lithium | data/Model.php | Model._initialize | protected static function _initialize($class) {
$self = static::$_instances[$class];
if (isset(static::$_initialized[$class]) && static::$_initialized[$class]) {
return $self;
}
static::$_initialized[$class] = true;
$self->_inherit();
$source = [
'classes' => [], 'meta' => [], 'finders' => [], 'schema' => []
];
$meta = $self->_meta;
if ($meta['connection']) {
$classes = $self->_classes;
$conn = $classes['connections']::get($meta['connection']);
$source = (($conn) ? $conn->configureClass($class) : []) + $source;
}
$self->_classes += $source['classes'];
$self->_meta = compact('class') + $self->_meta + $source['meta'];
$self->_initializers += [
'name' => function($self) {
return basename(str_replace('\\', '/', $self));
},
'source' => function($self) {
return Inflector::tableize($self::meta('name'));
},
'title' => function($self) {
$titleKeys = ['title', 'name'];
$titleKeys = array_merge($titleKeys, (array) $self::meta('key'));
return $self::hasField($titleKeys);
}
];
if (is_object($self->_schema)) {
$self->_schema->append($source['schema']);
} else {
$self->_schema += $source['schema'];
}
$self->_finders += $source['finders'] + static::_finders();
$self->_classes += [
'query' => 'lithium\data\model\Query',
'validator' => 'lithium\util\Validator',
'entity' => 'lithium\data\Entity'
];
static::_relationsToLoad();
return $self;
} | php | protected static function _initialize($class) {
$self = static::$_instances[$class];
if (isset(static::$_initialized[$class]) && static::$_initialized[$class]) {
return $self;
}
static::$_initialized[$class] = true;
$self->_inherit();
$source = [
'classes' => [], 'meta' => [], 'finders' => [], 'schema' => []
];
$meta = $self->_meta;
if ($meta['connection']) {
$classes = $self->_classes;
$conn = $classes['connections']::get($meta['connection']);
$source = (($conn) ? $conn->configureClass($class) : []) + $source;
}
$self->_classes += $source['classes'];
$self->_meta = compact('class') + $self->_meta + $source['meta'];
$self->_initializers += [
'name' => function($self) {
return basename(str_replace('\\', '/', $self));
},
'source' => function($self) {
return Inflector::tableize($self::meta('name'));
},
'title' => function($self) {
$titleKeys = ['title', 'name'];
$titleKeys = array_merge($titleKeys, (array) $self::meta('key'));
return $self::hasField($titleKeys);
}
];
if (is_object($self->_schema)) {
$self->_schema->append($source['schema']);
} else {
$self->_schema += $source['schema'];
}
$self->_finders += $source['finders'] + static::_finders();
$self->_classes += [
'query' => 'lithium\data\model\Query',
'validator' => 'lithium\util\Validator',
'entity' => 'lithium\data\Entity'
];
static::_relationsToLoad();
return $self;
} | [
"protected",
"static",
"function",
"_initialize",
"(",
"$",
"class",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"$",
"_instances",
"[",
"$",
"class",
"]",
";",
"if",
"(",
"isset",
"(",
"static",
"::",
"$",
"_initialized",
"[",
"$",
"class",
"]",
")"... | Init default connection options and connects default finders.
This method will set the `Model::$_schema`, `Model::$_meta`, `Model::$_finders` class
attributes, as well as obtain a handle to the configured persistent storage connection
@param string $class The fully-namespaced class name to initialize.
@return object Returns the initialized model instance. | [
"Init",
"default",
"connection",
"options",
"and",
"connects",
"default",
"finders",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L355-L409 |
UnionOfRAD/lithium | data/Model.php | Model._inherit | protected function _inherit() {
$inherited = array_fill_keys($this->_inherited(), []);
foreach (static::_parents() as $parent) {
$parentConfig = get_class_vars($parent);
foreach ($inherited as $key => $value) {
if (isset($parentConfig["{$key}"])) {
$val = $parentConfig["{$key}"];
if (is_array($val)) {
$inherited[$key] += $val;
}
}
}
if ($parent === __CLASS__) {
break;
}
}
foreach ($inherited as $key => $value) {
if (is_array($this->{$key})) {
$this->{$key} += $value;
}
}
} | php | protected function _inherit() {
$inherited = array_fill_keys($this->_inherited(), []);
foreach (static::_parents() as $parent) {
$parentConfig = get_class_vars($parent);
foreach ($inherited as $key => $value) {
if (isset($parentConfig["{$key}"])) {
$val = $parentConfig["{$key}"];
if (is_array($val)) {
$inherited[$key] += $val;
}
}
}
if ($parent === __CLASS__) {
break;
}
}
foreach ($inherited as $key => $value) {
if (is_array($this->{$key})) {
$this->{$key} += $value;
}
}
} | [
"protected",
"function",
"_inherit",
"(",
")",
"{",
"$",
"inherited",
"=",
"array_fill_keys",
"(",
"$",
"this",
"->",
"_inherited",
"(",
")",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"static",
"::",
"_parents",
"(",
")",
"as",
"$",
"parent",
")",
"{"... | Merge parent class attributes to the current instance. | [
"Merge",
"parent",
"class",
"attributes",
"to",
"the",
"current",
"instance",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L414-L440 |
UnionOfRAD/lithium | data/Model.php | Model.respondsTo | public static function respondsTo($method, $internal = false) {
$self = static::_object();
$methods = static::instanceMethods();
$isFinder = isset($self->_finders[$method]);
preg_match('/^findBy(?P<field>\w+)$|^find(?P<type>\w+)By(?P<fields>\w+)$/', $method, $args);
$staticRepondsTo = $isFinder || $method === 'all' || !!$args;
$instanceRespondsTo = isset($methods[$method]);
return $instanceRespondsTo || $staticRepondsTo || parent::respondsTo($method, $internal);
} | php | public static function respondsTo($method, $internal = false) {
$self = static::_object();
$methods = static::instanceMethods();
$isFinder = isset($self->_finders[$method]);
preg_match('/^findBy(?P<field>\w+)$|^find(?P<type>\w+)By(?P<fields>\w+)$/', $method, $args);
$staticRepondsTo = $isFinder || $method === 'all' || !!$args;
$instanceRespondsTo = isset($methods[$method]);
return $instanceRespondsTo || $staticRepondsTo || parent::respondsTo($method, $internal);
} | [
"public",
"static",
"function",
"respondsTo",
"(",
"$",
"method",
",",
"$",
"internal",
"=",
"false",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"$",
"methods",
"=",
"static",
"::",
"instanceMethods",
"(",
")",
";",
"$",
"i... | 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/Model.php#L561-L569 |
UnionOfRAD/lithium | data/Model.php | Model.find | public static function find($type, array $options = []) {
$self = static::_object();
if (is_object($type) || !isset($self->_finders[$type])) {
$options['conditions'] = static::key($type);
$type = 'first';
}
$options += (array) $self->_query;
$meta = ['meta' => $self->_meta, 'name' => get_called_class()];
$params = compact('type', 'options');
$implementation = function($params) use ($meta) {
$options = $params['options'] + ['type' => 'read', 'model' => $meta['name']];
$query = static::_instance('query', $options);
return static::connection()->read($query, $options);
};
if (isset($self->_finders[$type])) {
$finder = $self->_finders[$type];
$reflect = new \ReflectionFunction($finder);
if ($reflect->getNumberOfParameters() > 2) {
$message = 'Old style finder function in file ' . $reflect->getFileName() . ' ';
$message .= 'on line ' . $reflect->getStartLine() . '. ';
$message .= 'The signature for finder functions has changed. It is now ';
$message .= '`($params, $next)` instead of the old `($self, $params, $chain)`. ';
$message .= 'Instead of `$self` use `$this` or `static`.';
trigger_error($message, E_USER_DEPRECATED);
return Filters::bcRun(
get_called_class(), __FUNCTION__, $params, $implementation, [$finder]
);
}
$implementation = function($params) use ($finder, $implementation) {
return $finder($params, $implementation);
};
}
return Filters::run(get_called_class(), __FUNCTION__, $params, $implementation);
} | php | public static function find($type, array $options = []) {
$self = static::_object();
if (is_object($type) || !isset($self->_finders[$type])) {
$options['conditions'] = static::key($type);
$type = 'first';
}
$options += (array) $self->_query;
$meta = ['meta' => $self->_meta, 'name' => get_called_class()];
$params = compact('type', 'options');
$implementation = function($params) use ($meta) {
$options = $params['options'] + ['type' => 'read', 'model' => $meta['name']];
$query = static::_instance('query', $options);
return static::connection()->read($query, $options);
};
if (isset($self->_finders[$type])) {
$finder = $self->_finders[$type];
$reflect = new \ReflectionFunction($finder);
if ($reflect->getNumberOfParameters() > 2) {
$message = 'Old style finder function in file ' . $reflect->getFileName() . ' ';
$message .= 'on line ' . $reflect->getStartLine() . '. ';
$message .= 'The signature for finder functions has changed. It is now ';
$message .= '`($params, $next)` instead of the old `($self, $params, $chain)`. ';
$message .= 'Instead of `$self` use `$this` or `static`.';
trigger_error($message, E_USER_DEPRECATED);
return Filters::bcRun(
get_called_class(), __FUNCTION__, $params, $implementation, [$finder]
);
}
$implementation = function($params) use ($finder, $implementation) {
return $finder($params, $implementation);
};
}
return Filters::run(get_called_class(), __FUNCTION__, $params, $implementation);
} | [
"public",
"static",
"function",
"find",
"(",
"$",
"type",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"if",
"(",
"is_object",
"(",
"$",
"type",
")",
"||",
"!",
"isset",
"(",
... | The `find` method allows you to retrieve data from the connected data source.
Examples:
```
Posts::find('all'); // returns all records
Posts::find('count'); // returns a count of all records
// The first ten records that have `'author'` set to `'Bob'`.
Posts::find('all', [
'conditions' => ['author' => 'Bob'],
'limit' => 10
]);
// First record where the id matches 23.
Posts::find('first', [
'conditions' => ['id' => 23]
]);
```
Shorthands:
```
// Shorthand for find first by primary key.
Posts::find(23);
// Also works with objects.
Posts::find(new MongoId(23));
```
@see lithium\data\Model::finder()
@param string|object|integer $type The name of the finder to use. By default the
following finders are available. Custom finders can be added via `Model::finder()`.
- `'all'`: Returns all records matching the conditions.
- `'first'`: Returns the first record matching the conditions.
- `'count'`: Returns an integer count of all records matching the conditions.
When using `Database` adapter, you can specify the field to count on
via `fields`, when multiple fields are given does a count on all fields (`'*'`).
- `'list'`: Returns a one dimensional array, where the key is the (primary)p
key and the value the title of the record (the record must have a `'title'`
field). A result may look like: `[1 => 'Foo', 2 => 'Bar']`.
Instead of the name of a finder, also supports shorthand usage with an object or
integer as the first parameter. When passed such a value it is equal to
`Model::find('first', ['conditions' => ['<key>' => <value>]])`.
Note: When an undefined finder is tried to be used, the method will not error out, but
fallback to the `'all'` finder.
@param array $options Options for the query.
Common options accepted are:
- `'conditions'` _array_: The conditions for the query
i.e. `'array('is_published' => true)`.
- `'fields'` _array|null_: The fields that should be retrieved. When set to
`null` or `'*'` and by default, uses all fields. To optimize query performance,
limit the fields to just the ones actually needed.
- `'order'` _array|string_: The order in which the data will be returned,
i.e. `'created ASC'` sorts by created date in ascending order. To sort by
multiple fields use the array syntax `array('title' => 'ASC', 'id' => 'ASC)`.
- `'limit'` _integer_: The maximum number of records to return.
- `'page'` _integer_: Allows to paginate data sets. Specifies the page of the set
together with the limit option specifying the number of records per page. The first
page starts at `1`. Equals limit * offset.
- `'with'` _array_: Relationship names to be included in the query.
Also supported are:
- `'offset'` _integer_
- `'having'` _array|string_
- `'group'` _array|string_
- `'joins'` _array_
@return mixed The result/s of the find. Actual result depends on the finder being used. Most
often this is an instance of `lithium\data\Collection` or `lithium\data\Entity`.
@filter Allows to execute logic before querying (i.e. for rewriting of $options)
or after i.e. for caching results. | [
"The",
"find",
"method",
"allows",
"you",
"to",
"retrieve",
"data",
"from",
"the",
"connected",
"data",
"source",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L643-L683 |
UnionOfRAD/lithium | data/Model.php | Model.finder | public static function finder($name, $finder = null) {
$self = static::_object();
if ($finder === null) {
return isset($self->_finders[$name]) ? $self->_finders[$name] : null;
}
if (is_array($finder)) {
$finder = function($params, $next) use ($finder) {
$params['options'] = Set::merge($params['options'], $finder);
return $next($params);
};
}
$self->_finders[$name] = $finder;
} | php | public static function finder($name, $finder = null) {
$self = static::_object();
if ($finder === null) {
return isset($self->_finders[$name]) ? $self->_finders[$name] : null;
}
if (is_array($finder)) {
$finder = function($params, $next) use ($finder) {
$params['options'] = Set::merge($params['options'], $finder);
return $next($params);
};
}
$self->_finders[$name] = $finder;
} | [
"public",
"static",
"function",
"finder",
"(",
"$",
"name",
",",
"$",
"finder",
"=",
"null",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"if",
"(",
"$",
"finder",
"===",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"se... | Sets or gets a custom finder by name. The finder definition can be an array of
default query options, or an anonymous functions that accepts an array of query
options, and a function to continue. To get a finder specify just the name.
In this example we define and use `'published'` finder to quickly
retrieve all published posts.
```
Posts::finder('published', [
'conditions' => ['is_published' => true]
]);
Posts::find('published');
```
Here we define the same finder using an anonymous function which
gives us more control over query modification.
```
Posts::finder('published', function($params, $next) {
$params['options']['conditions']['is_published'] = true;
// Perform modifications before executing the query...
$result = $next($params);
// ... or after it has executed.
return $result;
});
```
When using finder array definitions the option array is _recursivly_ merged
(using `Set::merge()`) with additional options specified on the `Model::find()`
call. Options specificed on the find will overwrite options specified in the
finder.
Array finder definitions are normalized here, so that it can be relied upon that defined
finders are always anonymous functions.
@see lithium\util\Set::merge()
@param string $name The finder name, e.g. `'first'`.
@param string|callable|null $finder The finder definition.
@return callable|void Returns finder definition if querying, or void if setting. | [
"Sets",
"or",
"gets",
"a",
"custom",
"finder",
"by",
"name",
".",
"The",
"finder",
"definition",
"can",
"be",
"an",
"array",
"of",
"default",
"query",
"options",
"or",
"an",
"anonymous",
"functions",
"that",
"accepts",
"an",
"array",
"of",
"query",
"option... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L727-L740 |
UnionOfRAD/lithium | data/Model.php | Model._finders | protected static function _finders() {
$self = static::_object();
return [
'all' => function($params, $next) {
return $next($params);
},
'first' => function($params, $next) {
$options =& $params['options'];
$options['limit'] = 1;
$data = $next($params);
if (isset($options['return']) && $options['return'] === 'array') {
$data = is_array($data) ? reset($data) : $data;
} else {
$data = is_object($data) ? $data->rewind() : $data;
}
return $data ?: null;
},
'list' => function($params, $next) use ($self) {
$result = [];
$meta = $self::meta();
$name = $meta['key'];
foreach ($next($params) as $entity) {
$key = $entity->{$name};
$result[is_scalar($key) ? $key : (string) $key] = $entity->title();
}
return $result;
},
'count' => function($params, $next) use ($self) {
$options = array_diff_key($params['options'], $self->_query);
if ($options && !isset($params['options']['conditions'])) {
$options = ['conditions' => $options];
} else {
$options = $params['options'];
}
$options += ['type' => 'read', 'model' => $self];
$query = $self::invokeMethod('_instance', ['query', $options]);
return $self::connection()->calculation('count', $query, $options);
}
];
} | php | protected static function _finders() {
$self = static::_object();
return [
'all' => function($params, $next) {
return $next($params);
},
'first' => function($params, $next) {
$options =& $params['options'];
$options['limit'] = 1;
$data = $next($params);
if (isset($options['return']) && $options['return'] === 'array') {
$data = is_array($data) ? reset($data) : $data;
} else {
$data = is_object($data) ? $data->rewind() : $data;
}
return $data ?: null;
},
'list' => function($params, $next) use ($self) {
$result = [];
$meta = $self::meta();
$name = $meta['key'];
foreach ($next($params) as $entity) {
$key = $entity->{$name};
$result[is_scalar($key) ? $key : (string) $key] = $entity->title();
}
return $result;
},
'count' => function($params, $next) use ($self) {
$options = array_diff_key($params['options'], $self->_query);
if ($options && !isset($params['options']['conditions'])) {
$options = ['conditions' => $options];
} else {
$options = $params['options'];
}
$options += ['type' => 'read', 'model' => $self];
$query = $self::invokeMethod('_instance', ['query', $options]);
return $self::connection()->calculation('count', $query, $options);
}
];
} | [
"protected",
"static",
"function",
"_finders",
"(",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"return",
"[",
"'all'",
"=>",
"function",
"(",
"$",
"params",
",",
"$",
"next",
")",
"{",
"return",
"$",
"next",
"(",
"$",
"pa... | Returns an array with the default finders.
@see lithium\data\Model::_initialize()
@return array | [
"Returns",
"an",
"array",
"with",
"the",
"default",
"finders",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L748-L792 |
UnionOfRAD/lithium | data/Model.php | Model.query | public static function query($query = null) {
$self = static::_object();
if (!$query) {
return $self->_query;
}
$self->_query = $query + $self->_query;
} | php | public static function query($query = null) {
$self = static::_object();
if (!$query) {
return $self->_query;
}
$self->_query = $query + $self->_query;
} | [
"public",
"static",
"function",
"query",
"(",
"$",
"query",
"=",
"null",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"if",
"(",
"!",
"$",
"query",
")",
"{",
"return",
"$",
"self",
"->",
"_query",
";",
"}",
"$",
"self",
... | Gets or sets the default query for the model.
@param array $query Possible options are:
- `'conditions'`: The conditional query elements, e.g.
`'conditions' => ['published' => true]`
- `'fields'`: The fields that should be retrieved. When set to `null`, defaults to
all fields.
- `'order'`: The order in which the data will be returned, e.g. `'order' => 'ASC'`.
- `'limit'`: The maximum number of records to return.
- `'page'`: For pagination of data.
- `'with'`: An array of relationship names to be included in the query.
@return mixed Returns the query definition if querying, or `null` if setting. | [
"Gets",
"or",
"sets",
"the",
"default",
"query",
"for",
"the",
"model",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L808-L815 |
UnionOfRAD/lithium | data/Model.php | Model.meta | public static function meta($key = null, $value = null) {
$self = static::_object();
$isArray = is_array($key);
if ($value || $isArray) {
$value ? $self->_meta[$key] = $value : $self->_meta = $key + $self->_meta;
return;
}
return $self->_getMetaKey($isArray ? null : $key);
} | php | public static function meta($key = null, $value = null) {
$self = static::_object();
$isArray = is_array($key);
if ($value || $isArray) {
$value ? $self->_meta[$key] = $value : $self->_meta = $key + $self->_meta;
return;
}
return $self->_getMetaKey($isArray ? null : $key);
} | [
"public",
"static",
"function",
"meta",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"self",
"=",
"static",
"::",
"_object",
"(",
")",
";",
"$",
"isArray",
"=",
"is_array",
"(",
"$",
"key",
")",
";",
"if",
"(",
"... | Gets or sets Model's metadata.
@see lithium\data\Model::$_meta
@param string $key Model metadata key.
@param string $value Model metadata value.
@return mixed Metadata value for a given key. | [
"Gets",
"or",
"sets",
"Model",
"s",
"metadata",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L825-L834 |
UnionOfRAD/lithium | data/Model.php | Model._getMetaKey | protected function _getMetaKey($key = null) {
if (!$key) {
$all = array_keys($this->_initializers);
$call = [&$this, '_getMetaKey'];
return $all ? array_combine($all, array_map($call, $all)) + $this->_meta : $this->_meta;
}
if (isset($this->_meta[$key])) {
return $this->_meta[$key];
}
if (isset($this->_initializers[$key]) && $initializer = $this->_initializers[$key]) {
unset($this->_initializers[$key]);
return ($this->_meta[$key] = $initializer(get_called_class()));
}
} | php | protected function _getMetaKey($key = null) {
if (!$key) {
$all = array_keys($this->_initializers);
$call = [&$this, '_getMetaKey'];
return $all ? array_combine($all, array_map($call, $all)) + $this->_meta : $this->_meta;
}
if (isset($this->_meta[$key])) {
return $this->_meta[$key];
}
if (isset($this->_initializers[$key]) && $initializer = $this->_initializers[$key]) {
unset($this->_initializers[$key]);
return ($this->_meta[$key] = $initializer(get_called_class()));
}
} | [
"protected",
"function",
"_getMetaKey",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"key",
")",
"{",
"$",
"all",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"_initializers",
")",
";",
"$",
"call",
"=",
"[",
"&",
"$",
"this",
",",
... | Helper method used by `meta()` to generate and cache metadata values.
@param string $key The name of the meta value to return, or `null`, to return all values.
@return mixed Returns the value of the meta key specified by `$key`, or an array of all meta
values if `$key` is `null`. | [
"Helper",
"method",
"used",
"by",
"meta",
"()",
"to",
"generate",
"and",
"cache",
"metadata",
"values",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L843-L857 |
UnionOfRAD/lithium | data/Model.php | Model.key | public static function key($values = null) {
$key = static::meta('key');
if ($values === null) {
return $key;
}
$self = static::_object();
$entity = $self->_classes['entity'];
if (is_object($values) && is_string($key)) {
return static::_key($key, $values, $entity);
} elseif ($values instanceof $entity) {
$values = $values->to('array');
}
if (!is_array($values) && !is_array($key)) {
return [$key => $values];
}
$key = (array) $key;
$result = [];
foreach ($key as $value) {
if (!isset($values[$value])) {
return null;
}
$result[$value] = $values[$value];
}
return $result;
} | php | public static function key($values = null) {
$key = static::meta('key');
if ($values === null) {
return $key;
}
$self = static::_object();
$entity = $self->_classes['entity'];
if (is_object($values) && is_string($key)) {
return static::_key($key, $values, $entity);
} elseif ($values instanceof $entity) {
$values = $values->to('array');
}
if (!is_array($values) && !is_array($key)) {
return [$key => $values];
}
$key = (array) $key;
$result = [];
foreach ($key as $value) {
if (!isset($values[$value])) {
return null;
}
$result[$value] = $values[$value];
}
return $result;
} | [
"public",
"static",
"function",
"key",
"(",
"$",
"values",
"=",
"null",
")",
"{",
"$",
"key",
"=",
"static",
"::",
"meta",
"(",
"'key'",
")",
";",
"if",
"(",
"$",
"values",
"===",
"null",
")",
"{",
"return",
"$",
"key",
";",
"}",
"$",
"self",
"... | If no values supplied, returns the name of the `Model` key. If values
are supplied, returns the key value.
@param mixed $values An array of values or object with values. If `$values` is `null`,
the meta `'key'` of the model is returned.
@return mixed Key value. | [
"If",
"no",
"values",
"supplied",
"returns",
"the",
"name",
"of",
"the",
"Model",
"key",
".",
"If",
"values",
"are",
"supplied",
"returns",
"the",
"key",
"value",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L885-L913 |
UnionOfRAD/lithium | data/Model.php | Model._key | protected static function _key($key, $values, $entity) {
if (isset($values->$key)) {
return [$key => $values->$key];
} elseif (!$values instanceof $entity) {
return [$key => $values];
}
return null;
} | php | protected static function _key($key, $values, $entity) {
if (isset($values->$key)) {
return [$key => $values->$key];
} elseif (!$values instanceof $entity) {
return [$key => $values];
}
return null;
} | [
"protected",
"static",
"function",
"_key",
"(",
"$",
"key",
",",
"$",
"values",
",",
"$",
"entity",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"values",
"->",
"$",
"key",
")",
")",
"{",
"return",
"[",
"$",
"key",
"=>",
"$",
"values",
"->",
"$",
"k... | Helper for the `Model::key()` function
@see lithium\data\Model::key()
@param string $key The key
@param object $values Object with attributes.
@param string $entity The fully-namespaced entity class name.
@return mixed The key value array or `null` if the `$values` object has no attribute
named `$key` | [
"Helper",
"for",
"the",
"Model",
"::",
"key",
"()",
"function"
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L925-L932 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.