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
action/Request.php
Request._init
protected function _init() { parent::_init(); $mobile = [ 'iPhone', 'MIDP', 'AvantGo', 'BlackBerry', 'J2ME', 'Opera Mini', 'DoCoMo', 'NetFront', 'Nokia', 'PalmOS', 'PalmSource', 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'iPod', 'SonyEricsson', 'Symbian', 'UP\.Browser', 'Windows CE', 'Xiino', 'Android' ]; if (!empty($this->_config['detectors']['mobile'][1])) { $mobile = array_merge($mobile, (array) $this->_config['detectors']['mobile'][1]); } $this->_detectors['mobile'][1] = $mobile; $this->data = (array) $this->_config['data']; if (isset($this->data['_method'])) { $this->_computed['HTTP_X_HTTP_METHOD_OVERRIDE'] = strtoupper($this->data['_method']); unset($this->data['_method']); } $type = $this->type($this->_config['type'] ?: $this->env('CONTENT_TYPE')); $this->method = strtoupper($this->env('REQUEST_METHOD')); $hasBody = in_array($this->method, ['POST', 'PUT', 'PATCH']); if ($this->_config['drain'] && !$this->body && $hasBody && $type !== 'html') { $this->_stream = $this->_stream ?: fopen('php://input', 'r'); $this->body = stream_get_contents($this->_stream); fclose($this->_stream); } if (!$this->data && $this->body) { $this->data = $this->body(null, ['decode' => true, 'encode' => false]); } $this->body = $this->data; if ($this->_config['globals'] && !empty($_FILES)) { $this->data = Set::merge($this->data, $this->_parseFiles($_FILES)); } }
php
protected function _init() { parent::_init(); $mobile = [ 'iPhone', 'MIDP', 'AvantGo', 'BlackBerry', 'J2ME', 'Opera Mini', 'DoCoMo', 'NetFront', 'Nokia', 'PalmOS', 'PalmSource', 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'iPod', 'SonyEricsson', 'Symbian', 'UP\.Browser', 'Windows CE', 'Xiino', 'Android' ]; if (!empty($this->_config['detectors']['mobile'][1])) { $mobile = array_merge($mobile, (array) $this->_config['detectors']['mobile'][1]); } $this->_detectors['mobile'][1] = $mobile; $this->data = (array) $this->_config['data']; if (isset($this->data['_method'])) { $this->_computed['HTTP_X_HTTP_METHOD_OVERRIDE'] = strtoupper($this->data['_method']); unset($this->data['_method']); } $type = $this->type($this->_config['type'] ?: $this->env('CONTENT_TYPE')); $this->method = strtoupper($this->env('REQUEST_METHOD')); $hasBody = in_array($this->method, ['POST', 'PUT', 'PATCH']); if ($this->_config['drain'] && !$this->body && $hasBody && $type !== 'html') { $this->_stream = $this->_stream ?: fopen('php://input', 'r'); $this->body = stream_get_contents($this->_stream); fclose($this->_stream); } if (!$this->data && $this->body) { $this->data = $this->body(null, ['decode' => true, 'encode' => false]); } $this->body = $this->data; if ($this->_config['globals'] && !empty($_FILES)) { $this->data = Set::merge($this->data, $this->_parseFiles($_FILES)); } }
[ "protected", "function", "_init", "(", ")", "{", "parent", "::", "_init", "(", ")", ";", "$", "mobile", "=", "[", "'iPhone'", ",", "'MIDP'", ",", "'AvantGo'", ",", "'BlackBerry'", ",", "'J2ME'", ",", "'Opera Mini'", ",", "'DoCoMo'", ",", "'NetFront'", ",...
Initializes request object by setting up mobile detectors, determining method and populating the data property either by using i.e. form data or reading from STDIN in case binary data is streamed. Will merge any files posted in forms with parsed data. Note that only beginning with PHP 5.6 STDIN can be opened/read and closed more than once. @see lithium\action\Request::_parseFiles()
[ "Initializes", "request", "object", "by", "setting", "up", "mobile", "detectors", "determining", "method", "and", "populating", "the", "data", "property", "either", "by", "using", "i", ".", "e", ".", "form", "data", "or", "reading", "from", "STDIN", "in", "c...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L247-L283
UnionOfRAD/lithium
action/Request.php
Request.env
public function env($key) { if (array_key_exists($key, $this->_computed)) { return $this->_computed[$key]; } $val = null; if (!empty($this->_env[$key])) { $val = $this->_env[$key]; if ($key !== 'REMOTE_ADDR' && $key !== 'HTTPS' && $key !== 'REQUEST_METHOD') { return $this->_computed[$key] = $val; } } switch ($key) { case 'BASE': case 'base': $val = $this->_base($this->_config['base']); break; case 'HTTP_HOST': $val = 'localhost'; break; case 'SERVER_PROTOCOL': $val = 'HTTP/1.1'; break; case 'REQUEST_METHOD': if ($this->env('HTTP_X_HTTP_METHOD_OVERRIDE')) { $val = $this->env('HTTP_X_HTTP_METHOD_OVERRIDE'); } elseif (isset($this->_env['REQUEST_METHOD'])) { $val = $this->_env['REQUEST_METHOD']; } else { $val = 'GET'; } break; case 'CONTENT_TYPE': $val = 'text/html'; break; case 'PLATFORM': $envs = ['isapi' => 'IIS', 'cgi' => 'CGI', 'cgi-fcgi' => 'CGI']; $val = isset($envs[PHP_SAPI]) ? $envs[PHP_SAPI] : null; break; case 'REMOTE_ADDR': $https = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_PC_REMOTE_ADDR', 'HTTP_X_REAL_IP' ]; foreach ($https as $altKey) { if ($addr = $this->env($altKey)) { list($val) = explode(', ', $addr); break; } } break; case 'SCRIPT_NAME': if ($this->env('PLATFORM') === 'CGI') { return $this->env('SCRIPT_URL'); } $val = null; break; case 'HTTPS': if (isset($this->_env['SCRIPT_URI'])) { $val = strpos($this->_env['SCRIPT_URI'], 'https://') === 0; } elseif (isset($this->_env['HTTPS'])) { $val = (!empty($this->_env['HTTPS']) && $this->_env['HTTPS'] !== 'off'); } else { $val = false; } break; case 'SERVER_ADDR': if (empty($this->_env['SERVER_ADDR']) && !empty($this->_env['LOCAL_ADDR'])) { $val = $this->_env['LOCAL_ADDR']; } elseif (isset($this->_env['SERVER_ADDR'])) { $val = $this->_env['SERVER_ADDR']; } break; case 'SCRIPT_FILENAME': if ($this->env('PLATFORM') === 'IIS') { $val = str_replace('\\\\', '\\', $this->env('PATH_TRANSLATED')); } elseif (isset($this->_env['DOCUMENT_ROOT']) && isset($this->_env['PHP_SELF'])) { $val = $this->_env['DOCUMENT_ROOT'] . $this->_env['PHP_SELF']; } break; case 'DOCUMENT_ROOT': $fileName = $this->env('SCRIPT_FILENAME'); $offset = (!strpos($this->env('SCRIPT_NAME'), '.php')) ? 4 : 0; $offset = strlen($fileName) - (strlen($this->env('SCRIPT_NAME')) + $offset); $val = substr($fileName, 0, $offset); break; case 'PHP_SELF': $val = '/'; break; case 'CGI': case 'CGI_MODE': $val = $this->env('PLATFORM') === 'CGI'; break; case 'HTTP_BASE': $val = preg_replace('/^([^.])*/i', null, $this->env('HTTP_HOST')); break; case 'PHP_AUTH_USER': case 'PHP_AUTH_PW': case 'PHP_AUTH_DIGEST': if (!$header = $this->env('HTTP_AUTHORIZATION')) { if (!$header = $this->env('REDIRECT_HTTP_AUTHORIZATION')) { return $this->_computed[$key] = $val; } } if (stripos($header, 'basic') === 0) { $decoded = base64_decode(substr($header, strlen('basic '))); if (strpos($decoded, ':') !== false) { list($user, $password) = explode(':', $decoded, 2); $this->_computed['PHP_AUTH_USER'] = $user; $this->_computed['PHP_AUTH_PW'] = $password; return $this->_computed[$key]; } } elseif (stripos($header, 'digest') === 0) { return $this->_computed[$key] = substr($header, strlen('digest ')); } default: $val = array_key_exists($key, $this->_env) ? $this->_env[$key] : $val; break; } return $this->_computed[$key] = $val; }
php
public function env($key) { if (array_key_exists($key, $this->_computed)) { return $this->_computed[$key]; } $val = null; if (!empty($this->_env[$key])) { $val = $this->_env[$key]; if ($key !== 'REMOTE_ADDR' && $key !== 'HTTPS' && $key !== 'REQUEST_METHOD') { return $this->_computed[$key] = $val; } } switch ($key) { case 'BASE': case 'base': $val = $this->_base($this->_config['base']); break; case 'HTTP_HOST': $val = 'localhost'; break; case 'SERVER_PROTOCOL': $val = 'HTTP/1.1'; break; case 'REQUEST_METHOD': if ($this->env('HTTP_X_HTTP_METHOD_OVERRIDE')) { $val = $this->env('HTTP_X_HTTP_METHOD_OVERRIDE'); } elseif (isset($this->_env['REQUEST_METHOD'])) { $val = $this->_env['REQUEST_METHOD']; } else { $val = 'GET'; } break; case 'CONTENT_TYPE': $val = 'text/html'; break; case 'PLATFORM': $envs = ['isapi' => 'IIS', 'cgi' => 'CGI', 'cgi-fcgi' => 'CGI']; $val = isset($envs[PHP_SAPI]) ? $envs[PHP_SAPI] : null; break; case 'REMOTE_ADDR': $https = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_PC_REMOTE_ADDR', 'HTTP_X_REAL_IP' ]; foreach ($https as $altKey) { if ($addr = $this->env($altKey)) { list($val) = explode(', ', $addr); break; } } break; case 'SCRIPT_NAME': if ($this->env('PLATFORM') === 'CGI') { return $this->env('SCRIPT_URL'); } $val = null; break; case 'HTTPS': if (isset($this->_env['SCRIPT_URI'])) { $val = strpos($this->_env['SCRIPT_URI'], 'https://') === 0; } elseif (isset($this->_env['HTTPS'])) { $val = (!empty($this->_env['HTTPS']) && $this->_env['HTTPS'] !== 'off'); } else { $val = false; } break; case 'SERVER_ADDR': if (empty($this->_env['SERVER_ADDR']) && !empty($this->_env['LOCAL_ADDR'])) { $val = $this->_env['LOCAL_ADDR']; } elseif (isset($this->_env['SERVER_ADDR'])) { $val = $this->_env['SERVER_ADDR']; } break; case 'SCRIPT_FILENAME': if ($this->env('PLATFORM') === 'IIS') { $val = str_replace('\\\\', '\\', $this->env('PATH_TRANSLATED')); } elseif (isset($this->_env['DOCUMENT_ROOT']) && isset($this->_env['PHP_SELF'])) { $val = $this->_env['DOCUMENT_ROOT'] . $this->_env['PHP_SELF']; } break; case 'DOCUMENT_ROOT': $fileName = $this->env('SCRIPT_FILENAME'); $offset = (!strpos($this->env('SCRIPT_NAME'), '.php')) ? 4 : 0; $offset = strlen($fileName) - (strlen($this->env('SCRIPT_NAME')) + $offset); $val = substr($fileName, 0, $offset); break; case 'PHP_SELF': $val = '/'; break; case 'CGI': case 'CGI_MODE': $val = $this->env('PLATFORM') === 'CGI'; break; case 'HTTP_BASE': $val = preg_replace('/^([^.])*/i', null, $this->env('HTTP_HOST')); break; case 'PHP_AUTH_USER': case 'PHP_AUTH_PW': case 'PHP_AUTH_DIGEST': if (!$header = $this->env('HTTP_AUTHORIZATION')) { if (!$header = $this->env('REDIRECT_HTTP_AUTHORIZATION')) { return $this->_computed[$key] = $val; } } if (stripos($header, 'basic') === 0) { $decoded = base64_decode(substr($header, strlen('basic '))); if (strpos($decoded, ':') !== false) { list($user, $password) = explode(':', $decoded, 2); $this->_computed['PHP_AUTH_USER'] = $user; $this->_computed['PHP_AUTH_PW'] = $password; return $this->_computed[$key]; } } elseif (stripos($header, 'digest') === 0) { return $this->_computed[$key] = substr($header, strlen('digest ')); } default: $val = array_key_exists($key, $this->_env) ? $this->_env[$key] : $val; break; } return $this->_computed[$key] = $val; }
[ "public", "function", "env", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_computed", ")", ")", "{", "return", "$", "this", "->", "_computed", "[", "$", "key", "]", ";", "}", "$", "val", "=",...
Queries PHP's environment settings, and provides an abstraction for standardizing expected environment values across varying platforms, as well as specify custom environment flags. Defines an artificial `'PLATFORM'` environment variable as either `'IIS'`, `'CGI'` or `null` to allow checking for the SAPI in a normalized way. @param string $key The environment variable required. @return string The requested variables value. @todo Refactor to lazy-load environment settings
[ "Queries", "PHP", "s", "environment", "settings", "and", "provides", "an", "abstraction", "for", "standardizing", "expected", "environment", "values", "across", "varying", "platforms", "as", "well", "as", "specify", "custom", "environment", "flags", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L323-L446
UnionOfRAD/lithium
action/Request.php
Request.accepts
public function accepts($type = null) { $media = $this->_classes['media']; if ($type === true) { return $this->_accept ?: ($this->_accept = $this->_parseAccept()); } if ($type) { return ($media::negotiate($this) ?: 'html') === $type; } if (isset($this->params['type'])) { return $this->params['type']; } return $media::negotiate($this) ?: 'html'; }
php
public function accepts($type = null) { $media = $this->_classes['media']; if ($type === true) { return $this->_accept ?: ($this->_accept = $this->_parseAccept()); } if ($type) { return ($media::negotiate($this) ?: 'html') === $type; } if (isset($this->params['type'])) { return $this->params['type']; } return $media::negotiate($this) ?: 'html'; }
[ "public", "function", "accepts", "(", "$", "type", "=", "null", ")", "{", "$", "media", "=", "$", "this", "->", "_classes", "[", "'media'", "]", ";", "if", "(", "$", "type", "===", "true", ")", "{", "return", "$", "this", "->", "_accept", "?", ":...
Returns information about the type of content that the client is requesting. This method may work different then you might think. This is a _convenience_ method working exclusively with short type names it knows about. Only those types will be matched. You can tell this method about more types via `Media::type()`. Note: In case negotiation fails, `'html'` is used as a fallback type. @see lithium\net\http\Media::negotiate() @param boolean|string $type Optionally a type name i.e. `'json'` or `true`. 1. If not specified, returns the media type name that the client prefers, using a potentially set `type` param, then content negotiation and that fails, ultimately falling back and returning the string `'html'`. 2. If a media type name (string) is passed, returns `true` or `false`, indicating whether or not that type is accepted by the client at all. 3. If `true`, returns the raw content types from the `Accept` header, parsed into an array and sorted by client preference. @return string|boolean|array Returns a type name (i.e. 'json'`) or a boolean or an array, depending on the value of `$type`.
[ "Returns", "information", "about", "the", "type", "of", "content", "that", "the", "client", "is", "requesting", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L469-L482
UnionOfRAD/lithium
action/Request.php
Request._parseAccept
protected function _parseAccept() { $accept = $this->env('HTTP_ACCEPT'); $accept = (preg_match('/[a-z,-]/i', $accept)) ? explode(',', $accept) : ['text/html']; foreach (array_reverse($accept) as $i => $type) { unset($accept[$i]); list($type, $q) = (explode(';q=', $type, 2) + [$type, 1.0 + $i / 100]); $accept[$type] = ($type === '*/*') ? 0.1 : floatval($q); } arsort($accept, SORT_NUMERIC); if (isset($accept['application/xhtml+xml']) && $accept['application/xhtml+xml'] >= 1) { unset($accept['application/xml']); } $media = $this->_classes['media']; if (isset($this->params['type']) && ($handler = $media::type($this->params['type']))) { if (isset($handler['content'])) { $type = (array) $handler['content']; $accept = [current($type) => 1] + $accept; } } return array_keys($accept); }
php
protected function _parseAccept() { $accept = $this->env('HTTP_ACCEPT'); $accept = (preg_match('/[a-z,-]/i', $accept)) ? explode(',', $accept) : ['text/html']; foreach (array_reverse($accept) as $i => $type) { unset($accept[$i]); list($type, $q) = (explode(';q=', $type, 2) + [$type, 1.0 + $i / 100]); $accept[$type] = ($type === '*/*') ? 0.1 : floatval($q); } arsort($accept, SORT_NUMERIC); if (isset($accept['application/xhtml+xml']) && $accept['application/xhtml+xml'] >= 1) { unset($accept['application/xml']); } $media = $this->_classes['media']; if (isset($this->params['type']) && ($handler = $media::type($this->params['type']))) { if (isset($handler['content'])) { $type = (array) $handler['content']; $accept = [current($type) => 1] + $accept; } } return array_keys($accept); }
[ "protected", "function", "_parseAccept", "(", ")", "{", "$", "accept", "=", "$", "this", "->", "env", "(", "'HTTP_ACCEPT'", ")", ";", "$", "accept", "=", "(", "preg_match", "(", "'/[a-z,-]/i'", ",", "$", "accept", ")", ")", "?", "explode", "(", "','", ...
Parses the `HTTP_ACCEPT` information the requesting client sends, and converts that data to an array for consumption by the rest of the framework. @return array All the types of content the client can accept.
[ "Parses", "the", "HTTP_ACCEPT", "information", "the", "requesting", "client", "sends", "and", "converts", "that", "data", "to", "an", "array", "for", "consumption", "by", "the", "rest", "of", "the", "framework", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L490-L513
UnionOfRAD/lithium
action/Request.php
Request.get
public function get($key) { list($var, $key) = explode(':', $key); switch (true) { case in_array($var, ['params', 'data', 'query']): return isset($this->{$var}[$key]) ? $this->{$var}[$key] : null; case ($var === 'env'): return $this->env(strtoupper($key)); case ($var === 'http' && $key === 'method'): return $this->env('REQUEST_METHOD'); case ($var === 'http'): return $this->env('HTTP_' . strtoupper($key)); } }
php
public function get($key) { list($var, $key) = explode(':', $key); switch (true) { case in_array($var, ['params', 'data', 'query']): return isset($this->{$var}[$key]) ? $this->{$var}[$key] : null; case ($var === 'env'): return $this->env(strtoupper($key)); case ($var === 'http' && $key === 'method'): return $this->env('REQUEST_METHOD'); case ($var === 'http'): return $this->env('HTTP_' . strtoupper($key)); } }
[ "public", "function", "get", "(", "$", "key", ")", "{", "list", "(", "$", "var", ",", "$", "key", ")", "=", "explode", "(", "':'", ",", "$", "key", ")", ";", "switch", "(", "true", ")", "{", "case", "in_array", "(", "$", "var", ",", "[", "'pa...
This method allows easy extraction of any request data using a prefixed key syntax. By passing keys in the form of `'prefix:key'`, it is possible to query different information of various different types, including GET and POST data, and server environment variables. The full list of prefixes is as follows: - `'data'`: Retrieves values from POST data. - `'params'`: Retrieves query parameters returned from the routing system. - `'query'`: Retrieves values from GET data. - `'env'`: Retrieves values from the server or environment, such as `'env:https'`, or custom environment values, like `'env:base'`. See the `env()` method for more info. - `'http'`: Retrieves header values (i.e. `'http:accept'`), or the HTTP request method (i.e. `'http:method'`). This method is used in several different places in the framework in order to provide the ability to act conditionally on different aspects of the request. See `Media::type()` (the section on content negotiation) and the routing system for more information. _Note_: All keys should be _lower-cased_, even when getting HTTP headers. @see lithium\action\Request::env() @see lithium\net\http\Media::type() @see lithium\net\http\Router @param string $key A prefixed key indicating what part of the request data the requested value should come from, and the name of the value to retrieve, in lower case. @return string Returns the value of a GET, POST, routing or environment variable, or an HTTP header or method name.
[ "This", "method", "allows", "easy", "extraction", "of", "any", "request", "data", "using", "a", "prefixed", "key", "syntax", ".", "By", "passing", "keys", "in", "the", "form", "of", "prefix", ":", "key", "it", "is", "possible", "to", "query", "different", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L543-L556
UnionOfRAD/lithium
action/Request.php
Request.is
public function is($flag) { $media = $this->_classes['media']; if (!isset($this->_detectors[$flag])) { if (!in_array($flag, $media::types())) { return false; } return $this->type() === $flag; } $detector = $this->_detectors[$flag]; if (!is_array($detector) && is_callable($detector)) { return $detector($this); } if (!is_array($detector)) { return (boolean) $this->env($detector); } list($key, $check) = $detector + ['', '']; if (is_array($check)) { $check = '/' . join('|', $check) . '/i'; } if (Validator::isRegex($check)) { return (boolean) preg_match($check, $this->env($key)); } return ($this->env($key) === $check); }
php
public function is($flag) { $media = $this->_classes['media']; if (!isset($this->_detectors[$flag])) { if (!in_array($flag, $media::types())) { return false; } return $this->type() === $flag; } $detector = $this->_detectors[$flag]; if (!is_array($detector) && is_callable($detector)) { return $detector($this); } if (!is_array($detector)) { return (boolean) $this->env($detector); } list($key, $check) = $detector + ['', '']; if (is_array($check)) { $check = '/' . join('|', $check) . '/i'; } if (Validator::isRegex($check)) { return (boolean) preg_match($check, $this->env($key)); } return ($this->env($key) === $check); }
[ "public", "function", "is", "(", "$", "flag", ")", "{", "$", "media", "=", "$", "this", "->", "_classes", "[", "'media'", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "_detectors", "[", "$", "flag", "]", ")", ")", "{", "if", "(", ...
Provides a simple syntax for making assertions about the properties of a request. By default, the `Request` object is configured with several different types of assertions, which are individually known as _detectors_. Detectors are invoked by calling the `is()` and passing the name of the detector flag, i.e. `$request->is('<name>')`, which returns `true` or `false`, depending on whether or not the the properties (usually headers or data) contained in the request match the detector. The default detectors include the following: - `'mobile'`: Uses a regular expression to match common mobile browser user agents. - `'ajax'`: Checks to see if the `X-Requested-With` header is present, and matches the value `'XMLHttpRequest'`. - `'flash'`: Checks to see if the user agent is `'Shockwave Flash'`. - `'ssl'`: Verifies that the request is SSL-secured. - `'get'` / `'post'` / `'put'` / `'delete'` / `'head'` / `'options'`: Checks that the HTTP request method matches the one specified. In addition to the above, this method also accepts media type names (see `Media::type()`) to make assertions against the format of the request body (for POST or PUT requests), i.e. `$request->is('json')`. This will return `true` if the client has made a POST request with JSON data. For information about adding custom detectors or overriding the ones in the core, see the `detect()` method. While these detectors are useful in controllers or other similar contexts, they're also useful when performing _content negotiation_, which is the process of modifying the response format to suit the client (see the `'conditions'` field of the `$options` parameter in `Media::type()`). @see lithium\action\Request::detect() @see lithium\net\http\Media::type() @param string $flag The name of the flag to check, which should be the name of a valid detector (that is either built-in or defined with `detect()`). @return boolean Returns `true` if the detector check succeeds (see the details for the built-in detectors above, or `detect()`), otherwise `false`.
[ "Provides", "a", "simple", "syntax", "for", "making", "assertions", "about", "the", "properties", "of", "a", "request", ".", "By", "default", "the", "Request", "object", "is", "configured", "with", "several", "different", "types", "of", "assertions", "which", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L594-L620
UnionOfRAD/lithium
action/Request.php
Request.type
public function type($type = null) { if (!$type && !empty($this->params['type'])) { $type = $this->params['type']; } return parent::type($type); }
php
public function type($type = null) { if (!$type && !empty($this->params['type'])) { $type = $this->params['type']; } return parent::type($type); }
[ "public", "function", "type", "(", "$", "type", "=", "null", ")", "{", "if", "(", "!", "$", "type", "&&", "!", "empty", "(", "$", "this", "->", "params", "[", "'type'", "]", ")", ")", "{", "$", "type", "=", "$", "this", "->", "params", "[", "...
Sets/Gets the content type. If `'type'` is null, the method will attempt to determine the type from the params, then from the environment setting @param string $type a full content type i.e. `'application/json'` or simple name `'json'` @return string A simple content type name, i.e. `'html'`, `'xml'`, `'json'`, etc., depending on the content type of the request.
[ "Sets", "/", "Gets", "the", "content", "type", ".", "If", "type", "is", "null", "the", "method", "will", "attempt", "to", "determine", "the", "type", "from", "the", "params", "then", "from", "the", "environment", "setting" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L630-L635
UnionOfRAD/lithium
action/Request.php
Request.detect
public function detect($flag, $detector = null) { if (is_array($flag)) { $this->_detectors = $flag + $this->_detectors; } else { $this->_detectors[$flag] = $detector; } }
php
public function detect($flag, $detector = null) { if (is_array($flag)) { $this->_detectors = $flag + $this->_detectors; } else { $this->_detectors[$flag] = $detector; } }
[ "public", "function", "detect", "(", "$", "flag", ",", "$", "detector", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "flag", ")", ")", "{", "$", "this", "->", "_detectors", "=", "$", "flag", "+", "$", "this", "->", "_detectors", ";", "...
Creates a _detector_ used with `Request::is()`. A detector is a boolean check that is created to determine something about a request. A detector check can be either an exact string match or a regular expression match against a header or environment variable. A detector check can also be a closure that accepts the `Request` object instance as a parameter. For example, to detect whether a request is from an iPhone, you can do the following: ``` embed:lithium\tests\cases\action\RequestTest::testDetect(11-12) ``` @see lithium\action\Request::is() @param string $flag The name of the detector check. Used in subsequent calls to `Request::is()`. @param mixed $detector Detectors can be specified in four different ways: - The name of an HTTP header or environment variable. If a string, calling the detector will check that the header or environment variable exists and is set to a non-empty value. - A two-element array containing a header/environment variable name, and a value to match against. The second element of the array must be an exact match to the header or variable value. - A two-element array containing a header/environment variable name, and a regular expression that matches against the value, as in the example above. - A closure which accepts an instance of the `Request` object and returns a boolean value. @return void
[ "Creates", "a", "_detector_", "used", "with", "Request", "::", "is", "()", ".", "A", "detector", "is", "a", "boolean", "check", "that", "is", "created", "to", "determine", "something", "about", "a", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L663-L669
UnionOfRAD/lithium
action/Request.php
Request.referer
public function referer($default = null, $local = false) { if ($ref = $this->env('HTTP_REFERER')) { if (!$local) { return $ref; } $url = parse_url($ref) + ['path' => '']; if (empty($url['host']) || $url['host'] === $this->env('HTTP_HOST')) { $ref = $url['path']; if (!empty($url['query'])) { $ref .= '?' . $url['query']; } if (!empty($url['fragment'])) { $ref .= '#' . $url['fragment']; } return $ref; } } return ($default !== null) ? $default : '/'; }
php
public function referer($default = null, $local = false) { if ($ref = $this->env('HTTP_REFERER')) { if (!$local) { return $ref; } $url = parse_url($ref) + ['path' => '']; if (empty($url['host']) || $url['host'] === $this->env('HTTP_HOST')) { $ref = $url['path']; if (!empty($url['query'])) { $ref .= '?' . $url['query']; } if (!empty($url['fragment'])) { $ref .= '#' . $url['fragment']; } return $ref; } } return ($default !== null) ? $default : '/'; }
[ "public", "function", "referer", "(", "$", "default", "=", "null", ",", "$", "local", "=", "false", ")", "{", "if", "(", "$", "ref", "=", "$", "this", "->", "env", "(", "'HTTP_REFERER'", ")", ")", "{", "if", "(", "!", "$", "local", ")", "{", "r...
Gets the referring URL of this request. @param string $default Default URL to use if HTTP_REFERER cannot be read from headers. @param boolean $local If true, restrict referring URLs to local server. @return string Referring URL.
[ "Gets", "the", "referring", "URL", "of", "this", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L678-L696
UnionOfRAD/lithium
action/Request.php
Request.to
public function to($format, array $options = []) { $defaults = [ 'path' => $this->env('base') . '/' . $this->url ]; return parent::to($format, $options + $defaults); }
php
public function to($format, array $options = []) { $defaults = [ 'path' => $this->env('base') . '/' . $this->url ]; return parent::to($format, $options + $defaults); }
[ "public", "function", "to", "(", "$", "format", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'path'", "=>", "$", "this", "->", "env", "(", "'base'", ")", ".", "'/'", ".", "$", "this", "->", "url", "]", ";",...
Overrides `lithium\net\http\Request::to()` to provide the correct options for generating URLs. For information about this method, see the parent implementation. @see lithium\net\http\Request::to() @param string $format The format to convert to. @param array $options Override options. @return mixed The return value type depends on `$format`.
[ "Overrides", "lithium", "\\", "net", "\\", "http", "\\", "Request", "::", "to", "()", "to", "provide", "the", "correct", "options", "for", "generating", "URLs", ".", "For", "information", "about", "this", "method", "see", "the", "parent", "implementation", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L707-L712
UnionOfRAD/lithium
action/Request.php
Request.locale
public function locale($locale = null) { if ($locale) { $this->_locale = $locale; } if ($this->_locale) { return $this->_locale; } if (isset($this->params['locale'])) { return $this->params['locale']; } }
php
public function locale($locale = null) { if ($locale) { $this->_locale = $locale; } if ($this->_locale) { return $this->_locale; } if (isset($this->params['locale'])) { return $this->params['locale']; } }
[ "public", "function", "locale", "(", "$", "locale", "=", "null", ")", "{", "if", "(", "$", "locale", ")", "{", "$", "this", "->", "_locale", "=", "$", "locale", ";", "}", "if", "(", "$", "this", "->", "_locale", ")", "{", "return", "$", "this", ...
Sets or returns the current locale string. For more information, see "[Globalization](http://li3.me/docs/book/manual/1.x/common-tasks/globalization)" in the manual. @param string $locale An optional locale string like `'en'`, `'en_US'` or `'de_DE'`. If specified, will overwrite the existing locale. @return string Returns the currently set locale string.
[ "Sets", "or", "returns", "the", "current", "locale", "string", ".", "For", "more", "information", "see", "[", "Globalization", "]", "(", "http", ":", "//", "li3", ".", "me", "/", "docs", "/", "book", "/", "manual", "/", "1", ".", "x", "/", "common", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L722-L732
UnionOfRAD/lithium
action/Request.php
Request._base
protected function _base($base = null) { if ($base === null) { $base = preg_replace('/[^\/]+$/', '', $this->env('PHP_SELF')); } $base = trim(str_replace(["/app/webroot", '/webroot'], '', $base), '/'); return $base ? '/' . $base : ''; }
php
protected function _base($base = null) { if ($base === null) { $base = preg_replace('/[^\/]+$/', '', $this->env('PHP_SELF')); } $base = trim(str_replace(["/app/webroot", '/webroot'], '', $base), '/'); return $base ? '/' . $base : ''; }
[ "protected", "function", "_base", "(", "$", "base", "=", "null", ")", "{", "if", "(", "$", "base", "===", "null", ")", "{", "$", "base", "=", "preg_replace", "(", "'/[^\\/]+$/'", ",", "''", ",", "$", "this", "->", "env", "(", "'PHP_SELF'", ")", ")"...
Find the base path of the current request. @param string $base The base path. If `null`, `'PHP_SELF'` will be used instead. @return string
[ "Find", "the", "base", "path", "of", "the", "current", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L740-L746
UnionOfRAD/lithium
action/Request.php
Request._url
protected function _url($url = null) { if ($url !== null) { return '/' . trim($url, '/'); } elseif ($uri = $this->env('REQUEST_URI')) { list($uri) = explode('?', $uri, 2); $base = '/^' . preg_quote($this->_base, '/') . '/'; return '/' . trim(preg_replace($base, '', $uri), '/') ?: '/'; } return '/'; }
php
protected function _url($url = null) { if ($url !== null) { return '/' . trim($url, '/'); } elseif ($uri = $this->env('REQUEST_URI')) { list($uri) = explode('?', $uri, 2); $base = '/^' . preg_quote($this->_base, '/') . '/'; return '/' . trim(preg_replace($base, '', $uri), '/') ?: '/'; } return '/'; }
[ "protected", "function", "_url", "(", "$", "url", "=", "null", ")", "{", "if", "(", "$", "url", "!==", "null", ")", "{", "return", "'/'", ".", "trim", "(", "$", "url", ",", "'/'", ")", ";", "}", "elseif", "(", "$", "uri", "=", "$", "this", "-...
Extract the url from `REQUEST_URI` && `PHP_SELF` environment variables. @param string The base url If `null`, environment variables will be used instead. @return string
[ "Extract", "the", "url", "from", "REQUEST_URI", "&&", "PHP_SELF", "environment", "variables", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L754-L763
UnionOfRAD/lithium
action/Request.php
Request._parseFiles
protected function _parseFiles($data) { $result = []; $normalize = function($key, $value) use ($result, &$normalize){ foreach ($value as $param => $content) { foreach ($content as $num => $val) { if (is_numeric($num)) { $result[$key][$num][$param] = $val; continue; } if (is_array($val)) { foreach ($val as $next => $one) { $result[$key][$num][$next][$param] = $one; } continue; } $result[$key][$num][$param] = $val; } } return $result; }; foreach ($data as $key => $value) { if (isset($value['name'])) { if (is_string($value['name'])) { $result[$key] = $value; continue; } if (is_array($value['name'])) { $result += $normalize($key, $value); } } } return $result; }
php
protected function _parseFiles($data) { $result = []; $normalize = function($key, $value) use ($result, &$normalize){ foreach ($value as $param => $content) { foreach ($content as $num => $val) { if (is_numeric($num)) { $result[$key][$num][$param] = $val; continue; } if (is_array($val)) { foreach ($val as $next => $one) { $result[$key][$num][$next][$param] = $one; } continue; } $result[$key][$num][$param] = $val; } } return $result; }; foreach ($data as $key => $value) { if (isset($value['name'])) { if (is_string($value['name'])) { $result[$key] = $value; continue; } if (is_array($value['name'])) { $result += $normalize($key, $value); } } } return $result; }
[ "protected", "function", "_parseFiles", "(", "$", "data", ")", "{", "$", "result", "=", "[", "]", ";", "$", "normalize", "=", "function", "(", "$", "key", ",", "$", "value", ")", "use", "(", "$", "result", ",", "&", "$", "normalize", ")", "{", "f...
Normalizes the data from the `$_FILES` superglobal. @param array $data Data as formatted in the `$_FILES` superglobal. @return array Normalized data.
[ "Normalizes", "the", "data", "from", "the", "$_FILES", "superglobal", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/action/Request.php#L771-L804
UnionOfRAD/lithium
template/helper/Security.php
Security.requestToken
public function requestToken(array $options = []) { $defaults = ['name' => 'security.token', 'id' => false]; $options += $defaults; $requestToken = $this->_classes['requestToken']; $flags = array_intersect_key($this->_config, ['sessionKey' => '', 'salt' => '']); $value = $requestToken::key($flags); $name = $options['name']; unset($options['name']); return $this->_context->form->hidden($name, compact('value') + $options); }
php
public function requestToken(array $options = []) { $defaults = ['name' => 'security.token', 'id' => false]; $options += $defaults; $requestToken = $this->_classes['requestToken']; $flags = array_intersect_key($this->_config, ['sessionKey' => '', 'salt' => '']); $value = $requestToken::key($flags); $name = $options['name']; unset($options['name']); return $this->_context->form->hidden($name, compact('value') + $options); }
[ "public", "function", "requestToken", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'name'", "=>", "'security.token'", ",", "'id'", "=>", "false", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$", "requestT...
Generates a request key used to protect your forms against CSRF attacks. See the `RequestToken` class for examples and proper usage. @see lithium\security\validation\RequestToken @param array $options Options used as HTML when generating the field. @return string Returns a hidden `<input />` field containing a request-specific CSRF token key.
[ "Generates", "a", "request", "key", "used", "to", "protect", "your", "forms", "against", "CSRF", "attacks", ".", "See", "the", "RequestToken", "class", "for", "examples", "and", "proper", "usage", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Security.php#L51-L62
UnionOfRAD/lithium
template/helper/Security.php
Security.sign
public function sign($form = null) { $form = $form ?: $this->_context->form; if (isset($state[spl_object_hash($form)])) { return; } Filters::apply($form, 'create', function($params, $next) use ($form) { $this->_state[spl_object_hash($form)] = [ 'fields' => [], 'locked' => [], 'excluded' => [] ]; return $next($params); }); Filters::apply($form, 'end', function($params, $next) use ($form) { $id = spl_object_hash($form); if (!$this->_state[$id]) { return $next($params); } $formSignature = $this->_classes['formSignature']; $value = $formSignature::key($this->_state[$id]); echo $form->hidden('security.signature', compact('value')); $this->_state[$id] = []; return $next($params); }); Filters::apply($form, '_defaults', function($params, $next) use ($form) { $defaults = [ 'locked' => ($params['method'] === 'hidden' && $params['name'] !== '_method'), 'exclude' => $params['name'] === '_method' ]; $options = $params['options']; $options += $defaults; $params['options'] = array_diff_key($options, $defaults); $result = $next($params); if ($params['method'] === 'label') { return $result; } $value = isset($params['options']['value']) ? $params['options']['value'] : ""; $type = [ $options['exclude'] => 'excluded', !$options['exclude'] => 'fields', $options['locked'] => 'locked' ]; if (!$name = preg_replace('/(\.\d+)+$/', '', $params['name'])) { return $result; } $this->_state[spl_object_hash($form)][$type[true]][$name] = $value; return $result; }); }
php
public function sign($form = null) { $form = $form ?: $this->_context->form; if (isset($state[spl_object_hash($form)])) { return; } Filters::apply($form, 'create', function($params, $next) use ($form) { $this->_state[spl_object_hash($form)] = [ 'fields' => [], 'locked' => [], 'excluded' => [] ]; return $next($params); }); Filters::apply($form, 'end', function($params, $next) use ($form) { $id = spl_object_hash($form); if (!$this->_state[$id]) { return $next($params); } $formSignature = $this->_classes['formSignature']; $value = $formSignature::key($this->_state[$id]); echo $form->hidden('security.signature', compact('value')); $this->_state[$id] = []; return $next($params); }); Filters::apply($form, '_defaults', function($params, $next) use ($form) { $defaults = [ 'locked' => ($params['method'] === 'hidden' && $params['name'] !== '_method'), 'exclude' => $params['name'] === '_method' ]; $options = $params['options']; $options += $defaults; $params['options'] = array_diff_key($options, $defaults); $result = $next($params); if ($params['method'] === 'label') { return $result; } $value = isset($params['options']['value']) ? $params['options']['value'] : ""; $type = [ $options['exclude'] => 'excluded', !$options['exclude'] => 'fields', $options['locked'] => 'locked' ]; if (!$name = preg_replace('/(\.\d+)+$/', '', $params['name'])) { return $result; } $this->_state[spl_object_hash($form)][$type[true]][$name] = $value; return $result; }); }
[ "public", "function", "sign", "(", "$", "form", "=", "null", ")", "{", "$", "form", "=", "$", "form", "?", ":", "$", "this", "->", "_context", "->", "form", ";", "if", "(", "isset", "(", "$", "state", "[", "spl_object_hash", "(", "$", "form", ")"...
Binds the `Security` helper to the `Form` helper to create a signature used to secure form fields against tampering. First `FormSignature` must be provided with a secret unique to your app. This is best done in the bootstrap process. The secret key should be a random lengthy string. ```php use lithium\security\validation\FormSignature; FormSignature::config(['secret' => 'a long secret key']); ``` In the view call the `sign()` method before creating the form. ```php <?php $this->security->sign(); ?> <?=$this->form->create(...); ?> // Form fields... <?=$this->form->end(); ?> ``` In the corresponding controller action verify the signature. ```php if ($this->request->is('post') && !FormSignature::check($this->request)) { // The key didn't match, meaning the request has been tampered with. } ``` Calling this method before a form is created adds two additional options to the `$options` parameter in all form inputs: - `'locked'` _boolean_: If `true`, _locks_ the value specified in the field when the field is generated, such that tampering with the value will invalidate the signature. Defaults to `true` for hidden fields, and `false` for all other form inputs. - `'exclude'` _boolean_: If `true`, this field and all subfields of the same name will be excluded from the signature calculation. This is useful in situations where fields may be added dynamically on the client side. Defaults to `false`. @see lithium\template\helper\Form @see lithium\security\validation\FormSignature @param object $form Optional. Allows specifying an instance of the `Form` helper manually. @return void
[ "Binds", "the", "Security", "helper", "to", "the", "Form", "helper", "to", "create", "a", "signature", "used", "to", "secure", "form", "fields", "against", "tampering", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Security.php#L106-L164
UnionOfRAD/lithium
data/source/database/adapter/pdo/Result.php
Result._fetch
protected function _fetch() { if (!$this->_resource instanceof PDOStatement) { $this->close(); return false; } try { if ($result = $this->_resource->fetch(PDO::FETCH_NUM)) { return [$this->_iterator++, $result]; } } catch (PDOException $e) { $this->close(); return false; } return null; }
php
protected function _fetch() { if (!$this->_resource instanceof PDOStatement) { $this->close(); return false; } try { if ($result = $this->_resource->fetch(PDO::FETCH_NUM)) { return [$this->_iterator++, $result]; } } catch (PDOException $e) { $this->close(); return false; } return null; }
[ "protected", "function", "_fetch", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_resource", "instanceof", "PDOStatement", ")", "{", "$", "this", "->", "close", "(", ")", ";", "return", "false", ";", "}", "try", "{", "if", "(", "$", "result", ...
Fetches the next result from the resource. @return array|boolean|null Returns a key/value pair for the next result, `null` if there is none, `false` if something bad happened.
[ "Fetches", "the", "next", "result", "from", "the", "resource", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/database/adapter/pdo/Result.php#L31-L45
UnionOfRAD/lithium
net/http/Service.php
Service._init
protected function _init() { $config = ['classes' => $this->_classes] + $this->_config; try { $this->connection = Libraries::instance('socket', $config['socket'], $config); } catch(ClassNotFoundException $e) { $this->connection = null; } $this->_responseTypes += [ 'headers' => function($response) { return $response->headers; }, 'body' => function($response) { return $response->body(); }, 'code' => function($response) { return $response->status['code']; } ]; }
php
protected function _init() { $config = ['classes' => $this->_classes] + $this->_config; try { $this->connection = Libraries::instance('socket', $config['socket'], $config); } catch(ClassNotFoundException $e) { $this->connection = null; } $this->_responseTypes += [ 'headers' => function($response) { return $response->headers; }, 'body' => function($response) { return $response->body(); }, 'code' => function($response) { return $response->status['code']; } ]; }
[ "protected", "function", "_init", "(", ")", "{", "$", "config", "=", "[", "'classes'", "=>", "$", "this", "->", "_classes", "]", "+", "$", "this", "->", "_config", ";", "try", "{", "$", "this", "->", "connection", "=", "Libraries", "::", "instance", ...
Initialize connection. @return void
[ "Initialize", "connection", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L106-L119
UnionOfRAD/lithium
net/http/Service.php
Service.head
public function head($path = null, $data = [], array $options = []) { $defaults = ['return' => 'headers', 'type' => false]; return $this->send(__FUNCTION__, $path, $data, $options + $defaults); }
php
public function head($path = null, $data = [], array $options = []) { $defaults = ['return' => 'headers', 'type' => false]; return $this->send(__FUNCTION__, $path, $data, $options + $defaults); }
[ "public", "function", "head", "(", "$", "path", "=", "null", ",", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'return'", "=>", "'headers'", ",", "'type'", "=>", "false", "]", ";",...
Send HEAD request. @param string $path @param array $data @param array $options @return string
[ "Send", "HEAD", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L154-L157
UnionOfRAD/lithium
net/http/Service.php
Service.post
public function post($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
php
public function post($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
[ "public", "function", "post", "(", "$", "path", "=", "null", ",", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "__FUNCTION__", ",", "$", "path", ",", "$", "data", "...
Send POST request. @param string $path @param array $data @param array $options @return string
[ "Send", "POST", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L180-L182
UnionOfRAD/lithium
net/http/Service.php
Service.put
public function put($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
php
public function put($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
[ "public", "function", "put", "(", "$", "path", "=", "null", ",", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "__FUNCTION__", ",", "$", "path", ",", "$", "data", ",...
Send PUT request. @param string $path @param array $data @param array $options @return string
[ "Send", "PUT", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L192-L194
UnionOfRAD/lithium
net/http/Service.php
Service.patch
public function patch($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
php
public function patch($path = null, $data = [], array $options = []) { return $this->send(__FUNCTION__, $path, $data, $options); }
[ "public", "function", "patch", "(", "$", "path", "=", "null", ",", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "send", "(", "__FUNCTION__", ",", "$", "path", ",", "$", "data", ...
Send PATCH request. @param string $path @param array $data @param array $options @return string
[ "Send", "PATCH", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L204-L206
UnionOfRAD/lithium
net/http/Service.php
Service.send
public function send($method, $path = null, $data = [], array $options = []) { $defaults = ['return' => 'body']; $options += $defaults; $request = $this->_request($method, $path, $data, $options); $options += ['message' => $request]; if (!$this->connection || !$this->connection->open($options)) { return; } $response = $this->connection->send($request, $options); $this->connection->close(); if ($response->status['code'] == 401 && $auth = $response->digest()) { $request->auth = $auth; $this->connection->open(['message' => $request] + $options); $response = $this->connection->send($request, $options); $this->connection->close(); } $this->last = (object) compact('request', 'response'); $handlers = $this->_responseTypes; $handler = isset($handlers[$options['return']]) ? $handlers[$options['return']] : null; return $handler ? $handler($response) : $response; }
php
public function send($method, $path = null, $data = [], array $options = []) { $defaults = ['return' => 'body']; $options += $defaults; $request = $this->_request($method, $path, $data, $options); $options += ['message' => $request]; if (!$this->connection || !$this->connection->open($options)) { return; } $response = $this->connection->send($request, $options); $this->connection->close(); if ($response->status['code'] == 401 && $auth = $response->digest()) { $request->auth = $auth; $this->connection->open(['message' => $request] + $options); $response = $this->connection->send($request, $options); $this->connection->close(); } $this->last = (object) compact('request', 'response'); $handlers = $this->_responseTypes; $handler = isset($handlers[$options['return']]) ? $handlers[$options['return']] : null; return $handler ? $handler($response) : $response; }
[ "public", "function", "send", "(", "$", "method", ",", "$", "path", "=", "null", ",", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'return'", "=>", "'body'", "]", ";", "$", "opti...
Send request and return response data. Will open the connection if needed and always close it after sending the request. Will automatically authenticate when receiving a `401` HTTP status code then continue retrying sending initial request. @param string $method @param string $path @param array $data the parameters for the request. For GET/DELETE this is the query string for POST/PUT this is the body @param array $options passed to request and socket @return string
[ "Send", "request", "and", "return", "response", "data", ".", "Will", "open", "the", "connection", "if", "needed", "and", "always", "close", "it", "after", "sending", "the", "request", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L235-L259
UnionOfRAD/lithium
net/http/Service.php
Service._request
protected function _request($method, $path, $data, $options) { $defaults = ['type' => 'form']; $options += $defaults + $this->_config; $request = $this->_instance('request', $options); $request->path = str_replace('//', '/', "{$request->path}{$path}"); $request->method = $method = strtoupper($method); $hasBody = in_array($method, ['POST', 'PUT', 'PATCH']); $hasBody ? $request->body($data) : $request->query = $data; return $request; }
php
protected function _request($method, $path, $data, $options) { $defaults = ['type' => 'form']; $options += $defaults + $this->_config; $request = $this->_instance('request', $options); $request->path = str_replace('//', '/', "{$request->path}{$path}"); $request->method = $method = strtoupper($method); $hasBody = in_array($method, ['POST', 'PUT', 'PATCH']); $hasBody ? $request->body($data) : $request->query = $data; return $request; }
[ "protected", "function", "_request", "(", "$", "method", ",", "$", "path", ",", "$", "data", ",", "$", "options", ")", "{", "$", "defaults", "=", "[", "'type'", "=>", "'form'", "]", ";", "$", "options", "+=", "$", "defaults", "+", "$", "this", "->"...
Instantiates a request object (usually an instance of `http\Request`) and tests its properties based on the request type and data to be sent. @param string $method The HTTP method of the request, i.e. `'GET'`, `'HEAD'`, `'OPTIONS'`, etc. Can be passed in upper- or lower-case. @param string $path The @param string $data @param string $options @return object Returns an instance of `http\Request`, configured with an HTTP method, query string or POST/PUT/PATCH data, and URL.
[ "Instantiates", "a", "request", "object", "(", "usually", "an", "instance", "of", "http", "\\", "Request", ")", "and", "tests", "its", "properties", "based", "on", "the", "request", "type", "and", "data", "to", "be", "sent", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Service.php#L273-L283
UnionOfRAD/lithium
data/Source.php
Source.isConnected
public function isConnected(array $options = []) { $defaults = ['autoConnect' => false]; $options += $defaults; if (!$this->_isConnected && $options['autoConnect']) { try { $this->connect(); } catch (NetworkException $e) { $this->_isConnected = false; } } return $this->_isConnected; }
php
public function isConnected(array $options = []) { $defaults = ['autoConnect' => false]; $options += $defaults; if (!$this->_isConnected && $options['autoConnect']) { try { $this->connect(); } catch (NetworkException $e) { $this->_isConnected = false; } } return $this->_isConnected; }
[ "public", "function", "isConnected", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'autoConnect'", "=>", "false", "]", ";", "$", "options", "+=", "$", "defaults", ";", "if", "(", "!", "$", "this", "->", "_isConnec...
Checks the connection status of this data source. If the `'autoConnect'` option is set to true and the source connection is not currently active, a connection attempt will be made before returning the result of the connection status. @param array $options The options available for this method: - 'autoConnect': If true, and the connection is not currently active, calls `connect()` on this object. Defaults to `false`. @return boolean Returns the current value of `$_isConnected`, indicating whether or not the object's connection is currently active. This value may not always be accurate, as the connection could have timed out or otherwise been dropped by the remote resource during the course of the request.
[ "Checks", "the", "connection", "status", "of", "this", "data", "source", ".", "If", "the", "autoConnect", "option", "is", "set", "to", "true", "and", "the", "source", "connection", "is", "not", "currently", "active", "a", "connection", "attempt", "will", "be...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Source.php#L128-L140
UnionOfRAD/lithium
data/Source.php
Source.relationFieldName
public function relationFieldName($type, $name) { $fieldName = Inflector::underscore($name); if (preg_match('/Many$/', $type)) { $fieldName = Inflector::pluralize($fieldName); } else { $fieldName = Inflector::singularize($fieldName); } return $fieldName; }
php
public function relationFieldName($type, $name) { $fieldName = Inflector::underscore($name); if (preg_match('/Many$/', $type)) { $fieldName = Inflector::pluralize($fieldName); } else { $fieldName = Inflector::singularize($fieldName); } return $fieldName; }
[ "public", "function", "relationFieldName", "(", "$", "type", ",", "$", "name", ")", "{", "$", "fieldName", "=", "Inflector", "::", "underscore", "(", "$", "name", ")", ";", "if", "(", "preg_match", "(", "'/Many$/'", ",", "$", "type", ")", ")", "{", "...
Returns the field name of a relation name (underscore). @param string The type of the relation. @param string The name of the relation. @return string
[ "Returns", "the", "field", "name", "of", "a", "relation", "name", "(", "underscore", ")", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Source.php#L291-L299
UnionOfRAD/lithium
net/http/Response.php
Response.status
public function status($key = null, $status = null) { if ($status === null) { $status = $key; } if ($status) { $this->status = ['code' => null, 'message' => null]; if (is_array($status)) { $key = null; $this->status = $status + $this->status; } elseif (is_numeric($status) && isset($this->_statuses[$status])) { $this->status = ['code' => $status, 'message' => $this->_statuses[$status]]; } else { $statuses = array_flip($this->_statuses); if (isset($statuses[$status])) { $this->status = ['code' => $statuses[$status], 'message' => $status]; } } } if (!isset($this->_statuses[$this->status['code']])) { return false; } if (isset($this->status[$key])) { return $this->status[$key]; } return "{$this->protocol} {$this->status['code']} {$this->status['message']}"; }
php
public function status($key = null, $status = null) { if ($status === null) { $status = $key; } if ($status) { $this->status = ['code' => null, 'message' => null]; if (is_array($status)) { $key = null; $this->status = $status + $this->status; } elseif (is_numeric($status) && isset($this->_statuses[$status])) { $this->status = ['code' => $status, 'message' => $this->_statuses[$status]]; } else { $statuses = array_flip($this->_statuses); if (isset($statuses[$status])) { $this->status = ['code' => $statuses[$status], 'message' => $status]; } } } if (!isset($this->_statuses[$this->status['code']])) { return false; } if (isset($this->status[$key])) { return $this->status[$key]; } return "{$this->protocol} {$this->status['code']} {$this->status['message']}"; }
[ "public", "function", "status", "(", "$", "key", "=", "null", ",", "$", "status", "=", "null", ")", "{", "if", "(", "$", "status", "===", "null", ")", "{", "$", "status", "=", "$", "key", ";", "}", "if", "(", "$", "status", ")", "{", "$", "th...
Set and get the status for the response. @param string $key Optional. Set to `'code'` or `'message'` to return just the code or message of the status, otherwise returns the full status header. @param string|null $status The code or message of the status you wish to set. @return string|boolean Returns the full HTTP status, with version, code and message or dending on $key just the code or message.
[ "Set", "and", "get", "the", "status", "for", "the", "response", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L184-L211
UnionOfRAD/lithium
net/http/Response.php
Response.cookies
public function cookies($key = null, $value = null) { if (!$key) { $key = $this->cookies; $this->cookies = []; } if (is_array($key)) { foreach ($key as $cookie => $value) { $this->cookies($cookie, $value); } } elseif (is_string($key)) { if ($value === null) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null; } if ($value === false) { unset($this->cookies[$key]); } else { if (is_array($value)) { if (array_values($value) === $value) { foreach ($value as $i => $set) { if (!is_array($set)) { $value[$i] = ['value' => $set]; } } } } else { $value = ['value' => $value]; } if (isset($this->cookies[$key])) { $orig = $this->cookies[$key]; if (array_values($orig) !== $orig) { $orig = [$orig]; } if (array_values($value) !== $value) { $value = [$value]; } $this->cookies[$key] = array_merge($orig, $value); } else { $this->cookies[$key] = $value; } } } return $this->cookies; }
php
public function cookies($key = null, $value = null) { if (!$key) { $key = $this->cookies; $this->cookies = []; } if (is_array($key)) { foreach ($key as $cookie => $value) { $this->cookies($cookie, $value); } } elseif (is_string($key)) { if ($value === null) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null; } if ($value === false) { unset($this->cookies[$key]); } else { if (is_array($value)) { if (array_values($value) === $value) { foreach ($value as $i => $set) { if (!is_array($set)) { $value[$i] = ['value' => $set]; } } } } else { $value = ['value' => $value]; } if (isset($this->cookies[$key])) { $orig = $this->cookies[$key]; if (array_values($orig) !== $orig) { $orig = [$orig]; } if (array_values($value) !== $value) { $value = [$value]; } $this->cookies[$key] = array_merge($orig, $value); } else { $this->cookies[$key] = $value; } } } return $this->cookies; }
[ "public", "function", "cookies", "(", "$", "key", "=", "null", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "$", "key", ")", "{", "$", "key", "=", "$", "this", "->", "cookies", ";", "$", "this", "->", "cookies", "=", "[", "]", ";...
Add a cookie to header output, or return a single cookie or full cookie list. This function's parameters are designed to be analogous to setcookie(). Function parameters `expire`, `path`, `domain`, `secure`, and `httponly` may be passed in as an associative array alongside `value` inside `$value`. 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. NOTE: Cookie values are stored as an associative array containing at minimum a `value` key. Cookies which have been set multiple times do not overwrite each other. Rather they are stored as an array of associative arrays. @link http://php.net/function.setcookie.php @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/Response.php#L232-L274
UnionOfRAD/lithium
net/http/Response.php
Response._cookies
protected function _cookies() { $cookies = []; foreach ($this->cookies() as $name => $value) { if (!isset($value['value'])) { foreach ($value as $set) { $cookies[] = compact('name') + $set; } } else { $cookies[] = compact('name') + $value; } } $invalid = str_split(",; \+\t\r\n\013\014"); $replace = array_map('rawurlencode', $invalid); $replace = array_combine($invalid, $replace); foreach ($cookies as &$cookie) { if (!is_scalar($cookie['value'])) { $message = "Non-scalar value cannot be rendered for cookie `{$cookie['name']}`"; throw new UnexpectedValueException($message); } $value = strtr($cookie['value'], $replace); $header = $cookie['name'] . '=' . $value; if (!empty($cookie['expires'])) { if (is_string($cookie['expires'])) { $cookie['expires'] = strtotime($cookie['expires']); } $header .= '; Expires=' . gmdate('D, d-M-Y H:i:s', $cookie['expires']) . ' GMT'; } if (!empty($cookie['path'])) { $header .= '; Path=' . strtr($cookie['path'], $replace); } if (!empty($cookie['domain'])) { $header .= '; Domain=' . strtr($cookie['domain'], $replace); } if (!empty($cookie['secure'])) { $header .= '; Secure'; } if (!empty($cookie['httponly'])) { $header .= '; HttpOnly'; } $cookie = $header; } return $cookies ?: null; }
php
protected function _cookies() { $cookies = []; foreach ($this->cookies() as $name => $value) { if (!isset($value['value'])) { foreach ($value as $set) { $cookies[] = compact('name') + $set; } } else { $cookies[] = compact('name') + $value; } } $invalid = str_split(",; \+\t\r\n\013\014"); $replace = array_map('rawurlencode', $invalid); $replace = array_combine($invalid, $replace); foreach ($cookies as &$cookie) { if (!is_scalar($cookie['value'])) { $message = "Non-scalar value cannot be rendered for cookie `{$cookie['name']}`"; throw new UnexpectedValueException($message); } $value = strtr($cookie['value'], $replace); $header = $cookie['name'] . '=' . $value; if (!empty($cookie['expires'])) { if (is_string($cookie['expires'])) { $cookie['expires'] = strtotime($cookie['expires']); } $header .= '; Expires=' . gmdate('D, d-M-Y H:i:s', $cookie['expires']) . ' GMT'; } if (!empty($cookie['path'])) { $header .= '; Path=' . strtr($cookie['path'], $replace); } if (!empty($cookie['domain'])) { $header .= '; Domain=' . strtr($cookie['domain'], $replace); } if (!empty($cookie['secure'])) { $header .= '; Secure'; } if (!empty($cookie['httponly'])) { $header .= '; HttpOnly'; } $cookie = $header; } return $cookies ?: null; }
[ "protected", "function", "_cookies", "(", ")", "{", "$", "cookies", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "cookies", "(", ")", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "value", "[", "'...
Render `Set-Cookie` headers, urlencoding invalid characters. NOTE: Technically '+' is a valid character, but many browsers erroneously convert these to spaces, so we must escape this too. @return array Array of `Set-Cookie` headers or `null` if no cookies to set.
[ "Render", "Set", "-", "Cookie", "headers", "urlencoding", "invalid", "characters", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L284-L328
UnionOfRAD/lithium
net/http/Response.php
Response.digest
public function digest() { if (empty($this->headers['WWW-Authenticate'])) { return []; } $auth = $this->_classes['auth']; return $auth::decode($this->headers['WWW-Authenticate']); }
php
public function digest() { if (empty($this->headers['WWW-Authenticate'])) { return []; } $auth = $this->_classes['auth']; return $auth::decode($this->headers['WWW-Authenticate']); }
[ "public", "function", "digest", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "headers", "[", "'WWW-Authenticate'", "]", ")", ")", "{", "return", "[", "]", ";", "}", "$", "auth", "=", "$", "this", "->", "_classes", "[", "'auth'", "]", ...
Looks at the WWW-Authenticate. Will return array of key/values if digest. @param string $header value of WWW-Authenticate @return array
[ "Looks", "at", "the", "WWW", "-", "Authenticate", ".", "Will", "return", "array", "of", "key", "/", "values", "if", "digest", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L336-L342
UnionOfRAD/lithium
net/http/Response.php
Response._parseMessage
protected function _parseMessage($body) { if (!($parts = explode("\r\n\r\n", $body, 2)) || count($parts) === 1) { return trim($body); } list($headers, $body) = $parts; $headers = str_replace("\r", "", explode("\n", $headers)); if (array_filter($headers) === []) { return trim($body); } preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)(?:\s+(.*))?/i', array_shift($headers), $match); $this->headers($headers, false); if (!$match) { return trim($body); } list($line, $this->version, $code) = $match; if (isset($this->_statuses[$code])) { $message = $this->_statuses[$code]; } if (isset($match[3])) { $message = $match[3]; } $this->status = compact('code', 'message') + $this->status; $this->protocol = "HTTP/{$this->version}"; return $body; }
php
protected function _parseMessage($body) { if (!($parts = explode("\r\n\r\n", $body, 2)) || count($parts) === 1) { return trim($body); } list($headers, $body) = $parts; $headers = str_replace("\r", "", explode("\n", $headers)); if (array_filter($headers) === []) { return trim($body); } preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)(?:\s+(.*))?/i', array_shift($headers), $match); $this->headers($headers, false); if (!$match) { return trim($body); } list($line, $this->version, $code) = $match; if (isset($this->_statuses[$code])) { $message = $this->_statuses[$code]; } if (isset($match[3])) { $message = $match[3]; } $this->status = compact('code', 'message') + $this->status; $this->protocol = "HTTP/{$this->version}"; return $body; }
[ "protected", "function", "_parseMessage", "(", "$", "body", ")", "{", "if", "(", "!", "(", "$", "parts", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "body", ",", "2", ")", ")", "||", "count", "(", "$", "parts", ")", "===", "1", ")", "{", "...
Accepts an entire HTTP message including headers and body, and parses it into a message body an array of headers, and the HTTP status. @param string $body The full body of the message. @return After parsing out other message components, returns just the message body.
[ "Accepts", "an", "entire", "HTTP", "message", "including", "headers", "and", "body", "and", "parses", "it", "into", "a", "message", "body", "an", "array", "of", "headers", "and", "the", "HTTP", "status", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L351-L377
UnionOfRAD/lithium
net/http/Response.php
Response._parseCookies
protected function _parseCookies($headers) { foreach ((array) $headers as $header) { $parts = array_map('trim', array_filter(explode('; ', $header))); $cookie = array_shift($parts); list($name, $value) = array_map('urldecode', explode('=', $cookie, 2)) + ['','']; $options = []; foreach ($parts as $part) { $part = array_map('urldecode', explode('=', $part, 2)) + ['','']; $options[strtolower($part[0])] = $part[1] ?: true; } if (isset($options['expires'])) { $options['expires'] = strtotime($options['expires']); } $this->cookies($name, compact('value') + $options); } }
php
protected function _parseCookies($headers) { foreach ((array) $headers as $header) { $parts = array_map('trim', array_filter(explode('; ', $header))); $cookie = array_shift($parts); list($name, $value) = array_map('urldecode', explode('=', $cookie, 2)) + ['','']; $options = []; foreach ($parts as $part) { $part = array_map('urldecode', explode('=', $part, 2)) + ['','']; $options[strtolower($part[0])] = $part[1] ?: true; } if (isset($options['expires'])) { $options['expires'] = strtotime($options['expires']); } $this->cookies($name, compact('value') + $options); } }
[ "protected", "function", "_parseCookies", "(", "$", "headers", ")", "{", "foreach", "(", "(", "array", ")", "$", "headers", "as", "$", "header", ")", "{", "$", "parts", "=", "array_map", "(", "'trim'", ",", "array_filter", "(", "explode", "(", "'; '", ...
Parse `Set-Cookie` headers. @param array $headers Array of `Set-Cookie` headers or `null` if no cookies to set.
[ "Parse", "Set", "-", "Cookie", "headers", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L384-L400
UnionOfRAD/lithium
net/http/Response.php
Response._httpChunkedDecode
protected function _httpChunkedDecode($body) { if (stripos($this->headers('Transfer-Encoding'), 'chunked') === false) { return $body; } $stream = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); stream_filter_append($stream, 'dechunk'); return trim(stream_get_contents($stream)); }
php
protected function _httpChunkedDecode($body) { if (stripos($this->headers('Transfer-Encoding'), 'chunked') === false) { return $body; } $stream = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); stream_filter_append($stream, 'dechunk'); return trim(stream_get_contents($stream)); }
[ "protected", "function", "_httpChunkedDecode", "(", "$", "body", ")", "{", "if", "(", "stripos", "(", "$", "this", "->", "headers", "(", "'Transfer-Encoding'", ")", ",", "'chunked'", ")", "===", "false", ")", "{", "return", "$", "body", ";", "}", "$", ...
Decodes content bodies transferred with HTTP chunked encoding. @link http://en.wikipedia.org/wiki/Chunked_transfer_encoding Wikipedia: Chunked encoding @param string $body A chunked HTTP message body. @return string Returns the value of `$body` with chunks decoded, but only if the value of the `Transfer-Encoding` header is set to `'chunked'`. Otherwise, returns `$body` unmodified.
[ "Decodes", "content", "bodies", "transferred", "with", "HTTP", "chunked", "encoding", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Response.php#L411-L418
UnionOfRAD/lithium
net/http/Message.php
Message.headers
public function headers($key = null, $value = null, $replace = true) { if ($key === null && $value === null) { $headers = []; foreach ($this->headers as $key => $value) { if (is_scalar($value)) { $headers[] = "{$key}: {$value}"; continue; } foreach ($value as $val) { $headers[] = "{$key}: {$val}"; } } return $headers; } if ($value === null && is_string($key) && strpos($key, ':') === false) { return isset($this->headers[$key]) ? $this->headers[$key] : null; } if (is_string($key)) { if (strpos($key, ':') !== false && preg_match('/(.*?):(.+)/', $key, $match)) { $key = $match[1]; $value = trim($match[2]); } elseif ($value === false) { unset($this->headers[$key]); return; } if ($replace || !isset($this->headers[$key])) { $this->headers[$key] = $value; } elseif ($value !== $this->headers[$key]) { $this->headers[$key] = (array) $this->headers[$key]; if (is_string($value)) { $this->headers[$key][] = $value; } else { $this->headers[$key] = array_merge($this->headers[$key], $value); } } } else { $replace = ($value === false) ? $value : $replace; foreach ((array) $key as $header => $value) { if (is_string($header)) { $this->headers($header, $value, $replace); continue; } $this->headers($value, null, $replace); } } }
php
public function headers($key = null, $value = null, $replace = true) { if ($key === null && $value === null) { $headers = []; foreach ($this->headers as $key => $value) { if (is_scalar($value)) { $headers[] = "{$key}: {$value}"; continue; } foreach ($value as $val) { $headers[] = "{$key}: {$val}"; } } return $headers; } if ($value === null && is_string($key) && strpos($key, ':') === false) { return isset($this->headers[$key]) ? $this->headers[$key] : null; } if (is_string($key)) { if (strpos($key, ':') !== false && preg_match('/(.*?):(.+)/', $key, $match)) { $key = $match[1]; $value = trim($match[2]); } elseif ($value === false) { unset($this->headers[$key]); return; } if ($replace || !isset($this->headers[$key])) { $this->headers[$key] = $value; } elseif ($value !== $this->headers[$key]) { $this->headers[$key] = (array) $this->headers[$key]; if (is_string($value)) { $this->headers[$key][] = $value; } else { $this->headers[$key] = array_merge($this->headers[$key], $value); } } } else { $replace = ($value === false) ? $value : $replace; foreach ((array) $key as $header => $value) { if (is_string($header)) { $this->headers($header, $value, $replace); continue; } $this->headers($value, null, $replace); } } }
[ "public", "function", "headers", "(", "$", "key", "=", "null", ",", "$", "value", "=", "null", ",", "$", "replace", "=", "true", ")", "{", "if", "(", "$", "key", "===", "null", "&&", "$", "value", "===", "null", ")", "{", "$", "headers", "=", "...
Adds, gets or removes one or multiple headers at the same time. Header names are not normalized and their casing left untouched. When headers are retrieved no sorting takes place. This behavior is inline with the specification which states header names should be treated in a case-insensitive way. Sorting is suggested but not required. ``` // Get single or multiple headers. $request->headers('Content-Type'); // returns 'text/plain' $request->headers(); // returns ['Content-Type: text/plain', ... ] // Set single or multiple headers. $request->headers('Content-Type', 'text/plain'); $request->headers(['Content-Type' => 'text/plain', ...]); // Alternatively use full header line. $request->headers('Content-Type: text/plain'); $request->headers(['Content-Type: text/plain', ...]); // Removing single or multiple headers. $request->headers('Content-Type', false); $request->headers(['Content-Type' => false, ...]); ``` Certain header fields support multiple values. These can be separated by comma or alternatively the header repeated for each value in the list. When explicitly adding a value to an already existing header (that is when $replace is `false`) an array with those values is kept/created internally. Later when retrieving headers the header will be repeated for each value. Note: Multiple headers of the same name are only valid if the values of that header can be separated by comma as defined in section 4.2 of RFC2616. ``` // Replace single or multiple headers $request->headers('Cache-Control', 'no-store'); $request->headers(['Cache-Control' => 'public']); $request->headers('Cache-Control'); // returns 'public' // Merging with existing array headers. // Note that new elements are just appended and no sorting takes place. $request->headers('Cache-Control', 'no-store'); $request->headers('Cache-Control', 'no-cache', false); $request->headers(); // returns ['Cache-Control: no-store', 'Cache-Control: no-cache'] $request->headers('Cache-Control', 'no-store'); $request->headers('Cache-Control', ['no-cache'], false); $request->headers(); // returns ['Cache-Control: no-store', 'Cache-Control: no-cache'] $request->headers('Cache-Control', 'max-age=0'); $request->headers('Cache-Control', 'no-store, no-cache'); $request->headers(); // returns ['Cache-Control: no-store, no-cache'] ``` @link http://www.ietf.org/rfc/rfc2616.txt Section 4.2 Message Headers @param string|array $key A header name, a full header line (`'<key>: <value>'`), or an array of headers to set in `key => value` form. @param mixed $value A value to set if `$key` is a string. It can be an array to set multiple headers with the same key. If `null`, returns the value of the header corresponding to `$key`. If `false`, it unsets the header corresponding to `$key`. @param boolean $replace Whether to override or add alongside any existing header with the same name. @return mixed When called with just $key provided, the value of a single header or an array of values in case there is multiple headers with this key. When calling the method without any arguments, an array of compiled headers in the form `array('<key>: <value>', ...)` is returned. All set and replace operations return no value for performance reasons.
[ "Adds", "gets", "or", "removes", "one", "or", "multiple", "headers", "at", "the", "same", "time", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Message.php#L164-L213
UnionOfRAD/lithium
net/http/Message.php
Message.type
public function type($type = null) { if ($type === false) { unset($this->headers['Content-Type']); $this->_type = false; return; } $media = $this->_classes['media']; if (!$type && $this->_type) { return $this->_type; } $headers = $this->headers + ['Content-Type' => null]; $type = $type ?: $headers['Content-Type']; if (!$type) { return; } $header = $type; if (!$data = $media::type($type)) { $this->headers('Content-Type', $type); return ($this->_type = $type); } if (is_string($data)) { $type = $data; } elseif (!empty($data['content'])) { $header = is_string($data['content']) ? $data['content'] : reset($data['content']); } $this->headers('Content-Type', $header); return ($this->_type = $type); }
php
public function type($type = null) { if ($type === false) { unset($this->headers['Content-Type']); $this->_type = false; return; } $media = $this->_classes['media']; if (!$type && $this->_type) { return $this->_type; } $headers = $this->headers + ['Content-Type' => null]; $type = $type ?: $headers['Content-Type']; if (!$type) { return; } $header = $type; if (!$data = $media::type($type)) { $this->headers('Content-Type', $type); return ($this->_type = $type); } if (is_string($data)) { $type = $data; } elseif (!empty($data['content'])) { $header = is_string($data['content']) ? $data['content'] : reset($data['content']); } $this->headers('Content-Type', $header); return ($this->_type = $type); }
[ "public", "function", "type", "(", "$", "type", "=", "null", ")", "{", "if", "(", "$", "type", "===", "false", ")", "{", "unset", "(", "$", "this", "->", "headers", "[", "'Content-Type'", "]", ")", ";", "$", "this", "->", "_type", "=", "false", "...
Sets/gets the content type. @param string $type A full content type i.e. `'application/json'` or simple name `'json'` @return string A simple content type name, i.e. `'html'`, `'xml'`, `'json'`, etc., depending on the content type of the request.
[ "Sets", "/", "gets", "the", "content", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Message.php#L222-L252
UnionOfRAD/lithium
net/http/Message.php
Message.body
public function body($data = null, $options = []) { $default = ['buffer' => null, 'encode' => false, 'decode' => false]; $options += $default; if ($data !== null) { $this->body = array_merge((array) $this->body, (array) $data); } $body = $this->body; if (empty($options['buffer']) && $body === null) { return ""; } if ($options['encode']) { $body = $this->_encode($body); } $body = is_string($body) ? $body : join("\r\n", (array) $body); if ($options['decode']) { $body = $this->_decode($body); } return ($options['buffer']) ? str_split($body, $options['buffer']) : $body; }
php
public function body($data = null, $options = []) { $default = ['buffer' => null, 'encode' => false, 'decode' => false]; $options += $default; if ($data !== null) { $this->body = array_merge((array) $this->body, (array) $data); } $body = $this->body; if (empty($options['buffer']) && $body === null) { return ""; } if ($options['encode']) { $body = $this->_encode($body); } $body = is_string($body) ? $body : join("\r\n", (array) $body); if ($options['decode']) { $body = $this->_decode($body); } return ($options['buffer']) ? str_split($body, $options['buffer']) : $body; }
[ "public", "function", "body", "(", "$", "data", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "default", "=", "[", "'buffer'", "=>", "null", ",", "'encode'", "=>", "false", ",", "'decode'", "=>", "false", "]", ";", "$", "options",...
Add data to and compile the HTTP message body, optionally encoding or decoding its parts according to content type. @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
[ "Add", "data", "to", "and", "compile", "the", "HTTP", "message", "body", "optionally", "encoding", "or", "decoding", "its", "parts", "according", "to", "content", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Message.php#L265-L286
UnionOfRAD/lithium
net/http/Message.php
Message._encode
protected function _encode($body) { $media = $this->_classes['media']; if ($media::type($this->_type)) { $encoded = $media::encode($this->_type, $body); $body = $encoded !== null ? $encoded : $body; } return $body; }
php
protected function _encode($body) { $media = $this->_classes['media']; if ($media::type($this->_type)) { $encoded = $media::encode($this->_type, $body); $body = $encoded !== null ? $encoded : $body; } return $body; }
[ "protected", "function", "_encode", "(", "$", "body", ")", "{", "$", "media", "=", "$", "this", "->", "_classes", "[", "'media'", "]", ";", "if", "(", "$", "media", "::", "type", "(", "$", "this", "->", "_type", ")", ")", "{", "$", "encoded", "="...
Encode the body based on the content type @see lithium\net\http\Message::type() @param mixed $body @return string
[ "Encode", "the", "body", "based", "on", "the", "content", "type" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Message.php#L295-L303
UnionOfRAD/lithium
net/http/Message.php
Message._decode
protected function _decode($body) { $media = $this->_classes['media']; if ($media::type($this->_type)) { $decoded = $media::decode($this->_type, $body); $body = $decoded !== null ? $decoded : $body; } return $body; }
php
protected function _decode($body) { $media = $this->_classes['media']; if ($media::type($this->_type)) { $decoded = $media::decode($this->_type, $body); $body = $decoded !== null ? $decoded : $body; } return $body; }
[ "protected", "function", "_decode", "(", "$", "body", ")", "{", "$", "media", "=", "$", "this", "->", "_classes", "[", "'media'", "]", ";", "if", "(", "$", "media", "::", "type", "(", "$", "this", "->", "_type", ")", ")", "{", "$", "decoded", "="...
Decode the body based on the content type @see lithium\net\http\Message::type() @param string $body @return mixed
[ "Decode", "the", "body", "based", "on", "the", "content", "type" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Message.php#L312-L320
UnionOfRAD/lithium
g11n/catalog/adapter/Code.php
Code.read
public function read($category, $locale, $scope) { if ($scope !== $this->_config['scope']) { return null; } $path = $this->_config['path']; switch ($category) { case 'messageTemplate': return $this->_readMessageTemplate($path); default: return null; } }
php
public function read($category, $locale, $scope) { if ($scope !== $this->_config['scope']) { return null; } $path = $this->_config['path']; switch ($category) { case 'messageTemplate': return $this->_readMessageTemplate($path); default: return null; } }
[ "public", "function", "read", "(", "$", "category", ",", "$", "locale", ",", "$", "scope", ")", "{", "if", "(", "$", "scope", "!==", "$", "this", "->", "_config", "[", "'scope'", "]", ")", "{", "return", "null", ";", "}", "$", "path", "=", "$", ...
Reads data. @param string $category A category. `'messageTemplate'` is the only category supported. @param string $locale A locale identifier. @param string $scope The scope for the current operation. @return array Returns the message template. If the scope is not equal to the current scope or `$category` is not `'messageTemplate'` null is returned.
[ "Reads", "data", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Code.php#L65-L77
UnionOfRAD/lithium
g11n/catalog/adapter/Code.php
Code._readMessageTemplate
protected function _readMessageTemplate($path) { $base = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($base); $data = []; foreach ($iterator as $item) { $file = $item->getPathname(); switch (pathinfo($file, PATHINFO_EXTENSION)) { case 'php': $data += $this->_parsePhp($file); break; } } return $data; }
php
protected function _readMessageTemplate($path) { $base = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($base); $data = []; foreach ($iterator as $item) { $file = $item->getPathname(); switch (pathinfo($file, PATHINFO_EXTENSION)) { case 'php': $data += $this->_parsePhp($file); break; } } return $data; }
[ "protected", "function", "_readMessageTemplate", "(", "$", "path", ")", "{", "$", "base", "=", "new", "RecursiveDirectoryIterator", "(", "$", "path", ")", ";", "$", "iterator", "=", "new", "RecursiveIteratorIterator", "(", "$", "base", ")", ";", "$", "data",...
Extracts data from files within configured path recursively. @param string $path Base path to start extracting from. @return array
[ "Extracts", "data", "from", "files", "within", "configured", "path", "recursively", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Code.php#L85-L100
UnionOfRAD/lithium
g11n/catalog/adapter/Code.php
Code._parsePhp
protected function _parsePhp($file) { $contents = file_get_contents($file); $contents = Compiler::compile($contents); $defaults = [ 'ids' => [], 'context' => null, 'open' => false, 'position' => 0, 'occurrence' => ['file' => $file, 'line' => null] ]; extract($defaults); $data = []; if (strpos($contents, '$t(') === false && strpos($contents, '$tn(') === false) { return $data; } $tokens = token_get_all($contents); unset($contents); $findContext = function ($position) use ($tokens) { $ignore = [T_WHITESPACE, '(', ')', T_ARRAY, ',']; $open = 1; $options = []; $depth = 0; while (isset($tokens[$position]) && $token = $tokens[$position]) { if (!is_array($token)) { $token = [0 => null, 1 => $token, 2 => null]; } if ($token[1] === '[' || $token[1] === '(') { $open++; } elseif (($token[1] === ']' || $token[1] === ')') && --$open === 0) { break; } if ($token[1] === '[' || $token[0] === T_ARRAY) { $depth++; } elseif ($depth > 1 && ($token[1] === ']' || $token[1] === ')')) { $depth--; } if ($depth === 1 && $open === 2) { if (!in_array($token[0] ? : $token[1], $ignore)) { $options[] = $token; } } $position++; } foreach ($options as $i => $token) { if (!(isset($options[$i + 1]) && isset($options[$i + 2]))) { break; } $condition1 = substr($token[1], 1, -1) === 'context'; $condition2 = $options[$i + 1][0] === T_DOUBLE_ARROW; $condition3 = $options[$i + 2][0] === T_CONSTANT_ENCAPSED_STRING; if ($condition1 && $condition2 && $condition3) { return $options[$i + 2][1]; } } return null; }; foreach ($tokens as $key => $token) { if (!is_array($token)) { $token = [0 => null, 1 => $token, 2 => null]; } if ($open) { if ($position >= ($open === 'singular' ? 1 : 2)) { $data = $this->_merge($data, [ 'id' => $ids['singular'], 'ids' => $ids, 'occurrences' => [$occurrence], 'context' => $context ]); extract($defaults, EXTR_OVERWRITE); } elseif ($token[0] === T_CONSTANT_ENCAPSED_STRING) { $ids[$ids ? 'plural' : 'singular'] = $token[1]; $position++; } } else { if (isset($tokens[$key + 1]) && $tokens[$key + 1] === '(') { if ($token[1] === '$t') { $open = 'singular'; } elseif ($token[1] === '$tn') { $open = 'plural'; } else { continue; } $occurrence['line'] = $token[2]; $context = $findContext($key + 2); } } } return $data; }
php
protected function _parsePhp($file) { $contents = file_get_contents($file); $contents = Compiler::compile($contents); $defaults = [ 'ids' => [], 'context' => null, 'open' => false, 'position' => 0, 'occurrence' => ['file' => $file, 'line' => null] ]; extract($defaults); $data = []; if (strpos($contents, '$t(') === false && strpos($contents, '$tn(') === false) { return $data; } $tokens = token_get_all($contents); unset($contents); $findContext = function ($position) use ($tokens) { $ignore = [T_WHITESPACE, '(', ')', T_ARRAY, ',']; $open = 1; $options = []; $depth = 0; while (isset($tokens[$position]) && $token = $tokens[$position]) { if (!is_array($token)) { $token = [0 => null, 1 => $token, 2 => null]; } if ($token[1] === '[' || $token[1] === '(') { $open++; } elseif (($token[1] === ']' || $token[1] === ')') && --$open === 0) { break; } if ($token[1] === '[' || $token[0] === T_ARRAY) { $depth++; } elseif ($depth > 1 && ($token[1] === ']' || $token[1] === ')')) { $depth--; } if ($depth === 1 && $open === 2) { if (!in_array($token[0] ? : $token[1], $ignore)) { $options[] = $token; } } $position++; } foreach ($options as $i => $token) { if (!(isset($options[$i + 1]) && isset($options[$i + 2]))) { break; } $condition1 = substr($token[1], 1, -1) === 'context'; $condition2 = $options[$i + 1][0] === T_DOUBLE_ARROW; $condition3 = $options[$i + 2][0] === T_CONSTANT_ENCAPSED_STRING; if ($condition1 && $condition2 && $condition3) { return $options[$i + 2][1]; } } return null; }; foreach ($tokens as $key => $token) { if (!is_array($token)) { $token = [0 => null, 1 => $token, 2 => null]; } if ($open) { if ($position >= ($open === 'singular' ? 1 : 2)) { $data = $this->_merge($data, [ 'id' => $ids['singular'], 'ids' => $ids, 'occurrences' => [$occurrence], 'context' => $context ]); extract($defaults, EXTR_OVERWRITE); } elseif ($token[0] === T_CONSTANT_ENCAPSED_STRING) { $ids[$ids ? 'plural' : 'singular'] = $token[1]; $position++; } } else { if (isset($tokens[$key + 1]) && $tokens[$key + 1] === '(') { if ($token[1] === '$t') { $open = 'singular'; } elseif ($token[1] === '$tn') { $open = 'plural'; } else { continue; } $occurrence['line'] = $token[2]; $context = $findContext($key + 2); } } } return $data; }
[ "protected", "function", "_parsePhp", "(", "$", "file", ")", "{", "$", "contents", "=", "file_get_contents", "(", "$", "file", ")", ";", "$", "contents", "=", "Compiler", "::", "compile", "(", "$", "contents", ")", ";", "$", "defaults", "=", "[", "'ids...
Parses a PHP file for messages marked as translatable. Recognized as message marking are `$t()` and `$tn()` which are implemented in the `View` class. This is a rather simple and stupid parser but also fast and easy to grasp. It doesn't actively attempt to detect and work around syntax errors in marker functions. @see lithium\g11n\Message::aliases() @param string $file Absolute path to a PHP file. @return array
[ "Parses", "a", "PHP", "file", "for", "messages", "marked", "as", "translatable", ".", "Recognized", "as", "message", "marking", "are", "$t", "()", "and", "$tn", "()", "which", "are", "implemented", "in", "the", "View", "class", ".", "This", "is", "a", "r...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Code.php#L112-L211
UnionOfRAD/lithium
g11n/catalog/adapter/Code.php
Code._merge
protected function _merge(array $data, array $item) { $filter = function ($value) use (&$filter) { if (is_array($value)) { return array_map($filter, $value); } return substr($value, 1, -1); }; $fields = ['id', 'ids', 'translated', 'context']; foreach ($fields as $field) { if (isset($item[$field])) { $item[$field] = $filter($item[$field]); } } return parent::_merge($data, $item); }
php
protected function _merge(array $data, array $item) { $filter = function ($value) use (&$filter) { if (is_array($value)) { return array_map($filter, $value); } return substr($value, 1, -1); }; $fields = ['id', 'ids', 'translated', 'context']; foreach ($fields as $field) { if (isset($item[$field])) { $item[$field] = $filter($item[$field]); } } return parent::_merge($data, $item); }
[ "protected", "function", "_merge", "(", "array", "$", "data", ",", "array", "$", "item", ")", "{", "$", "filter", "=", "function", "(", "$", "value", ")", "use", "(", "&", "$", "filter", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")...
Merges an item into given data and removes quotation marks from the beginning and end of message strings. @see lithium\g11n\catalog\Adapter::_merge() @param array $data Data to merge item into. @param array $item Item to merge into $data. @return array The merged data.
[ "Merges", "an", "item", "into", "given", "data", "and", "removes", "quotation", "marks", "from", "the", "beginning", "and", "end", "of", "message", "strings", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Code.php#L222-L237
UnionOfRAD/lithium
data/Entity.php
Entity.&
public function &__get($name) { if (isset($this->_relationships[$name])) { return $this->_relationships[$name]; } if (isset($this->_updated[$name])) { return $this->_updated[$name]; } $null = null; return $null; }
php
public function &__get($name) { if (isset($this->_relationships[$name])) { return $this->_relationships[$name]; } if (isset($this->_updated[$name])) { return $this->_updated[$name]; } $null = null; return $null; }
[ "public", "function", "&", "__get", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_relationships", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "_relationships", "[", "$", "name", "]", ";", "}", "i...
Overloading for reading inaccessible properties. @param string $name Property name. @return mixed Result.
[ "Overloading", "for", "reading", "inaccessible", "properties", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L151-L160
UnionOfRAD/lithium
data/Entity.php
Entity.__isset
public function __isset($name) { return isset($this->_updated[$name]) || isset($this->_relationships[$name]); }
php
public function __isset($name) { return isset($this->_updated[$name]) || isset($this->_relationships[$name]); }
[ "public", "function", "__isset", "(", "$", "name", ")", "{", "return", "isset", "(", "$", "this", "->", "_updated", "[", "$", "name", "]", ")", "||", "isset", "(", "$", "this", "->", "_relationships", "[", "$", "name", "]", ")", ";", "}" ]
Overloading for calling `isset()` or `empty()` on inaccessible properties. @param string $name Property name. @return mixed Result.
[ "Overloading", "for", "calling", "isset", "()", "or", "empty", "()", "on", "inaccessible", "properties", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L181-L183
UnionOfRAD/lithium
data/Entity.php
Entity.respondsTo
public function respondsTo($method, $internal = false) { if (method_exists($class = $this->_model, '_object')) { $result = $class::invokeMethod('_object')->respondsTo($method); } else { $result = Inspector::isCallable($class, $method, $internal); } $result = $result || parent::respondsTo($method, $internal); $result = $result || $class::respondsTo($method, $internal); return $result; }
php
public function respondsTo($method, $internal = false) { if (method_exists($class = $this->_model, '_object')) { $result = $class::invokeMethod('_object')->respondsTo($method); } else { $result = Inspector::isCallable($class, $method, $internal); } $result = $result || parent::respondsTo($method, $internal); $result = $result || $class::respondsTo($method, $internal); return $result; }
[ "public", "function", "respondsTo", "(", "$", "method", ",", "$", "internal", "=", "false", ")", "{", "if", "(", "method_exists", "(", "$", "class", "=", "$", "this", "->", "_model", ",", "'_object'", ")", ")", "{", "$", "result", "=", "$", "class", ...
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/Entity.php#L214-L224
UnionOfRAD/lithium
data/Entity.php
Entity.set
public function set(array $data) { foreach ($data as $name => $value) { $this->__set($name, $value); } }
php
public function set(array $data) { foreach ($data as $name => $value) { $this->__set($name, $value); } }
[ "public", "function", "set", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this", "->", "__set", "(", "$", "name", ",", "$", "value", ")", ";", "}", "}" ]
Allows several properties to be assigned at once, i.e.: ``` $record->set(['title' => 'Lorem Ipsum', 'value' => 42]); ``` @param array $data An associative array of fields and values to assign to this `Entity` instance. @return void
[ "Allows", "several", "properties", "to", "be", "assigned", "at", "once", "i", ".", "e", ".", ":", "$record", "-", ">", "set", "(", "[", "title", "=", ">", "Lorem", "Ipsum", "value", "=", ">", "42", "]", ")", ";" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L236-L240
UnionOfRAD/lithium
data/Entity.php
Entity.errors
public function errors($field = null, $value = null) { if ($field === false) { return ($this->_errors = []); } if ($field === null) { return $this->_errors; } if (is_array($field)) { return ($this->_errors = array_merge_recursive($this->_errors, $field)); } if ($value === null && isset($this->_errors[$field])) { return $this->_errors[$field]; } if ($value !== null) { if (array_key_exists($field, $this->_errors)) { $current = $this->_errors[$field]; return ($this->_errors[$field] = array_merge((array) $current, (array) $value)); } return ($this->_errors[$field] = $value); } return $value; }
php
public function errors($field = null, $value = null) { if ($field === false) { return ($this->_errors = []); } if ($field === null) { return $this->_errors; } if (is_array($field)) { return ($this->_errors = array_merge_recursive($this->_errors, $field)); } if ($value === null && isset($this->_errors[$field])) { return $this->_errors[$field]; } if ($value !== null) { if (array_key_exists($field, $this->_errors)) { $current = $this->_errors[$field]; return ($this->_errors[$field] = array_merge((array) $current, (array) $value)); } return ($this->_errors[$field] = $value); } return $value; }
[ "public", "function", "errors", "(", "$", "field", "=", "null", ",", "$", "value", "=", "null", ")", "{", "if", "(", "$", "field", "===", "false", ")", "{", "return", "(", "$", "this", "->", "_errors", "=", "[", "]", ")", ";", "}", "if", "(", ...
Access the errors of the record. @see lithium\data\Entity::$_errors @param array|string $field If an array, overwrites `$this->_errors` if it is empty, if not, merges the errors with the current values. If a string, and `$value` is not `null`, sets the corresponding key in `$this->_errors` to `$value`. Setting `$field` to `false` will reset the current state. @param string $value Value to set. @return mixed Either the `$this->_errors` array, or single value from it.
[ "Access", "the", "errors", "of", "the", "record", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L301-L322
UnionOfRAD/lithium
data/Entity.php
Entity.sync
public function sync($id = null, array $data = [], array $options = []) { $defaults = ['materialize' => true, 'dematerialize' => false]; $options += $defaults; $model = $this->_model; $key = []; if ($options['materialize']) { $this->_exists = true; } if ($options['dematerialize']) { $this->_exists = false; } if ($id && $model) { $key = $model::meta('key'); $key = is_array($key) ? array_combine($key, $id) : [$key => $id]; } $this->_increment = []; $this->_data = $this->_updated = ($key + $data + $this->_updated); }
php
public function sync($id = null, array $data = [], array $options = []) { $defaults = ['materialize' => true, 'dematerialize' => false]; $options += $defaults; $model = $this->_model; $key = []; if ($options['materialize']) { $this->_exists = true; } if ($options['dematerialize']) { $this->_exists = false; } if ($id && $model) { $key = $model::meta('key'); $key = is_array($key) ? array_combine($key, $id) : [$key => $id]; } $this->_increment = []; $this->_data = $this->_updated = ($key + $data + $this->_updated); }
[ "public", "function", "sync", "(", "$", "id", "=", "null", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'materialize'", "=>", "true", ",", "'dematerialize'", "=>", "fal...
Called after an `Entity` is saved. Updates the object's internal state to reflect the corresponding database entity, and sets the `Entity` object's key, if this is a newly-created object. **Do not** call this method if you intend to update the database's copy of the entity. Instead, see `Model::save()`. @see lithium\data\Model::save() @param mixed $id The ID to assign, where applicable. @param array $data Any additional generated data assigned to the object by the database. @param array $options Method options: - `'materialize'` _boolean_: Determines whether or not the flag should be set that indicates that this entity exists in the data store. Defaults to `true`. - `'dematerialize'` _boolean_: If set to `true`, indicates that this entity has been deleted from the data store and no longer exists. Defaults to `false`.
[ "Called", "after", "an", "Entity", "is", "saved", ".", "Updates", "the", "object", "s", "internal", "state", "to", "reflect", "the", "corresponding", "database", "entity", "and", "sets", "the", "Entity", "object", "s", "key", "if", "this", "is", "a", "newl...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L349-L367
UnionOfRAD/lithium
data/Entity.php
Entity.increment
public function increment($field, $value = 1) { if (!isset($this->_updated[$field])) { $this->_updated[$field] = 0; } elseif (!is_numeric($this->_updated[$field])) { throw new UnexpectedValueException("Field `'{$field}'` cannot be incremented."); } if (!isset($this->_increment[$field])) { $this->_increment[$field] = 0; } $this->_increment[$field] += $value; return $this->_updated[$field] += $value; }
php
public function increment($field, $value = 1) { if (!isset($this->_updated[$field])) { $this->_updated[$field] = 0; } elseif (!is_numeric($this->_updated[$field])) { throw new UnexpectedValueException("Field `'{$field}'` cannot be incremented."); } if (!isset($this->_increment[$field])) { $this->_increment[$field] = 0; } $this->_increment[$field] += $value; return $this->_updated[$field] += $value; }
[ "public", "function", "increment", "(", "$", "field", ",", "$", "value", "=", "1", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_updated", "[", "$", "field", "]", ")", ")", "{", "$", "this", "->", "_updated", "[", "$", "field", "...
Safely (atomically) increments the value of the specified field by an arbitrary value. Defaults to `1` if no value is specified. Throws an exception if the specified field is non-numeric. @param string $field The name of the field to be incremented. @param integer|string $value The value to increment the field by. Defaults to `1` if this parameter is not specified. @return integer Returns the current value of `$field`, based on the value retrieved from the data source when the entity was loaded, plus any increments applied. Note that it may not reflect the most current value in the persistent backend data source. @throws UnexpectedValueException Throws an exception when `$field` is set to a non-numeric type.
[ "Safely", "(", "atomically", ")", "increments", "the", "value", "of", "the", "specified", "field", "by", "an", "arbitrary", "value", ".", "Defaults", "to", "1", "if", "no", "value", "is", "specified", ".", "Throws", "an", "exception", "if", "the", "specifi...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L383-L396
UnionOfRAD/lithium
data/Entity.php
Entity.modified
public function modified($field = null) { if ($field) { if (!isset($this->_updated[$field]) && !isset($this->_data[$field])) { return null; } if (!array_key_exists($field, $this->_updated)) { return false; } $value = $this->_updated[$field]; if (is_object($value) && method_exists($value, 'modified')) { $modified = $value->modified(); return $modified === true || is_array($modified) && in_array(true, $modified, true); } $isSet = isset($this->_data[$field]); return !$isSet || ($this->_data[$field] !== $this->_updated[$field]); } $fields = array_fill_keys(array_keys($this->_data), false); foreach ($this->_updated as $field => $value) { if (is_object($value) && method_exists($value, 'modified')) { if (!isset($this->_data[$field])) { $fields[$field] = true; continue; } $modified = $value->modified(); $fields[$field] = ( $modified === true || is_array($modified) && in_array(true, $modified, true) ); } else { $fields[$field] = ( !isset($fields[$field]) || $this->_data[$field] !== $this->_updated[$field] ); } } return $fields; }
php
public function modified($field = null) { if ($field) { if (!isset($this->_updated[$field]) && !isset($this->_data[$field])) { return null; } if (!array_key_exists($field, $this->_updated)) { return false; } $value = $this->_updated[$field]; if (is_object($value) && method_exists($value, 'modified')) { $modified = $value->modified(); return $modified === true || is_array($modified) && in_array(true, $modified, true); } $isSet = isset($this->_data[$field]); return !$isSet || ($this->_data[$field] !== $this->_updated[$field]); } $fields = array_fill_keys(array_keys($this->_data), false); foreach ($this->_updated as $field => $value) { if (is_object($value) && method_exists($value, 'modified')) { if (!isset($this->_data[$field])) { $fields[$field] = true; continue; } $modified = $value->modified(); $fields[$field] = ( $modified === true || is_array($modified) && in_array(true, $modified, true) ); } else { $fields[$field] = ( !isset($fields[$field]) || $this->_data[$field] !== $this->_updated[$field] ); } } return $fields; }
[ "public", "function", "modified", "(", "$", "field", "=", "null", ")", "{", "if", "(", "$", "field", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_updated", "[", "$", "field", "]", ")", "&&", "!", "isset", "(", "$", "this", "->",...
Gets the current state for a given field or, if no field is given, gets the array of fields modified on this entity. @param string The field name to check its state. @return mixed Returns `true` if a field is given and was updated, `false` otherwise and `null` if the field was not set at all. If no field is given returns an arra where the keys are entity field names, and the values are `true` for changed fields.
[ "Gets", "the", "current", "state", "for", "a", "given", "field", "or", "if", "no", "field", "is", "given", "gets", "the", "array", "of", "fields", "modified", "on", "this", "entity", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L421-L461
UnionOfRAD/lithium
data/Entity.php
Entity.to
public function to($format, array $options = []) { $defaults = ['handlers' => []]; $options += $defaults; $options['handlers'] += $this->_handlers; switch ($format) { case 'array': $data = $this->_updated; $rel = array_map(function($obj) { return $obj->data(); }, $this->_relationships); $data = $rel + $data; $options['indexed'] = isset($options['indexed']) ? $options['indexed'] : false; $result = Collection::toArray($data, $options); break; case 'string': $result = $this->__toString(); break; default: $result = $this; break; } return $result; }
php
public function to($format, array $options = []) { $defaults = ['handlers' => []]; $options += $defaults; $options['handlers'] += $this->_handlers; switch ($format) { case 'array': $data = $this->_updated; $rel = array_map(function($obj) { return $obj->data(); }, $this->_relationships); $data = $rel + $data; $options['indexed'] = isset($options['indexed']) ? $options['indexed'] : false; $result = Collection::toArray($data, $options); break; case 'string': $result = $this->__toString(); break; default: $result = $this; break; } return $result; }
[ "public", "function", "to", "(", "$", "format", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'handlers'", "=>", "[", "]", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$", "options", "[", "'handlers'",...
Converts the data in the record set to a different format, i.e. an array. @param string $format Currently only `array`. @param array $options Options for converting: - `'indexed'` _boolean_: Allows to control how converted data of nested collections is keyed. When set to `true` will force indexed conversion of nested collection data. By default `false` which will only index the root level. @return mixed
[ "Converts", "the", "data", "in", "the", "record", "set", "to", "a", "different", "format", "i", ".", "e", ".", "an", "array", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Entity.php#L495-L516
UnionOfRAD/lithium
analysis/logger/adapter/Cache.php
Cache.write
public function write($priority, $message) { $config = $this->_config + $this->_classes; return function($params) use ($config) { $params += ['timestamp' => strtotime('now')]; $key = $config['key']; $key = is_callable($key) ? $key($params) : Text::insert($key, $params); $cache = $config['cache']; return $cache::write($config['config'], $key, $params['message'], $config['expiry']); }; }
php
public function write($priority, $message) { $config = $this->_config + $this->_classes; return function($params) use ($config) { $params += ['timestamp' => strtotime('now')]; $key = $config['key']; $key = is_callable($key) ? $key($params) : Text::insert($key, $params); $cache = $config['cache']; return $cache::write($config['config'], $key, $params['message'], $config['expiry']); }; }
[ "public", "function", "write", "(", "$", "priority", ",", "$", "message", ")", "{", "$", "config", "=", "$", "this", "->", "_config", "+", "$", "this", "->", "_classes", ";", "return", "function", "(", "$", "params", ")", "use", "(", "$", "config", ...
Writes the message to the configured cache adapter. @param string $priority @param string $message @return \Closure Function returning boolean `true` on successful write, `false` otherwise.
[ "Writes", "the", "message", "to", "the", "configured", "cache", "adapter", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/logger/adapter/Cache.php#L80-L91
UnionOfRAD/lithium
template/view/Renderer.php
Renderer._init
protected function _init() { parent::_init(); $req =& $this->_request; $ctx =& $this->_context; $classes =& $this->_classes; $h = $this->_view ? $this->_view->outputFilters['h'] : null; $this->_handlers += [ 'url' => function($url, $ref, array $options = []) use (&$classes, &$req, $h) { $url = $classes['router']::match($url ?: '', $req, $options); return $h ? str_replace('&amp;', '&', $h($url)) : $url; }, 'path' => function($path, $ref, array $options = []) use (&$classes, &$req, $h) { $defaults = ['base' => $req ? $req->env('base') : '']; $type = 'generic'; if (is_array($ref) && $ref[0] && $ref[1]) { list($helper, $methodRef) = $ref; list($class, $method) = explode('::', $methodRef); $type = $helper->contentMap[$method]; } $path = $classes['media']::asset($path, $type, $options + $defaults); return $h ? $h($path) : $path; }, 'options' => '_attributes', 'title' => 'escape', 'value' => 'escape', 'scripts' => function($scripts) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['scripts']) . "\n"; }, 'styles' => function($styles) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['styles']) . "\n"; }, 'head' => function($head) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['head']) . "\n"; } ]; unset($this->_config['view']); }
php
protected function _init() { parent::_init(); $req =& $this->_request; $ctx =& $this->_context; $classes =& $this->_classes; $h = $this->_view ? $this->_view->outputFilters['h'] : null; $this->_handlers += [ 'url' => function($url, $ref, array $options = []) use (&$classes, &$req, $h) { $url = $classes['router']::match($url ?: '', $req, $options); return $h ? str_replace('&amp;', '&', $h($url)) : $url; }, 'path' => function($path, $ref, array $options = []) use (&$classes, &$req, $h) { $defaults = ['base' => $req ? $req->env('base') : '']; $type = 'generic'; if (is_array($ref) && $ref[0] && $ref[1]) { list($helper, $methodRef) = $ref; list($class, $method) = explode('::', $methodRef); $type = $helper->contentMap[$method]; } $path = $classes['media']::asset($path, $type, $options + $defaults); return $h ? $h($path) : $path; }, 'options' => '_attributes', 'title' => 'escape', 'value' => 'escape', 'scripts' => function($scripts) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['scripts']) . "\n"; }, 'styles' => function($styles) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['styles']) . "\n"; }, 'head' => function($head) use (&$ctx) { return "\n\t" . join("\n\t", $ctx['head']) . "\n"; } ]; unset($this->_config['view']); }
[ "protected", "function", "_init", "(", ")", "{", "parent", "::", "_init", "(", ")", ";", "$", "req", "=", "&", "$", "this", "->", "_request", ";", "$", "ctx", "=", "&", "$", "this", "->", "_context", ";", "$", "classes", "=", "&", "$", "this", ...
Sets the default output handlers for string template inputs. The default handlers available are: - `url`: Allows generating escaped and routed URLs using `Router::match()`. Note that all falsey values, which includes an empty array, will result in `'/'` being returned. For empty arrays this behavior is slightly different from using `Router::match()` directly. - `path`: Generates an asset path. - `options`: Converts a set of parameters to HTML attributes into a string. - `title`: Returns the escaped title. - `value`: Returns an escaped value. - `scripts`: Returns a markup string of styles from context. - `styles`: Returns a markup string of scripts from context. - `head` @see lithium\net\http\Router::match() @see lithium\net\http\Media::asset() @see lithium\template\Helper::_attributes() @return void
[ "Sets", "the", "default", "output", "handlers", "for", "string", "template", "inputs", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L212-L251
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.helper
public function helper($name, array $config = []) { if (isset($this->_helpers[$name])) { return $this->_helpers[$name]; } try { $config += ['context' => $this]; return $this->_helpers[$name] = Libraries::instance('helper', ucfirst($name), $config); } catch (ClassNotFoundException $e) { if (ob_get_length()) { ob_end_clean(); } throw new RuntimeException("Helper `{$name}` not found."); } }
php
public function helper($name, array $config = []) { if (isset($this->_helpers[$name])) { return $this->_helpers[$name]; } try { $config += ['context' => $this]; return $this->_helpers[$name] = Libraries::instance('helper', ucfirst($name), $config); } catch (ClassNotFoundException $e) { if (ob_get_length()) { ob_end_clean(); } throw new RuntimeException("Helper `{$name}` not found."); } }
[ "public", "function", "helper", "(", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_helpers", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "_helpers", "[", ...
Brokers access to helpers attached to this rendering context, and loads helpers on-demand if they are not available. @param string $name Helper name @param array $config @return object
[ "Brokers", "access", "to", "helpers", "attached", "to", "this", "rendering", "context", "and", "loads", "helpers", "on", "-", "demand", "if", "they", "are", "not", "available", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L343-L356
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.strings
public function strings($strings = null) { if (is_array($strings)) { return $this->_strings = $this->_strings + $strings; } if (is_string($strings)) { return isset($this->_strings[$strings]) ? $this->_strings[$strings] : null; } return $this->_strings; }
php
public function strings($strings = null) { if (is_array($strings)) { return $this->_strings = $this->_strings + $strings; } if (is_string($strings)) { return isset($this->_strings[$strings]) ? $this->_strings[$strings] : null; } return $this->_strings; }
[ "public", "function", "strings", "(", "$", "strings", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "strings", ")", ")", "{", "return", "$", "this", "->", "_strings", "=", "$", "this", "->", "_strings", "+", "$", "strings", ";", "}", "if"...
Manages template strings. @param mixed $strings @return mixed
[ "Manages", "template", "strings", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L364-L372
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.context
public function context($property = null) { if ($property) { return isset($this->_context[$property]) ? $this->_context[$property] : null; } return $this->_context; }
php
public function context($property = null) { if ($property) { return isset($this->_context[$property]) ? $this->_context[$property] : null; } return $this->_context; }
[ "public", "function", "context", "(", "$", "property", "=", "null", ")", "{", "if", "(", "$", "property", ")", "{", "return", "isset", "(", "$", "this", "->", "_context", "[", "$", "property", "]", ")", "?", "$", "this", "->", "_context", "[", "$",...
Returns either one or all context values for this rendering context. Context values persist across all templates rendered in the current context, and are usually outputted in a layout template. @see lithium\template\view\Renderer::$_context @param string $property If unspecified, an associative array of all context values is returned. If a string is specified, the context value matching the name given will be returned, or `null` if that name does not exist. @return mixed A string or array, depending on whether `$property` is specified.
[ "Returns", "either", "one", "or", "all", "context", "values", "for", "this", "rendering", "context", ".", "Context", "values", "persist", "across", "all", "templates", "rendered", "in", "the", "current", "context", "and", "are", "usually", "outputted", "in", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L385-L390
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.handlers
public function handlers($handlers = null) { if (is_array($handlers)) { return $this->_handlers += $handlers; } if (is_string($handlers)) { return isset($this->_handlers[$handlers]) ? $this->_handlers[$handlers] : null; } return $this->_handlers; }
php
public function handlers($handlers = null) { if (is_array($handlers)) { return $this->_handlers += $handlers; } if (is_string($handlers)) { return isset($this->_handlers[$handlers]) ? $this->_handlers[$handlers] : null; } return $this->_handlers; }
[ "public", "function", "handlers", "(", "$", "handlers", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "handlers", ")", ")", "{", "return", "$", "this", "->", "_handlers", "+=", "$", "handlers", ";", "}", "if", "(", "is_string", "(", "$", ...
Gets or adds content handlers from/to this rendering context, depending on the value of `$handlers`. For more on how to implement handlers and the various types, see `applyHandler()`. @see lithium\template\view\Renderer::applyHandler() @see lithium\template\view\Renderer::$_handlers @param mixed $handlers If `$handlers` is empty or no value is provided, the current list of handlers is returned. If `$handlers` is a string, the handler with the name matching the string will be returned, or null if one does not exist. If `$handlers` is an array, the handlers named in the array will be merged into the list of handlers in this rendering context, with the pre-existing handlers taking precedence over those newly added. @return mixed Returns an array of handlers or a single handler reference, depending on the value of `$handlers`.
[ "Gets", "or", "adds", "content", "handlers", "from", "/", "to", "this", "rendering", "context", "depending", "on", "the", "value", "of", "$handlers", ".", "For", "more", "on", "how", "to", "implement", "handlers", "and", "the", "various", "types", "see", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L408-L416
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.applyHandler
public function applyHandler($helper, $method, $name, $value, array $options = []) { if (!(isset($this->_handlers[$name]) && $handler = $this->_handlers[$name])) { return $value; } switch (true) { case is_string($handler) && !$helper: $helper = $this->helper('html'); case is_string($handler) && is_object($helper): return $helper->invokeMethod($handler, [$value, $method, $options]); case is_array($handler) && is_object($handler[0]): list($object, $func) = $handler; return $object->invokeMethod($func, [$value, $method, $options]); case is_callable($handler): return $handler($value, [$helper, $method], $options); default: return $value; } }
php
public function applyHandler($helper, $method, $name, $value, array $options = []) { if (!(isset($this->_handlers[$name]) && $handler = $this->_handlers[$name])) { return $value; } switch (true) { case is_string($handler) && !$helper: $helper = $this->helper('html'); case is_string($handler) && is_object($helper): return $helper->invokeMethod($handler, [$value, $method, $options]); case is_array($handler) && is_object($handler[0]): list($object, $func) = $handler; return $object->invokeMethod($func, [$value, $method, $options]); case is_callable($handler): return $handler($value, [$helper, $method], $options); default: return $value; } }
[ "public", "function", "applyHandler", "(", "$", "helper", ",", "$", "method", ",", "$", "name", ",", "$", "value", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "(", "isset", "(", "$", "this", "->", "_handlers", "[", "$",...
Filters a piece of content through a content handler. A handler can be: - a string containing the name of a method defined in `$helper`. The method is called with 3 parameters: the value to be handled, the helper method called (`$method`) and the `$options` that were passed into `applyHandler`. - an array where the first element is an object reference, and the second element is a method name. The method name given will be called on the object with the same parameters as above. - a closure, which takes the value as the first parameter, an array containing an instance of the calling helper and the calling method name as the second, and `$options` as the third. In all cases, handlers should return the transformed version of `$value`. @see lithium\template\view\Renderer::handlers() @see lithium\template\view\Renderer::$_handlers @param object $helper The instance of the object (usually a helper) that is invoking @param string $method The object (helper) method which is applying the handler to the content @param string $name The name of the value to which the handler is applied, i.e. `'url'`, `'path'` or `'title'`. @param mixed $value The value to be transformed by the handler, which is ultimately returned. @param array $options Any options which should be passed to the handler used in this call. @return mixed The transformed value of `$value`, after it has been processed by a handler.
[ "Filters", "a", "piece", "of", "content", "through", "a", "content", "handler", ".", "A", "handler", "can", "be", ":", "-", "a", "string", "containing", "the", "name", "of", "a", "method", "defined", "in", "$helper", ".", "The", "method", "is", "called",...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L440-L458
UnionOfRAD/lithium
template/view/Renderer.php
Renderer.set
public function set(array $data = []) { $this->_data = $data + $this->_data; $this->_vars = $data + $this->_vars; }
php
public function set(array $data = []) { $this->_data = $data + $this->_data; $this->_vars = $data + $this->_vars; }
[ "public", "function", "set", "(", "array", "$", "data", "=", "[", "]", ")", "{", "$", "this", "->", "_data", "=", "$", "data", "+", "$", "this", "->", "_data", ";", "$", "this", "->", "_vars", "=", "$", "data", "+", "$", "this", "->", "_vars", ...
Allows variables to be set by one template and used in subsequent templates rendered using the same context. For example, a variable can be set in a template and used in an element rendered within a template, or an element or template could set a variable which would be made available in the layout. @param array $data An array of key/value pairs representing local variables that should be made available to all other templates rendered in this rendering context. @return void
[ "Allows", "variables", "to", "be", "set", "by", "one", "template", "and", "used", "in", "subsequent", "templates", "rendered", "using", "the", "same", "context", ".", "For", "example", "a", "variable", "can", "be", "set", "in", "a", "template", "and", "use...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L509-L512
UnionOfRAD/lithium
template/view/Renderer.php
Renderer._render
protected function _render($type, $template, array $data = [], array $options = []) { $context = $this->_options; $options += $this->_options; $result = $this->_view->render($type, $data + $this->_data, compact('template') + $options); $this->_options = $context; return $result; }
php
protected function _render($type, $template, array $data = [], array $options = []) { $context = $this->_options; $options += $this->_options; $result = $this->_view->render($type, $data + $this->_data, compact('template') + $options); $this->_options = $context; return $result; }
[ "protected", "function", "_render", "(", "$", "type", ",", "$", "template", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "context", "=", "$", "this", "->", "_options", ";", "$", "options", ...
Shortcut method used to render elements and other nested templates from inside the templating layer. @see lithium\template\View::$_processes @see lithium\template\View::render() @param string $type The type of template to render, usually either `'element'` or `'template'`. Indicates the process used to render the content. See `lithium\template\View::$_processes` for more info. @param string $template The template file name. For example, if `'header'` is passed, and `$type` is set to `'element'`, then the template rendered will be `views/elements/header.html.php` (assuming the default configuration). @param array $data An array of any other local variables that should be injected into the template. By default, only the values used to render the current template will be sent. If `$data` is non-empty, both sets of variables will be merged. @param array $options Any options accepted by `template\View::render()`. @return string Returns a the rendered template content as a string.
[ "Shortcut", "method", "used", "to", "render", "elements", "and", "other", "nested", "templates", "from", "inside", "the", "templating", "layer", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/view/Renderer.php#L532-L538
UnionOfRAD/lithium
console/command/g11n/Extract.php
Extract.run
public function run() { $this->header('Message Extraction'); if (!$data = $this->_extract()) { $this->error('Yielded no items.'); return 1; } $count = count($data); $this->out("Yielded {$count} item(s)."); $this->out(); $this->header('Message Template Creation'); if (!$this->_writeTemplate($data)) { $this->error('Failed to write template.'); return 1; } $this->out(); return 0; }
php
public function run() { $this->header('Message Extraction'); if (!$data = $this->_extract()) { $this->error('Yielded no items.'); return 1; } $count = count($data); $this->out("Yielded {$count} item(s)."); $this->out(); $this->header('Message Template Creation'); if (!$this->_writeTemplate($data)) { $this->error('Failed to write template.'); return 1; } $this->out(); return 0; }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "header", "(", "'Message Extraction'", ")", ";", "if", "(", "!", "$", "data", "=", "$", "this", "->", "_extract", "(", ")", ")", "{", "$", "this", "->", "error", "(", "'Yielded no items.'...
The main method of the command. @return void
[ "The", "main", "method", "of", "the", "command", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/g11n/Extract.php#L38-L58
UnionOfRAD/lithium
console/command/g11n/Extract.php
Extract._extract
protected function _extract() { $message = []; $message[] = 'A `Catalog` class configuration with an adapter that is capable of'; $message[] = 'handling read requests for the `messageTemplate` category is needed'; $message[] = 'in order to proceed. This may also be referred to as `extractor`.'; $this->out($message); $this->out(); $name = $this->_configuration([ 'adapter' => 'Code', 'path' => $this->source, 'scope' => $this->scope ]); $configs = Catalog::config(); try { return Catalog::read($name, 'messageTemplate', 'root', [ 'scope' => $configs[$name]['scope'], 'lossy' => false ]); } catch (Exception $e) { return false; } }
php
protected function _extract() { $message = []; $message[] = 'A `Catalog` class configuration with an adapter that is capable of'; $message[] = 'handling read requests for the `messageTemplate` category is needed'; $message[] = 'in order to proceed. This may also be referred to as `extractor`.'; $this->out($message); $this->out(); $name = $this->_configuration([ 'adapter' => 'Code', 'path' => $this->source, 'scope' => $this->scope ]); $configs = Catalog::config(); try { return Catalog::read($name, 'messageTemplate', 'root', [ 'scope' => $configs[$name]['scope'], 'lossy' => false ]); } catch (Exception $e) { return false; } }
[ "protected", "function", "_extract", "(", ")", "{", "$", "message", "=", "[", "]", ";", "$", "message", "[", "]", "=", "'A `Catalog` class configuration with an adapter that is capable of'", ";", "$", "message", "[", "]", "=", "'handling read requests for the `message...
Extracts translatable strings from multiple files. @return array Returns the catalog specified. Returns boolean `false` when an error occurs.
[ "Extracts", "translatable", "strings", "from", "multiple", "files", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/g11n/Extract.php#L65-L89
UnionOfRAD/lithium
console/command/g11n/Extract.php
Extract._writeTemplate
protected function _writeTemplate($data) { $message = []; $message[] = 'In order to proceed you need to choose a `Catalog` configuration'; $message[] = 'which is used for writing the template. The adapter for the configuration'; $message[] = 'should be capable of handling write requests for the `messageTemplate`'; $message[] = 'category.'; $this->out($message); $this->out(); $name = $this->_configuration([ 'adapter' => 'Gettext', 'path' => $this->destination, 'scope' => $this->scope ]); if ($name != 'temporary') { $scope = $this->in('Scope:', ['default' => $this->scope]); } $message = []; $message[] = 'The template is now ready to be saved.'; $message[] = 'Please note that an existing template will be overwritten.'; $this->out($message); $this->out(); if ($this->in('Save?', ['choices' => ['y', 'n'], 'default' => 'y']) != 'y') { $this->out('Aborting upon user request.'); $this->stop(1); } try { return Catalog::write($name, 'messageTemplate', 'root', $data, compact('scope')); } catch (Exception $e) { return false; } }
php
protected function _writeTemplate($data) { $message = []; $message[] = 'In order to proceed you need to choose a `Catalog` configuration'; $message[] = 'which is used for writing the template. The adapter for the configuration'; $message[] = 'should be capable of handling write requests for the `messageTemplate`'; $message[] = 'category.'; $this->out($message); $this->out(); $name = $this->_configuration([ 'adapter' => 'Gettext', 'path' => $this->destination, 'scope' => $this->scope ]); if ($name != 'temporary') { $scope = $this->in('Scope:', ['default' => $this->scope]); } $message = []; $message[] = 'The template is now ready to be saved.'; $message[] = 'Please note that an existing template will be overwritten.'; $this->out($message); $this->out(); if ($this->in('Save?', ['choices' => ['y', 'n'], 'default' => 'y']) != 'y') { $this->out('Aborting upon user request.'); $this->stop(1); } try { return Catalog::write($name, 'messageTemplate', 'root', $data, compact('scope')); } catch (Exception $e) { return false; } }
[ "protected", "function", "_writeTemplate", "(", "$", "data", ")", "{", "$", "message", "=", "[", "]", ";", "$", "message", "[", "]", "=", "'In order to proceed you need to choose a `Catalog` configuration'", ";", "$", "message", "[", "]", "=", "'which is used for ...
Prompts for data source and writes template. @param array $data Data to save. @return boolean|void Return `false` if writing the catalog failed.
[ "Prompts", "for", "data", "source", "and", "writes", "template", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/g11n/Extract.php#L97-L132
UnionOfRAD/lithium
console/command/g11n/Extract.php
Extract._configuration
protected function _configuration(array $options = []) { $configs = (array) Catalog::config(); if (isset($configs['temporary'])) { unset($configs['temporary']); } if ($configs) { $this->out('Available `Catalog` Configurations:'); $prompt = 'Please choose a configuration or hit enter to add a new one:'; foreach ($configs as $name => $config) { $this->out(" - {$name}"); } } else { $this->out(' - No configuration found. -'); $prompt = 'Please hit enter to add a temporary configuration:'; } $this->out(); $name = $this->in($prompt, [ 'choices' => array_keys($configs), 'default' => 'temporary' ]); if ($name == 'temporary') { foreach ($options as $option => $default) { $configs[$name][$option] = $this->in(ucfirst($option) . ':', compact('default')); } Catalog::config($configs); } return $name; }
php
protected function _configuration(array $options = []) { $configs = (array) Catalog::config(); if (isset($configs['temporary'])) { unset($configs['temporary']); } if ($configs) { $this->out('Available `Catalog` Configurations:'); $prompt = 'Please choose a configuration or hit enter to add a new one:'; foreach ($configs as $name => $config) { $this->out(" - {$name}"); } } else { $this->out(' - No configuration found. -'); $prompt = 'Please hit enter to add a temporary configuration:'; } $this->out(); $name = $this->in($prompt, [ 'choices' => array_keys($configs), 'default' => 'temporary' ]); if ($name == 'temporary') { foreach ($options as $option => $default) { $configs[$name][$option] = $this->in(ucfirst($option) . ':', compact('default')); } Catalog::config($configs); } return $name; }
[ "protected", "function", "_configuration", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "configs", "=", "(", "array", ")", "Catalog", "::", "config", "(", ")", ";", "if", "(", "isset", "(", "$", "configs", "[", "'temporary'", "]", ")",...
Helps in selecting or - if required - adding a new `Catalog` collection used for extracting or writing the template. A special configuration with the name `temporary` may be created. Should a configuration with that same name exist prior to entering this method it will be unset. @param array $options Options paired with defaults to prompt for. @return string The name of the selected or newly created configuration.
[ "Helps", "in", "selecting", "or", "-", "if", "required", "-", "adding", "a", "new", "Catalog", "collection", "used", "for", "extracting", "or", "writing", "the", "template", ".", "A", "special", "configuration", "with", "the", "name", "temporary", "may", "be...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/g11n/Extract.php#L143-L175
UnionOfRAD/lithium
storage/session/adapter/Cookie.php
Cookie.read
public function read($key = null, array $options = []) { return function($params) { $key = $params['key']; if (!$key) { if (isset($_COOKIE[$this->_config['name']])) { return $_COOKIE[$this->_config['name']]; } return []; } if (strpos($key, '.') !== false) { $key = explode('.', $key); if (isset($_COOKIE[$this->_config['name']])) { $result = $_COOKIE[$this->_config['name']]; } else { $result = []; } foreach ($key as $k) { if (!isset($result[$k])) { return null; } $result = $result[$k]; } return $result; } if (isset($_COOKIE[$this->_config['name']][$key])) { return $_COOKIE[$this->_config['name']][$key]; } }; }
php
public function read($key = null, array $options = []) { return function($params) { $key = $params['key']; if (!$key) { if (isset($_COOKIE[$this->_config['name']])) { return $_COOKIE[$this->_config['name']]; } return []; } if (strpos($key, '.') !== false) { $key = explode('.', $key); if (isset($_COOKIE[$this->_config['name']])) { $result = $_COOKIE[$this->_config['name']]; } else { $result = []; } foreach ($key as $k) { if (!isset($result[$k])) { return null; } $result = $result[$k]; } return $result; } if (isset($_COOKIE[$this->_config['name']][$key])) { return $_COOKIE[$this->_config['name']][$key]; } }; }
[ "public", "function", "read", "(", "$", "key", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "function", "(", "$", "params", ")", "{", "$", "key", "=", "$", "params", "[", "'key'", "]", ";", "if", "(", "!", "$", ...
Read a value from the cookie. @param null|string $key Key of the entry to be read. If $key is null, returns all cookie key/value pairs that have been set. @param array $options Options array. Not used in this adapter. @return \Closure Function returning data in the session if successful, `null` otherwise.
[ "Read", "a", "value", "from", "the", "cookie", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Cookie.php#L113-L143
UnionOfRAD/lithium
storage/session/adapter/Cookie.php
Cookie.write
public function write($key, $value = null, array $options = []) { $expire = (!isset($options['expire']) && empty($this->_config['expire'])); $cookieClass = __CLASS__; if ($expire && $key !== $this->_config['name']) { return null; } $expires = (isset($options['expire'])) ? $options['expire'] : $this->_config['expire']; return function($params) use (&$expires, $cookieClass) { $key = $params['key']; $value = $params['value']; $key = [$key => $value]; if (is_array($value)) { $key = Set::flatten($key); } foreach ($key as $name => $val) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), $val, strtotime($expires), $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error setting {$name} cookie."); } } return true; }; }
php
public function write($key, $value = null, array $options = []) { $expire = (!isset($options['expire']) && empty($this->_config['expire'])); $cookieClass = __CLASS__; if ($expire && $key !== $this->_config['name']) { return null; } $expires = (isset($options['expire'])) ? $options['expire'] : $this->_config['expire']; return function($params) use (&$expires, $cookieClass) { $key = $params['key']; $value = $params['value']; $key = [$key => $value]; if (is_array($value)) { $key = Set::flatten($key); } foreach ($key as $name => $val) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), $val, strtotime($expires), $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error setting {$name} cookie."); } } return true; }; }
[ "public", "function", "write", "(", "$", "key", ",", "$", "value", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "expire", "=", "(", "!", "isset", "(", "$", "options", "[", "'expire'", "]", ")", "&&", "empty", "(", "$...
Write a value to the cookie store. @param string $key Key of the item to be stored. @param mixed $value The value to be stored. @param array $options Options array. @return \Closure Function returning boolean `true` on successful write, `false` otherwise.
[ "Write", "a", "value", "to", "the", "cookie", "store", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Cookie.php#L153-L186
UnionOfRAD/lithium
storage/session/adapter/Cookie.php
Cookie.delete
public function delete($key, array $options = []) { $cookieClass = get_called_class(); return function($params) use ($cookieClass) { $key = $params['key']; $path = '/' . str_replace('.', '/', $this->_config['name'] . '.' . $key) . '/.'; $cookies = current(Set::extract($_COOKIE, $path)); if (is_array($cookies)) { $cookies = array_keys(Set::flatten($cookies)); foreach ($cookies as &$name) { $name = $key . '.' . $name; } } else { $cookies = [$key]; } foreach ($cookies as &$name) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), "", 1, $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error deleting {$name} cookie."); } } return true; }; }
php
public function delete($key, array $options = []) { $cookieClass = get_called_class(); return function($params) use ($cookieClass) { $key = $params['key']; $path = '/' . str_replace('.', '/', $this->_config['name'] . '.' . $key) . '/.'; $cookies = current(Set::extract($_COOKIE, $path)); if (is_array($cookies)) { $cookies = array_keys(Set::flatten($cookies)); foreach ($cookies as &$name) { $name = $key . '.' . $name; } } else { $cookies = [$key]; } foreach ($cookies as &$name) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), "", 1, $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error deleting {$name} cookie."); } } return true; }; }
[ "public", "function", "delete", "(", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "cookieClass", "=", "get_called_class", "(", ")", ";", "return", "function", "(", "$", "params", ")", "use", "(", "$", "cookieClass", ")", "{...
Delete a value from the cookie store. @param string $key The key to be deleted from the cookie store. @param array $options Options array. @return \Closure Function returning boolean `true` on successful delete, `false` otherwise.
[ "Delete", "a", "value", "from", "the", "cookie", "store", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Cookie.php#L195-L226
UnionOfRAD/lithium
storage/session/adapter/Cookie.php
Cookie.clear
public function clear(array $options = []) { $options += ['destroySession' => true]; $cookieClass = get_called_class(); return function($params) use ($options, $cookieClass) { if ($options['destroySession'] && session_id()) { session_destroy(); } if (!isset($_COOKIE[$this->_config['name']])) { return true; } $cookies = array_keys(Set::flatten($_COOKIE[$this->_config['name']])); foreach ($cookies as $name) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), "", 1, $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error clearing {$cookie} cookie."); } } unset($_COOKIE[$this->_config['name']]); return true; }; }
php
public function clear(array $options = []) { $options += ['destroySession' => true]; $cookieClass = get_called_class(); return function($params) use ($options, $cookieClass) { if ($options['destroySession'] && session_id()) { session_destroy(); } if (!isset($_COOKIE[$this->_config['name']])) { return true; } $cookies = array_keys(Set::flatten($_COOKIE[$this->_config['name']])); foreach ($cookies as $name) { $result = setcookie( $cookieClass::keyFormat($name, $this->_config), "", 1, $this->_config['path'], $this->_config['domain'], $this->_config['secure'], $this->_config['httponly'] ); if (!$result) { throw new RuntimeException("There was an error clearing {$cookie} cookie."); } } unset($_COOKIE[$this->_config['name']]); return true; }; }
[ "public", "function", "clear", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "+=", "[", "'destroySession'", "=>", "true", "]", ";", "$", "cookieClass", "=", "get_called_class", "(", ")", ";", "return", "function", "(", "$", "pa...
Clears all cookies. @param array $options Options array. Not used fro this adapter method. @return boolean True on successful clear, false otherwise.
[ "Clears", "all", "cookies", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Cookie.php#L234-L263
UnionOfRAD/lithium
security/auth/adapter/Form.php
Form._init
protected function _init() { parent::_init(); foreach ($this->_fields as $key => $val) { if (is_int($key)) { unset($this->_fields[$key]); $this->_fields[$val] = $val; } } if (!class_exists($model = Libraries::locate('models', $this->_model))) { throw new ClassNotFoundException("Model class '{$this->_model}' not found."); } $this->_model = $model; }
php
protected function _init() { parent::_init(); foreach ($this->_fields as $key => $val) { if (is_int($key)) { unset($this->_fields[$key]); $this->_fields[$val] = $val; } } if (!class_exists($model = Libraries::locate('models', $this->_model))) { throw new ClassNotFoundException("Model class '{$this->_model}' not found."); } $this->_model = $model; }
[ "protected", "function", "_init", "(", ")", "{", "parent", "::", "_init", "(", ")", ";", "foreach", "(", "$", "this", "->", "_fields", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "unset", "...
Initializes values configured in the constructor. @return void
[ "Initializes", "values", "configured", "in", "the", "constructor", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/auth/adapter/Form.php#L307-L320
UnionOfRAD/lithium
security/auth/adapter/Form.php
Form.check
public function check($credentials, array $options = []) { $model = $this->_model; $query = $this->_query; $data = $this->_filters($this->_data($credentials->data)); $validate = array_flip(array_intersect_key($this->_fields, $this->_validators)); $conditions = $this->_scope + array_diff_key($data, $validate); $user = $model::$query(compact('conditions') + $options); if (!$user) { return false; } return $this->_validate($user, $data); }
php
public function check($credentials, array $options = []) { $model = $this->_model; $query = $this->_query; $data = $this->_filters($this->_data($credentials->data)); $validate = array_flip(array_intersect_key($this->_fields, $this->_validators)); $conditions = $this->_scope + array_diff_key($data, $validate); $user = $model::$query(compact('conditions') + $options); if (!$user) { return false; } return $this->_validate($user, $data); }
[ "public", "function", "check", "(", "$", "credentials", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "model", "=", "$", "this", "->", "_model", ";", "$", "query", "=", "$", "this", "->", "_query", ";", "$", "data", "=", "$", "this"...
Called by the `Auth` class to run an authentication check against a model class using the credentials in a data container (a `Request` object), and returns an array of user information on success, or `false` on failure. @param object $credentials A data container which wraps the authentication credentials used to query the model (usually a `Request` object). See the documentation for this class for further details. @param array $options Additional configuration options. Not currently implemented in this adapter. @return array Returns an array containing user information on success, or `false` on failure.
[ "Called", "by", "the", "Auth", "class", "to", "run", "an", "authentication", "check", "against", "a", "model", "class", "using", "the", "credentials", "in", "a", "data", "container", "(", "a", "Request", "object", ")", "and", "returns", "an", "array", "of"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/auth/adapter/Form.php#L334-L347
UnionOfRAD/lithium
security/auth/adapter/Form.php
Form._filters
protected function _filters($data) { $result = []; foreach ($this->_fields as $from => $to) { $result[$to] = isset($data[$from]) ? $data[$from] : null; if (!isset($this->_filters[$from])) { $result[$to] = is_scalar($result[$to]) ? $result[$to] : null; continue; } if ($this->_filters[$from] === false) { continue; } if (!is_callable($this->_filters[$from])) { $message = "Authentication filter for `{$from}` is not callable."; throw new UnexpectedValueException($message); } $result[$to] = call_user_func($this->_filters[$from], $result[$to]); } if (!isset($this->_filters[0])) { return $result; } if (!is_callable($this->_filters[0])) { throw new UnexpectedValueException("Authentication filter is not callable."); } return call_user_func($this->_filters[0], $result); }
php
protected function _filters($data) { $result = []; foreach ($this->_fields as $from => $to) { $result[$to] = isset($data[$from]) ? $data[$from] : null; if (!isset($this->_filters[$from])) { $result[$to] = is_scalar($result[$to]) ? $result[$to] : null; continue; } if ($this->_filters[$from] === false) { continue; } if (!is_callable($this->_filters[$from])) { $message = "Authentication filter for `{$from}` is not callable."; throw new UnexpectedValueException($message); } $result[$to] = call_user_func($this->_filters[$from], $result[$to]); } if (!isset($this->_filters[0])) { return $result; } if (!is_callable($this->_filters[0])) { throw new UnexpectedValueException("Authentication filter is not callable."); } return call_user_func($this->_filters[0], $result); }
[ "protected", "function", "_filters", "(", "$", "data", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_fields", "as", "$", "from", "=>", "$", "to", ")", "{", "$", "result", "[", "$", "to", "]", "=", "isset", "(...
Iterates over the filters configured in `$_filters` which are applied to submitted form data _before_ it is used in the query. @see lithium\security\auth\adapter\Form::$_filters @param array $data The array of raw form data to be filtered. @return array Callback result.
[ "Iterates", "over", "the", "filters", "configured", "in", "$_filters", "which", "are", "applied", "to", "submitted", "form", "data", "_before_", "it", "is", "used", "in", "the", "query", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/auth/adapter/Form.php#L378-L404
UnionOfRAD/lithium
security/auth/adapter/Form.php
Form._validate
protected function _validate($user, array $data) { foreach ($this->_validators as $field => $validator) { if (!isset($this->_fields[$field]) || $field === 0) { continue; } if (!is_callable($validator)) { $message = "Authentication validator for `{$field}` is not callable."; throw new UnexpectedValueException($message); } $field = $this->_fields[$field]; $value = isset($data[$field]) ? $data[$field] : null; if (!call_user_func($validator, $value, $user->data($field))) { return false; } } $user = $user->data(); if (!isset($this->_validators[0])) { return $user; } if (!is_callable($this->_validators[0])) { throw new UnexpectedValueException("Authentication validator is not callable."); } return call_user_func($this->_validators[0], $data, $user) ? $user : false; }
php
protected function _validate($user, array $data) { foreach ($this->_validators as $field => $validator) { if (!isset($this->_fields[$field]) || $field === 0) { continue; } if (!is_callable($validator)) { $message = "Authentication validator for `{$field}` is not callable."; throw new UnexpectedValueException($message); } $field = $this->_fields[$field]; $value = isset($data[$field]) ? $data[$field] : null; if (!call_user_func($validator, $value, $user->data($field))) { return false; } } $user = $user->data(); if (!isset($this->_validators[0])) { return $user; } if (!is_callable($this->_validators[0])) { throw new UnexpectedValueException("Authentication validator is not callable."); } return call_user_func($this->_validators[0], $data, $user) ? $user : false; }
[ "protected", "function", "_validate", "(", "$", "user", ",", "array", "$", "data", ")", "{", "foreach", "(", "$", "this", "->", "_validators", "as", "$", "field", "=>", "$", "validator", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_...
After an authentication query against the configured model class has occurred, this method iterates over the configured validators and checks each one by passing the submitted form value as the first parameter, and the corresponding database value as the second. The validator then returns a boolean to indicate success. If the validator fails, it will cause the entire authentication operation to fail. Note that any filters applied to a form field will affect the data passed to the validator. @see lithium\security\auth\adapter\Form::__construct() @see lithium\security\auth\adapter\Form::$_validators @param object $user The user object returned from the database. This object must support a `data()` method, which returns the object's array representation, and also returns individual field values by name. @param array $data The form data submitted in the request and passed to `Form::check()`. @return array Returns an array of authenticated user data on success, otherwise `false` if any of the configured validators fails. See `'validators'` in the `$config` parameter of `__construct()`.
[ "After", "an", "authentication", "query", "against", "the", "configured", "model", "class", "has", "occurred", "this", "method", "iterates", "over", "the", "configured", "validators", "and", "checks", "each", "one", "by", "passing", "the", "submitted", "form", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/auth/adapter/Form.php#L424-L451
UnionOfRAD/lithium
security/auth/adapter/Form.php
Form._data
protected function _data($data) { $model = $this->_model; $index = strtolower(Inflector::singularize($model::meta('name'))); return isset($data[$index]) && is_array($data[$index]) ? $data[$index] : $data; }
php
protected function _data($data) { $model = $this->_model; $index = strtolower(Inflector::singularize($model::meta('name'))); return isset($data[$index]) && is_array($data[$index]) ? $data[$index] : $data; }
[ "protected", "function", "_data", "(", "$", "data", ")", "{", "$", "model", "=", "$", "this", "->", "_model", ";", "$", "index", "=", "strtolower", "(", "Inflector", "::", "singularize", "(", "$", "model", "::", "meta", "(", "'name'", ")", ")", ")", ...
Checks if the data container values are inside indexed arrays from binding. Get the values from the binding coresponding to the model if such exists. @see lithium\security\auth\adapter\Form::check @param array $data The array of raw form data. @return array Original or sub array of the form data.
[ "Checks", "if", "the", "data", "container", "values", "are", "inside", "indexed", "arrays", "from", "binding", ".", "Get", "the", "values", "from", "the", "binding", "coresponding", "to", "the", "model", "if", "such", "exists", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/auth/adapter/Form.php#L461-L465
UnionOfRAD/lithium
data/source/mongo_db/Exporter.php
Exporter._update
protected static function _update($export) { $export += [ 'data' => [], 'update' => [], 'remove' => [], 'rename' => [], 'key' => '' ]; $path = $export['key'] ? "{$export['key']}." : ""; $result = ['update' => [], 'remove' => []]; $left = static::_diff($export['data'], $export['update']); $right = static::_diff($export['update'], $export['data']); $objects = array_filter($export['update'], function($value) { return (is_object($value) && method_exists($value, 'export')); }); array_map(function($key) use (&$left) { unset($left[$key]); }, array_keys($right)); foreach ($left as $key => $value) { $result = static::_append($result, "{$path}{$key}", $value, 'remove'); } $update = $right + $objects; foreach ($update as $key => $value) { $original = $export['data']; $isArray = is_object($value) && $value instanceof static::$_classes['set']; $options = [ 'indexed' => null, 'handlers' => [ 'MongoDate' => function($value) { return $value; }, 'MongoId' => function($value) { return $value; } ] ]; if ($isArray) { $newValue = $value->to('array', $options); $originalValue = null; $shouldConvert = (isset($original[$key]) && ( $original[$key] instanceof static::$_classes['set'] || $original[$key] instanceof static::$_classes['entity'] )); if ($shouldConvert) { $originalValue = $original[$key]->to('array', $options); } if ($newValue !== $originalValue) { $value = $newValue; } } $result = static::_append($result, "{$path}{$key}", $value, 'update'); } return array_filter($result); }
php
protected static function _update($export) { $export += [ 'data' => [], 'update' => [], 'remove' => [], 'rename' => [], 'key' => '' ]; $path = $export['key'] ? "{$export['key']}." : ""; $result = ['update' => [], 'remove' => []]; $left = static::_diff($export['data'], $export['update']); $right = static::_diff($export['update'], $export['data']); $objects = array_filter($export['update'], function($value) { return (is_object($value) && method_exists($value, 'export')); }); array_map(function($key) use (&$left) { unset($left[$key]); }, array_keys($right)); foreach ($left as $key => $value) { $result = static::_append($result, "{$path}{$key}", $value, 'remove'); } $update = $right + $objects; foreach ($update as $key => $value) { $original = $export['data']; $isArray = is_object($value) && $value instanceof static::$_classes['set']; $options = [ 'indexed' => null, 'handlers' => [ 'MongoDate' => function($value) { return $value; }, 'MongoId' => function($value) { return $value; } ] ]; if ($isArray) { $newValue = $value->to('array', $options); $originalValue = null; $shouldConvert = (isset($original[$key]) && ( $original[$key] instanceof static::$_classes['set'] || $original[$key] instanceof static::$_classes['entity'] )); if ($shouldConvert) { $originalValue = $original[$key]->to('array', $options); } if ($newValue !== $originalValue) { $value = $newValue; } } $result = static::_append($result, "{$path}{$key}", $value, 'update'); } return array_filter($result); }
[ "protected", "static", "function", "_update", "(", "$", "export", ")", "{", "$", "export", "+=", "[", "'data'", "=>", "[", "]", ",", "'update'", "=>", "[", "]", ",", "'remove'", "=>", "[", "]", ",", "'rename'", "=>", "[", "]", ",", "'key'", "=>", ...
Calculates changesets for update operations, and produces an array which can be converted to a set of native MongoDB update operations. @todo Implement remove and rename. @param array $export An array of fields exported from a call to `Document::export()`, and should contain the following keys: - `'data'` _array_: An array representing the original data loaded from the database for the document. - `'update'` _array_: An array representing the current state of the document, containing any modifications made. - `'key'` _string_: If this is a nested document, this is a dot-separated path from the root-level document. @return array Returns an array representing the changes to be made to the document. These are converted to database-native commands by the `toCommand()` method.
[ "Calculates", "changesets", "for", "update", "operations", "and", "produces", "an", "array", "which", "can", "be", "converted", "to", "a", "set", "of", "native", "MongoDB", "update", "operations", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/mongo_db/Exporter.php#L88-L140
UnionOfRAD/lithium
data/source/mongo_db/Exporter.php
Exporter._diff
protected static function _diff($left, $right) { $result = []; foreach ($left as $key => $value) { if (!array_key_exists($key, $right) || $left[$key] !== $right[$key]) { $result[$key] = $value; } } return $result; }
php
protected static function _diff($left, $right) { $result = []; foreach ($left as $key => $value) { if (!array_key_exists($key, $right) || $left[$key] !== $right[$key]) { $result[$key] = $value; } } return $result; }
[ "protected", "static", "function", "_diff", "(", "$", "left", ",", "$", "right", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "left", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$...
Handle diffing operations between `Document` object states. Implemented because all of PHP's array comparison functions are broken when working with objects. @param array $left The left-hand comparison array. @param array $right The right-hand comparison array. @return array Returns an array of the differences of `$left` compared to `$right`.
[ "Handle", "diffing", "operations", "between", "Document", "object", "states", ".", "Implemented", "because", "all", "of", "PHP", "s", "array", "comparison", "functions", "are", "broken", "when", "working", "with", "objects", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/mongo_db/Exporter.php#L150-L159
UnionOfRAD/lithium
data/source/mongo_db/Exporter.php
Exporter._append
protected static function _append($changes, $key, $value, $change) { $options = ['finalize' => false]; if (!is_object($value) || !method_exists($value, 'export')) { $changes[$change][$key] = ($change === 'update') ? $value : true; return $changes; } if (!$value->exists()) { $changes[$change][$key] = static::_create($value->export(), $options); return $changes; } if ($change === 'update') { $export = compact('key') + $value->export(); return Set::merge($changes, static::_update($export)); } if ($children = static::_update($value->export())) { return Set::merge($changes, $children); } $changes[$change][$key] = true; return $changes; }
php
protected static function _append($changes, $key, $value, $change) { $options = ['finalize' => false]; if (!is_object($value) || !method_exists($value, 'export')) { $changes[$change][$key] = ($change === 'update') ? $value : true; return $changes; } if (!$value->exists()) { $changes[$change][$key] = static::_create($value->export(), $options); return $changes; } if ($change === 'update') { $export = compact('key') + $value->export(); return Set::merge($changes, static::_update($export)); } if ($children = static::_update($value->export())) { return Set::merge($changes, $children); } $changes[$change][$key] = true; return $changes; }
[ "protected", "static", "function", "_append", "(", "$", "changes", ",", "$", "key", ",", "$", "value", ",", "$", "change", ")", "{", "$", "options", "=", "[", "'finalize'", "=>", "false", "]", ";", "if", "(", "!", "is_object", "(", "$", "value", ")...
Handles appending nested objects to document changesets. @param array $changes The full set of changes to be made to the database. @param string $key The key of the field to append, which may be a dot-separated path if the value is or is contained within a nested object. @param mixed $value The value to append to the changeset. Can be a scalar value, array, a nested object, or part of a nested object. @param string $change The type of change, as to whether update/remove or rename etc. @return array Returns the value of `$changes`, with any new changed values appended.
[ "Handles", "appending", "nested", "objects", "to", "document", "changesets", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/mongo_db/Exporter.php#L172-L192
UnionOfRAD/lithium
security/Auth.php
Auth._initConfig
protected static function _initConfig($name, $config) { $defaults = ['session' => [ 'key' => $name, 'class' => static::$_classes['session'], 'options' => [], 'persist' => [] ]]; $config = parent::_initConfig($name, $config) + $defaults; $config['session'] += $defaults['session']; return $config; }
php
protected static function _initConfig($name, $config) { $defaults = ['session' => [ 'key' => $name, 'class' => static::$_classes['session'], 'options' => [], 'persist' => [] ]]; $config = parent::_initConfig($name, $config) + $defaults; $config['session'] += $defaults['session']; return $config; }
[ "protected", "static", "function", "_initConfig", "(", "$", "name", ",", "$", "config", ")", "{", "$", "defaults", "=", "[", "'session'", "=>", "[", "'key'", "=>", "$", "name", ",", "'class'", "=>", "static", "::", "$", "_classes", "[", "'session'", "]...
Called when an adapter configuration is first accessed, this method sets the default configuration for session handling. While each configuration can use its own session class and options, this method initializes them to the default dependencies written into the class. For the session key name, the default value is set to the name of the configuration. @param string $name The name of the adapter configuration being accessed. @param array $config The user-specified configuration. @return array Returns an array that merges the user-specified configuration with the generated default values.
[ "Called", "when", "an", "adapter", "configuration", "is", "first", "accessed", "this", "method", "sets", "the", "default", "configuration", "for", "session", "handling", ".", "While", "each", "configuration", "can", "use", "its", "own", "session", "class", "and"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Auth.php#L86-L96
UnionOfRAD/lithium
security/Auth.php
Auth.check
public static function check($name, $credentials = null, array $options = []) { $config = static::config($name); $defaults = [ 'checkSession' => true, 'writeSession' => true, 'persist' => $config['session']['persist'] ?: static::_config('persist') ]; $options += $defaults; $params = compact('name', 'credentials', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); if ($config === null) { throw new ConfigException("Configuration `{$name}` has not been defined."); } $session = $config['session']; if ($options['checkSession']) { if ($data = $session['class']::read($session['key'], $session['options'])) { return $data; } } if (($credentials) && $data = static::adapter($name)->check($credentials, $options)) { if ($options['persist'] && is_array($data)) { $data = array_intersect_key($data, array_fill_keys($options['persist'], true)); } elseif (is_array($data)) { unset($data['password']); } return ($options['writeSession']) ? static::set($name, $data) : $data; } return false; }); }
php
public static function check($name, $credentials = null, array $options = []) { $config = static::config($name); $defaults = [ 'checkSession' => true, 'writeSession' => true, 'persist' => $config['session']['persist'] ?: static::_config('persist') ]; $options += $defaults; $params = compact('name', 'credentials', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); if ($config === null) { throw new ConfigException("Configuration `{$name}` has not been defined."); } $session = $config['session']; if ($options['checkSession']) { if ($data = $session['class']::read($session['key'], $session['options'])) { return $data; } } if (($credentials) && $data = static::adapter($name)->check($credentials, $options)) { if ($options['persist'] && is_array($data)) { $data = array_intersect_key($data, array_fill_keys($options['persist'], true)); } elseif (is_array($data)) { unset($data['password']); } return ($options['writeSession']) ? static::set($name, $data) : $data; } return false; }); }
[ "public", "static", "function", "check", "(", "$", "name", ",", "$", "credentials", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "config", "=", "static", "::", "config", "(", "$", "name", ")", ";", "$", "defaults", "=", ...
Performs an authentication check against the specified configuration, and writes the resulting user information to the session such that credentials are not required for subsequent authentication checks, and user information is returned directly from the session. @param string $name The name of the `Auth` configuration/adapter to check against. @param mixed $credentials A container for the authentication credentials used in this check. This will vary by adapter, but generally will be an object or array containing a user name and password. In the case of the `Form` adapter, it contains a `Request` object containing `POST` data with user login information. @param array $options Additional options used when performing the authentication check. The options available will vary by adapter, please consult the documentation for the `check()` method of the adapter you intend to use. The global options for this method are: - `'checkSession'` _boolean_: By default, the session store configured for the adapter will always be queried first, to see if an authentication check has already been performed during the current user session. If yes, then the session data will be returned. By setting `'checkSession'` to `false`, session checks are bypassed and the credentials provided are always checked against the adapter directly. - `'writeSession'` _boolean_: Upon a successful credentials check, the returned user information is, by default, written to the session. Set this to `false` to disable session writing for this authentication check. - `'persist'` _array_: A list of fields that should be stored in the session. If no list is provided will store all fields in the session except the `'password'` field. @return array After a successful credential check against the adapter (or a successful lookup against the current session), returns an array of user information from the storage backend used by the configured adapter. @filter
[ "Performs", "an", "authentication", "check", "against", "the", "specified", "configuration", "and", "writes", "the", "resulting", "user", "information", "to", "the", "session", "such", "that", "credentials", "are", "not", "required", "for", "subsequent", "authentica...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Auth.php#L129-L165
UnionOfRAD/lithium
security/Auth.php
Auth.set
public static function set($name, $data, array $options = []) { $params = compact('name', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); $session = $config['session']; if ($data = static::adapter($name)->set($data, $options)) { $session['class']::write($session['key'], $data, $options + $session['options']); return $data; } return false; }); }
php
public static function set($name, $data, array $options = []) { $params = compact('name', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); $session = $config['session']; if ($data = static::adapter($name)->set($data, $options)) { $session['class']::write($session['key'], $data, $options + $session['options']); return $data; } return false; }); }
[ "public", "static", "function", "set", "(", "$", "name", ",", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'name'", ",", "'data'", ",", "'options'", ")", ";", "return", "Filters", "::", "r...
Manually authenticate a user with the given set of data. Rather than checking a user's credentials, this method allows you to manually specify a user for whom you'd like to initialize an authenticated session. By default, before writing the data to the session, the `set()` method of the named configuration's adapter receives the data to be written, and has an opportunity to modify or reject it. @param string $name The name of the adapter configuration to. @param array $data The user data to be written to the session. @param array $options Any additional session-writing options. These may override any options set by the default session configuration for `$name`. @return array Returns the array of data written to the session, or `false` if the adapter rejects the data. @filter
[ "Manually", "authenticate", "a", "user", "with", "the", "given", "set", "of", "data", ".", "Rather", "than", "checking", "a", "user", "s", "credentials", "this", "method", "allows", "you", "to", "manually", "specify", "a", "user", "for", "whom", "you", "d"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Auth.php#L184-L198
UnionOfRAD/lithium
security/Auth.php
Auth.clear
public static function clear($name, array $options = []) { $defaults = ['clearSession' => true]; $options += $defaults; $params = compact('name', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); $session = $config['session']; if ($options['clearSession']) { $session['class']::delete($session['key'], $session['options']); } static::adapter($name)->clear($options); }); }
php
public static function clear($name, array $options = []) { $defaults = ['clearSession' => true]; $options += $defaults; $params = compact('name', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); $config = static::_config($name); $session = $config['session']; if ($options['clearSession']) { $session['class']::delete($session['key'], $session['options']); } static::adapter($name)->clear($options); }); }
[ "public", "static", "function", "clear", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'clearSession'", "=>", "true", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$", "params", "=", "...
Removes session information for the given configuration, and allows the configuration's adapter to perform any associated cleanup tasks. @param string $name The name of the `Auth` configuration to clear the login information for. Calls the `clear()` method of the given configuration's adapter, and removes the information in the session key used by this configuration. @param array $options Additional options used when clearing the authenticated session. See each adapter's `clear()` method for all available options. Global options: - `'clearSession'` _boolean_: If `true` (the default), session data for the specified configuration is removed, otherwise it is retained. @return void @filter
[ "Removes", "session", "information", "for", "the", "given", "configuration", "and", "allows", "the", "configuration", "s", "adapter", "to", "perform", "any", "associated", "cleanup", "tasks", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Auth.php#L214-L230
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.read
public function read(array $keys) { $results = []; foreach ($keys as $key) { if (array_key_exists($key, $this->_cache)) { $results[$key] = $this->_cache[$key]; } } return $results; }
php
public function read(array $keys) { $results = []; foreach ($keys as $key) { if (array_key_exists($key, $this->_cache)) { $results[$key] = $this->_cache[$key]; } } return $results; }
[ "public", "function", "read", "(", "array", "$", "keys", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_cache", ")",...
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/Memory.php#L67-L76
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.write
public function write(array $keys, $expiry = null) { foreach ($keys as $key => &$value) { $this->_cache[$key] = $value; } return true; }
php
public function write(array $keys, $expiry = null) { foreach ($keys as $key => &$value) { $this->_cache[$key] = $value; } return true; }
[ "public", "function", "write", "(", "array", "$", "keys", ",", "$", "expiry", "=", "null", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "$", "this", "->", "_cache", "[", "$", "key", "]", "=", "$", ...
Write values to the cache. @param array $keys Key/value pairs with keys to uniquely identify the to-be-cached item. @param mixed $data The value to be cached. @param null|string $expiry Unused. @return boolean `true` on successful write, `false` otherwise.
[ "Write", "values", "to", "the", "cache", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memory.php#L86-L91
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.delete
public function delete(array $keys) { foreach ($keys as $key) { if (!isset($this->_cache[$key])) { return false; } unset($this->_cache[$key]); } return true; }
php
public function delete(array $keys) { foreach ($keys as $key) { if (!isset($this->_cache[$key])) { return false; } unset($this->_cache[$key]); } return true; }
[ "public", "function", "delete", "(", "array", "$", "keys", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_cache", "[", "$", "key", "]", ")", ")", "{", "return", "false", ";"...
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/Memory.php#L99-L107
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.decrement
public function decrement($key, $offset = 1) { if (!array_key_exists($key, $this->_cache)) { return false; } return $this->_cache[$key] -= $offset; }
php
public function decrement($key, $offset = 1) { if (!array_key_exists($key, $this->_cache)) { return false; } return $this->_cache[$key] -= $offset; }
[ "public", "function", "decrement", "(", "$", "key", ",", "$", "offset", "=", "1", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_cache", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", ...
Performs a decrement operation on specified numeric cache item. @param string $key Key of numeric cache item to decrement. @param integer $offset Offset to decrement - defaults to `1`. @return integer|boolean The item's new value on successful decrement, else `false`.
[ "Performs", "a", "decrement", "operation", "on", "specified", "numeric", "cache", "item", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memory.php#L116-L121
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.increment
public function increment($key, $offset = 1) { if (!array_key_exists($key, $this->_cache)) { return false; } return $this->_cache[$key] += $offset; }
php
public function increment($key, $offset = 1) { if (!array_key_exists($key, $this->_cache)) { return false; } return $this->_cache[$key] += $offset; }
[ "public", "function", "increment", "(", "$", "key", ",", "$", "offset", "=", "1", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_cache", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", ...
Performs an increment operation on specified numeric cache item. @param string $key Key of numeric cache item to increment. @param integer $offset Offset to increment - defaults to `1`. @return integer|boolean The item's new value on successful increment, else `false`.
[ "Performs", "an", "increment", "operation", "on", "specified", "numeric", "cache", "item", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memory.php#L130-L135
UnionOfRAD/lithium
storage/cache/adapter/Memory.php
Memory.clear
public function clear() { foreach ($this->_cache as $key => &$value) { unset($this->_cache[$key]); } return true; }
php
public function clear() { foreach ($this->_cache as $key => &$value) { unset($this->_cache[$key]); } return true; }
[ "public", "function", "clear", "(", ")", "{", "foreach", "(", "$", "this", "->", "_cache", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "unset", "(", "$", "this", "->", "_cache", "[", "$", "key", "]", ")", ";", "}", "return", "true", ";...
Clears entire cache by flushing it. All cache keys using the configuration but *without* honoring the scope are removed. The operation will continue to remove keys even if removing one single key fails, clearing thoroughly as possible. In any case this method will return `true`. @return boolean Always returns `true`.
[ "Clears", "entire", "cache", "by", "flushing", "it", ".", "All", "cache", "keys", "using", "the", "configuration", "but", "*", "without", "*", "honoring", "the", "scope", "are", "removed", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Memory.php#L147-L152
UnionOfRAD/lithium
core/Environment.php
Environment.reset
public static function reset($env = null) { if ($env) { unset(static::$_configurations[$env]); return; } static::$_current = ''; static::$_detector = null; static::$_configurations = [ 'production' => [], 'development' => [], 'test' => [] ]; }
php
public static function reset($env = null) { if ($env) { unset(static::$_configurations[$env]); return; } static::$_current = ''; static::$_detector = null; static::$_configurations = [ 'production' => [], 'development' => [], 'test' => [] ]; }
[ "public", "static", "function", "reset", "(", "$", "env", "=", "null", ")", "{", "if", "(", "$", "env", ")", "{", "unset", "(", "static", "::", "$", "_configurations", "[", "$", "env", "]", ")", ";", "return", ";", "}", "static", "::", "$", "_cur...
Resets the `Environment` class to its default state, including unsetting the current environment, removing any environment-specific configurations, and removing the custom environment detector, if any has been specified. @param $env If set, delete the defined environment only.
[ "Resets", "the", "Environment", "class", "to", "its", "default", "state", "including", "unsetting", "the", "current", "environment", "removing", "any", "environment", "-", "specific", "configurations", "and", "removing", "the", "custom", "environment", "detector", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Environment.php#L124-L136
UnionOfRAD/lithium
core/Environment.php
Environment.is
public static function is($detect) { if (is_callable($detect)) { static::$_detector = $detect; } if (!is_array($detect)) { return (static::$_current == $detect); } static::$_detector = function($request) use ($detect) { if ($request->env || $request->command == 'test') { return $request->env ?: 'test'; } $host = method_exists($request, 'get') ? $request->get('http:host') : '.console'; foreach ($detect as $environment => $hosts) { if (is_string($hosts) && preg_match($hosts, $host)) { return $environment; } if (is_array($hosts) && in_array($host, $hosts)) { return $environment; } } return "production"; }; }
php
public static function is($detect) { if (is_callable($detect)) { static::$_detector = $detect; } if (!is_array($detect)) { return (static::$_current == $detect); } static::$_detector = function($request) use ($detect) { if ($request->env || $request->command == 'test') { return $request->env ?: 'test'; } $host = method_exists($request, 'get') ? $request->get('http:host') : '.console'; foreach ($detect as $environment => $hosts) { if (is_string($hosts) && preg_match($hosts, $host)) { return $environment; } if (is_array($hosts) && in_array($host, $hosts)) { return $environment; } } return "production"; }; }
[ "public", "static", "function", "is", "(", "$", "detect", ")", "{", "if", "(", "is_callable", "(", "$", "detect", ")", ")", "{", "static", "::", "$", "_detector", "=", "$", "detect", ";", "}", "if", "(", "!", "is_array", "(", "$", "detect", ")", ...
A simple boolean detector that can be used to test which environment the application is running under. For example `Environment::is('development')` will return `true` if `'development'` is, in fact, the current environment. This method also handles how the environment is detected at the beginning of the request. #### Custom Detection While the default detection rules are very simple (if the `'SERVER_ADDR'` variable is set to `127.0.0.1`, the environment is assumed to be `'development'`, or if the string `'test'` is found anywhere in the host name, it is assumed to be `'test'`, and in all other cases it is assumed to be `'production'`), you can define your own detection rule set easily using a closure that accepts an instance of the `Request` object, and returns the name of the correct environment, as in the following example: ``` embed:lithium\tests\cases\core\EnvironmentTest::testCustomDetector(1-9) ``` In the above example, the user-specified closure takes in a `Request` object, and using the server data which it encapsulates, returns the correct environment name as a string. #### Host Mapping The most common use case is to set the environment depending on host name. For convenience, the `is()` method also accepts an array that matches host names to environment names, where each key is an environment, and each value is either an array of valid host names, or a regular expression used to match a valid host name. ``` embed:lithium\tests\cases\core\EnvironmentTest::testDetectionWithArrayMap(1-5) ``` In this example, a regular expression is being used to match local domains (i.e. `localhost`), as well as the built-in `.console` domain, for console requests. Note that in the console, the environment can always be overridden by specifying the `--env` option. Then, one or more host names are matched up to `'test'` and `'staging'`, respectively. Note that no rule is present for production: this is because `'production'` is the default value if no other environment matches. @param mixed $detect Either the name of an environment to check against the current, i.e. `'development'` or `'production'`, or a closure which `Environment` will use to determine the current environment name, or an array mapping environment names to host names. @return boolean If `$detect` is a string, returns `true` if the current environment matches the value of `$detect`, or `false` if no match. If used to set a custom detector, returns `null`.
[ "A", "simple", "boolean", "detector", "that", "can", "be", "used", "to", "test", "which", "environment", "the", "application", "is", "running", "under", ".", "For", "example", "Environment", "::", "is", "(", "development", ")", "will", "return", "true", "if"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Environment.php#L184-L207
UnionOfRAD/lithium
core/Environment.php
Environment.get
public static function get($name = null) { $cur = static::$_current; if (!$name) { return $cur; } if ($name === true) { return isset(static::$_configurations[$cur]) ? static::$_configurations[$cur] : null; } if (isset(static::$_configurations[$name])) { return static::_processDotPath($name, static::$_configurations); } if (!isset(static::$_configurations[$cur])) { return static::_processDotPath($name, static::$_configurations); } return static::_processDotPath($name, static::$_configurations[$cur]); }
php
public static function get($name = null) { $cur = static::$_current; if (!$name) { return $cur; } if ($name === true) { return isset(static::$_configurations[$cur]) ? static::$_configurations[$cur] : null; } if (isset(static::$_configurations[$name])) { return static::_processDotPath($name, static::$_configurations); } if (!isset(static::$_configurations[$cur])) { return static::_processDotPath($name, static::$_configurations); } return static::_processDotPath($name, static::$_configurations[$cur]); }
[ "public", "static", "function", "get", "(", "$", "name", "=", "null", ")", "{", "$", "cur", "=", "static", "::", "$", "_current", ";", "if", "(", "!", "$", "name", ")", "{", "return", "$", "cur", ";", "}", "if", "(", "$", "name", "===", "true",...
Gets the current environment name, a setting associated with the current environment, or the entire configuration array for the current environment. @param string $name The name of the environment setting to retrieve, or the name of an environment, if that environment's entire configuration is to be retrieved. If retrieving the current environment name, `$name` should not be passed. @return mixed If `$name` is unspecified, returns the name of the current environment name as a string (i.e. `'production'`). If an environment name is specified, returns that environment's entire configuration as an array.
[ "Gets", "the", "current", "environment", "name", "a", "setting", "associated", "with", "the", "current", "environment", "or", "the", "entire", "configuration", "array", "for", "the", "current", "environment", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Environment.php#L220-L237
UnionOfRAD/lithium
core/Environment.php
Environment.set
public static function set($env, $config = null) { if ($config === null) { if (is_object($env) || is_array($env)) { static::$_current = static::_detector()->__invoke($env); } elseif (isset(static::$_configurations[$env])) { static::$_current = $env; } return; } if (is_array($env)) { foreach ($env as $name) { static::set($name, $config); } return; } $env = ($env === true) ? static::$_current : $env; if (isset(static::$_configurations[$env])) { $config = Set::merge(static::$_configurations[$env], $config); } return static::$_configurations[$env] = $config; }
php
public static function set($env, $config = null) { if ($config === null) { if (is_object($env) || is_array($env)) { static::$_current = static::_detector()->__invoke($env); } elseif (isset(static::$_configurations[$env])) { static::$_current = $env; } return; } if (is_array($env)) { foreach ($env as $name) { static::set($name, $config); } return; } $env = ($env === true) ? static::$_current : $env; if (isset(static::$_configurations[$env])) { $config = Set::merge(static::$_configurations[$env], $config); } return static::$_configurations[$env] = $config; }
[ "public", "static", "function", "set", "(", "$", "env", ",", "$", "config", "=", "null", ")", "{", "if", "(", "$", "config", "===", "null", ")", "{", "if", "(", "is_object", "(", "$", "env", ")", "||", "is_array", "(", "$", "env", ")", ")", "{"...
Creates, modifies or switches to an existing environment configuration. To create a new configuration, or to update an existing configuration, pass an environment name and an array that defines its configuration: ``` embed:lithium\tests\cases\core\EnvironmentTest::testModifyEnvironmentConfig(1-1) ``` You can then add to an existing configuration by calling the `set()` method again with the same environment name: ``` embed:lithium\tests\cases\core\EnvironmentTest::testModifyEnvironmentConfig(6-6) ``` The settings for the environment will then be the aggregate of all `set()` calls: ``` embed:lithium\tests\cases\core\EnvironmentTest::testModifyEnvironmentConfig(7-7) ``` By passing an array to `$env`, you can assign the same configuration to multiple environments: ``` embed:lithium\tests\cases\core\EnvironmentTest::testSetMultipleEnvironments(5-7) ``` The `set()` method can also be called to manually set which environment to operate in: ``` embed:lithium\tests\cases\core\EnvironmentTest::testSetAndGetCurrentEnvironment(5-5) ``` Finally, `set()` can accept a `Request` object, to automatically detect the correct environment. ``` embed:lithium\tests\cases\core\EnvironmentTest::testEnvironmentDetection(9-10) ``` For more information on defining custom rules to automatically detect your application's environment, see the documentation for `Environment::is()`. @see lithium\action\Request @see lithium\core\Environment::is() @param mixed $env The name(s) of the environment(s) you wish to create, update or switch to (string/array), or a `Request` object or `$_SERVER` / `$_ENV` array used to detect (and switch to) the application's current environment. @param array $config If creating or updating a configuration, accepts an array of settings. If the environment name specified in `$env` already exists, the values in `$config` will be recursively merged with any pre-existing settings. @return array If creating or updating a configuration, returns an array of the environment's settings. If updating an existing configuration, this will be the newly-applied configuration merged with the pre-existing values. If setting the environment itself (i.e. `$config` is unspecified), returns `null`.
[ "Creates", "modifies", "or", "switches", "to", "an", "existing", "environment", "configuration", ".", "To", "create", "a", "new", "configuration", "or", "to", "update", "an", "existing", "configuration", "pass", "an", "environment", "name", "and", "an", "array",...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Environment.php#L297-L318
UnionOfRAD/lithium
core/Environment.php
Environment._detector
protected static function _detector() { return static::$_detector ?: function($request) { $isLocal = in_array($request->env('SERVER_ADDR'), ['::1', '127.0.0.1']); switch (true) { case (isset($request->env)): return $request->env; case ($request->command == 'test'): return 'test'; case ($request->env('PLATFORM') == 'CLI'): return 'development'; case (preg_match('/^\/test/', $request->url) && $isLocal): return 'test'; case ($isLocal): return 'development'; case (preg_match('/^test/', $request->env('HTTP_HOST'))): return 'test'; default: return 'production'; } }; }
php
protected static function _detector() { return static::$_detector ?: function($request) { $isLocal = in_array($request->env('SERVER_ADDR'), ['::1', '127.0.0.1']); switch (true) { case (isset($request->env)): return $request->env; case ($request->command == 'test'): return 'test'; case ($request->env('PLATFORM') == 'CLI'): return 'development'; case (preg_match('/^\/test/', $request->url) && $isLocal): return 'test'; case ($isLocal): return 'development'; case (preg_match('/^test/', $request->env('HTTP_HOST'))): return 'test'; default: return 'production'; } }; }
[ "protected", "static", "function", "_detector", "(", ")", "{", "return", "static", "::", "$", "_detector", "?", ":", "function", "(", "$", "request", ")", "{", "$", "isLocal", "=", "in_array", "(", "$", "request", "->", "env", "(", "'SERVER_ADDR'", ")", ...
Accessor method for `Environment::$_detector`. If `$_detector` is unset, returns the default detector built into the class. For more information on setting and using `$_detector`, see the documentation for `Environment::is()`. The `_detector()` method is called at the beginning of the application's life-cycle, when `Environment::set()` is passed either an instance of a `Request` object, or the `$_SERVER` or `$_ENV` array. This object (or array) is then passed onto `$_detector`, which returns the correct environment. @see lithium\core\Environment::is() @see lithium\core\Environment::set() @see lithium\core\Environment::$_detector @return object Returns a callable object (anonymous function) which detects the application's current environment.
[ "Accessor", "method", "for", "Environment", "::", "$_detector", ".", "If", "$_detector", "is", "unset", "returns", "the", "default", "detector", "built", "into", "the", "class", ".", "For", "more", "information", "on", "setting", "and", "using", "$_detector", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Environment.php#L334-L354
UnionOfRAD/lithium
data/source/Database.php
Database._init
protected function _init() { parent::_init(); if (!$this->_config['database']) { throw new ConfigException('No database configured.'); } $formatters = $this->_formatters(); foreach ($this->_columns as $type => $column) { if (isset($formatters[$type])) { $this->_columns[$type]['formatter'] = $formatters[$type]; } } $this->_strings += [ 'read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' . '{:having} {:order} {:limit};{:comment}' ]; $this->_strategies += [ 'joined' => function($model, $context) { $with = $context->with(); $strategy = function($me, $model, $tree, $path, $from, &$deps) use ($context, $with) { foreach ($tree as $name => $childs) { if (!$rel = $model::relations($name)) { throw new QueryException("Model relationship `{$name}` not found."); } $constraints = []; $alias = $name; $relPath = $path ? $path . '.' . $name : $name; if (isset($with[$relPath])) { list($unallowed, $allowed) = Set::slice($with[$relPath], [ 'alias', 'constraints' ]); if ($unallowed) { $message = "Only `'alias'` and `'constraints'` are allowed in "; $message .= "`'with'` using the `'joined'` strategy."; throw new QueryException($message); } extract($with[$relPath]); } $to = $context->alias($alias, $relPath); $deps[$to] = $deps[$from]; $deps[$to][] = $from; if ($context->relationships($relPath) === null) { $context->relationships($relPath, [ 'type' => $rel->type(), 'model' => $rel->to(), 'fieldName' => $rel->fieldName(), 'alias' => $to ]); $this->join($context, $rel, $from, $to, $constraints); } if (!empty($childs)) { $me($me, $rel->to(), $childs, $relPath, $to, $deps); } } }; $tree = Set::expand(array_fill_keys(array_keys($with), false)); $alias = $context->alias(); $deps = [$alias => []]; $strategy($strategy, $model, $tree, '', $alias, $deps); $models = $context->models(); foreach ($context->fields() as $field) { if (!is_string($field)) { continue; } list($alias, $field) = $this->_splitFieldname($field); $alias = $alias ?: $field; if ($alias && isset($models[$alias])) { foreach ($deps[$alias] as $depAlias) { $depModel = $models[$depAlias]; $context->fields([$depAlias => (array) $depModel::meta('key')]); } } } }, 'nested' => function($model, $context) { throw new QueryException("This strategy is not yet implemented."); } ]; }
php
protected function _init() { parent::_init(); if (!$this->_config['database']) { throw new ConfigException('No database configured.'); } $formatters = $this->_formatters(); foreach ($this->_columns as $type => $column) { if (isset($formatters[$type])) { $this->_columns[$type]['formatter'] = $formatters[$type]; } } $this->_strings += [ 'read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' . '{:having} {:order} {:limit};{:comment}' ]; $this->_strategies += [ 'joined' => function($model, $context) { $with = $context->with(); $strategy = function($me, $model, $tree, $path, $from, &$deps) use ($context, $with) { foreach ($tree as $name => $childs) { if (!$rel = $model::relations($name)) { throw new QueryException("Model relationship `{$name}` not found."); } $constraints = []; $alias = $name; $relPath = $path ? $path . '.' . $name : $name; if (isset($with[$relPath])) { list($unallowed, $allowed) = Set::slice($with[$relPath], [ 'alias', 'constraints' ]); if ($unallowed) { $message = "Only `'alias'` and `'constraints'` are allowed in "; $message .= "`'with'` using the `'joined'` strategy."; throw new QueryException($message); } extract($with[$relPath]); } $to = $context->alias($alias, $relPath); $deps[$to] = $deps[$from]; $deps[$to][] = $from; if ($context->relationships($relPath) === null) { $context->relationships($relPath, [ 'type' => $rel->type(), 'model' => $rel->to(), 'fieldName' => $rel->fieldName(), 'alias' => $to ]); $this->join($context, $rel, $from, $to, $constraints); } if (!empty($childs)) { $me($me, $rel->to(), $childs, $relPath, $to, $deps); } } }; $tree = Set::expand(array_fill_keys(array_keys($with), false)); $alias = $context->alias(); $deps = [$alias => []]; $strategy($strategy, $model, $tree, '', $alias, $deps); $models = $context->models(); foreach ($context->fields() as $field) { if (!is_string($field)) { continue; } list($alias, $field) = $this->_splitFieldname($field); $alias = $alias ?: $field; if ($alias && isset($models[$alias])) { foreach ($deps[$alias] as $depAlias) { $depModel = $models[$depAlias]; $context->fields([$depAlias => (array) $depModel::meta('key')]); } } } }, 'nested' => function($model, $context) { throw new QueryException("This strategy is not yet implemented."); } ]; }
[ "protected", "function", "_init", "(", ")", "{", "parent", "::", "_init", "(", ")", ";", "if", "(", "!", "$", "this", "->", "_config", "[", "'database'", "]", ")", "{", "throw", "new", "ConfigException", "(", "'No database configured.'", ")", ";", "}", ...
Initializer. Initializes properties like `Database::$_strategies` because closures cannot be created within the class definition. @see lithium\data\source\Database::$_columns @see lithium\data\source\Database::$_strings @see lithium\data\source\Database::$_strategies
[ "Initializer", ".", "Initializes", "properties", "like", "Database", "::", "$_strategies", "because", "closures", "cannot", "be", "created", "within", "the", "class", "definition", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L209-L300
UnionOfRAD/lithium
data/source/Database.php
Database.connect
public function connect() { $this->_isConnected = false; $config = $this->_config; if (!$config['dsn']) { throw new ConfigException('No DSN setup for database connection.'); } $dsn = $config['dsn']; $options = $config['options'] + [ PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $this->connection = new PDO($dsn, $config['login'], $config['password'], $options); } catch (PDOException $e) { preg_match('/SQLSTATE\[(.+?)\]/', $e->getMessage(), $code); $code = empty($code[1]) ? 0 : $code[0]; switch (true) { case $code === 'HY000' || substr($code, 0, 2) === '08': $msg = "Unable to connect to host `{$config['host']}`."; throw new NetworkException($msg, null, $e); break; case in_array($code, ['28000', '42000']): $msg = "Host connected, but could not access database `{$config['database']}`."; throw new ConfigException($msg, null, $e); break; } throw new ConfigException('An unknown configuration error has occured.', null, $e); } $this->_isConnected = true; if ($this->_config['encoding'] && !$this->encoding($this->_config['encoding'])) { return false; } return $this->_isConnected; }
php
public function connect() { $this->_isConnected = false; $config = $this->_config; if (!$config['dsn']) { throw new ConfigException('No DSN setup for database connection.'); } $dsn = $config['dsn']; $options = $config['options'] + [ PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $this->connection = new PDO($dsn, $config['login'], $config['password'], $options); } catch (PDOException $e) { preg_match('/SQLSTATE\[(.+?)\]/', $e->getMessage(), $code); $code = empty($code[1]) ? 0 : $code[0]; switch (true) { case $code === 'HY000' || substr($code, 0, 2) === '08': $msg = "Unable to connect to host `{$config['host']}`."; throw new NetworkException($msg, null, $e); break; case in_array($code, ['28000', '42000']): $msg = "Host connected, but could not access database `{$config['database']}`."; throw new ConfigException($msg, null, $e); break; } throw new ConfigException('An unknown configuration error has occured.', null, $e); } $this->_isConnected = true; if ($this->_config['encoding'] && !$this->encoding($this->_config['encoding'])) { return false; } return $this->_isConnected; }
[ "public", "function", "connect", "(", ")", "{", "$", "this", "->", "_isConnected", "=", "false", ";", "$", "config", "=", "$", "this", "->", "_config", ";", "if", "(", "!", "$", "config", "[", "'dsn'", "]", ")", "{", "throw", "new", "ConfigException"...
Connects to the database by creating a PDO intance using the constructed DSN string. Will set general options on the connection as provided (persistence, encoding). @see lithium\data\source\Database::encoding() @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", "general", "options", "on", "the", "connection", "as", "provided", "(", "persistence", "encoding", ")", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L310-L347
UnionOfRAD/lithium
data/source/Database.php
Database.name
public function name($name) { if (isset($this->_cachedNames[$name])) { return $this->_cachedNames[$name]; } list($open, $close) = $this->_quotes; list($first, $second) = $this->_splitFieldname($name); if ($first) { $result = "{$open}{$first}{$close}.{$open}{$second}{$close}"; } elseif (preg_match('/^[a-z0-9_-]+$/iS', $name)) { $result = "{$open}{$name}{$close}"; } else { $result = $name; } return $this->_cachedNames[$name] = $result; }
php
public function name($name) { if (isset($this->_cachedNames[$name])) { return $this->_cachedNames[$name]; } list($open, $close) = $this->_quotes; list($first, $second) = $this->_splitFieldname($name); if ($first) { $result = "{$open}{$first}{$close}.{$open}{$second}{$close}"; } elseif (preg_match('/^[a-z0-9_-]+$/iS', $name)) { $result = "{$open}{$name}{$close}"; } else { $result = $name; } return $this->_cachedNames[$name] = $result; }
[ "public", "function", "name", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_cachedNames", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "_cachedNames", "[", "$", "name", "]", ";", "}", "list", "(",...
Field name handler to ensure proper escaping. @param string $name Field or identifier name. @return string Returns `$name` quoted according to the rules and quote characters of the database adapter subclass.
[ "Field", "name", "handler", "to", "ensure", "proper", "escaping", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L369-L385
UnionOfRAD/lithium
data/source/Database.php
Database._splitFieldname
protected function _splitFieldname($field) { $regex = '/^([a-z0-9_-]+)\.([a-z 0-9_-]+|\*)$/iS'; if (strpos($field, '.') !== false && preg_match($regex, $field, $matches)) { return [$matches[1], $matches[2]]; } return [null, $field]; }
php
protected function _splitFieldname($field) { $regex = '/^([a-z0-9_-]+)\.([a-z 0-9_-]+|\*)$/iS'; if (strpos($field, '.') !== false && preg_match($regex, $field, $matches)) { return [$matches[1], $matches[2]]; } return [null, $field]; }
[ "protected", "function", "_splitFieldname", "(", "$", "field", ")", "{", "$", "regex", "=", "'/^([a-z0-9_-]+)\\.([a-z 0-9_-]+|\\*)$/iS'", ";", "if", "(", "strpos", "(", "$", "field", ",", "'.'", ")", "!==", "false", "&&", "preg_match", "(", "$", "regex", ","...
Return the alias and the field name from an identifier name. @param string $field Field name or identifier name. @return array Returns an array with the alias (or `null` if not applicable) as first value and the field name as second value.
[ "Return", "the", "alias", "and", "the", "field", "name", "from", "an", "identifier", "name", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L394-L401
UnionOfRAD/lithium
data/source/Database.php
Database._fieldName
protected function _fieldName($field) { $regex = '/^[a-z0-9_-]+\.[a-z0-9_-]+$/iS'; if (strpos($field, '.') !== false && preg_match($regex, $field)) { list($first, $second) = explode('.', $field, 2); return $second; } return $field; }
php
protected function _fieldName($field) { $regex = '/^[a-z0-9_-]+\.[a-z0-9_-]+$/iS'; if (strpos($field, '.') !== false && preg_match($regex, $field)) { list($first, $second) = explode('.', $field, 2); return $second; } return $field; }
[ "protected", "function", "_fieldName", "(", "$", "field", ")", "{", "$", "regex", "=", "'/^[a-z0-9_-]+\\.[a-z0-9_-]+$/iS'", ";", "if", "(", "strpos", "(", "$", "field", ",", "'.'", ")", "!==", "false", "&&", "preg_match", "(", "$", "regex", ",", "$", "fi...
Return the field name from a conditions key. @param string $field Field or identifier name. @return string Returns the field name without the table alias, if applicable. @todo Eventually, this should be refactored and moved to the Query or Schema class. Also, by handling field resolution in this way we are not handling cases where query conditions use the same field name in multiple tables. e.g. Foos.bar and Bars.bar will both return bar.
[ "Return", "the", "field", "name", "from", "a", "conditions", "key", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L413-L421
UnionOfRAD/lithium
data/source/Database.php
Database.value
public function value($value, array $schema = []) { $schema += ['default' => null, 'null' => false]; if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $this->value($val, isset($schema[$key]) ? $schema[$key] : $schema); } return $value; } if (is_object($value) && isset($value->scalar)) { return $value->scalar; } $type = isset($schema['type']) ? $schema['type'] : $this->_introspectType($value); $column = isset($this->_columns[$type]) ? $this->_columns[$type] : null; return $this->_cast($type, $value, $column, $schema); }
php
public function value($value, array $schema = []) { $schema += ['default' => null, 'null' => false]; if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $this->value($val, isset($schema[$key]) ? $schema[$key] : $schema); } return $value; } if (is_object($value) && isset($value->scalar)) { return $value->scalar; } $type = isset($schema['type']) ? $schema['type'] : $this->_introspectType($value); $column = isset($this->_columns[$type]) ? $this->_columns[$type] : null; return $this->_cast($type, $value, $column, $schema); }
[ "public", "function", "value", "(", "$", "value", ",", "array", "$", "schema", "=", "[", "]", ")", "{", "$", "schema", "+=", "[", "'default'", "=>", "null", ",", "'null'", "=>", "false", "]", ";", "if", "(", "is_array", "(", "$", "value", ")", ")...
Converts a given value into the proper type based on a given schema definition. Will bypass any formatters and casting - effectively forcing the engine "to keep its hands off" - when `$value` is an object with the property `scalar` (created by casting a scalar value to an object i.e. `(object) 'foo')`. This feature allows to construct values or queries that are not (yet) supported by the engine. @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.php#L436-L453
UnionOfRAD/lithium
data/source/Database.php
Database._cast
protected function _cast($type, $value, $column, $schema = []) { $column += ['formatter' => null, 'format' => null]; if ($value === null) { return 'NULL'; } if (is_object($value)) { return $value; } if (!$formatter = $column['formatter']) { return $this->connection->quote($value); } if (!$format = $column['format']) { return $formatter($value); } if (($value = $formatter($format, $value)) === false) { $value = $formatter($format, $schema['default']); } return $value !== false ? $value : 'NULL'; }
php
protected function _cast($type, $value, $column, $schema = []) { $column += ['formatter' => null, 'format' => null]; if ($value === null) { return 'NULL'; } if (is_object($value)) { return $value; } if (!$formatter = $column['formatter']) { return $this->connection->quote($value); } if (!$format = $column['format']) { return $formatter($value); } if (($value = $formatter($format, $value)) === false) { $value = $formatter($format, $schema['default']); } return $value !== false ? $value : 'NULL'; }
[ "protected", "function", "_cast", "(", "$", "type", ",", "$", "value", ",", "$", "column", ",", "$", "schema", "=", "[", "]", ")", "{", "$", "column", "+=", "[", "'formatter'", "=>", "null", ",", "'format'", "=>", "null", "]", ";", "if", "(", "$"...
Cast a value according to a column type, used by `Database::value()`. @see lithium\data\source\Database::value() @param string $type Name of the column type. @param string $value Value to cast. @param array $column The column definition. @param array $schema Formatted array from `lithium\data\source\Database::schema()`. @return mixed Casted value.
[ "Cast", "a", "value", "according", "to", "a", "column", "type", "used", "by", "Database", "::", "value", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L465-L484
UnionOfRAD/lithium
data/source/Database.php
Database._formatters
protected function _formatters() { $datetime = $timestamp = $date = $time = function($format, $value) { if ($format && (($time = strtotime($value)) !== false)) { $value = date($format, $time); } else { return false; } return $this->connection->quote($value); }; return compact('datetime', 'timestamp', 'date', 'time') + [ 'boolean' => function($value) { return $value ? 1 : 0; } ]; }
php
protected function _formatters() { $datetime = $timestamp = $date = $time = function($format, $value) { if ($format && (($time = strtotime($value)) !== false)) { $value = date($format, $time); } else { return false; } return $this->connection->quote($value); }; return compact('datetime', 'timestamp', 'date', 'time') + [ 'boolean' => function($value) { return $value ? 1 : 0; } ]; }
[ "protected", "function", "_formatters", "(", ")", "{", "$", "datetime", "=", "$", "timestamp", "=", "$", "date", "=", "$", "time", "=", "function", "(", "$", "format", ",", "$", "value", ")", "{", "if", "(", "$", "format", "&&", "(", "(", "$", "t...
Provide an associative array of Closures to be used as the `'formatter'` key inside of the `Database::$_columns` specification. Each Closure should return the appropriately quoted or unquoted value and accept one or two parameters: `$format`, the format to apply to value and `$value`, the value to be formatted. Example formatter function: ``` function($format, $value) { return is_numeric($value) ? (integer) $value : false; } ``` @see lithium\data\source\Database::$_columns @see lithium\data\source\Database::_init() @return array of column types to Closure formatter
[ "Provide", "an", "associative", "array", "of", "Closures", "to", "be", "used", "as", "the", "formatter", "key", "inside", "of", "the", "Database", "::", "$_columns", "specification", ".", "Each", "Closure", "should", "return", "the", "appropriately", "quoted", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L503-L518
UnionOfRAD/lithium
data/source/Database.php
Database.create
public function create($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $model = $entity = $object = $id = null; if (is_object($query)) { $object = $query; $model = $query->model(); $params = $query->export($this); $entity =& $query->entity(); $query = $this->renderCommand('create', $params, $query); } else { $query = Text::insert($query, $this->value($params['options'])); } if (!$this->_execute($query)) { return false; } if ($entity) { if (($model) && !$model::key($entity)) { $id = $this->_insertId($object); } $entity->sync($id); } return true; }); }
php
public function create($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $model = $entity = $object = $id = null; if (is_object($query)) { $object = $query; $model = $query->model(); $params = $query->export($this); $entity =& $query->entity(); $query = $this->renderCommand('create', $params, $query); } else { $query = Text::insert($query, $this->value($params['options'])); } if (!$this->_execute($query)) { return false; } if ($entity) { if (($model) && !$model::key($entity)) { $id = $this->_insertId($object); } $entity->sync($id); } return true; }); }
[ "public", "function", "create", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'query'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ",", "__FUNCTION_...
Inserts a new record into the database based on a the `Query`. The record is updated with the id of the insert. @see lithium\util\Text::insert() @param object $query An SQL query string, or `lithium\data\model\Query` object instance. @param array $options If $query is a string, $options contains an array of bind values to be escaped, quoted, and inserted into `$query` using `Text::insert()`. @return boolean Returns `true` if the query succeeded, otherwise `false`. @filter
[ "Inserts", "a", "new", "record", "into", "the", "database", "based", "on", "a", "the", "Query", ".", "The", "record", "is", "updated", "with", "the", "id", "of", "the", "insert", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L531-L560