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
data/Model.php
Model.relations
public static function relations($type = null) { $self = static::_object(); if ($type === null) { return static::_relations(); } if (isset($self->_relationFieldNames[$type])) { $type = $self->_relationFieldNames[$type]; } if (isset($self->_relations[$type])) { return $self->_relations[$type]; } if (isset($self->_relationsToLoad[$type])) { return static::_relations(null, $type); } if (in_array($type, $self->_relationTypes, true)) { return array_keys(static::_relations($type)); } }
php
public static function relations($type = null) { $self = static::_object(); if ($type === null) { return static::_relations(); } if (isset($self->_relationFieldNames[$type])) { $type = $self->_relationFieldNames[$type]; } if (isset($self->_relations[$type])) { return $self->_relations[$type]; } if (isset($self->_relationsToLoad[$type])) { return static::_relations(null, $type); } if (in_array($type, $self->_relationTypes, true)) { return array_keys(static::_relations($type)); } }
[ "public", "static", "function", "relations", "(", "$", "type", "=", "null", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "if", "(", "$", "type", "===", "null", ")", "{", "return", "static", "::", "_relations", "(", ")", ";"...
Returns a list of models related to `Model`, or a list of models related to this model, but of a certain type. @param string $type A type of model relation. @return array|object|void An array of relation instances or an instance of relation.
[ "Returns", "a", "list", "of", "models", "related", "to", "Model", "or", "a", "list", "of", "models", "related", "to", "this", "model", "but", "of", "a", "certain", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L941-L960
UnionOfRAD/lithium
data/Model.php
Model._relations
protected static function _relations($type = null, $name = null) { $self = static::_object(); if ($name) { if (isset($self->_relationsToLoad[$name])) { $t = $self->_relationsToLoad[$name]; unset($self->_relationsToLoad[$name]); return static::bind($t, $name, (array) $self->{$t}[$name]); } return isset($self->_relations[$name]) ? $self->_relations[$name] : null; } if (!$type) { foreach ($self->_relationsToLoad as $name => $t) { static::bind($t, $name, (array) $self->{$t}[$name]); } $self->_relationsToLoad = []; return $self->_relations; } foreach ($self->_relationsToLoad as $name => $t) { if ($type === $t) { static::bind($t, $name, (array) $self->{$t}[$name]); unset($self->_relationsToLoad[$name]); } } return array_filter($self->_relations, function($i) use ($type) { return $i->data('type') === $type; }); }
php
protected static function _relations($type = null, $name = null) { $self = static::_object(); if ($name) { if (isset($self->_relationsToLoad[$name])) { $t = $self->_relationsToLoad[$name]; unset($self->_relationsToLoad[$name]); return static::bind($t, $name, (array) $self->{$t}[$name]); } return isset($self->_relations[$name]) ? $self->_relations[$name] : null; } if (!$type) { foreach ($self->_relationsToLoad as $name => $t) { static::bind($t, $name, (array) $self->{$t}[$name]); } $self->_relationsToLoad = []; return $self->_relations; } foreach ($self->_relationsToLoad as $name => $t) { if ($type === $t) { static::bind($t, $name, (array) $self->{$t}[$name]); unset($self->_relationsToLoad[$name]); } } return array_filter($self->_relations, function($i) use ($type) { return $i->data('type') === $type; }); }
[ "protected", "static", "function", "_relations", "(", "$", "type", "=", "null", ",", "$", "name", "=", "null", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "if", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", ...
This method automagically bind in the fly unloaded relations. @see lithium\data\Model::relations() @param $type A type of model relation. @param $name A relation name. @return An array of relation instances or an instance of relation.
[ "This", "method", "automagically", "bind", "in", "the", "fly", "unloaded", "relations", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L970-L997
UnionOfRAD/lithium
data/Model.php
Model.bind
public static function bind($type, $name, array $config = []) { $self = static::_object(); if (!isset($config['fieldName'])) { $config['fieldName'] = $self->_relationFieldName($type, $name); } if (!in_array($type, $self->_relationTypes)) { throw new ConfigException("Invalid relationship type `{$type}` specified."); } $self->_relationFieldNames[$config['fieldName']] = $name; $rel = static::connection()->relationship(get_called_class(), $type, $name, $config); return $self->_relations[$name] = $rel; }
php
public static function bind($type, $name, array $config = []) { $self = static::_object(); if (!isset($config['fieldName'])) { $config['fieldName'] = $self->_relationFieldName($type, $name); } if (!in_array($type, $self->_relationTypes)) { throw new ConfigException("Invalid relationship type `{$type}` specified."); } $self->_relationFieldNames[$config['fieldName']] = $name; $rel = static::connection()->relationship(get_called_class(), $type, $name, $config); return $self->_relations[$name] = $rel; }
[ "public", "static", "function", "bind", "(", "$", "type", ",", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "config", "[", "'fi...
Creates a relationship binding between this model and another. @see lithium\data\model\Relationship @param string $type The type of relationship to create. Must be one of `'hasOne'`, `'hasMany'` or `'belongsTo'`. @param string $name The name of the relationship. If this is also the name of the model, the model must be in the same namespace as this model. Otherwise, the fully-namespaced path to the model class must be specified in `$config`. @param array $config Any other configuration that should be specified in the relationship. See the `Relationship` class for more information. @return object Returns an instance of the `Relationship` class that defines the connection.
[ "Creates", "a", "relationship", "binding", "between", "this", "model", "and", "another", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1012-L1024
UnionOfRAD/lithium
data/Model.php
Model.schema
public static function schema($field = null) { $self = static::_object(); if (!is_object($self->_schema)) { $self->_schema = static::connection()->describe( $self::meta('source'), $self->_schema, $self->_meta ); if (!is_object($self->_schema)) { $class = get_called_class(); throw new ConfigException("Could not load schema object for model `{$class}`."); } $key = (array) $self::meta('key'); if ($self->_schema && $self->_schema->fields() && !$self->_schema->has($key)) { $key = implode('`, `', $key); throw new ConfigException("Missing key `{$key}` from schema."); } } if ($field === false) { return $self->_schema->reset(); } if (is_array($field)) { return $self->_schema->append($field); } return $field ? $self->_schema->fields($field) : $self->_schema; }
php
public static function schema($field = null) { $self = static::_object(); if (!is_object($self->_schema)) { $self->_schema = static::connection()->describe( $self::meta('source'), $self->_schema, $self->_meta ); if (!is_object($self->_schema)) { $class = get_called_class(); throw new ConfigException("Could not load schema object for model `{$class}`."); } $key = (array) $self::meta('key'); if ($self->_schema && $self->_schema->fields() && !$self->_schema->has($key)) { $key = implode('`, `', $key); throw new ConfigException("Missing key `{$key}` from schema."); } } if ($field === false) { return $self->_schema->reset(); } if (is_array($field)) { return $self->_schema->append($field); } return $field ? $self->_schema->fields($field) : $self->_schema; }
[ "public", "static", "function", "schema", "(", "$", "field", "=", "null", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "if", "(", "!", "is_object", "(", "$", "self", "->", "_schema", ")", ")", "{", "$", "self", "->", "_sc...
Lazy-initialize the schema for this Model object, if it is not already manually set in the object. You can declare `protected $_schema = [...]` to define the schema manually. @param mixed $field Optional. You may pass a field name to get schema information for just one field. Otherwise, an array containing all fields is returned. If `false`, the schema is reset to an empty value. If an array, field definitions contained are appended to the schema. @return array|lithium\data\Schema
[ "Lazy", "-", "initialize", "the", "schema", "for", "this", "Model", "object", "if", "it", "is", "not", "already", "manually", "set", "in", "the", "object", ".", "You", "can", "declare", "protected", "$_schema", "=", "[", "...", "]", "to", "define", "the"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1036-L1060
UnionOfRAD/lithium
data/Model.php
Model.hasField
public static function hasField($field) { if (!is_array($field)) { return static::schema()->fields($field); } foreach ($field as $f) { if (static::hasField($f)) { return $f; } } return false; }
php
public static function hasField($field) { if (!is_array($field)) { return static::schema()->fields($field); } foreach ($field as $f) { if (static::hasField($f)) { return $f; } } return false; }
[ "public", "static", "function", "hasField", "(", "$", "field", ")", "{", "if", "(", "!", "is_array", "(", "$", "field", ")", ")", "{", "return", "static", "::", "schema", "(", ")", "->", "fields", "(", "$", "field", ")", ";", "}", "foreach", "(", ...
Checks to see if a particular field exists in a model's schema. Can check a single field, or return the first field found in an array of multiple options. @param mixed $field A single field (string) or list of fields (array) to check the existence of. @return mixed If `$field` is a string, returns a boolean indicating whether or not that field exists. If `$field` is an array, returns the first field found, or `false` if none of the fields in the list are found.
[ "Checks", "to", "see", "if", "a", "particular", "field", "exists", "in", "a", "model", "s", "schema", ".", "Can", "check", "a", "single", "field", "or", "return", "the", "first", "field", "found", "in", "an", "array", "of", "multiple", "options", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1072-L1082
UnionOfRAD/lithium
data/Model.php
Model.create
public static function create(array $data = [], array $options = []) { $defaults = ['defaults' => true, 'class' => 'entity']; $options += $defaults; $params = compact('data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $class = $params['options']['class']; unset($params['options']['class']); if ($class === 'entity' && $params['options']['defaults']) { $data = Set::merge(Set::expand(static::schema()->defaults()), $params['data']); } else { $data = $params['data']; } return static::_instance($class, [ 'model' => get_called_class(), 'data' => $data ] + $params['options']); }); }
php
public static function create(array $data = [], array $options = []) { $defaults = ['defaults' => true, 'class' => 'entity']; $options += $defaults; $params = compact('data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $class = $params['options']['class']; unset($params['options']['class']); if ($class === 'entity' && $params['options']['defaults']) { $data = Set::merge(Set::expand(static::schema()->defaults()), $params['data']); } else { $data = $params['data']; } return static::_instance($class, [ 'model' => get_called_class(), 'data' => $data ] + $params['options']); }); }
[ "public", "static", "function", "create", "(", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'defaults'", "=>", "true", ",", "'class'", "=>", "'entity'", "]", ";", "$", "opti...
Instantiates a new record or document object, initialized with any data passed in. For example: ``` $post = Posts::create(['title' => 'New post']); echo $post->title; // echoes 'New post' $success = $post->save(); ``` Note that while this method creates a new object, there is no effect on the database until the `save()` method is called. In addition, this method can be used to simulate loading a pre-existing object from the database, without actually querying the database: ``` $post = Posts::create(['id' => $id, 'moreData' => 'foo'], ['exists' => true]); $post->title = 'New title'; $success = $post->save(); ``` This will create an update query against the object with an ID matching `$id`. Also note that only the `title` field will be updated. @param array $data Any data that this object should be populated with initially. @param array $options Options to be passed to item. @return object Returns a new, _un-saved_ record or document object. In addition to the values passed to `$data`, the object will also contain any values assigned to the `'default'` key of each field defined in `$_schema`. @filter
[ "Instantiates", "a", "new", "record", "or", "document", "object", "initialized", "with", "any", "data", "passed", "in", ".", "For", "example", ":" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1116-L1135
UnionOfRAD/lithium
data/Model.php
Model.instanceMethods
public static function instanceMethods(array $methods = null) { $class = get_called_class(); if (!isset(static::$_instanceMethods[$class])) { static::$_instanceMethods[$class] = []; } if ($methods === []) { return static::$_instanceMethods[$class] = []; } if ($methods !== null) { static::$_instanceMethods[$class] = $methods + static::$_instanceMethods[$class]; } return static::$_instanceMethods[$class]; }
php
public static function instanceMethods(array $methods = null) { $class = get_called_class(); if (!isset(static::$_instanceMethods[$class])) { static::$_instanceMethods[$class] = []; } if ($methods === []) { return static::$_instanceMethods[$class] = []; } if ($methods !== null) { static::$_instanceMethods[$class] = $methods + static::$_instanceMethods[$class]; } return static::$_instanceMethods[$class]; }
[ "public", "static", "function", "instanceMethods", "(", "array", "$", "methods", "=", "null", ")", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "if", "(", "!", "isset", "(", "static", "::", "$", "_instanceMethods", "[", "$", "class", "]", ...
Getter and setter for custom instance methods. This is used in `Entity::__call()`. ``` Model::instanceMethods([ 'methodName' => ['Class', 'method'], 'anotherMethod' => [$object, 'method'], 'closureCallback' => function($entity) {} ]); ``` @see lithium\data\Entity::__call() @param array $methods @return array
[ "Getter", "and", "setter", "for", "custom", "instance", "methods", ".", "This", "is", "used", "in", "Entity", "::", "__call", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1152-L1165
UnionOfRAD/lithium
data/Model.php
Model.save
public function save($entity, $data = null, array $options = []) { $self = static::_object(); $_meta = ['model' => get_called_class()] + $self->_meta; $_schema = $self->schema(); $defaults = [ 'validate' => true, 'events' => $entity->exists() ? 'update' : 'create', 'whitelist' => null, 'callbacks' => true, 'locked' => $self->_meta['locked'] ]; $options += $defaults; $params = compact('entity', 'data', 'options'); $filter = function($params) use ($_meta, $_schema) { $entity = $params['entity']; $options = $params['options']; if ($params['data']) { $entity->set($params['data']); } if (($whitelist = $options['whitelist']) || $options['locked']) { $whitelist = $whitelist ?: array_keys($_schema->fields()); } if ($rules = $options['validate']) { $events = $options['events']; $validateOpts = compact('events', 'whitelist'); if (is_array($rules)) { $validateOpts['rules'] = $rules; } if (!$entity->validates($validateOpts)) { return false; } } $type = $entity->exists() ? 'update' : 'create'; $query = static::_instance('query', compact('type', 'whitelist', 'entity') + $options + $_meta ); return static::connection()->{$type}($query, $options); }; if (!$options['callbacks']) { return $filter($params); } return Filters::run(get_called_class(), __FUNCTION__, $params, $filter); }
php
public function save($entity, $data = null, array $options = []) { $self = static::_object(); $_meta = ['model' => get_called_class()] + $self->_meta; $_schema = $self->schema(); $defaults = [ 'validate' => true, 'events' => $entity->exists() ? 'update' : 'create', 'whitelist' => null, 'callbacks' => true, 'locked' => $self->_meta['locked'] ]; $options += $defaults; $params = compact('entity', 'data', 'options'); $filter = function($params) use ($_meta, $_schema) { $entity = $params['entity']; $options = $params['options']; if ($params['data']) { $entity->set($params['data']); } if (($whitelist = $options['whitelist']) || $options['locked']) { $whitelist = $whitelist ?: array_keys($_schema->fields()); } if ($rules = $options['validate']) { $events = $options['events']; $validateOpts = compact('events', 'whitelist'); if (is_array($rules)) { $validateOpts['rules'] = $rules; } if (!$entity->validates($validateOpts)) { return false; } } $type = $entity->exists() ? 'update' : 'create'; $query = static::_instance('query', compact('type', 'whitelist', 'entity') + $options + $_meta ); return static::connection()->{$type}($query, $options); }; if (!$options['callbacks']) { return $filter($params); } return Filters::run(get_called_class(), __FUNCTION__, $params, $filter); }
[ "public", "function", "save", "(", "$", "entity", ",", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "$", "_meta", "=", "[", "'model'", "=>", "get_call...
An instance method (called on record and document objects) to create or update the record or document in the database that corresponds to `$entity`. For example, to create a new record or document: ``` $post = Posts::create(); // Creates a new object, which doesn't exist in the database yet $post->title = "My post"; $success = $post->save(); ``` It is also used to update existing database objects, as in the following: ``` $post = Posts::first($id); $post->title = "Revised title"; $success = $post->save(); ``` By default, an object's data will be checked against the validation rules of the model it is bound to. Any validation errors that result can then be accessed through the `errors()` method. ``` if (!$post->save($someData)) { return ['errors' => $post->errors()]; } ``` To override the validation checks and save anyway, you can pass the `'validate'` option: ``` $post->title = "We Don't Need No Stinkin' Validation"; $post->body = "I know what I'm doing."; $post->save(null, ['validate' => false]); ``` By default only validates and saves fields from the schema (if available). This behavior can be controlled via the `'whitelist'` and `'locked'` options. @see lithium\data\Model::$validates @see lithium\data\Model::validates() @see lithium\data\Entity::errors() @param object $entity The record or document object to be saved in the database. This parameter is implicit and should not be passed under normal circumstances. In the above example, the call to `save()` on the `$post` object is transparently proxied through to the `Posts` model class, and `$post` is passed in as the `$entity` parameter. @param array $data Any data that should be assigned to the record before it is saved. @param array $options Options: - `'callbacks'` _boolean_: If `false`, all callbacks will be disabled before executing. Defaults to `true`. - `'validate'` _boolean|array_: If `false`, validation will be skipped, and the record will be immediately saved. Defaults to `true`. May also be specified as an array, in which case it will replace the default validation rules specified in the `$validates` property of the model. - `'events'` _string|array_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. They will be passed to the validates() method if `'validate'` is not `false`. - `'whitelist'` _array_: An array of fields that are allowed to be saved to this record. When unprovided will - if available - default to fields of the current schema and the `'locked'` option is not `false`. - `'locked'` _boolean_: Whether to use schema for saving just fields from the schema or not. Defaults to `true`. @return boolean Returns `true` on a successful save operation, `false` on failure. @filter
[ "An", "instance", "method", "(", "called", "on", "record", "and", "document", "objects", ")", "to", "create", "or", "update", "the", "record", "or", "document", "in", "the", "database", "that", "corresponds", "to", "$entity", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1234-L1282
UnionOfRAD/lithium
data/Model.php
Model.validates
public function validates($entity, array $options = []) { $defaults = [ 'rules' => $this->validates, 'events' => $entity->exists() ? 'update' : 'create', 'model' => get_called_class(), 'required' => null, 'whitelist' => null ]; $options += $defaults; if ($options['required'] === null) { $options['required'] = !$entity->exists(); } $self = static::_object(); $validator = $self->_classes['validator']; $entity->errors(false); $params = compact('entity', 'options'); $implementation = function($params) use ($validator) { $entity = $params['entity']; $options = $params['options']; $rules = $options['rules']; unset($options['rules']); if ($whitelist = $options['whitelist']) { $whitelist = array_combine($whitelist, $whitelist); $rules = array_intersect_key($rules, $whitelist); } if ($errors = $validator::check($entity->data(), $rules, $options)) { $entity->errors($errors); } return empty($errors); }; return Filters::run(get_called_class(), __FUNCTION__, $params, $implementation); }
php
public function validates($entity, array $options = []) { $defaults = [ 'rules' => $this->validates, 'events' => $entity->exists() ? 'update' : 'create', 'model' => get_called_class(), 'required' => null, 'whitelist' => null ]; $options += $defaults; if ($options['required'] === null) { $options['required'] = !$entity->exists(); } $self = static::_object(); $validator = $self->_classes['validator']; $entity->errors(false); $params = compact('entity', 'options'); $implementation = function($params) use ($validator) { $entity = $params['entity']; $options = $params['options']; $rules = $options['rules']; unset($options['rules']); if ($whitelist = $options['whitelist']) { $whitelist = array_combine($whitelist, $whitelist); $rules = array_intersect_key($rules, $whitelist); } if ($errors = $validator::check($entity->data(), $rules, $options)) { $entity->errors($errors); } return empty($errors); }; return Filters::run(get_called_class(), __FUNCTION__, $params, $implementation); }
[ "public", "function", "validates", "(", "$", "entity", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'rules'", "=>", "$", "this", "->", "validates", ",", "'events'", "=>", "$", "entity", "->", "exists", "(", ")", ...
An important part of describing the business logic of a model class is defining the validation rules. In Lithium models, rules are defined through the `$validates` class property, and are used by this method before saving to verify the correctness of the data being sent to the backend data source. Note that these are application-level validation rules, and do not interact with any rules or constraints defined in your data source. If such constraints fail, an exception will be thrown by the database layer. The `validates()` method only checks against the rules defined in application code. This method uses the `Validator` class to perform data validation. An array representation of the entity object to be tested is passed to the `check()` method, along with the model's validation rules. Any rules defined in the `Validator` class can be used to validate fields. See the `Validator` class to add custom rules, or override built-in rules. @see lithium\data\Model::$validates @see lithium\util\Validator::check() @see lithium\data\Entity::errors() @param object $entity Model entity to validate. Typically either a `Record` or `Document` object. In the following example: ``` $post = Posts::create($data); $success = $post->validates(); ``` The `$entity` parameter is equal to the `$post` object instance. @param array $options Available options: - `'rules'` _array_: If specified, this array will _replace_ the default validation rules defined in `$validates`. - `'events'` _mixed_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. For example, by default, `'events'` is set to either `'create'` or `'update'`, depending on whether `$entity` already exists. Then, individual rules can specify `'on' => 'create'` or `'on' => 'update'` to only be applied at certain times. Using this parameter, you can set up custom events in your rules as well, such as `'on' => 'login'`. Note that when defining validation rules, the `'on'` key can also be an array of multiple events. - `'required`' _mixed_: Represents whether the value is required to be present in `$values`. If `'required'` is set to `true`, the validation rule will be checked. if `'required'` is set to 'false' , the validation rule will be skipped if the corresponding key is not present. If don't set `'required'` or set this to `null`, the validation rule will be skipped if the corresponding key is not present in update and will be checked in insert. Defaults is set to `null`. - `'whitelist'` _array_: If specified, only fields in this array will be validated and others will be skipped. @return boolean Returns `true` if all validation rules on all fields succeed, otherwise `false`. After validation, the messages for any validation failures are assigned to the entity, and accessible through the `errors()` method of the entity object. @filter
[ "An", "important", "part", "of", "describing", "the", "business", "logic", "of", "a", "model", "class", "is", "defining", "the", "validation", "rules", ".", "In", "Lithium", "models", "rules", "are", "defined", "through", "the", "$validates", "class", "propert...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1335-L1369
UnionOfRAD/lithium
data/Model.php
Model.delete
public function delete($entity, array $options = []) { $params = compact('entity', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params + $params['options'] + [ 'model' => get_called_class(), 'type' => 'delete' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->delete($query, $options); }); }
php
public function delete($entity, array $options = []) { $params = compact('entity', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params + $params['options'] + [ 'model' => get_called_class(), 'type' => 'delete' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->delete($query, $options); }); }
[ "public", "function", "delete", "(", "$", "entity", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'entity'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "get_called_class", "(", ")", ...
Deletes the data associated with the current `Model`. @param object $entity Entity to delete. @param array $options Options. @return boolean Success. @filter Good for executing logic for i.e. invalidating cached results.
[ "Deletes", "the", "data", "associated", "with", "the", "current", "Model", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1379-L1392
UnionOfRAD/lithium
data/Model.php
Model.update
public static function update($data, $conditions = [], array $options = []) { $params = compact('data', 'conditions', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params + $params['options'] + [ 'model' => get_called_class(), 'type' => 'update' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->update($query, $options); }); }
php
public static function update($data, $conditions = [], array $options = []) { $params = compact('data', 'conditions', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params + $params['options'] + [ 'model' => get_called_class(), 'type' => 'update' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->update($query, $options); }); }
[ "public", "static", "function", "update", "(", "$", "data", ",", "$", "conditions", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'data'", ",", "'conditions'", ",", "'options'", ")", ";", ...
Update multiple records or documents with the given data, restricted by the given set of criteria (optional). @param mixed $data Typically an array of key/value pairs that specify the new data with which the records will be updated. For SQL databases, this can optionally be an SQL fragment representing the `SET` clause of an `UPDATE` query. @param mixed $conditions An array of key/value pairs representing the scope of the records to be updated. @param array $options Any database-specific options to use when performing the operation. See the `delete()` method of the corresponding backend database for available options. @return boolean Returns `true` if the update operation succeeded, otherwise `false`. @filter
[ "Update", "multiple", "records", "or", "documents", "with", "the", "given", "data", "restricted", "by", "the", "given", "set", "of", "criteria", "(", "optional", ")", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1409-L1422
UnionOfRAD/lithium
data/Model.php
Model.remove
public static function remove($conditions = [], array $options = []) { $params = compact('conditions', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params['options'] + $params + [ 'model' => get_called_class(), 'type' => 'delete' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->delete($query, $options); }); }
php
public static function remove($conditions = [], array $options = []) { $params = compact('conditions', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $options = $params['options'] + $params + [ 'model' => get_called_class(), 'type' => 'delete' ]; unset($options['options']); $query = static::_instance('query', $options); return static::connection()->delete($query, $options); }); }
[ "public", "static", "function", "remove", "(", "$", "conditions", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'conditions'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", ...
Remove multiple documents or records based on a given set of criteria. **WARNING**: If no criteria are specified, or if the criteria (`$conditions`) is an empty value (i.e. an empty array or `null`), all the data in the backend data source (i.e. table or collection) _will_ be deleted. @param mixed $conditions An array of key/value pairs representing the scope of the records or documents to be deleted. @param array $options Any database-specific options to use when performing the operation. See the `delete()` method of the corresponding backend database for available options. @return boolean Returns `true` if the remove operation succeeded, otherwise `false`. @filter
[ "Remove", "multiple", "documents", "or", "records", "based", "on", "a", "given", "set", "of", "criteria", ".", "**", "WARNING", "**", ":", "If", "no", "criteria", "are", "specified", "or", "if", "the", "criteria", "(", "$conditions", ")", "is", "an", "em...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1438-L1451
UnionOfRAD/lithium
data/Model.php
Model.&
public static function &connection() { $self = static::_object(); $connections = $self->_classes['connections']; $name = isset($self->_meta['connection']) ? $self->_meta['connection'] : null; if ($conn = $connections::get($name)) { return $conn; } $class = get_called_class(); $msg = "The data connection `{$name}` is not configured for model `{$class}`."; throw new ConfigException($msg); }
php
public static function &connection() { $self = static::_object(); $connections = $self->_classes['connections']; $name = isset($self->_meta['connection']) ? $self->_meta['connection'] : null; if ($conn = $connections::get($name)) { return $conn; } $class = get_called_class(); $msg = "The data connection `{$name}` is not configured for model `{$class}`."; throw new ConfigException($msg); }
[ "public", "static", "function", "&", "connection", "(", ")", "{", "$", "self", "=", "static", "::", "_object", "(", ")", ";", "$", "connections", "=", "$", "self", "->", "_classes", "[", "'connections'", "]", ";", "$", "name", "=", "isset", "(", "$",...
Gets the connection object to which this model is bound. Throws exceptions if a connection isn't set, or if the connection named isn't configured. @return object Returns an instance of `lithium\data\Source` from the connection configuration to which this model is bound.
[ "Gets", "the", "connection", "object", "to", "which", "this", "model", "is", "bound", ".", "Throws", "exceptions", "if", "a", "connection", "isn", "t", "set", "or", "if", "the", "connection", "named", "isn", "t", "configured", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1460-L1471
UnionOfRAD/lithium
data/Model.php
Model._relationsToLoad
protected static function _relationsToLoad() { try { if (!$connection = static::connection()) { return; } } catch (ConfigException $e) { return; } if (!$connection::enabled('relationships')) { return; } $self = static::_object(); foreach ($self->_relationTypes as $type) { $self->$type = Set::normalize($self->$type); foreach ($self->$type as $name => $config) { $self->_relationsToLoad[$name] = $type; $fieldName = $self->_relationFieldName($type, $name); $self->_relationFieldNames[$fieldName] = $name; } } }
php
protected static function _relationsToLoad() { try { if (!$connection = static::connection()) { return; } } catch (ConfigException $e) { return; } if (!$connection::enabled('relationships')) { return; } $self = static::_object(); foreach ($self->_relationTypes as $type) { $self->$type = Set::normalize($self->$type); foreach ($self->$type as $name => $config) { $self->_relationsToLoad[$name] = $type; $fieldName = $self->_relationFieldName($type, $name); $self->_relationFieldNames[$fieldName] = $name; } } }
[ "protected", "static", "function", "_relationsToLoad", "(", ")", "{", "try", "{", "if", "(", "!", "$", "connection", "=", "static", "::", "connection", "(", ")", ")", "{", "return", ";", "}", "}", "catch", "(", "ConfigException", "$", "e", ")", "{", ...
Iterates through relationship types to construct relation map. @todo See if this can be rewritten to be lazy. @return void
[ "Iterates", "through", "relationship", "types", "to", "construct", "relation", "map", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Model.php#L1490-L1513
UnionOfRAD/lithium
console/command/create/View.php
View._save
protected function _save(array $params = []) { $params['path'] = Inflector::underscore($this->request->action); $params['file'] = $this->request->args(0); $contents = $this->_template(); $result = Text::insert($contents, $params); if (!empty($this->_library['path'])) { $path = $this->_library['path'] . "/views/{$params['path']}/{$params['file']}"; $file = str_replace('//', '/', "{$path}.php"); $directory = dirname($file); if (!is_dir($directory)) { if (!mkdir($directory, 0755, true)) { return false; } } $directory = str_replace($this->_library['path'] . '/', '', $directory); if (file_exists($file)) { $prompt = "{$file} already exists. Overwrite?"; $choices = ['y', 'n']; if ($this->in($prompt, compact('choices')) !== 'y') { return "{$params['file']} skipped."; } } if (is_int(file_put_contents($file, $result))) { return "{$params['file']}.php created in {$directory}."; } } return false; }
php
protected function _save(array $params = []) { $params['path'] = Inflector::underscore($this->request->action); $params['file'] = $this->request->args(0); $contents = $this->_template(); $result = Text::insert($contents, $params); if (!empty($this->_library['path'])) { $path = $this->_library['path'] . "/views/{$params['path']}/{$params['file']}"; $file = str_replace('//', '/', "{$path}.php"); $directory = dirname($file); if (!is_dir($directory)) { if (!mkdir($directory, 0755, true)) { return false; } } $directory = str_replace($this->_library['path'] . '/', '', $directory); if (file_exists($file)) { $prompt = "{$file} already exists. Overwrite?"; $choices = ['y', 'n']; if ($this->in($prompt, compact('choices')) !== 'y') { return "{$params['file']} skipped."; } } if (is_int(file_put_contents($file, $result))) { return "{$params['file']}.php created in {$directory}."; } } return false; }
[ "protected", "function", "_save", "(", "array", "$", "params", "=", "[", "]", ")", "{", "$", "params", "[", "'path'", "]", "=", "Inflector", "::", "underscore", "(", "$", "this", "->", "request", "->", "action", ")", ";", "$", "params", "[", "'file'"...
Override the save method to handle view specific params. @param array $params @return mixed
[ "Override", "the", "save", "method", "to", "handle", "view", "specific", "params", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/command/create/View.php#L60-L90
UnionOfRAD/lithium
data/collection/DocumentSet.php
DocumentSet.modified
public function modified() { if (count($this->_original) !== count($this->_data)) { return true; } foreach ($this->_original as $key => $doc) { $updated = $this->_data[$key]; if (!isset($updated)) { return true; } if ($doc !== $updated) { return true; } if (!is_object($updated) || !method_exists($updated, 'modified')) { continue; } $modified = $this->_data[$key]->modified(); if (in_array(true, $modified)) { return true; } } return false; }
php
public function modified() { if (count($this->_original) !== count($this->_data)) { return true; } foreach ($this->_original as $key => $doc) { $updated = $this->_data[$key]; if (!isset($updated)) { return true; } if ($doc !== $updated) { return true; } if (!is_object($updated) || !method_exists($updated, 'modified')) { continue; } $modified = $this->_data[$key]->modified(); if (in_array(true, $modified)) { return true; } } return false; }
[ "public", "function", "modified", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "_original", ")", "!==", "count", "(", "$", "this", "->", "_data", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "$", "this", "->", "_original...
Determines if the `DocumentSet` has been modified since it was last saved @return boolean
[ "Determines", "if", "the", "DocumentSet", "has", "been", "modified", "since", "it", "was", "last", "saved" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/collection/DocumentSet.php#L50-L72
UnionOfRAD/lithium
data/collection/DocumentSet.php
DocumentSet.to
public function to($format, array $options = []) { $this->offsetGet(null); return parent::to($format, $options); }
php
public function to($format, array $options = []) { $this->offsetGet(null); return parent::to($format, $options); }
[ "public", "function", "to", "(", "$", "format", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "offsetGet", "(", "null", ")", ";", "return", "parent", "::", "to", "(", "$", "format", ",", "$", "options", ")", ";", "}" ]
Adds conversions checks to ensure certain class types and embedded values are properly cast. @param string $format Currently only `array` is supported. @param array $options @return mixed
[ "Adds", "conversions", "checks", "to", "ensure", "certain", "class", "types", "and", "embedded", "values", "are", "properly", "cast", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/collection/DocumentSet.php#L81-L84
UnionOfRAD/lithium
data/collection/DocumentSet.php
DocumentSet._populate
protected function _populate() { if ($this->closed() || !$this->_result->valid()) { return; } $data = $this->_result->current(); $result = $this->_set($data, null, ['exists' => true, 'original' => true]); $this->_result->next(); return $result; }
php
protected function _populate() { if ($this->closed() || !$this->_result->valid()) { return; } $data = $this->_result->current(); $result = $this->_set($data, null, ['exists' => true, 'original' => true]); $this->_result->next(); return $result; }
[ "protected", "function", "_populate", "(", ")", "{", "if", "(", "$", "this", "->", "closed", "(", ")", "||", "!", "$", "this", "->", "_result", "->", "valid", "(", ")", ")", "{", "return", ";", "}", "$", "data", "=", "$", "this", "->", "_result",...
Extract the next item from the result ressource and wraps it into a `Document` object. @return mixed Returns the next `Document` if exists. Returns `null` otherwise
[ "Extract", "the", "next", "item", "from", "the", "result", "ressource", "and", "wraps", "it", "into", "a", "Document", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/collection/DocumentSet.php#L101-L110
UnionOfRAD/lithium
data/collection/DocumentSet.php
DocumentSet._set
protected function _set($data = null, $offset = null, $options = []) { if ($schema = $this->schema()) { $model = $this->_model; $pathKey = $this->_pathKey; $options = compact('model', 'pathKey') + $options; $data = !is_object($data) ? $schema->cast($this, $offset, $data, $options) : $data; $key = $model && $data instanceof Document ? $model::key($data) : $offset; } else { $key = $offset; } if (is_array($key)) { $key = count($key) === 1 ? current($key) : null; } if (is_object($key)) { $key = (string) $key; } if (is_object($data) && method_exists($data, 'assignTo')) { $data->assignTo($this); } $key !== null ? $this->_data[$key] = $data : $this->_data[] = $data; if (isset($options['original']) && $options['original']) { $key !== null ? $this->_original[$key] = $data : $this->_original[] = $data; } return $data; }
php
protected function _set($data = null, $offset = null, $options = []) { if ($schema = $this->schema()) { $model = $this->_model; $pathKey = $this->_pathKey; $options = compact('model', 'pathKey') + $options; $data = !is_object($data) ? $schema->cast($this, $offset, $data, $options) : $data; $key = $model && $data instanceof Document ? $model::key($data) : $offset; } else { $key = $offset; } if (is_array($key)) { $key = count($key) === 1 ? current($key) : null; } if (is_object($key)) { $key = (string) $key; } if (is_object($data) && method_exists($data, 'assignTo')) { $data->assignTo($this); } $key !== null ? $this->_data[$key] = $data : $this->_data[] = $data; if (isset($options['original']) && $options['original']) { $key !== null ? $this->_original[$key] = $data : $this->_original[] = $data; } return $data; }
[ "protected", "function", "_set", "(", "$", "data", "=", "null", ",", "$", "offset", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "schema", "=", "$", "this", "->", "schema", "(", ")", ")", "{", "$", "model", "=", ...
Helper method to normalize and set data. @param mixed $data @param null|integer|string $offset @param array $options @return mixed The (potentially) cast data.
[ "Helper", "method", "to", "normalize", "and", "set", "data", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/collection/DocumentSet.php#L120-L144
UnionOfRAD/lithium
data/Connections.php
Connections.add
public static function add($name, array $config = []) { $defaults = [ 'type' => null, 'adapter' => null ]; return static::$_configurations[$name] = $config + $defaults; }
php
public static function add($name, array $config = []) { $defaults = [ 'type' => null, 'adapter' => null ]; return static::$_configurations[$name] = $config + $defaults; }
[ "public", "static", "function", "add", "(", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'type'", "=>", "null", ",", "'adapter'", "=>", "null", "]", ";", "return", "static", "::", "$", "_configuration...
Add connection configurations to your app in `config/bootstrap/connections.php` For example: ``` Connections::add('default', [ 'type' => 'database', 'adapter' => 'MySql', 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'my_blog' ]); ``` or ``` Connections::add('couch', [ 'type' => 'http', 'adapter' => 'CouchDb', 'host' => '127.0.0.1', 'port' => 5984 ]); ``` or ``` Connections::add('mongo', [ 'type' => 'MongoDb', 'database' => 'my_app' ]); ``` @see lithium\data\Model::$_meta @param string $name The name by which this connection is referenced. Use this name to retrieve the connection again using `Connections::get()`, or to bind a model to it using `Model::$_meta['connection']`. @param array $config Contains all additional configuration information used by the connection, including the name of the adapter class where applicable (i.e. `MySql`), and typcially the server host/socket to connect to, the name of the database or other entity to use. Each adapter has its own specific configuration settings for handling things like connection persistence, data encoding, etc. See the individual adapter or data source class for more information on what configuration settings it supports. Basic / required options supported are: - `'type'` _string_: The type of data source that defines this connection; typically a class or namespace name. Relational database data sources, use `'database'`, while CouchDB and other HTTP-related data sources use `'http'`, etc. For classes which directly extend `lithium\data\Source`, and do not use an adapter, simply use the name of the class, i.e. `'MongoDb'`. - `'adapter'` _string_: For `type`s such as `'database'` which are adapter-driven, provides the name of the adapter associated with this configuration. @return array Returns the final post-processed connection information, as stored in the internal configuration array used by `Connections`.
[ "Add", "connection", "configurations", "to", "your", "app", "in", "config", "/", "bootstrap", "/", "connections", ".", "php" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Connections.php#L102-L108
UnionOfRAD/lithium
data/Connections.php
Connections.get
public static function get($name = null, array $options = []) { static $mockAdapter; $defaults = ['config' => false, 'autoCreate' => true]; $options += $defaults; if ($name === false) { if (!$mockAdapter) { $class = Libraries::locate('data.source', 'Mock'); $mockAdapter = new $class(); } return $mockAdapter; } if (!$name) { return array_keys(static::$_configurations); } if (!isset(static::$_configurations[$name])) { return null; } if ($options['config']) { return static::_config($name); } $settings = static::$_configurations[$name]; if (!isset($settings[0]['object']) && !$options['autoCreate']) { return null; } return static::adapter($name); }
php
public static function get($name = null, array $options = []) { static $mockAdapter; $defaults = ['config' => false, 'autoCreate' => true]; $options += $defaults; if ($name === false) { if (!$mockAdapter) { $class = Libraries::locate('data.source', 'Mock'); $mockAdapter = new $class(); } return $mockAdapter; } if (!$name) { return array_keys(static::$_configurations); } if (!isset(static::$_configurations[$name])) { return null; } if ($options['config']) { return static::_config($name); } $settings = static::$_configurations[$name]; if (!isset($settings[0]['object']) && !$options['autoCreate']) { return null; } return static::adapter($name); }
[ "public", "static", "function", "get", "(", "$", "name", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "static", "$", "mockAdapter", ";", "$", "defaults", "=", "[", "'config'", "=>", "false", ",", "'autoCreate'", "=>", "true", "...
Read the configuration or access the connections you have set up. Usage: ``` // Gets the names of all available configurations $configurations = Connections::get(); // Gets the configuration array for the connection named 'db' $config = Connections::get('db', ['config' => true]); // Gets the instance of the connection object, configured with the settings defined for // this object in Connections::add() $dbConnection = Connections::get('db'); // Gets the connection object, but only if it has already been built. // Otherwise returns null. $dbConnection = Connections::get('db', ['autoCreate' => false]); ``` @param string $name The name of the connection to get, as defined in the first parameter of `add()`, when the connection was initially created. @param array $options Options to use when returning the connection: - `'autoCreate'`: If `false`, the connection object is only returned if it has already been instantiated by a previous call. - `'config'`: If `true`, returns an array representing the connection's internal configuration, instead of the connection itself. @return mixed A configured instance of the connection, or an array of the configuration used.
[ "Read", "the", "configuration", "or", "access", "the", "connections", "you", "have", "set", "up", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Connections.php#L148-L178
UnionOfRAD/lithium
data/Connections.php
Connections._class
protected static function _class($config, $paths = []) { if (!$config['adapter']) { $config['adapter'] = $config['type']; } else { $paths = array_merge(["adapter.data.source.{$config['type']}"], (array) $paths); } return parent::_class($config, $paths); }
php
protected static function _class($config, $paths = []) { if (!$config['adapter']) { $config['adapter'] = $config['type']; } else { $paths = array_merge(["adapter.data.source.{$config['type']}"], (array) $paths); } return parent::_class($config, $paths); }
[ "protected", "static", "function", "_class", "(", "$", "config", ",", "$", "paths", "=", "[", "]", ")", "{", "if", "(", "!", "$", "config", "[", "'adapter'", "]", ")", "{", "$", "config", "[", "'adapter'", "]", "=", "$", "config", "[", "'type'", ...
Constructs a data source or adapter object instance from a configuration array. @param array $config @param array $paths @return object
[ "Constructs", "a", "data", "source", "or", "adapter", "object", "instance", "from", "a", "configuration", "array", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/Connections.php#L187-L194
UnionOfRAD/lithium
console/Response.php
Response.output
public function output($output) { return fwrite($this->output, Text::insert($output, $this->styles())); }
php
public function output($output) { return fwrite($this->output, Text::insert($output, $this->styles())); }
[ "public", "function", "output", "(", "$", "output", ")", "{", "return", "fwrite", "(", "$", "this", "->", "output", ",", "Text", "::", "insert", "(", "$", "output", ",", "$", "this", "->", "styles", "(", ")", ")", ")", ";", "}" ]
Writes string to output stream @param string $output @return mixed
[ "Writes", "string", "to", "output", "stream" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Response.php#L90-L92
UnionOfRAD/lithium
console/Response.php
Response.error
public function error($error) { return fwrite($this->error, Text::insert($error, $this->styles())); }
php
public function error($error) { return fwrite($this->error, Text::insert($error, $this->styles())); }
[ "public", "function", "error", "(", "$", "error", ")", "{", "return", "fwrite", "(", "$", "this", "->", "error", ",", "Text", "::", "insert", "(", "$", "error", ",", "$", "this", "->", "styles", "(", ")", ")", ")", ";", "}" ]
Writes string to error stream @param string $error @return mixed
[ "Writes", "string", "to", "error", "stream" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Response.php#L100-L102
UnionOfRAD/lithium
console/Response.php
Response.styles
public function styles($styles = []) { $defaults = [ 'end' => "\033[0m", 'black' => "\033[0;30m", 'red' => "\033[0;31m", 'green' => "\033[0;32m", 'yellow' => "\033[0;33m", 'blue' => "\033[0;34m", 'purple' => "\033[0;35m", 'cyan' => "\033[0;36m", 'white' => "\033[0;37m", 'heading' => "\033[1;36m", 'option' => "\033[0;35m", 'command' => "\033[0;35m", 'error' => "\033[0;31m", 'success' => "\033[0;32m", 'bold' => "\033[1m", ]; if ($styles === false || $this->plain || strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return array_combine(array_keys($defaults), array_pad([], count($defaults), null)); } return $styles + $defaults; }
php
public function styles($styles = []) { $defaults = [ 'end' => "\033[0m", 'black' => "\033[0;30m", 'red' => "\033[0;31m", 'green' => "\033[0;32m", 'yellow' => "\033[0;33m", 'blue' => "\033[0;34m", 'purple' => "\033[0;35m", 'cyan' => "\033[0;36m", 'white' => "\033[0;37m", 'heading' => "\033[1;36m", 'option' => "\033[0;35m", 'command' => "\033[0;35m", 'error' => "\033[0;31m", 'success' => "\033[0;32m", 'bold' => "\033[1m", ]; if ($styles === false || $this->plain || strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return array_combine(array_keys($defaults), array_pad([], count($defaults), null)); } return $styles + $defaults; }
[ "public", "function", "styles", "(", "$", "styles", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'end'", "=>", "\"\\033[0m\"", ",", "'black'", "=>", "\"\\033[0;30m\"", ",", "'red'", "=>", "\"\\033[0;31m\"", ",", "'green'", "=>", "\"\\033[0;32m\"", ...
Handles styling output. Uses ANSI escape sequences for colorization. These may not always be supported (i.e. on Windows). @param array|boolean $styles @return array
[ "Handles", "styling", "output", ".", "Uses", "ANSI", "escape", "sequences", "for", "colorization", ".", "These", "may", "not", "always", "be", "supported", "(", "i", ".", "e", ".", "on", "Windows", ")", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Response.php#L125-L147
UnionOfRAD/lithium
data/DocumentSchema.php
DocumentSchema._castType
protected function _castType($value, $field) { if ($this->is('null', $field) && ($value === null || $value === "")) { return null; } if (!is_scalar($value)) { return $value; } $type = $this->type($field); return isset($this->_handlers[$type]) ? $this->_handlers[$type]($value) : $value; }
php
protected function _castType($value, $field) { if ($this->is('null', $field) && ($value === null || $value === "")) { return null; } if (!is_scalar($value)) { return $value; } $type = $this->type($field); return isset($this->_handlers[$type]) ? $this->_handlers[$type]($value) : $value; }
[ "protected", "function", "_castType", "(", "$", "value", ",", "$", "field", ")", "{", "if", "(", "$", "this", "->", "is", "(", "'null'", ",", "$", "field", ")", "&&", "(", "$", "value", "===", "null", "||", "$", "value", "===", "\"\"", ")", ")", ...
Casts a scalar (non-object/array) value to its corresponding database-native value or custom value object based on a handler assigned to `$field`'s data type. @param mixed $value The value to be cast. @param string $field The name of the field that `$value` is or will be stored in. If it is a nested field, `$field` should be the full dot-separated path to the sub-object's field. @return mixed Returns the result of `$value`, modified by a matching handler data type handler, if available.
[ "Casts", "a", "scalar", "(", "non", "-", "object", "/", "array", ")", "value", "to", "its", "corresponding", "database", "-", "native", "value", "or", "custom", "value", "object", "based", "on", "a", "handler", "assigned", "to", "$field", "s", "data", "t...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/DocumentSchema.php#L117-L126
UnionOfRAD/lithium
core/StaticObject.php
StaticObject.invokeMethod
public static function invokeMethod($method, $params = []) { switch (count($params)) { case 0: return static::$method(); case 1: return static::$method($params[0]); case 2: return static::$method($params[0], $params[1]); case 3: return static::$method($params[0], $params[1], $params[2]); case 4: return static::$method($params[0], $params[1], $params[2], $params[3]); case 5: return static::$method($params[0], $params[1], $params[2], $params[3], $params[4]); default: return forward_static_call_array([get_called_class(), $method], $params); } }
php
public static function invokeMethod($method, $params = []) { switch (count($params)) { case 0: return static::$method(); case 1: return static::$method($params[0]); case 2: return static::$method($params[0], $params[1]); case 3: return static::$method($params[0], $params[1], $params[2]); case 4: return static::$method($params[0], $params[1], $params[2], $params[3]); case 5: return static::$method($params[0], $params[1], $params[2], $params[3], $params[4]); default: return forward_static_call_array([get_called_class(), $method], $params); } }
[ "public", "static", "function", "invokeMethod", "(", "$", "method", ",", "$", "params", "=", "[", "]", ")", "{", "switch", "(", "count", "(", "$", "params", ")", ")", "{", "case", "0", ":", "return", "static", "::", "$", "method", "(", ")", ";", ...
Calls a method on this object with the given parameters. Provides an OO wrapper for `forward_static_call_array()`, and improves performance by using straight method calls in most cases. @param string $method Name of the method to call. @param array $params Parameter list to use when calling `$method`. @return mixed Returns the result of the method call.
[ "Calls", "a", "method", "on", "this", "object", "with", "the", "given", "parameters", ".", "Provides", "an", "OO", "wrapper", "for", "forward_static_call_array", "()", "and", "improves", "performance", "by", "using", "straight", "method", "calls", "in", "most", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/StaticObject.php#L40-L57
UnionOfRAD/lithium
core/StaticObject.php
StaticObject._instance
protected static function _instance($name, array $options = []) { if (is_string($name) && isset(static::$_classes[$name])) { $name = static::$_classes[$name]; } return Libraries::instance(null, $name, $options); }
php
protected static function _instance($name, array $options = []) { if (is_string($name) && isset(static::$_classes[$name])) { $name = static::$_classes[$name]; } return Libraries::instance(null, $name, $options); }
[ "protected", "static", "function", "_instance", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_string", "(", "$", "name", ")", "&&", "isset", "(", "static", "::", "$", "_classes", "[", "$", "name", "]", ")",...
Returns an instance of a class with given `config`. The `name` could be a key from the `classes` array, a fully namespaced class name, or an object. Typically this method is used in `_init` to create the dependencies used in the current class. @param string|object $name A `classes` key or fully-namespaced class name. @param array $options The configuration passed to the constructor. @return object
[ "Returns", "an", "instance", "of", "a", "class", "with", "given", "config", ".", "The", "name", "could", "be", "a", "key", "from", "the", "classes", "array", "a", "fully", "namespaced", "class", "name", "or", "an", "object", ".", "Typically", "this", "me...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/StaticObject.php#L81-L86
UnionOfRAD/lithium
util/Inflector.php
Inflector.reset
public static function reset() { static::$_singularized = static::$_pluralized = []; static::$_camelized = static::$_underscored = []; static::$_humanized = []; static::$_plural['regexUninflected'] = static::$_singular['regexUninflected'] = null; static::$_plural['regexIrregular'] = static::$_singular['regexIrregular'] = null; static::$_transliteration = [ '/à|á|å|â/' => 'a', '/è|é|ê|ẽ|ë/' => 'e', '/ì|í|î/' => 'i', '/ò|ó|ô|ø/' => 'o', '/ù|ú|ů|û/' => 'u', '/ç|ć|č/' => 'c', '/đ/' => 'dj', '/š/' => 's', '/ž/' => 'z', '/ñ/' => 'n', '/ä|æ/' => 'ae', '/ö/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/ß/' => 'ss', '/Č|Ć/' => 'C', '/DŽ/' => 'Dz', '/Đ/' => 'Dj', '/Š/' => 'S', '/Ž/' => 'Z' ]; }
php
public static function reset() { static::$_singularized = static::$_pluralized = []; static::$_camelized = static::$_underscored = []; static::$_humanized = []; static::$_plural['regexUninflected'] = static::$_singular['regexUninflected'] = null; static::$_plural['regexIrregular'] = static::$_singular['regexIrregular'] = null; static::$_transliteration = [ '/à|á|å|â/' => 'a', '/è|é|ê|ẽ|ë/' => 'e', '/ì|í|î/' => 'i', '/ò|ó|ô|ø/' => 'o', '/ù|ú|ů|û/' => 'u', '/ç|ć|č/' => 'c', '/đ/' => 'dj', '/š/' => 's', '/ž/' => 'z', '/ñ/' => 'n', '/ä|æ/' => 'ae', '/ö/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/ß/' => 'ss', '/Č|Ć/' => 'C', '/DŽ/' => 'Dz', '/Đ/' => 'Dj', '/Š/' => 'S', '/Ž/' => 'Z' ]; }
[ "public", "static", "function", "reset", "(", ")", "{", "static", "::", "$", "_singularized", "=", "static", "::", "$", "_pluralized", "=", "[", "]", ";", "static", "::", "$", "_camelized", "=", "static", "::", "$", "_underscored", "=", "[", "]", ";", ...
Clears local in-memory caches. Can be used to force a full-cache clear when updating inflection rules mid-way through request execution.
[ "Clears", "local", "in", "-", "memory", "caches", ".", "Can", "be", "used", "to", "force", "a", "full", "-", "cache", "clear", "when", "updating", "inflection", "rules", "mid", "-", "way", "through", "request", "execution", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Inflector.php#L230-L261
UnionOfRAD/lithium
util/Inflector.php
Inflector.singularize
public static function singularize($word) { if (isset(static::$_singularized[$word])) { return static::$_singularized[$word]; } if (empty(static::$_singular['irregular'])) { static::$_singular['irregular'] = array_flip(static::$_plural['irregular']); } extract(static::$_singular); if (!isset($regexUninflected) || !isset($regexIrregular)) { $regexUninflected = static::_enclose(join('|', $uninflected + static::$_uninflected)); $regexIrregular = static::_enclose(join('|', array_keys($irregular))); static::$_singular += compact('regexUninflected', 'regexIrregular'); } if (preg_match("/(.*)\\b({$regexIrregular})\$/i", $word, $regs)) { $singular = substr($word, 0, 1) . substr($irregular[strtolower($regs[2])], 1); return static::$_singularized[$word] = $regs[1] . $singular; } if (preg_match('/^(' . $regexUninflected . ')$/i', $word, $regs)) { return static::$_singularized[$word] = $word; } foreach ($rules as $rule => $replacement) { if (preg_match($rule, $word)) { return static::$_singularized[$word] = preg_replace($rule, $replacement, $word); } } return static::$_singularized[$word] = $word; }
php
public static function singularize($word) { if (isset(static::$_singularized[$word])) { return static::$_singularized[$word]; } if (empty(static::$_singular['irregular'])) { static::$_singular['irregular'] = array_flip(static::$_plural['irregular']); } extract(static::$_singular); if (!isset($regexUninflected) || !isset($regexIrregular)) { $regexUninflected = static::_enclose(join('|', $uninflected + static::$_uninflected)); $regexIrregular = static::_enclose(join('|', array_keys($irregular))); static::$_singular += compact('regexUninflected', 'regexIrregular'); } if (preg_match("/(.*)\\b({$regexIrregular})\$/i", $word, $regs)) { $singular = substr($word, 0, 1) . substr($irregular[strtolower($regs[2])], 1); return static::$_singularized[$word] = $regs[1] . $singular; } if (preg_match('/^(' . $regexUninflected . ')$/i', $word, $regs)) { return static::$_singularized[$word] = $word; } foreach ($rules as $rule => $replacement) { if (preg_match($rule, $word)) { return static::$_singularized[$word] = preg_replace($rule, $replacement, $word); } } return static::$_singularized[$word] = $word; }
[ "public", "static", "function", "singularize", "(", "$", "word", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "_singularized", "[", "$", "word", "]", ")", ")", "{", "return", "static", "::", "$", "_singularized", "[", "$", "word", "]", ";"...
Changes the form of a word from plural to singular. @param string $word Word in plural form. @return string Word in singular form.
[ "Changes", "the", "form", "of", "a", "word", "from", "plural", "to", "singular", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Inflector.php#L361-L388
UnionOfRAD/lithium
util/Inflector.php
Inflector.camelize
public static function camelize($word, $cased = true) { $_word = $word; if (isset(static::$_camelized[$_word]) && $cased) { return static::$_camelized[$_word]; } $word = str_replace(" ", "", ucwords(str_replace(["_", '-'], " ", $word))); if (!$cased) { return lcfirst($word); } return static::$_camelized[$_word] = $word; }
php
public static function camelize($word, $cased = true) { $_word = $word; if (isset(static::$_camelized[$_word]) && $cased) { return static::$_camelized[$_word]; } $word = str_replace(" ", "", ucwords(str_replace(["_", '-'], " ", $word))); if (!$cased) { return lcfirst($word); } return static::$_camelized[$_word] = $word; }
[ "public", "static", "function", "camelize", "(", "$", "word", ",", "$", "cased", "=", "true", ")", "{", "$", "_word", "=", "$", "word", ";", "if", "(", "isset", "(", "static", "::", "$", "_camelized", "[", "$", "_word", "]", ")", "&&", "$", "case...
Takes a under_scored word and turns it into a CamelCased or camelBack word @param string $word An under_scored or slugged word (i.e. `'red_bike'` or `'red-bike'`). @param boolean $cased If false, first character is not upper cased @return string CamelCased version of the word (i.e. `'RedBike'`).
[ "Takes", "a", "under_scored", "word", "and", "turns", "it", "into", "a", "CamelCased", "or", "camelBack", "word" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Inflector.php#L397-L409
UnionOfRAD/lithium
util/Inflector.php
Inflector.underscore
public static function underscore($word) { if (isset(static::$_underscored[$word])) { return static::$_underscored[$word]; } return static::$_underscored[$word] = strtolower(static::slug($word, '_')); }
php
public static function underscore($word) { if (isset(static::$_underscored[$word])) { return static::$_underscored[$word]; } return static::$_underscored[$word] = strtolower(static::slug($word, '_')); }
[ "public", "static", "function", "underscore", "(", "$", "word", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "_underscored", "[", "$", "word", "]", ")", ")", "{", "return", "static", "::", "$", "_underscored", "[", "$", "word", "]", ";", ...
Takes a CamelCased version of a word and turns it into an under_scored one. @param string $word CamelCased version of a word (i.e. `'RedBike'`). @return string Under_scored version of the workd (i.e. `'red_bike'`).
[ "Takes", "a", "CamelCased", "version", "of", "a", "word", "and", "turns", "it", "into", "an", "under_scored", "one", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Inflector.php#L417-L422
UnionOfRAD/lithium
util/Inflector.php
Inflector.humanize
public static function humanize($word, $separator = '_') { if (isset(static::$_humanized[$key = $word . ':' . $separator])) { return static::$_humanized[$key]; } return static::$_humanized[$key] = ucwords(str_replace($separator, " ", $word)); }
php
public static function humanize($word, $separator = '_') { if (isset(static::$_humanized[$key = $word . ':' . $separator])) { return static::$_humanized[$key]; } return static::$_humanized[$key] = ucwords(str_replace($separator, " ", $word)); }
[ "public", "static", "function", "humanize", "(", "$", "word", ",", "$", "separator", "=", "'_'", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "_humanized", "[", "$", "key", "=", "$", "word", ".", "':'", ".", "$", "separator", "]", ")", ...
Takes an under_scored version of a word and turns it into an human- readable form by replacing underscores with a space, and by upper casing the initial character. @param string $word Under_scored version of a word (i.e. `'red_bike'`). @param string $separator The separator character used in the initial string. @return string Human readable version of the word (i.e. `'Red Bike'`).
[ "Takes", "an", "under_scored", "version", "of", "a", "word", "and", "turns", "it", "into", "an", "human", "-", "readable", "form", "by", "replacing", "underscores", "with", "a", "space", "and", "by", "upper", "casing", "the", "initial", "character", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Inflector.php#L452-L457
UnionOfRAD/lithium
g11n/catalog/adapter/Memory.php
Memory.read
public function read($category, $locale, $scope) { $scope = $scope ?: 'default'; if (isset($this->_data[$scope][$category][$locale])) { return $this->_data[$scope][$category][$locale]; } }
php
public function read($category, $locale, $scope) { $scope = $scope ?: 'default'; if (isset($this->_data[$scope][$category][$locale])) { return $this->_data[$scope][$category][$locale]; } }
[ "public", "function", "read", "(", "$", "category", ",", "$", "locale", ",", "$", "scope", ")", "{", "$", "scope", "=", "$", "scope", "?", ":", "'default'", ";", "if", "(", "isset", "(", "$", "this", "->", "_data", "[", "$", "scope", "]", "[", ...
Reads data. @param string $category A category. @param string $locale A locale identifier. @param string $scope The scope for the current operation. @return array
[ "Reads", "data", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Memory.php#L35-L41
UnionOfRAD/lithium
g11n/catalog/adapter/Memory.php
Memory.write
public function write($category, $locale, $scope, array $data) { $scope = $scope ?: 'default'; if (!isset($this->_data[$scope][$category][$locale])) { $this->_data[$scope][$category][$locale] = []; } foreach ($data as $item) { $this->_data[$scope][$category][$locale] = $this->_merge( $this->_data[$scope][$category][$locale], $this->_prepareForWrite($item) ); } return true; }
php
public function write($category, $locale, $scope, array $data) { $scope = $scope ?: 'default'; if (!isset($this->_data[$scope][$category][$locale])) { $this->_data[$scope][$category][$locale] = []; } foreach ($data as $item) { $this->_data[$scope][$category][$locale] = $this->_merge( $this->_data[$scope][$category][$locale], $this->_prepareForWrite($item) ); } return true; }
[ "public", "function", "write", "(", "$", "category", ",", "$", "locale", ",", "$", "scope", ",", "array", "$", "data", ")", "{", "$", "scope", "=", "$", "scope", "?", ":", "'default'", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "_data"...
Writes data. @param string $category A category. @param string $locale A locale identifier. @param string $scope The scope for the current operation. @param array $data The data to write. @return boolean
[ "Writes", "data", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/catalog/adapter/Memory.php#L52-L65
UnionOfRAD/lithium
net/http/Router.php
Router.config
public static function config($config = []) { if (!$config) { return ['classes' => static::$_classes, 'unicode' => static::$_unicode]; } if (isset($config['classes'])) { static::$_classes = $config['classes'] + static::$_classes; } if (isset($config['unicode'])) { static::$_unicode = $config['unicode']; } }
php
public static function config($config = []) { if (!$config) { return ['classes' => static::$_classes, 'unicode' => static::$_unicode]; } if (isset($config['classes'])) { static::$_classes = $config['classes'] + static::$_classes; } if (isset($config['unicode'])) { static::$_unicode = $config['unicode']; } }
[ "public", "static", "function", "config", "(", "$", "config", "=", "[", "]", ")", "{", "if", "(", "!", "$", "config", ")", "{", "return", "[", "'classes'", "=>", "static", "::", "$", "_classes", ",", "'unicode'", "=>", "static", "::", "$", "_unicode"...
Modify `Router` configuration settings and dependencies. @param array $config Optional array to override configuration. Acceptable keys are `'classes'` and `'unicode'`. @return array Returns the current configuration settings.
[ "Modify", "Router", "configuration", "settings", "and", "dependencies", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L126-L136
UnionOfRAD/lithium
net/http/Router.php
Router.connect
public static function connect($template, $params = [], $options = []) { if (is_array($options) && isset($options['scope'])) { $name = $options['scope']; } else { $name = static::$_scope; } if (is_object($template)) { return (static::$_configurations[$name][] = $template); } if (is_string($params)) { $params = static::_parseString($params, false); } if (isset($params[0]) && is_array($tmp = static::_parseString($params[0], false))) { unset($params[0]); $params = $tmp + $params; } $params = static::_parseController($params); if (is_callable($options)) { $options = ['handler' => $options]; } $config = compact('template', 'params') + $options + [ 'formatters' => static::formatters(), 'modifiers' => static::modifiers(), 'unicode' => static::$_unicode ]; return (static::$_configurations[$name][] = static::_instance('route', $config)); }
php
public static function connect($template, $params = [], $options = []) { if (is_array($options) && isset($options['scope'])) { $name = $options['scope']; } else { $name = static::$_scope; } if (is_object($template)) { return (static::$_configurations[$name][] = $template); } if (is_string($params)) { $params = static::_parseString($params, false); } if (isset($params[0]) && is_array($tmp = static::_parseString($params[0], false))) { unset($params[0]); $params = $tmp + $params; } $params = static::_parseController($params); if (is_callable($options)) { $options = ['handler' => $options]; } $config = compact('template', 'params') + $options + [ 'formatters' => static::formatters(), 'modifiers' => static::modifiers(), 'unicode' => static::$_unicode ]; return (static::$_configurations[$name][] = static::_instance('route', $config)); }
[ "public", "static", "function", "connect", "(", "$", "template", ",", "$", "params", "=", "[", "]", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_array", "(", "$", "options", ")", "&&", "isset", "(", "$", "options", "[", "'scope'", ...
Connects a new route and returns the current routes array. This method creates a new `Route` object and registers it with the `Router`. The order in which routes are connected matters, since the order of precedence is taken into account in parsing and matching operations. A callable can be passed in place of `$options`. In this case the callable acts as a *route handler*. Route handlers should return an instance of `lithium\net\http\Response` and can be used to short-circuit the framework's lookup and invocation of controller actions: ``` Router::connect('/photos/{:id:[0-9]+}.jpg', [], function($request) { return new Response([ 'headers' => ['Content-type' => 'image/jpeg'], 'body' => Photos::first($request->id)->bytes() ]); }); ``` @see lithium\net\http\Route @see lithium\net\http\Route::$_handler @see lithium\net\http\Router::parse() @see lithium\net\http\Router::match() @see lithium\net\http\Router::_parseString() @see lithium\net\http\Response @param string|object $template An empty string, a route string `/` or an instance of `lithium\net\http\Route`. @param array|string $params An array describing the default or required elements of the route or alternatively a path string i.e. `Posts::index`. @param array|callable $options Either an array of options (`'handler'`, `'formatters'`, `'modifiers'`, `'unicode'` as well as any options for `Route`) or a callable that will be used as a route handler. @return \lithium\net\http\Route Instance of the connected route.
[ "Connects", "a", "new", "route", "and", "returns", "the", "current", "routes", "array", ".", "This", "method", "creates", "a", "new", "Route", "object", "and", "registers", "it", "with", "the", "Router", ".", "The", "order", "in", "which", "routes", "are",...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L172-L198
UnionOfRAD/lithium
net/http/Router.php
Router.modifiers
public static function modifiers(array $modifiers = []) { if (!static::$_modifiers) { static::$_modifiers = [ 'args' => function($value) { return explode('/', $value); }, 'controller' => function($value) { return Inflector::camelize($value); } ]; } if ($modifiers) { static::$_modifiers = array_filter($modifiers + static::$_modifiers); } return static::$_modifiers; }
php
public static function modifiers(array $modifiers = []) { if (!static::$_modifiers) { static::$_modifiers = [ 'args' => function($value) { return explode('/', $value); }, 'controller' => function($value) { return Inflector::camelize($value); } ]; } if ($modifiers) { static::$_modifiers = array_filter($modifiers + static::$_modifiers); } return static::$_modifiers; }
[ "public", "static", "function", "modifiers", "(", "array", "$", "modifiers", "=", "[", "]", ")", "{", "if", "(", "!", "static", "::", "$", "_modifiers", ")", "{", "static", "::", "$", "_modifiers", "=", "[", "'args'", "=>", "function", "(", "$", "val...
Used to get or set an array of named formatter closures, which are used to format route parameters when parsing URLs. For example, the following would match a `posts/index` url to a `PostsController::indexAction()` method. ``` use lithium\util\Inflector; Router::modifiers([ 'controller' => function($value) { return Inflector::camelize($value); }, 'action' => function($value) { return Inflector::camelize($value) . 'Action'; } ]); ``` _Note_: Because modifiers are copied to `Route` objects on an individual basis, make sure you append your custom modifiers _before_ connecting new routes. @param array $modifiers An array of named formatter closures to append to (or overwrite) the existing list. @return array Returns the formatters array.
[ "Used", "to", "get", "or", "set", "an", "array", "of", "named", "formatter", "closures", "which", "are", "used", "to", "format", "route", "parameters", "when", "parsing", "URLs", ".", "For", "example", "the", "following", "would", "match", "a", "posts", "/...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L239-L254
UnionOfRAD/lithium
net/http/Router.php
Router.formatters
public static function formatters(array $formatters = []) { if (!static::$_formatters) { static::$_formatters = [ 'args' => function($value) { return is_array($value) ? join('/', $value) : $value; }, 'controller' => function($value) { if (strpos($value, '\\')) { $value = explode('\\', $value); $value = end($value); } return Inflector::underscore($value); } ]; } if ($formatters) { static::$_formatters = array_filter($formatters + static::$_formatters); } return static::$_formatters; }
php
public static function formatters(array $formatters = []) { if (!static::$_formatters) { static::$_formatters = [ 'args' => function($value) { return is_array($value) ? join('/', $value) : $value; }, 'controller' => function($value) { if (strpos($value, '\\')) { $value = explode('\\', $value); $value = end($value); } return Inflector::underscore($value); } ]; } if ($formatters) { static::$_formatters = array_filter($formatters + static::$_formatters); } return static::$_formatters; }
[ "public", "static", "function", "formatters", "(", "array", "$", "formatters", "=", "[", "]", ")", "{", "if", "(", "!", "static", "::", "$", "_formatters", ")", "{", "static", "::", "$", "_formatters", "=", "[", "'args'", "=>", "function", "(", "$", ...
Used to get or set an array of named formatter closures, which are used to format route parameters when generating URLs. For example, for controller/action parameters to be dashed instead of underscored or camelBacked, you could do the following: ``` use lithium\util\Inflector; Router::formatters([ 'controller' => function($value) { return Inflector::slug($value); }, 'action' => function($value) { return Inflector::slug($value); } ]); ``` _Note_: Because formatters are copied to `Route` objects on an individual basis, make sure you append custom formatters _before_ connecting new routes. @param array $formatters An array of named formatter closures to append to (or overwrite) the existing list. @return array Returns the formatters array.
[ "Used", "to", "get", "or", "set", "an", "array", "of", "named", "formatter", "closures", "which", "are", "used", "to", "format", "route", "parameters", "when", "generating", "URLs", ".", "For", "example", "for", "controller", "/", "action", "parameters", "to...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L277-L296
UnionOfRAD/lithium
net/http/Router.php
Router.parse
public static function parse($request) { foreach (static::$_configurations as $name => $value) { $original = $request->params; $name = is_int($name) ? false : $name; if (!$url = static::_parseScope($name, $request)) { continue; } foreach (static::$_configurations[$name] as $route) { if (!$match = $route->parse($request, compact('url'))) { continue; } $request = $match; if ($route->canContinue() && isset($request->params['args'])) { $url = '/' . join('/', $request->params['args']); unset($request->params['args']); continue; } static::attach($name, null, isset($request->params) ? $request->params : []); static::scope($name); return $request; } $request->params = $original; } }
php
public static function parse($request) { foreach (static::$_configurations as $name => $value) { $original = $request->params; $name = is_int($name) ? false : $name; if (!$url = static::_parseScope($name, $request)) { continue; } foreach (static::$_configurations[$name] as $route) { if (!$match = $route->parse($request, compact('url'))) { continue; } $request = $match; if ($route->canContinue() && isset($request->params['args'])) { $url = '/' . join('/', $request->params['args']); unset($request->params['args']); continue; } static::attach($name, null, isset($request->params) ? $request->params : []); static::scope($name); return $request; } $request->params = $original; } }
[ "public", "static", "function", "parse", "(", "$", "request", ")", "{", "foreach", "(", "static", "::", "$", "_configurations", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "original", "=", "$", "request", "->", "params", ";", "$", "name", "...
Accepts an instance of `lithium\action\Request` (or a subclass) and matches it against each route, in the order that the routes are connected. If a route match the request, `lithium\net\http\Router::_scope` will be updated according the scope membership of the route @see lithium\action\Request @see lithium\net\http\Router::connect() @param object $request A request object containing URL and environment data. @return array Returns an array of parameters specifying how the given request should be routed. The keys returned depend on the `Route` object that was matched, but typically include `'controller'` and `'action'` keys.
[ "Accepts", "an", "instance", "of", "lithium", "\\", "action", "\\", "Request", "(", "or", "a", "subclass", ")", "and", "matches", "it", "against", "each", "route", "in", "the", "order", "that", "the", "routes", "are", "connected", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L312-L339
UnionOfRAD/lithium
net/http/Router.php
Router.match
public static function match($url = [], $context = null, array $options = []) { $options = static::_matchOptions($url, $context, $options); if (is_string($url = static::_prepareParams($url, $context, $options))) { return $url; } $base = $options['base']; $url += ['action' => 'index']; $stack = []; $suffix = isset($url['#']) ? "#{$url['#']}" : null; unset($url['#']); $scope = $options['scope']; if (isset(static::$_configurations[$scope])) { foreach (static::$_configurations[$scope] as $route) { if (!$match = $route->match($url + ['scope' => static::attached($scope)], $context)) { continue; } if ($route->canContinue()) { $stack[] = $match; $export = $route->export(); $keys = $export['match'] + $export['keys'] + $export['defaults']; unset($keys['args']); $url = array_diff_key($url, $keys); continue; } if ($stack) { $stack[] = $match; $match = static::_compileStack($stack); } $path = rtrim("{$base}{$match}{$suffix}", '/') ?: '/'; $path = ($options) ? static::_prefix($path, $context, $options) : $path; return $path ?: '/'; } } $url = static::_formatError($url); $message = "No parameter match found for URL `{$url}`"; $message .= $scope ? " in `{$scope}` scope." : '.'; throw new RoutingException($message); }
php
public static function match($url = [], $context = null, array $options = []) { $options = static::_matchOptions($url, $context, $options); if (is_string($url = static::_prepareParams($url, $context, $options))) { return $url; } $base = $options['base']; $url += ['action' => 'index']; $stack = []; $suffix = isset($url['#']) ? "#{$url['#']}" : null; unset($url['#']); $scope = $options['scope']; if (isset(static::$_configurations[$scope])) { foreach (static::$_configurations[$scope] as $route) { if (!$match = $route->match($url + ['scope' => static::attached($scope)], $context)) { continue; } if ($route->canContinue()) { $stack[] = $match; $export = $route->export(); $keys = $export['match'] + $export['keys'] + $export['defaults']; unset($keys['args']); $url = array_diff_key($url, $keys); continue; } if ($stack) { $stack[] = $match; $match = static::_compileStack($stack); } $path = rtrim("{$base}{$match}{$suffix}", '/') ?: '/'; $path = ($options) ? static::_prefix($path, $context, $options) : $path; return $path ?: '/'; } } $url = static::_formatError($url); $message = "No parameter match found for URL `{$url}`"; $message .= $scope ? " in `{$scope}` scope." : '.'; throw new RoutingException($message); }
[ "public", "static", "function", "match", "(", "$", "url", "=", "[", "]", ",", "$", "context", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "static", "::", "_matchOptions", "(", "$", "url", ",", "$", "co...
Attempts to match an array of route parameters (i.e. `'controller'`, `'action'`, etc.) against a connected `Route` object. For example, given the following route: ``` Router::connect('/login', ['controller' => 'users', 'action' => 'login']); ``` This will match: ``` $url = Router::match(['controller' => 'users', 'action' => 'login']); // returns /login ``` For URLs templates with no insert parameters (i.e. elements like `{:id}` that are replaced with a value), all parameters must match exactly as they appear in the route parameters. Alternatively to using a full array, you can specify routes using a more compact syntax. The above example can be written as: ``` $url = Router::match('Users::login'); // still returns /login ``` You can combine this with more complicated routes; for example: ``` Router::connect('/posts/{:id:\d+}', ['controller' => 'posts', 'action' => 'view']); ``` This will match: ``` $url = Router::match(['controller' => 'posts', 'action' => 'view', 'id' => '1138']); // returns /posts/1138 ``` Again, you can specify the same URL with a more compact syntax, as in the following: ``` $url = Router::match(['Posts::view', 'id' => '1138']); // again, returns /posts/1138 ``` You can use either syntax anywhere an URL is accepted, i.e. when redirecting or creating links using the `Html` helper. @see lithium\action\Controller::redirect() @see lithium\template\helper\Html::link() @param array|string $url An array of parameters to match, or paremeters in their shorthand form (i.e. `'Posts::view'`). Also takes non-routed, manually generated URL strings. @param \lithium\action\Request $context This supplies the context for any persistent parameters, as well as the base URL for the application. @param array $options Options for the generation of the matched URL. Currently accepted values are: - `'absolute'` _boolean_: Indicates whether or not the returned URL should be an absolute path (i.e. including scheme and host name). - `'host'` _string_: If `'absolute'` is `true`, sets the host name to be used, or overrides the one provided in `$context`. - `'scheme'` _string_: If `'absolute'` is `true`, sets the URL scheme to be used, or overrides the one provided in `$context`. - `'scope'` _string_: Optionnal scope name. @return string Returns a generated URL, based on the URL template of the matched route, and prefixed with the base URL of the application.
[ "Attempts", "to", "match", "an", "array", "of", "route", "parameters", "(", "i", ".", "e", ".", "controller", "action", "etc", ".", ")", "against", "a", "connected", "Route", "object", ".", "For", "example", "given", "the", "following", "route", ":" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L403-L444
UnionOfRAD/lithium
net/http/Router.php
Router._matchOptions
protected static function _matchOptions(&$url, $context, $options) { $defaults = [ 'scheme' => null, 'host' => null, 'absolute' => false, 'base' => '' ]; if ($context) { $defaults = [ 'base' => $context->env('base'), 'host' => $context->host, 'scheme' => $context->scheme . ($context->scheme ? '://' : '//') ] + $defaults; } $options += ['scope' => static::scope()]; $vars = []; $scope = $options['scope']; if (is_array($scope)) { $tmp = key($scope); $vars = current($scope); if (!is_array($vars)) { $vars = $scope; $scope = static::scope(); } else { $scope = $tmp; } } if ($config = static::attached($scope, $vars)) { if (is_array($url)) { unset($url['library']); } $config['host'] = $config['host'] ? : $defaults['host']; if ($config['scheme'] === false) { $config['scheme'] = '//'; } else { $config['scheme'] .= ($config['scheme'] ? '://' : $defaults['scheme']); } $config['scheme'] = $config['scheme'] ? : 'http://'; $base = isset($config['base']) ? '/' . $config['base'] : $defaults['base']; $base = $base . ($config['prefix'] ? '/' . $config['prefix'] : ''); $config['base'] = rtrim($config['absolute'] ? '/' . trim($base, '/') : $base, '/'); $defaults = $config + $defaults; } return $options + $defaults; }
php
protected static function _matchOptions(&$url, $context, $options) { $defaults = [ 'scheme' => null, 'host' => null, 'absolute' => false, 'base' => '' ]; if ($context) { $defaults = [ 'base' => $context->env('base'), 'host' => $context->host, 'scheme' => $context->scheme . ($context->scheme ? '://' : '//') ] + $defaults; } $options += ['scope' => static::scope()]; $vars = []; $scope = $options['scope']; if (is_array($scope)) { $tmp = key($scope); $vars = current($scope); if (!is_array($vars)) { $vars = $scope; $scope = static::scope(); } else { $scope = $tmp; } } if ($config = static::attached($scope, $vars)) { if (is_array($url)) { unset($url['library']); } $config['host'] = $config['host'] ? : $defaults['host']; if ($config['scheme'] === false) { $config['scheme'] = '//'; } else { $config['scheme'] .= ($config['scheme'] ? '://' : $defaults['scheme']); } $config['scheme'] = $config['scheme'] ? : 'http://'; $base = isset($config['base']) ? '/' . $config['base'] : $defaults['base']; $base = $base . ($config['prefix'] ? '/' . $config['prefix'] : ''); $config['base'] = rtrim($config['absolute'] ? '/' . trim($base, '/') : $base, '/'); $defaults = $config + $defaults; } return $options + $defaults; }
[ "protected", "static", "function", "_matchOptions", "(", "&", "$", "url", ",", "$", "context", ",", "$", "options", ")", "{", "$", "defaults", "=", "[", "'scheme'", "=>", "null", ",", "'host'", "=>", "null", ",", "'absolute'", "=>", "false", ",", "'bas...
Initialize options for `Router::match()`. @param string|array $url Options to match to a URL. Optionally, this can be a string containing a manually generated URL. @param \lithium\action\Request $context @param array $options Options for the generation of the matched URL. @return array The initialized options.
[ "Initialize", "options", "for", "Router", "::", "match", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L455-L502
UnionOfRAD/lithium
net/http/Router.php
Router._prepareParams
protected static function _prepareParams($url, $context, array $options) { if (is_string($url)) { if (strpos($url, '://') !== false) { return $url; } if (preg_match('%^((#|//)|(mailto|tel|sms|javascript):)%', $url)) { return $url; } if (is_string($url = static::_parseString($url, $context, $options))) { return static::_prefix($url, $context, $options); } } $isArray = ( isset($url[0]) && is_array($params = static::_parseString($url[0], $context, $options)) ); if ($isArray) { unset($url[0]); $url = $params + $url; } return static::_persist(static::_parseController($url), $context); }
php
protected static function _prepareParams($url, $context, array $options) { if (is_string($url)) { if (strpos($url, '://') !== false) { return $url; } if (preg_match('%^((#|//)|(mailto|tel|sms|javascript):)%', $url)) { return $url; } if (is_string($url = static::_parseString($url, $context, $options))) { return static::_prefix($url, $context, $options); } } $isArray = ( isset($url[0]) && is_array($params = static::_parseString($url[0], $context, $options)) ); if ($isArray) { unset($url[0]); $url = $params + $url; } return static::_persist(static::_parseController($url), $context); }
[ "protected", "static", "function", "_prepareParams", "(", "$", "url", ",", "$", "context", ",", "array", "$", "options", ")", "{", "if", "(", "is_string", "(", "$", "url", ")", ")", "{", "if", "(", "strpos", "(", "$", "url", ",", "'://'", ")", "!==...
Prepares URL parameters for matching. Detects and Passes through un-routed URL strings, leaving them untouched. Will not attempt to parse strings as shorthand parameters but instead interpret them as normal, non-routed URLs when they are prefixed with a known scheme. @param array|string $url An array of parameters, shorthand parameter string or URL string. @param \lithium\action\Request $context @param array $options @return array|string Depending on the type of $url either a string or an array.
[ "Prepares", "URL", "parameters", "for", "matching", ".", "Detects", "and", "Passes", "through", "un", "-", "routed", "URL", "strings", "leaving", "them", "untouched", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L546-L567
UnionOfRAD/lithium
net/http/Router.php
Router._prefix
protected static function _prefix($path, $context = null, array $options = []) { $defaults = ['scheme' => null, 'host' => null, 'absolute' => false]; $options += $defaults; return ($options['absolute']) ? "{$options['scheme']}{$options['host']}{$path}" : $path; }
php
protected static function _prefix($path, $context = null, array $options = []) { $defaults = ['scheme' => null, 'host' => null, 'absolute' => false]; $options += $defaults; return ($options['absolute']) ? "{$options['scheme']}{$options['host']}{$path}" : $path; }
[ "protected", "static", "function", "_prefix", "(", "$", "path", ",", "$", "context", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'scheme'", "=>", "null", ",", "'host'", "=>", "null", ",", "'absolute...
Returns the prefix (scheme + hostname) for a URL based on the passed `$options` and the `$context`. @param string $path The URL to be prefixed. @param object $context The request context. @param array $options Options for generating the proper prefix. Currently accepted values are: `'absolute' => true|false`, `'host' => string` and `'scheme' => string`. @return string The prefixed URL, depending on the passed options.
[ "Returns", "the", "prefix", "(", "scheme", "+", "hostname", ")", "for", "a", "URL", "based", "on", "the", "passed", "$options", "and", "the", "$context", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L579-L583
UnionOfRAD/lithium
net/http/Router.php
Router._persist
protected static function _persist($url, $context) { if (!$context || !isset($context->persist)) { return $url; } foreach ($context->persist as $key) { $url += [$key => $context->params[$key]]; if ($url[$key] === null) { unset($url[$key]); } } return $url; }
php
protected static function _persist($url, $context) { if (!$context || !isset($context->persist)) { return $url; } foreach ($context->persist as $key) { $url += [$key => $context->params[$key]]; if ($url[$key] === null) { unset($url[$key]); } } return $url; }
[ "protected", "static", "function", "_persist", "(", "$", "url", ",", "$", "context", ")", "{", "if", "(", "!", "$", "context", "||", "!", "isset", "(", "$", "context", "->", "persist", ")", ")", "{", "return", "$", "url", ";", "}", "foreach", "(", ...
Copies persistent parameters (parameters in the request which have been designated to persist) to the current URL, unless the parameter has been explicitly disabled from persisting by setting the value in the URL to `null`, or by assigning some other value. For example: ``` Router::connect('/{:controller}/{:action}/{:id:[0-9]+}', array(), array( 'persist' => array('controller', 'id') )); // URLs generated with $request will now have the 'controller' and 'id' // parameters copied to new URLs. $request = Router::process(new Request(array('url' => 'posts/view/1138'))); $params = array('action' => 'edit'); $url = Router::match($params, $request); // Returns: '/posts/edit/1138' ``` @see lithium\action\Request::$persist @param array $url The parameters that define the URL to be matched. @param \lithium\action\Request $context A request object, which contains a `$persist` property, which is an array of keys to be persisted in URLs between requests. @return array Returns the modified URL array.
[ "Copies", "persistent", "parameters", "(", "parameters", "in", "the", "request", "which", "have", "been", "designated", "to", "persist", ")", "to", "the", "current", "URL", "unless", "the", "parameter", "has", "been", "explicitly", "disabled", "from", "persistin...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L611-L623
UnionOfRAD/lithium
net/http/Router.php
Router.get
public static function get($route = null, $scope = null) { if ($route === null && $scope === null) { return static::$_configurations; } if ($scope === true) { $scope = static::$_scope; } if ($route === null && $scope !== null) { if (isset(static::$_configurations[$scope])) { return static::$_configurations[$scope]; } return []; } if (!isset(static::$_configurations[$scope][$route])) { return null; } return static::$_configurations[$scope][$route]; }
php
public static function get($route = null, $scope = null) { if ($route === null && $scope === null) { return static::$_configurations; } if ($scope === true) { $scope = static::$_scope; } if ($route === null && $scope !== null) { if (isset(static::$_configurations[$scope])) { return static::$_configurations[$scope]; } return []; } if (!isset(static::$_configurations[$scope][$route])) { return null; } return static::$_configurations[$scope][$route]; }
[ "public", "static", "function", "get", "(", "$", "route", "=", "null", ",", "$", "scope", "=", "null", ")", "{", "if", "(", "$", "route", "===", "null", "&&", "$", "scope", "===", "null", ")", "{", "return", "static", "::", "$", "_configurations", ...
Returns one or multiple connected routes. A specific route can be retrived by providing its index. All connected routes inside all scopes may be retrieved by providing `null` instead of the route index. To retrieve all routes for the current scope only, pass `true` for the `$scope` parameter. @param integer $route Index of the route. @param string|boolean $scope Name of the scope to get routes from. Uses default scope if `true`. @return object|array|null If $route is an integer, returns the route object at given index or if that fails returns `null`. If $route is `null` returns an array of routes or scopes with their respective routes depending on the value of $scope.
[ "Returns", "one", "or", "multiple", "connected", "routes", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L639-L659
UnionOfRAD/lithium
net/http/Router.php
Router._parseString
protected static function _parseString($path, $context, array $options = []) { if (!preg_match('/^[A-Za-z0-9._\\\\]+::[A-Za-z0-9_]+$/', $path)) { $base = rtrim($options['base'], '/'); if ((!$path || $path[0] != '/') && $context && isset($context->controller)) { $formatters = static::formatters(); $base .= '/' . $formatters['controller']($context->controller); } $path = trim($path, '/'); return "{$base}/{$path}"; } list($controller, $action) = explode('::', $path, 2); return compact('controller', 'action'); }
php
protected static function _parseString($path, $context, array $options = []) { if (!preg_match('/^[A-Za-z0-9._\\\\]+::[A-Za-z0-9_]+$/', $path)) { $base = rtrim($options['base'], '/'); if ((!$path || $path[0] != '/') && $context && isset($context->controller)) { $formatters = static::formatters(); $base .= '/' . $formatters['controller']($context->controller); } $path = trim($path, '/'); return "{$base}/{$path}"; } list($controller, $action) = explode('::', $path, 2); return compact('controller', 'action'); }
[ "protected", "static", "function", "_parseString", "(", "$", "path", ",", "$", "context", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "preg_match", "(", "'/^[A-Za-z0-9._\\\\\\\\]+::[A-Za-z0-9_]+$/'", ",", "$", "path", ")", ")", "...
Helper function for taking a path string and parsing it into a controller and action array. @param string $path Path string to parse i.e. `li3_bot.Logs::index` or `Posts::index`. @param boolean $context @return array
[ "Helper", "function", "for", "taking", "a", "path", "string", "and", "parsing", "it", "into", "a", "controller", "and", "action", "array", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L679-L691
UnionOfRAD/lithium
net/http/Router.php
Router.attach
public static function attach($name, $config = null, array $vars = []) { if ($name === false) { return null; } if (!isset(static::$_scopes)) { static::_initScopes(); } if ($config === null) { if ($vars && ($config = static::$_scopes->get($name))) { $config['values'] = $vars; static::$_scopes->set($name, $config); } return; } if (is_array($config) || $config === false) { static::$_scopes->set($name, $config); } }
php
public static function attach($name, $config = null, array $vars = []) { if ($name === false) { return null; } if (!isset(static::$_scopes)) { static::_initScopes(); } if ($config === null) { if ($vars && ($config = static::$_scopes->get($name))) { $config['values'] = $vars; static::$_scopes->set($name, $config); } return; } if (is_array($config) || $config === false) { static::$_scopes->set($name, $config); } }
[ "public", "static", "function", "attach", "(", "$", "name", ",", "$", "config", "=", "null", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "if", "(", "$", "name", "===", "false", ")", "{", "return", "null", ";", "}", "if", "(", "!", "isse...
Defines a scope and attaches it to a mount point. Example 1: ``` Router::attach('app', [ 'absolute' => true, 'host' => 'localhost', 'scheme' => 'http://', 'prefix' => 'web/tests' ]); ``` Example 2: ``` Router::attach('app', [ 'absolute' => true, 'host' => '{:subdomain:[a-z]+}.{:hostname}.{:tld}', 'scheme' => '{:scheme:https://}', 'prefix' => '' ]); ``` Attach the variables to populate for the app scope. ``` Router::attach('app', null, [ 'subdomain' => 'www', 'hostname' => 'li3', 'tld' => 'me' ]); ``` By default all routes attached to an `'app'` scope are attached to a library of the same name (i.e. the `'app'` library in this case). So you don't need to deal with an extra library in your routes definition when you are using scopes. Moreover you can override the attached library name with: ``` Router::attach('app', [ 'library' => 'custom_library_name' ]); ``` @see lithium\net\http\Router::scope() @see lithium\net\http\Router::attached() @param string Name of the scope. @param mixed Settings of the mount point or `null` for setting only variables to populate. @param array Variables to populate for the scope.
[ "Defines", "a", "scope", "and", "attaches", "it", "to", "a", "mount", "point", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L776-L796
UnionOfRAD/lithium
net/http/Router.php
Router.attached
public static function attached($name = null, array $vars = []) { if ($name === false) { return null; } if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === null) { return static::$_scopes->get(); } elseif (!$config = static::$_scopes->get($name)) { static::$_scopes->set($name, []); $config = static::$_scopes->get($name); } $vars += $config['values']; $match = '@\{:([^:}]+):?((?:[^{]+(?:\{[0-9,]+\})?)*?)\}@S'; $fields = ['scheme', 'host']; foreach ($fields as $field) { if (preg_match_all($match, $config[$field], $m)) { $tokens = $m[0]; $names = $m[1]; $regexs = $m[2]; foreach ($names as $i => $name) { if (isset($vars[$name])) { if (($regex = $regexs[$i]) && !preg_match("@^{$regex}\$@", $vars[$name])) { continue; } $config[$field] = str_replace($tokens[$i], $vars[$name], $config[$field]); } } } } return $config; }
php
public static function attached($name = null, array $vars = []) { if ($name === false) { return null; } if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === null) { return static::$_scopes->get(); } elseif (!$config = static::$_scopes->get($name)) { static::$_scopes->set($name, []); $config = static::$_scopes->get($name); } $vars += $config['values']; $match = '@\{:([^:}]+):?((?:[^{]+(?:\{[0-9,]+\})?)*?)\}@S'; $fields = ['scheme', 'host']; foreach ($fields as $field) { if (preg_match_all($match, $config[$field], $m)) { $tokens = $m[0]; $names = $m[1]; $regexs = $m[2]; foreach ($names as $i => $name) { if (isset($vars[$name])) { if (($regex = $regexs[$i]) && !preg_match("@^{$regex}\$@", $vars[$name])) { continue; } $config[$field] = str_replace($tokens[$i], $vars[$name], $config[$field]); } } } } return $config; }
[ "public", "static", "function", "attached", "(", "$", "name", "=", "null", ",", "array", "$", "vars", "=", "[", "]", ")", "{", "if", "(", "$", "name", "===", "false", ")", "{", "return", "null", ";", "}", "if", "(", "!", "isset", "(", "static", ...
Returns an attached mount point configuration. ``` Router::attach('app', [ 'absolute' => true, 'host' => '{:subdomain:[a-z]+}.{:hostname}.{:tld}', 'scheme' => '{:scheme:https://}', 'prefix' => '' ]); $result = Router::attached('app', [ 'subdomain' => 'app', 'hostname' => 'blog', 'tld' => 'co.uk' ]); // $result is: // [ // 'absolute' => true, // 'host' => 'blog.mysite.co.uk', // 'scheme' => 'http://', // 'prefix' => '' // ]; ``` @param string Name of the scope. @param array Optionnal variables which override the default setted variables with `lithium\net\http\Router::attach()`for population step. @return mixed The settings array of the scope or an array of settings array if `$name === null`.
[ "Returns", "an", "attached", "mount", "point", "configuration", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L830-L864
UnionOfRAD/lithium
net/http/Router.php
Router._initScopes
protected static function _initScopes() { static::$_scopes = static::_instance('configuration'); static::$_scopes->initConfig = function($name, $config) { $defaults = [ 'absolute' => false, 'host' => null, 'scheme' => null, 'base' => null, 'prefix' => '', 'pattern' => '', 'values' => [], 'library' => $name ]; $config += $defaults; if (!$config['pattern']) { $config = static::_compileScope($config); } $config['base'] = $config['base'] ? trim($config['base'], '/') : $config['base']; return $config; }; }
php
protected static function _initScopes() { static::$_scopes = static::_instance('configuration'); static::$_scopes->initConfig = function($name, $config) { $defaults = [ 'absolute' => false, 'host' => null, 'scheme' => null, 'base' => null, 'prefix' => '', 'pattern' => '', 'values' => [], 'library' => $name ]; $config += $defaults; if (!$config['pattern']) { $config = static::_compileScope($config); } $config['base'] = $config['base'] ? trim($config['base'], '/') : $config['base']; return $config; }; }
[ "protected", "static", "function", "_initScopes", "(", ")", "{", "static", "::", "$", "_scopes", "=", "static", "::", "_instance", "(", "'configuration'", ")", ";", "static", "::", "$", "_scopes", "->", "initConfig", "=", "function", "(", "$", "name", ",",...
Initialize `static::$_scopes` with a `lithium\core\Configuration` instance.
[ "Initialize", "static", "::", "$_scopes", "with", "a", "lithium", "\\", "core", "\\", "Configuration", "instance", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L869-L892
UnionOfRAD/lithium
net/http/Router.php
Router._compileScope
protected static function _compileScope(array $config) { $defaults = [ 'absolute' => false, 'host' => null, 'scheme' => null, 'base' => null, 'prefix' => '', 'pattern' => '', 'params' => [] ]; $config += $defaults; $config['prefix'] = trim($config['prefix'], '/'); $prefix = '/' . ($config['prefix'] ? $config['prefix'] . '/' : ''); if (!$config['absolute']) { $config['pattern'] = "@^{$prefix}@"; } else { $fields = ['scheme', 'host']; foreach ($fields as $field) { $dots = '/(?!\{[^\}]*)\.(?![^\{]*\})/'; $pattern[$field] = preg_replace($dots, '\.', $config[$field]); $match = '@\{:([^:}]+):?((?:[^{]+(?:\{[0-9,]+\})?)*?)\}@S'; if (preg_match_all($match, $pattern[$field], $m)) { $tokens = $m[0]; $names = $m[1]; $regexs = $m[2]; foreach ($names as $i => $name) { $regex = $regexs[$i] ? : '[^/]+?'; $pattern[$field] = str_replace( $tokens[$i], "(?P<{$name}>{$regex})", $pattern[$field] ); $config['params'][] = $name; } } } $pattern['host'] = $pattern['host'] ? : 'localhost'; $pattern['scheme'] = $pattern['scheme'] . ($pattern['scheme'] ? '://' : '(.*?)//'); $config['pattern'] = "@^{$pattern['scheme']}{$pattern['host']}{$prefix}@"; } return $config; }
php
protected static function _compileScope(array $config) { $defaults = [ 'absolute' => false, 'host' => null, 'scheme' => null, 'base' => null, 'prefix' => '', 'pattern' => '', 'params' => [] ]; $config += $defaults; $config['prefix'] = trim($config['prefix'], '/'); $prefix = '/' . ($config['prefix'] ? $config['prefix'] . '/' : ''); if (!$config['absolute']) { $config['pattern'] = "@^{$prefix}@"; } else { $fields = ['scheme', 'host']; foreach ($fields as $field) { $dots = '/(?!\{[^\}]*)\.(?![^\{]*\})/'; $pattern[$field] = preg_replace($dots, '\.', $config[$field]); $match = '@\{:([^:}]+):?((?:[^{]+(?:\{[0-9,]+\})?)*?)\}@S'; if (preg_match_all($match, $pattern[$field], $m)) { $tokens = $m[0]; $names = $m[1]; $regexs = $m[2]; foreach ($names as $i => $name) { $regex = $regexs[$i] ? : '[^/]+?'; $pattern[$field] = str_replace( $tokens[$i], "(?P<{$name}>{$regex})", $pattern[$field] ); $config['params'][] = $name; } } } $pattern['host'] = $pattern['host'] ? : 'localhost'; $pattern['scheme'] = $pattern['scheme'] . ($pattern['scheme'] ? '://' : '(.*?)//'); $config['pattern'] = "@^{$pattern['scheme']}{$pattern['host']}{$prefix}@"; } return $config; }
[ "protected", "static", "function", "_compileScope", "(", "array", "$", "config", ")", "{", "$", "defaults", "=", "[", "'absolute'", "=>", "false", ",", "'host'", "=>", "null", ",", "'scheme'", "=>", "null", ",", "'base'", "=>", "null", ",", "'prefix'", "...
Compiles the scope into regular expression patterns for matching against request URLs @param array $config Array of settings. @return array Returns the complied settings.
[ "Compiles", "the", "scope", "into", "regular", "expression", "patterns", "for", "matching", "against", "request", "URLs" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L900-L944
UnionOfRAD/lithium
net/http/Router.php
Router._parseScope
protected static function _parseScope($name, $request) { $url = trim($request->url, '/'); $url = $url ? '/' . $url . '/' : '/'; if (!$config = static::attached($name)) { return $url; } $scheme = $request->scheme . ($request->scheme ? '://' : '//'); $host = $request->host; if ($config['absolute']) { preg_match($config['pattern'], $scheme . $host . $url, $match); } else { preg_match($config['pattern'], $url, $match); } if ($match) { $result = array_intersect_key($match, array_flip($config['params'])); $request->params = []; if (isset($config['library'])) { $request->params['library'] = $config['library']; } $request->params += $result; if ($config['prefix']) { $url = preg_replace('@^/' . trim($config['prefix'], '/') . '@', '', $url); } return $url; } return false; }
php
protected static function _parseScope($name, $request) { $url = trim($request->url, '/'); $url = $url ? '/' . $url . '/' : '/'; if (!$config = static::attached($name)) { return $url; } $scheme = $request->scheme . ($request->scheme ? '://' : '//'); $host = $request->host; if ($config['absolute']) { preg_match($config['pattern'], $scheme . $host . $url, $match); } else { preg_match($config['pattern'], $url, $match); } if ($match) { $result = array_intersect_key($match, array_flip($config['params'])); $request->params = []; if (isset($config['library'])) { $request->params['library'] = $config['library']; } $request->params += $result; if ($config['prefix']) { $url = preg_replace('@^/' . trim($config['prefix'], '/') . '@', '', $url); } return $url; } return false; }
[ "protected", "static", "function", "_parseScope", "(", "$", "name", ",", "$", "request", ")", "{", "$", "url", "=", "trim", "(", "$", "request", "->", "url", ",", "'/'", ")", ";", "$", "url", "=", "$", "url", "?", "'/'", ".", "$", "url", ".", "...
Return the unscoped url to route. @param string $name Scope name. @param string $request A `lithium\action\Request` instance . @return mixed The url to route, or `false` if the request doesn't match the scope.
[ "Return", "the", "unscoped", "url", "to", "route", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Router.php#L953-L983
UnionOfRAD/lithium
storage/cache/adapter/File.php
File.write
public function write(array $keys, $expiry = null) { $expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry']; if (!$expiry || $expiry === Cache::PERSIST) { $expires = 0; } elseif (is_int($expiry)) { $expires = $expiry + time(); } else { $expires = strtotime($expiry); } if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys, '_'); } foreach ($keys as $key => $value) { if (!$this->_write($key, $value, $expires)) { return false; } } return true; }
php
public function write(array $keys, $expiry = null) { $expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry']; if (!$expiry || $expiry === Cache::PERSIST) { $expires = 0; } elseif (is_int($expiry)) { $expires = $expiry + time(); } else { $expires = strtotime($expiry); } if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys, '_'); } foreach ($keys as $key => $value) { if (!$this->_write($key, $value, $expires)) { return false; } } return true; }
[ "public", "function", "write", "(", "array", "$", "keys", ",", "$", "expiry", "=", "null", ")", "{", "$", "expiry", "=", "$", "expiry", "||", "$", "expiry", "===", "Cache", "::", "PERSIST", "?", "$", "expiry", ":", "$", "this", "->", "_config", "["...
Write values to the cache. All items to be cached will receive an expiration time of `$expiry`. @param array $keys Key/value pairs with keys to uniquely identify the to-be-cached item. @param string|integer $expiry A `strtotime()` compatible cache time or TTL in seconds. To persist an item use `\lithium\storage\Cache::PERSIST`. @return boolean `true` on successful write, `false` otherwise.
[ "Write", "values", "to", "the", "cache", ".", "All", "items", "to", "be", "cached", "will", "receive", "an", "expiration", "time", "of", "$expiry", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L95-L114
UnionOfRAD/lithium
storage/cache/adapter/File.php
File.read
public function read(array $keys) { if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys, '_'); } $results = []; foreach ($keys as $key) { if (!$item = $this->_read($key, $this->_config['streams'])) { continue; } if ($item['expiry'] < time() && $item['expiry'] != 0) { $this->_delete($key); continue; } $results[$key] = $item['value']; } if ($this->_config['scope']) { $results = $this->_removeScopePrefix($this->_config['scope'], $results, '_'); } return $results; }
php
public function read(array $keys) { if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys, '_'); } $results = []; foreach ($keys as $key) { if (!$item = $this->_read($key, $this->_config['streams'])) { continue; } if ($item['expiry'] < time() && $item['expiry'] != 0) { $this->_delete($key); continue; } $results[$key] = $item['value']; } if ($this->_config['scope']) { $results = $this->_removeScopePrefix($this->_config['scope'], $results, '_'); } return $results; }
[ "public", "function", "read", "(", "array", "$", "keys", ")", "{", "if", "(", "$", "this", "->", "_config", "[", "'scope'", "]", ")", "{", "$", "keys", "=", "$", "this", "->", "_addScopePrefix", "(", "$", "this", "->", "_config", "[", "'scope'", "]...
Read values from the cache. Will attempt to return an array of data containing key/value pairs of the requested data. Invalidates and cleans up expired items on-the-fly when found. @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/File.php#L127-L147
UnionOfRAD/lithium
storage/cache/adapter/File.php
File.decrement
public function decrement($key, $offset = 1) { if ($this->_config['scope']) { $key = "{$this->_config['scope']}_{$key}"; } if (!$result = $this->_read($key)) { return false; } if (!$this->_write($key, $result['value'] -= $offset, $result['expiry'])) { return false; } return $result['value']; }
php
public function decrement($key, $offset = 1) { if ($this->_config['scope']) { $key = "{$this->_config['scope']}_{$key}"; } if (!$result = $this->_read($key)) { return false; } if (!$this->_write($key, $result['value'] -= $offset, $result['expiry'])) { return false; } return $result['value']; }
[ "public", "function", "decrement", "(", "$", "key", ",", "$", "offset", "=", "1", ")", "{", "if", "(", "$", "this", "->", "_config", "[", "'scope'", "]", ")", "{", "$", "key", "=", "\"{$this->_config['scope']}_{$key}\"", ";", "}", "if", "(", "!", "$"...
Performs a decrement operation on a 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", "a", "specified", "numeric", "cache", "item", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L174-L185
UnionOfRAD/lithium
storage/cache/adapter/File.php
File.clear
public function clear() { $result = true; foreach (new DirectoryIterator($this->_config['path']) as $file) { if (!$file->isFile()) { continue; } $result = $this->_delete($file->getBasename()) && $result; } return $result; }
php
public function clear() { $result = true; foreach (new DirectoryIterator($this->_config['path']) as $file) { if (!$file->isFile()) { continue; } $result = $this->_delete($file->getBasename()) && $result; } return $result; }
[ "public", "function", "clear", "(", ")", "{", "$", "result", "=", "true", ";", "foreach", "(", "new", "DirectoryIterator", "(", "$", "this", "->", "_config", "[", "'path'", "]", ")", "as", "$", "file", ")", "{", "if", "(", "!", "$", "file", "->", ...
Clears entire cache by flushing it. Please note that a scope - in case one is set - is *not* honored. The operation will continue to remove keys even if removing one single key fails, clearing thoroughly as possible. @return boolean `true` on successful clearing, `false` if failed partially or entirely.
[ "Clears", "entire", "cache", "by", "flushing", "it", ".", "Please", "note", "that", "a", "scope", "-", "in", "case", "one", "is", "set", "-", "is", "*", "not", "*", "honored", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L216-L225
UnionOfRAD/lithium
storage/cache/adapter/File.php
File.clean
public function clean() { $result = true; foreach (new DirectoryIterator($this->_config['path']) as $file) { if (!$file->isFile()) { continue; } if (!$item = $this->_read($key = $file->getBasename())) { continue; } if ($item['expiry'] > time()) { continue; } $result = $this->_delete($key) && $result; } return $result; }
php
public function clean() { $result = true; foreach (new DirectoryIterator($this->_config['path']) as $file) { if (!$file->isFile()) { continue; } if (!$item = $this->_read($key = $file->getBasename())) { continue; } if ($item['expiry'] > time()) { continue; } $result = $this->_delete($key) && $result; } return $result; }
[ "public", "function", "clean", "(", ")", "{", "$", "result", "=", "true", ";", "foreach", "(", "new", "DirectoryIterator", "(", "$", "this", "->", "_config", "[", "'path'", "]", ")", "as", "$", "file", ")", "{", "if", "(", "!", "$", "file", "->", ...
Cleans entire cache running garbage collection on it. Please note that a scope - in case one is set - is *not* honored. The operation will continue to remove keys even if removing one single key fails, cleaning thoroughly as possible. @return boolean `true` on successful cleaning, `false` if failed partially or entirely.
[ "Cleans", "entire", "cache", "running", "garbage", "collection", "on", "it", ".", "Please", "note", "that", "a", "scope", "-", "in", "case", "one", "is", "set", "-", "is", "*", "not", "*", "honored", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L236-L251
UnionOfRAD/lithium
storage/cache/adapter/File.php
File._write
protected function _write($key, $value, $expires) { $path = "{$this->_config['path']}/{$key}"; if (!$stream = fopen($path, 'wb')) { return false; } fwrite($stream, "{:expiry:{$expires}}\n"); if (is_resource($value)) { stream_copy_to_stream($value, $stream); } else { fwrite($stream, $value); } return fclose($stream); }
php
protected function _write($key, $value, $expires) { $path = "{$this->_config['path']}/{$key}"; if (!$stream = fopen($path, 'wb')) { return false; } fwrite($stream, "{:expiry:{$expires}}\n"); if (is_resource($value)) { stream_copy_to_stream($value, $stream); } else { fwrite($stream, $value); } return fclose($stream); }
[ "protected", "function", "_write", "(", "$", "key", ",", "$", "value", ",", "$", "expires", ")", "{", "$", "path", "=", "\"{$this->_config['path']}/{$key}\"", ";", "if", "(", "!", "$", "stream", "=", "fopen", "(", "$", "path", ",", "'wb'", ")", ")", ...
Compiles value to format and writes file. @see lithium\storage\cache\adapter\File::write() @param string $key Key to uniquely identify the cached item. @param mixed $value Value or resource with value to store under given key. @param integer $expires UNIX timestamp after which the item is invalid. @return boolean `true` on success, `false` otherwise.
[ "Compiles", "value", "to", "format", "and", "writes", "file", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L262-L276
UnionOfRAD/lithium
storage/cache/adapter/File.php
File._read
protected function _read($key, $streams = false) { $path = "{$this->_config['path']}/{$key}"; if (!is_file($path) || !is_readable($path)) { return false; } if (!$stream = fopen($path, 'rb')) { return false; } $header = stream_get_line($stream, static::MAX_HEADER_LENGTH, "\n"); if (!preg_match('/^\{\:expiry\:(\d+)\}/', $header, $matches)) { return false; } if ($streams) { $value = fopen('php://temp', 'wb'); stream_copy_to_stream($stream, $value); rewind($value); } else { $value = stream_get_contents($stream); } fclose($stream); return ['expiry' => $matches[1], 'value' => $value]; }
php
protected function _read($key, $streams = false) { $path = "{$this->_config['path']}/{$key}"; if (!is_file($path) || !is_readable($path)) { return false; } if (!$stream = fopen($path, 'rb')) { return false; } $header = stream_get_line($stream, static::MAX_HEADER_LENGTH, "\n"); if (!preg_match('/^\{\:expiry\:(\d+)\}/', $header, $matches)) { return false; } if ($streams) { $value = fopen('php://temp', 'wb'); stream_copy_to_stream($stream, $value); rewind($value); } else { $value = stream_get_contents($stream); } fclose($stream); return ['expiry' => $matches[1], 'value' => $value]; }
[ "protected", "function", "_read", "(", "$", "key", ",", "$", "streams", "=", "false", ")", "{", "$", "path", "=", "\"{$this->_config['path']}/{$key}\"", ";", "if", "(", "!", "is_file", "(", "$", "path", ")", "||", "!", "is_readable", "(", "$", "path", ...
Reads from file, parses its format and returns its expiry and value. @see lithium\storage\cache\adapter\File::read() @param string $key Key to uniquely identify the cached item. @param boolean $streams When `true` will return stream handle instead of value. @return array|boolean Array with `expiry` and `value` or `false` otherwise.
[ "Reads", "from", "file", "parses", "its", "format", "and", "returns", "its", "expiry", "and", "value", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/File.php#L286-L311
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.respondsTo
public function respondsTo($method, $internal = false) { $parentRespondsTo = parent::respondsTo($method, $internal); return $parentRespondsTo || is_callable([$this->connection, $method]); }
php
public function respondsTo($method, $internal = false) { $parentRespondsTo = parent::respondsTo($method, $internal); return $parentRespondsTo || is_callable([$this->connection, $method]); }
[ "public", "function", "respondsTo", "(", "$", "method", ",", "$", "internal", "=", "false", ")", "{", "$", "parentRespondsTo", "=", "parent", "::", "respondsTo", "(", "$", "method", ",", "$", "internal", ")", ";", "return", "$", "parentRespondsTo", "||", ...
Determines if a given method can be called. @param string $method Name of the method. @param boolean $internal Provide `true` to perform check from inside the class/object. When `false` checks also for public visibility; defaults to `false`. @return boolean Returns `true` if the method can be called, `false` otherwise.
[ "Determines", "if", "a", "given", "method", "can", "be", "called", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L134-L137
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.describe
public function describe($entity, $schema = [], array $meta = []) { $database = $this->_config['database']; if (!$this->_db) { $result = $this->get($database); if (isset($result->db_name)) { $this->_db = true; } if (!$this->_db) { if (isset($result->error)) { if ($result->error === 'not_found') { $result = $this->put($database); } } if (isset($result->ok) || isset($result->db_name)) { $this->_db = true; } } } if (!$this->_db) { throw new ConfigException("Database `{$entity}` is not available."); } return $this->_instance('schema', [['fields' => $schema]]); }
php
public function describe($entity, $schema = [], array $meta = []) { $database = $this->_config['database']; if (!$this->_db) { $result = $this->get($database); if (isset($result->db_name)) { $this->_db = true; } if (!$this->_db) { if (isset($result->error)) { if ($result->error === 'not_found') { $result = $this->put($database); } } if (isset($result->ok) || isset($result->db_name)) { $this->_db = true; } } } if (!$this->_db) { throw new ConfigException("Database `{$entity}` is not available."); } return $this->_instance('schema', [['fields' => $schema]]); }
[ "public", "function", "describe", "(", "$", "entity", ",", "$", "schema", "=", "[", "]", ",", "array", "$", "meta", "=", "[", "]", ")", "{", "$", "database", "=", "$", "this", "->", "_config", "[", "'database'", "]", ";", "if", "(", "!", "$", "...
Describe database, create if it does not exist. @throws ConfigException @param string $entity @param array $schema Any schema data pre-defined by the model. @param array $meta @return lithium\data\Schema
[ "Describe", "database", "create", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L156-L180
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.create
public function create($query, array $options = []) { $defaults = ['model' => $query->model()]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $request = ['type' => 'json']; $query = $params['query']; $options = $params['options']; $data = $query->data(); $data += ['type' => $options['model']::meta('source')]; if (isset($data['id'])) { return $this->update($query, $options); } $retry = false; do { $result = $this->connection->post($this->_config['database'], $data, $request); $result = is_string($result) ? json_decode($result, true) : $result; $retry = $retry ? !$retry : $this->_autoBuild($result); } while ($retry); if (isset($result['_id']) || (isset($result['ok']) && $result['ok'] === true)) { $result = $this->_format($result, $options); $query->entity()->sync($result['id'], $result); return true; } return false; }); }
php
public function create($query, array $options = []) { $defaults = ['model' => $query->model()]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $request = ['type' => 'json']; $query = $params['query']; $options = $params['options']; $data = $query->data(); $data += ['type' => $options['model']::meta('source')]; if (isset($data['id'])) { return $this->update($query, $options); } $retry = false; do { $result = $this->connection->post($this->_config['database'], $data, $request); $result = is_string($result) ? json_decode($result, true) : $result; $retry = $retry ? !$retry : $this->_autoBuild($result); } while ($retry); if (isset($result['_id']) || (isset($result['ok']) && $result['ok'] === true)) { $result = $this->_format($result, $options); $query->entity()->sync($result['id'], $result); return true; } return false; }); }
[ "public", "function", "create", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'model'", "=>", "$", "query", "->", "model", "(", ")", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$"...
Create new document. @param string $query @param array $options @return boolean @filter
[ "Create", "new", "document", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L202-L233
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.read
public function read($query, array $options = []) { $defaults = ['return' => 'resource', 'model' => $query->model()]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $params = $query->export($this); list($_path, $conditions) = (array) $params['conditions']; $model = $query->model(); if (empty($_path)) { $_path = '_all_docs'; $conditions['include_docs'] = 'true'; } $path = "{$this->_config['database']}/{$_path}"; $args = (array) $conditions + (array) $params['limit'] + (array) $params['order']; $result = $this->connection->get($path, $args); $result = is_string($result) ? json_decode($result, true) : $result; $data = $stats = []; if (isset($result['_id'])) { $data = [$result]; } elseif (isset($result['rows'])) { $data = $result['rows']; unset($result['rows']); $stats = $result; } $stats += ['total_rows' => null, 'offset' => null]; $opts = compact('stats') + [ 'class' => 'set', 'exists' => true, 'defaults' => false ]; return $this->item($model, $data, $opts); }); }
php
public function read($query, array $options = []) { $defaults = ['return' => 'resource', 'model' => $query->model()]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $params = $query->export($this); list($_path, $conditions) = (array) $params['conditions']; $model = $query->model(); if (empty($_path)) { $_path = '_all_docs'; $conditions['include_docs'] = 'true'; } $path = "{$this->_config['database']}/{$_path}"; $args = (array) $conditions + (array) $params['limit'] + (array) $params['order']; $result = $this->connection->get($path, $args); $result = is_string($result) ? json_decode($result, true) : $result; $data = $stats = []; if (isset($result['_id'])) { $data = [$result]; } elseif (isset($result['rows'])) { $data = $result['rows']; unset($result['rows']); $stats = $result; } $stats += ['total_rows' => null, 'offset' => null]; $opts = compact('stats') + [ 'class' => 'set', 'exists' => true, 'defaults' => false ]; return $this->item($model, $data, $opts); }); }
[ "public", "function", "read", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'return'", "=>", "'resource'", ",", "'model'", "=>", "$", "query", "->", "model", "(", ")", "]", ";", "$", "options"...
Read from document. @param string $query @param array $options @return object @filter
[ "Read", "from", "document", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L243-L281
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.update
public function update($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $options = $params['options']; $params = $query->export($this); list($_path, $conditions) = (array) $params['conditions']; $data = $query->data(); foreach (['id', 'rev'] as $key) { $data["_{$key}"] = isset($data[$key]) ? (string) $data[$key] : null; unset($data[$key]); } $data = (array) $conditions + array_filter((array) $data); $retry = false; do { $result = $this->connection->put( "{$this->_config['database']}/{$_path}", $data, ['type' => 'json'] ); $result = is_string($result) ? json_decode($result, true) : $result; $retry = $retry ? !$retry : $this->_autoBuild($result); } while ($retry); if (isset($result['_id']) || (isset($result['ok']) && $result['ok'] === true)) { $result = $this->_format($result, $options); $query->entity()->sync($result['id'], ['rev' => $result['rev']]); return true; } if (isset($result['error'])) { $query->entity()->errors([$result['error']]); } return false; }); }
php
public function update($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $options = $params['options']; $params = $query->export($this); list($_path, $conditions) = (array) $params['conditions']; $data = $query->data(); foreach (['id', 'rev'] as $key) { $data["_{$key}"] = isset($data[$key]) ? (string) $data[$key] : null; unset($data[$key]); } $data = (array) $conditions + array_filter((array) $data); $retry = false; do { $result = $this->connection->put( "{$this->_config['database']}/{$_path}", $data, ['type' => 'json'] ); $result = is_string($result) ? json_decode($result, true) : $result; $retry = $retry ? !$retry : $this->_autoBuild($result); } while ($retry); if (isset($result['_id']) || (isset($result['ok']) && $result['ok'] === true)) { $result = $this->_format($result, $options); $query->entity()->sync($result['id'], ['rev' => $result['rev']]); return true; } if (isset($result['error'])) { $query->entity()->errors([$result['error']]); } return false; }); }
[ "public", "function", "update", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'query'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ",", "__FUNCTION_...
Update document. @param string $query @param array $options @return boolean @filter
[ "Update", "document", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L291-L329
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb._autoBuild
protected function _autoBuild($result) { $hasError = ( isset($result['error']) && isset($result['reason']) && $result['reason'] === "no_db_file" ); if ($hasError) { $this->connection->put($this->_config['database']); return true; } return false; }
php
protected function _autoBuild($result) { $hasError = ( isset($result['error']) && isset($result['reason']) && $result['reason'] === "no_db_file" ); if ($hasError) { $this->connection->put($this->_config['database']); return true; } return false; }
[ "protected", "function", "_autoBuild", "(", "$", "result", ")", "{", "$", "hasError", "=", "(", "isset", "(", "$", "result", "[", "'error'", "]", ")", "&&", "isset", "(", "$", "result", "[", "'reason'", "]", ")", "&&", "$", "result", "[", "'reason'",...
Helper used for auto building a CouchDB database. @param string $result A query result.
[ "Helper", "used", "for", "auto", "building", "a", "CouchDB", "database", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L336-L347
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.delete
public function delete($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $params = $query->export($this); list($_path, $conditions) = $params['conditions']; $data = $query->data(); if (!empty($data['rev'])) { $conditions['rev'] = $data['rev']; } $result = $this->connection->delete( "{$this->_config['database']}/{$_path}", $conditions ); $result = json_decode($result); $result = (isset($result->ok) && $result->ok === true); if ($query->entity()) { $query->entity()->sync(null, [], ['dematerialize' => true]); } return $result; }); }
php
public function delete($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $params = $query->export($this); list($_path, $conditions) = $params['conditions']; $data = $query->data(); if (!empty($data['rev'])) { $conditions['rev'] = $data['rev']; } $result = $this->connection->delete( "{$this->_config['database']}/{$_path}", $conditions ); $result = json_decode($result); $result = (isset($result->ok) && $result->ok === true); if ($query->entity()) { $query->entity()->sync(null, [], ['dematerialize' => true]); } return $result; }); }
[ "public", "function", "delete", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'query'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ",", "__FUNCTION_...
Delete document. @param string $query @param array $options @return boolean @filter
[ "Delete", "document", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L357-L381
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.calculation
public function calculation($type, $query, array $options = []) { switch ($type) { case 'count': return (integer) $this->read($query, $options)->stats('total_rows'); default: return null; } }
php
public function calculation($type, $query, array $options = []) { switch ($type) { case 'count': return (integer) $this->read($query, $options)->stats('total_rows'); default: return null; } }
[ "public", "function", "calculation", "(", "$", "type", ",", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'count'", ":", "return", "(", "integer", ")", "$", "this", "->", "read",...
Executes calculation-related queries, such as those required for `count`. @param string $type Only accepts `count`. @param mixed $query The query to be executed. @param array $options Optional arguments for the `read()` query that will be executed to obtain the calculation result. @return integer Result of the calculation.
[ "Executes", "calculation", "-", "related", "queries", "such", "as", "those", "required", "for", "count", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L392-L399
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.item
public function item($model, array $data = [], array $options = []) { $defaults = ['class' => 'entity']; $options += $defaults; if ($options['class'] === 'entity') { return $model::create($this->_format($data), $options); } foreach ($data as $key => $value) { if (isset($value['doc'])) { $value = $value['doc']; } if (isset($value['value'])) { $value = $value['value']; } $data[$key] = $this->_format($value); } return $model::create($data, $options); }
php
public function item($model, array $data = [], array $options = []) { $defaults = ['class' => 'entity']; $options += $defaults; if ($options['class'] === 'entity') { return $model::create($this->_format($data), $options); } foreach ($data as $key => $value) { if (isset($value['doc'])) { $value = $value['doc']; } if (isset($value['value'])) { $value = $value['value']; } $data[$key] = $this->_format($value); } return $model::create($data, $options); }
[ "public", "function", "item", "(", "$", "model", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'class'", "=>", "'entity'", "]", ";", "$", "options", "+=", "$", "defaul...
Returns a newly-created `Document` object, bound to a model and populated with default data and options. @param string $model A fully-namespaced class name representing the model class to which the `Document` object will be bound. @param array $data The default data with which the new `Document` should be populated. @param array $options Any additional options to pass to the `Document`'s constructor @return object Returns a new, un-saved `Document` object bound to the model class specified in `$model`.
[ "Returns", "a", "newly", "-", "created", "Document", "object", "bound", "to", "a", "model", "and", "populated", "with", "default", "data", "and", "options", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L412-L430
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb.conditions
public function conditions($conditions, $context) { $path = null; if (isset($conditions['design'])) { $paths = ['design', 'view']; foreach ($paths as $element) { if (isset($conditions[$element])) { $path .= "_{$element}/{$conditions[$element]}/"; unset($conditions[$element]); } } } if (isset($conditions['id'])) { $path = "{$conditions['id']}"; unset($conditions['id']); } if (isset($conditions['path'])) { $path = "{$conditions['path']}"; unset($conditions['path']); } return [$path, $conditions]; }
php
public function conditions($conditions, $context) { $path = null; if (isset($conditions['design'])) { $paths = ['design', 'view']; foreach ($paths as $element) { if (isset($conditions[$element])) { $path .= "_{$element}/{$conditions[$element]}/"; unset($conditions[$element]); } } } if (isset($conditions['id'])) { $path = "{$conditions['id']}"; unset($conditions['id']); } if (isset($conditions['path'])) { $path = "{$conditions['path']}"; unset($conditions['path']); } return [$path, $conditions]; }
[ "public", "function", "conditions", "(", "$", "conditions", ",", "$", "context", ")", "{", "$", "path", "=", "null", ";", "if", "(", "isset", "(", "$", "conditions", "[", "'design'", "]", ")", ")", "{", "$", "paths", "=", "[", "'design'", ",", "'vi...
Handle conditions. @param string $conditions @param string $context @return array
[ "Handle", "conditions", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L439-L459
UnionOfRAD/lithium
data/source/http/adapter/CouchDb.php
CouchDb._format
protected function _format(array $data) { foreach (['id', 'rev'] as $key) { if (isset($data["_{$key}"])) { $data[$key] = $data["_{$key}"]; unset($data["_{$key}"]); } } return $data; }
php
protected function _format(array $data) { foreach (['id', 'rev'] as $key) { if (isset($data["_{$key}"])) { $data[$key] = $data["_{$key}"]; unset($data["_{$key}"]); } } return $data; }
[ "protected", "function", "_format", "(", "array", "$", "data", ")", "{", "foreach", "(", "[", "'id'", ",", "'rev'", "]", "as", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "\"_{$key}\"", "]", ")", ")", "{", "$", "data", "[", ...
Formats a CouchDb result set into a standard result to be passed to item. @param array $data data returned from query @return array
[ "Formats", "a", "CouchDb", "result", "set", "into", "a", "standard", "result", "to", "be", "passed", "to", "item", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/http/adapter/CouchDb.php#L524-L532
UnionOfRAD/lithium
g11n/Message.php
Message.translate
public static function translate($id, array $options = []) { $defaults = [ 'count' => 1, 'locale' => Environment::get('locale'), 'scope' => null, 'context' => null, 'default' => null, 'noop' => false ]; $options += $defaults; if ($options['noop']) { $result = null; } else { $result = static::_translated($id, abs($options['count']), $options['locale'], [ 'scope' => $options['scope'], 'context' => $options['context'] ]); } if ($result = $result ?: $options['default']) { return strpos($result, '{:') !== false ? Text::insert($result, $options) : $result; } }
php
public static function translate($id, array $options = []) { $defaults = [ 'count' => 1, 'locale' => Environment::get('locale'), 'scope' => null, 'context' => null, 'default' => null, 'noop' => false ]; $options += $defaults; if ($options['noop']) { $result = null; } else { $result = static::_translated($id, abs($options['count']), $options['locale'], [ 'scope' => $options['scope'], 'context' => $options['context'] ]); } if ($result = $result ?: $options['default']) { return strpos($result, '{:') !== false ? Text::insert($result, $options) : $result; } }
[ "public", "static", "function", "translate", "(", "$", "id", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'count'", "=>", "1", ",", "'locale'", "=>", "Environment", "::", "get", "(", "'locale'", ")", ",", "'scope...
Translates a message according to the current or provided locale and into its correct plural form. Usage: ``` Message::translate('Mind the gap.'); Message::translate('house', ['count' => 23]); ``` `Text::insert()`-style placeholders may be used within the message and replacements provided directly within the `options` argument. Example: ``` Message::translate('I can see {:count} bike.'); Message::translate('This painting is {:color}.', [ 'color' => Message::translate('silver'), ]); ``` @see lithium\util\Text::insert() @param string $id The id to use when looking up the translation. @param array $options Valid options are: - `'count'`: Used to determine the correct plural form. You can either pass a signed or unsigned integer, the behavior when passing other types is yet undefined. The count is made absolute before being passed to the pluralization function. This has the effect that that with i.e. an English pluralization function passing `-1` results in a singular translation. - `'locale'`: The target locale, defaults to current locale. - `'scope'`: The scope of the message. - `'context'`: The disambiguating context (optional). - `'default'`: Is used as a fall back if `_translated()` returns without a result. - `'noop'`: If `true` no whatsoever lookup takes place. @return string The translation or the value of the `'default'` option if none could be found.
[ "Translates", "a", "message", "according", "to", "the", "current", "or", "provided", "locale", "and", "into", "its", "correct", "plural", "form", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Message.php#L100-L123
UnionOfRAD/lithium
g11n/Message.php
Message.aliases
public static function aliases() { $t = function($message, array $options = []) { return Message::translate($message, $options + ['default' => $message]); }; $tn = function($message1, $message2, $count, array $options = []) { return Message::translate($message1, $options + compact('count') + [ 'default' => $count === 1 ? $message1 : $message2 ]); }; return compact('t', 'tn'); }
php
public static function aliases() { $t = function($message, array $options = []) { return Message::translate($message, $options + ['default' => $message]); }; $tn = function($message1, $message2, $count, array $options = []) { return Message::translate($message1, $options + compact('count') + [ 'default' => $count === 1 ? $message1 : $message2 ]); }; return compact('t', 'tn'); }
[ "public", "static", "function", "aliases", "(", ")", "{", "$", "t", "=", "function", "(", "$", "message", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "Message", "::", "translate", "(", "$", "message", ",", "$", "options", "+", ...
Returns an array containing named closures which are aliases for `translate()`. They can be embedded as content filters in the template layer using a filter for `Media::_handle()` or be used in other places where needed. Usage: ``` $t('bike'); $tn('bike', 'bikes', 3); ``` Using in a method: ``` public function index() { extract(Message::aliases()); $notice = $t('look'); } ``` @see lithium\net\http\Media::_handle() @return array Named aliases (`'t'` and `'tn'`) for translation functions.
[ "Returns", "an", "array", "containing", "named", "closures", "which", "are", "aliases", "for", "translate", "()", ".", "They", "can", "be", "embedded", "as", "content", "filters", "in", "the", "template", "layer", "using", "a", "filter", "for", "Media", "::"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Message.php#L147-L157
UnionOfRAD/lithium
g11n/Message.php
Message.cache
public static function cache($cache = null) { if ($cache === false) { static::$_cachedPages = []; } if (is_array($cache)) { static::$_cachedPages += $cache; } return static::$_cachedPages; }
php
public static function cache($cache = null) { if ($cache === false) { static::$_cachedPages = []; } if (is_array($cache)) { static::$_cachedPages += $cache; } return static::$_cachedPages; }
[ "public", "static", "function", "cache", "(", "$", "cache", "=", "null", ")", "{", "if", "(", "$", "cache", "===", "false", ")", "{", "static", "::", "$", "_cachedPages", "=", "[", "]", ";", "}", "if", "(", "is_array", "(", "$", "cache", ")", ")"...
Returns or sets the page cache used for mapping message ids to translations. @param array $cache A multidimensional array to use when pre-populating the cache. The structure of the array is `scope/locale/id`. If `false`, the cache is cleared. @return array Returns an array of cached pages, formatted per the description for `$cache`.
[ "Returns", "or", "sets", "the", "page", "cache", "used", "for", "mapping", "message", "ids", "to", "translations", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Message.php#L166-L174
UnionOfRAD/lithium
g11n/Message.php
Message._translated
protected static function _translated($id, $count, $locale, array $options = []) { $params = compact('id', 'count', 'locale', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); if (isset($options['context']) && $options['context'] !== null) { $context = $options['context']; $id = "{$id}|{$context}"; } if (!isset(static::$_cachedPages[$options['scope']][$locale])) { static::$_cachedPages[$options['scope']][$locale] = Catalog::read( true, 'message', $locale, $options ); } $page = static::$_cachedPages[$options['scope']][$locale]; if (!isset($page[$id])) { return null; } if (!is_array($page[$id])) { return $page[$id]; } if (!isset($page['pluralRule']) || !is_callable($page['pluralRule'])) { return null; } $key = $page['pluralRule']($count); if (isset($page[$id][$key])) { return $page[$id][$key]; } }); }
php
protected static function _translated($id, $count, $locale, array $options = []) { $params = compact('id', 'count', 'locale', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { extract($params); if (isset($options['context']) && $options['context'] !== null) { $context = $options['context']; $id = "{$id}|{$context}"; } if (!isset(static::$_cachedPages[$options['scope']][$locale])) { static::$_cachedPages[$options['scope']][$locale] = Catalog::read( true, 'message', $locale, $options ); } $page = static::$_cachedPages[$options['scope']][$locale]; if (!isset($page[$id])) { return null; } if (!is_array($page[$id])) { return $page[$id]; } if (!isset($page['pluralRule']) || !is_callable($page['pluralRule'])) { return null; } $key = $page['pluralRule']($count); if (isset($page[$id][$key])) { return $page[$id][$key]; } }); }
[ "protected", "static", "function", "_translated", "(", "$", "id", ",", "$", "count", ",", "$", "locale", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'id'", ",", "'count'", ",", "'locale'", ",", "'option...
Retrieves translations through the `Catalog` class by using `$id` as the lookup key and taking the current or - if specified - the provided locale as well as the scope into account. Hereupon the correct plural form is determined by passing the value of the `'count'` option to a closure. @see lithium\g11n\Catalog @param string $id The lookup key. @param integer $count Used to determine the correct plural form. @param string $locale The target locale. @param array $options Passed through to `Catalog::read()`. Valid options are: - `'scope'`: The scope of the message. - `'context'`: The disambiguating context. @return string The translation or `null` if none could be found or the plural form could not be determined. @filter
[ "Retrieves", "translations", "through", "the", "Catalog", "class", "by", "using", "$id", "as", "the", "lookup", "key", "and", "taking", "the", "current", "or", "-", "if", "specified", "-", "the", "provided", "locale", "as", "well", "as", "the", "scope", "i...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Message.php#L193-L227
UnionOfRAD/lithium
net/http/Media.php
Media.type
public static function type($type, $content = null, array $options = []) { $defaults = [ 'view' => false, 'paths' => [ 'template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php' ], 'encode' => false, 'decode' => false, 'cast' => true, 'conditions' => [] ]; if ($content === false) { unset(static::$_types[$type], static::$_handlers[$type]); } if (!$content && !$options) { if (!$content = static::_types($type)) { return; } if (strpos($type, '/')) { return $content; } if (is_array($content) && isset($content['alias'])) { return static::type($content['alias']); } return compact('content') + ['options' => static::handlers($type)]; } if ($content) { static::$_types[$type] = (array) $content; } static::$_handlers[$type] = $options ? Set::merge($defaults, $options) : []; }
php
public static function type($type, $content = null, array $options = []) { $defaults = [ 'view' => false, 'paths' => [ 'template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php' ], 'encode' => false, 'decode' => false, 'cast' => true, 'conditions' => [] ]; if ($content === false) { unset(static::$_types[$type], static::$_handlers[$type]); } if (!$content && !$options) { if (!$content = static::_types($type)) { return; } if (strpos($type, '/')) { return $content; } if (is_array($content) && isset($content['alias'])) { return static::type($content['alias']); } return compact('content') + ['options' => static::handlers($type)]; } if ($content) { static::$_types[$type] = (array) $content; } static::$_handlers[$type] = $options ? Set::merge($defaults, $options) : []; }
[ "public", "static", "function", "type", "(", "$", "type", ",", "$", "content", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'view'", "=>", "false", ",", "'paths'", "=>", "[", "'template'", "=>", "'...
Maps a type name to a particular content-type (or multiple types) with a set of options, or retrieves information about a type that has been defined. Examples: ``` embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(1-2) ``` ``` embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(19-23) ``` ``` embed:lithium\tests\cases\net\http\MediaTest::testMediaTypes(43-44) ``` Alternatively, can be used to detect the type name of a registered content type: ``` Media::type('application/json'); // returns 'json' Media::type('application/javascript'); // returns 'javascript' Media::type('text/javascript'); // also returns 'javascript' Media::type('text/html'); // returns 'html' Media::type('application/xhtml+xml'); // also returns 'html' ``` #### Content negotiation When creating custom media types, specifying which content-type(s) to match isn't always enough. For example, if you wish to serve a different set of templates to mobile web browsers, you'd still want those templates served as HTML. You might add something like this: ``` Media::type('mobile', ['application/xhtml+xml', 'text/html']); ``` However, this would cause _all_ requests for HTML content to be interpreted as `'mobile'`-type requests. Instead, we can use _content negotiation_ to granularly specify how to match a particular type. Content negotiation is the process of examining the HTTP headers provided in the request (including the content-types listed in the `Accept` header, and optionally other things as well, like the `Accept-Language` or `User-Agent` headers), in order to produce the best representation of the requested resource for the client; in other words, the resource that most closely matches what the client is asking for. Content negotiation with media types is made possible through the `'conditions'` key of the `$options` parameter, which contains an array of assertions made against the `Request` object. Each assertion (array key) can be one of three different things: - `'type'` _boolean_: In the default routing, some routes have `{:type}` keys, which are designed to match file extensions in URLs. These values act as overrides for the HTTP `Accept` header, allowing different formats to be served with the same content type. For example, if you're serving JSONP, you'll want to serve it with the same content-type as JavaScript (since it is JavaScript), but you probably won't want to use the same template(s) or other settings. Therefore, when serving JSONP content, you can specify that the extension defined in the type must be present in the URL: ``` Media::type('jsonp', ['application/json'], [ // template settings... 'conditions' => ['type' => true] ]); ``` Then, JSONP content will only ever be served when the request URL ends in `.jsonp`. - `'<prefix>:<key>'` _string_: This type of assertion can be used to match against arbitrary information in the request, including headers (i.e. `'http:user_agent'`), environment variables (i.e. `'env:home'`), GET and POST data (i.e. `'query:foo'` or `'data:foo'`, respectively), and the HTTP method (`'http:method'`) of the request. For more information on possible keys, see `lithium\action\Request::get()`. - `'<detector>'` _boolean_: Uses detector checks added to the `Request` object to make boolean assertions against the request. For example, if a detector called `'iPhone'` is attached, you can add `'iPhone' => true` to the `'conditions'` array in order to filter for iPhone requests only. See `lithium\action\Request::detect()` for more information on adding detectors. @link http://en.wikipedia.org/wiki/JSON#JSONP @see lithium\net\http\Media::$_types @see lithium\net\http\Media::$_handlers @see lithium\net\http\Media::negotiate() @see lithium\action\Request::get() @see lithium\action\Request::is() @see lithium\action\Request::detect() @see lithium\util\Text::insert() @param string $type A file-extension-style type name, i.e. `'txt'`, `'js'`, or `'atom'`. Alternatively, a mapped content type, i.e. `'text/html'`, `'application/atom+xml'`, etc.; in which case, the matching type name (i.e. '`html'` or `'atom'`) will be returned. @param mixed $content Optional. A string or array containing the content-type(s) that `$type` should map to. If `$type` is an array of content-types, the first one listed should be the "primary" type, and will be used as the `Content-type` header of any `Response` objects served through this type. @param array $options Optional. The handling options for this media type. Possible keys are: - `'view'` _string_: Specifies the view class to use when rendering this content. Note that no `'view'` class is specified by default. If you want to render templates using Lithium's default view class, use `'lithium\template\View'` - `'decode'` _mixed_: A (string) function name or (object) closure that handles decoding or unserializing content from this format. - `'encode'` _mixed_: A (string) function name or (object) closure that handles encoding or serializing content into this format. - `'cast'` _boolean_: Used with `'encode'`. If `true`, all data passed into the specified encode function is first cast to array structures. - `'paths'` _array_: Optional key/value pairs mapping paths for `'template'`, `'layout'`, and `'element'` template files. Any keys ommitted will use the default path. The values should be `Text::insert()`-style paths or an array of `Text::insert()`-style paths. If it is an array, each path will be tried in the order specified until a template is found. This is useful for allowing custom templates while falling back on default templates if no custom template was found. If you want to render templates without a layout, use a `false` value for `'layout'`. - `'conditions'` _array_: Optional key/value pairs used as assertions in content negotiation. See the above section on **Content Negotiation**. @return mixed If `$content` and `$options` are empty, returns an array with `'content'` and `'options'` keys, where `'content'` is the content-type(s) that correspond to `$type` (can be a string or array, if multiple content-types are available), and `'options'` is the array of options which define how this content-type should be handled. If `$content` or `$options` are non-empty, returns `null`.
[ "Maps", "a", "type", "name", "to", "a", "particular", "content", "-", "type", "(", "or", "multiple", "types", ")", "with", "a", "set", "of", "options", "or", "retrieves", "information", "about", "a", "type", "that", "has", "been", "defined", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L244-L277
UnionOfRAD/lithium
net/http/Media.php
Media.negotiate
public static function negotiate($request) { $match = function($name) use ($request) { if (($cfg = static::type($name)) && static::match($request, compact('name') + $cfg)) { return true; } return false; }; if (($type = $request->type) && $match($type)) { return $type; } foreach ($request->accepts(true) as $type) { if (!$types = (array) static::_types($type)) { continue; } foreach ($types as $name) { if (!$match($name)) { continue; } return $name; } } }
php
public static function negotiate($request) { $match = function($name) use ($request) { if (($cfg = static::type($name)) && static::match($request, compact('name') + $cfg)) { return true; } return false; }; if (($type = $request->type) && $match($type)) { return $type; } foreach ($request->accepts(true) as $type) { if (!$types = (array) static::_types($type)) { continue; } foreach ($types as $name) { if (!$match($name)) { continue; } return $name; } } }
[ "public", "static", "function", "negotiate", "(", "$", "request", ")", "{", "$", "match", "=", "function", "(", "$", "name", ")", "use", "(", "$", "request", ")", "{", "if", "(", "(", "$", "cfg", "=", "static", "::", "type", "(", "$", "name", ")"...
Performs content-type negotiation on a `Request` object, by iterating over the accepted types in sequence, from most preferred to least, and attempting to match each one against a content type defined by `Media::type()`, until a match is found. If more than one defined type matches for a given content type, they will be checked in the order they were added (usually, this corresponds to the order they were defined in the application bootstrapping process). @see lithium\net\http\Media::type() @see lithium\net\http\Media::match() @see lithium\action\Request @param \lithium\action\Request $request The request which contains the details of the request to be content-negotiated. @return string|null Returns the first matching type name, i.e. `'html'` or `'json'`. When no matching type is found returns `null`.
[ "Performs", "content", "-", "type", "negotiation", "on", "a", "Request", "object", "by", "iterating", "over", "the", "accepted", "types", "in", "sequence", "from", "most", "preferred", "to", "least", "and", "attempting", "to", "match", "each", "one", "against"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L295-L318
UnionOfRAD/lithium
net/http/Media.php
Media.match
public static function match($request, array $config) { if (!isset($config['options']['conditions'])) { return true; } $conditions = $config['options']['conditions']; foreach ($conditions as $key => $value) { switch (true) { case $key === 'type': if ($value !== ($request->type === $config['name'])) { return false; } break; case strpos($key, ':'): if ($request->get($key) !== $value) { return false; } break; case ($request->is($key) !== $value): return false; break; } } return true; }
php
public static function match($request, array $config) { if (!isset($config['options']['conditions'])) { return true; } $conditions = $config['options']['conditions']; foreach ($conditions as $key => $value) { switch (true) { case $key === 'type': if ($value !== ($request->type === $config['name'])) { return false; } break; case strpos($key, ':'): if ($request->get($key) !== $value) { return false; } break; case ($request->is($key) !== $value): return false; break; } } return true; }
[ "public", "static", "function", "match", "(", "$", "request", ",", "array", "$", "config", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'options'", "]", "[", "'conditions'", "]", ")", ")", "{", "return", "true", ";", "}", "$", "cond...
Assists `Media::negotiate()` in processing the negotiation conditions of a content type, by iterating through the conditions and checking each one against the `Request` object. @see lithium\net\http\Media::negotiate() @see lithium\net\http\Media::type() @see lithium\action\Request @param \lithium\action\Request $request The request to be checked against a set of conditions (if applicable). @param array $config Represents a content type configuration, which is an array containing 3 keys: - `'name'` _string_: The type name, i.e. `'html'` or `'json'`. - `'content'` _mixed_: One or more content types that the configuration represents, i.e. `'text/html'`, `'application/xhtml+xml'` or `'application/json'`, or an array containing multiple content types. - `'options'` _array_: An array containing rendering information, and an optional `'conditions'` key, which contains an array of matching parameters. For more details on these matching parameters, see `Media::type()`. @return boolean Returns `true` if the information in `$request` matches the type configuration in `$config`, otherwise false.
[ "Assists", "Media", "::", "negotiate", "()", "in", "processing", "the", "negotiation", "conditions", "of", "a", "content", "type", "by", "iterating", "through", "the", "conditions", "and", "checking", "each", "one", "against", "the", "Request", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L341-L365
UnionOfRAD/lithium
net/http/Media.php
Media.assets
public static function assets($type = null, $options = []) { $defaults = ['suffix' => null, 'filter' => null, 'paths' => []]; if (!$type) { return static::_assets(); } if ($options === false) { unset(static::$_assets[$type]); } if (!$options) { return static::_assets($type); } $options = (array) $options + $defaults; if ($base = static::_assets($type)) { $options = array_merge($base, array_filter($options)); } static::$_assets[$type] = $options; }
php
public static function assets($type = null, $options = []) { $defaults = ['suffix' => null, 'filter' => null, 'paths' => []]; if (!$type) { return static::_assets(); } if ($options === false) { unset(static::$_assets[$type]); } if (!$options) { return static::_assets($type); } $options = (array) $options + $defaults; if ($base = static::_assets($type)) { $options = array_merge($base, array_filter($options)); } static::$_assets[$type] = $options; }
[ "public", "static", "function", "assets", "(", "$", "type", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'suffix'", "=>", "null", ",", "'filter'", "=>", "null", ",", "'paths'", "=>", "[", "]", "]", ";", "...
Gets or sets options for various asset types. @see lithium\util\Text::insert() @param string $type The name of the asset type, i.e. `'js'` or `'css'`. @param array $options If registering a new asset type or modifying an existing asset type, contains settings for the asset type, where the available keys are as follows: - `'suffix'`: The standard suffix for this content type, with leading dot ('.') if applicable. - `'filter'`: An array of key/value pairs representing simple string replacements to be done on a path once it is generated. - `'paths'`: An array of key/value pairs where the keys are `Text::insert()` compatible paths, and the values are array lists of keys to be inserted into the path string. @return array If `$type` is empty, an associative array of all registered types and all associated options is returned. If `$type` is a string and `$options` is empty, returns an associative array with the options for `$type`. If `$type` and `$options` are both non-empty, returns `null`.
[ "Gets", "or", "sets", "options", "for", "various", "asset", "types", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L386-L404
UnionOfRAD/lithium
net/http/Media.php
Media.asset
public static function asset($path, $type, array $options = []) { $options = static::_assetOptions($path, $type, $options); $params = compact('path', 'type', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $path = $params['path']; $type = $params['type']; $options = $params['options']; $library = $options['library']; if (preg_match('/^(?:[a-z0-9-]+:)?\/\//i', $path)) { return $path; } $config = Libraries::get($library); $paths = $options['paths']; $config['default'] ? end($paths) : reset($paths); $options['library'] = basename($config['path']); if ($options['suffix'] && strpos($path, $options['suffix']) === false) { $path .= $options['suffix']; } return static::filterAssetPath($path, $paths, $config, compact('type') + $options); }); }
php
public static function asset($path, $type, array $options = []) { $options = static::_assetOptions($path, $type, $options); $params = compact('path', 'type', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $path = $params['path']; $type = $params['type']; $options = $params['options']; $library = $options['library']; if (preg_match('/^(?:[a-z0-9-]+:)?\/\//i', $path)) { return $path; } $config = Libraries::get($library); $paths = $options['paths']; $config['default'] ? end($paths) : reset($paths); $options['library'] = basename($config['path']); if ($options['suffix'] && strpos($path, $options['suffix']) === false) { $path .= $options['suffix']; } return static::filterAssetPath($path, $paths, $config, compact('type') + $options); }); }
[ "public", "static", "function", "asset", "(", "$", "path", ",", "$", "type", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "static", "::", "_assetOptions", "(", "$", "path", ",", "$", "type", ",", "$", "options", ")", ...
Calculates the web-accessible path to a static asset, usually a JavaScript, CSS or image file. @see lithium\net\http\Media::$_assets @see lithium\action\Request::env() @param string $path The path to the asset, relative to the given `$type`s path and without a suffix. If the path contains a URI Scheme (eg. `http://`), no path munging will occur. @param string $type The asset type. See `Media::$_assets` or `Media::assets()`. @param array $options Contains setting for finding and handling the path, where the keys are the following: - `'base'`: The base URL of your application. Defaults to `null` for no base path. This is usually set with the return value of a call to `env('base')` on an instance of `lithium\action\Request`. - `'check'`: Check for the existence of the file before returning. Defaults to `false`. - `'filter'`: An array of key/value pairs representing simple string replacements to be done on a path once it is generated. - `'paths'`: An array of paths to search for the asset in. The paths should use `Text::insert()` formatting. See `Media::$_assets` for more. - `suffix`: The suffix to attach to the path, generally a file extension. - `'timestamp'`: Appends the last modified time of the file to the path if `true`. Defaults to `false`. - `'library'`: The name of the library from which to load the asset. Defaults to `true`, for the default library. @return string Returns the publicly-accessible absolute path to the static asset. If checking for the asset's existence (`$options['check']`), returns `false` if it does not exist in your `/webroot` directory, or the `/webroot` directories of one of your included plugins. @filter
[ "Calculates", "the", "web", "-", "accessible", "path", "to", "a", "static", "asset", "usually", "a", "JavaScript", "CSS", "or", "image", "file", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L437-L460
UnionOfRAD/lithium
net/http/Media.php
Media._assetOptions
protected static function _assetOptions($path, $type, $options) { $defaults = [ 'base' => null, 'timestamp' => false, 'filter' => null, 'paths' => [], 'suffix' => null, 'check' => false, 'library' => true ]; $base = isset($options['base']) ? rtrim($options['base'], '/') : ''; $options += ['scope' => static::scope()]; $name = $options['scope']; if ($config = static::attached($name)) { $base = isset($config['base']) ? '/' . $config['base'] : $base; $defaults = array_merge($defaults, $config); if (preg_match('/^((?:[a-z0-9-]+:)?\/\/)([^\/]*)/i', $base, $match)) { $options = array_merge($defaults, [ 'base' => rtrim($base . '/' . $defaults['prefix'], '/') ]); } else { $host = ''; if ($defaults['absolute']) { $host = $defaults['host']; if (is_array($host)) { $hash = substr(hexdec(md5($path)), 0, 10); $index = ((integer) $hash) % count($host); if (is_array($defaults['scheme'])) { $host = $defaults['scheme'][$index] . $host[$index]; } else { $host = $defaults['scheme'] . $host[$index]; } } else { $host = $defaults['scheme'] . $defaults['host']; } $base = trim($base, '/'); $base = $base ? '/' . $base : ''; } $options['base'] = rtrim($host . $base . '/' . $defaults['prefix'], '/'); } } if (!$paths = static::_assets($type)) { $paths = static::_assets('generic'); } return $options + $paths + $defaults; }
php
protected static function _assetOptions($path, $type, $options) { $defaults = [ 'base' => null, 'timestamp' => false, 'filter' => null, 'paths' => [], 'suffix' => null, 'check' => false, 'library' => true ]; $base = isset($options['base']) ? rtrim($options['base'], '/') : ''; $options += ['scope' => static::scope()]; $name = $options['scope']; if ($config = static::attached($name)) { $base = isset($config['base']) ? '/' . $config['base'] : $base; $defaults = array_merge($defaults, $config); if (preg_match('/^((?:[a-z0-9-]+:)?\/\/)([^\/]*)/i', $base, $match)) { $options = array_merge($defaults, [ 'base' => rtrim($base . '/' . $defaults['prefix'], '/') ]); } else { $host = ''; if ($defaults['absolute']) { $host = $defaults['host']; if (is_array($host)) { $hash = substr(hexdec(md5($path)), 0, 10); $index = ((integer) $hash) % count($host); if (is_array($defaults['scheme'])) { $host = $defaults['scheme'][$index] . $host[$index]; } else { $host = $defaults['scheme'] . $host[$index]; } } else { $host = $defaults['scheme'] . $defaults['host']; } $base = trim($base, '/'); $base = $base ? '/' . $base : ''; } $options['base'] = rtrim($host . $base . '/' . $defaults['prefix'], '/'); } } if (!$paths = static::_assets($type)) { $paths = static::_assets('generic'); } return $options + $paths + $defaults; }
[ "protected", "static", "function", "_assetOptions", "(", "$", "path", ",", "$", "type", ",", "$", "options", ")", "{", "$", "defaults", "=", "[", "'base'", "=>", "null", ",", "'timestamp'", "=>", "false", ",", "'filter'", "=>", "null", ",", "'paths'", ...
Initialize options for `Media::asset()`. @param string $path The path to the asset. @param string $type The asset type. @param array $options Contains setting for finding and handling the path. @return array The initialized options.
[ "Initialize", "options", "for", "Media", "::", "asset", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L470-L522
UnionOfRAD/lithium
net/http/Media.php
Media.filterAssetPath
public static function filterAssetPath($asset, $path, array $config, array $options = []) { $config += ['assets' => null]; if ($options['check'] || $options['timestamp']) { $file = static::path($asset, $options['type'], $options); } if ($options['check'] && !is_file($file)) { return false; } $isAbsolute = ($asset && $asset[0] === '/'); if ($isAbsolute && $options['base'] && strpos($asset, $options['base']) !== 0) { $asset = "{$options['base']}{$asset}"; } elseif (!$isAbsolute) { $asset = Text::insert(key($path), ['path' => $asset] + $options); } if (is_array($options['filter']) && !empty($options['filter'])) { $filter = $options['filter']; $asset = str_replace(array_keys($filter), array_values($filter), $asset); } if ($options['timestamp'] && is_file($file)) { $separator = (strpos($asset, '?') !== false) ? '&' : '?'; $asset .= $separator . filemtime($file); } if ($host = $config['assets']) { $type = $options['type']; $env = Environment::get(); $base = isset($host[$env][$type]) ? $host[$env][$type] : null; $base = (isset($host[$type]) && !$base) ? $host[$type] : $base; if ($base) { return "{$base}{$asset}"; } } return $asset; }
php
public static function filterAssetPath($asset, $path, array $config, array $options = []) { $config += ['assets' => null]; if ($options['check'] || $options['timestamp']) { $file = static::path($asset, $options['type'], $options); } if ($options['check'] && !is_file($file)) { return false; } $isAbsolute = ($asset && $asset[0] === '/'); if ($isAbsolute && $options['base'] && strpos($asset, $options['base']) !== 0) { $asset = "{$options['base']}{$asset}"; } elseif (!$isAbsolute) { $asset = Text::insert(key($path), ['path' => $asset] + $options); } if (is_array($options['filter']) && !empty($options['filter'])) { $filter = $options['filter']; $asset = str_replace(array_keys($filter), array_values($filter), $asset); } if ($options['timestamp'] && is_file($file)) { $separator = (strpos($asset, '?') !== false) ? '&' : '?'; $asset .= $separator . filemtime($file); } if ($host = $config['assets']) { $type = $options['type']; $env = Environment::get(); $base = isset($host[$env][$type]) ? $host[$env][$type] : null; $base = (isset($host[$type]) && !$base) ? $host[$type] : $base; if ($base) { return "{$base}{$asset}"; } } return $asset; }
[ "public", "static", "function", "filterAssetPath", "(", "$", "asset", ",", "$", "path", ",", "array", "$", "config", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "config", "+=", "[", "'assets'", "=>", "null", "]", ";", "if", "(", "$"...
Performs checks and applies transformations to asset paths, including verifying that the virtual path exists on the filesystem, appending a timestamp, prepending an asset host, or applying a user-defined filter. @see lithium\net\http\Media::asset() @param string $asset A full asset path, relative to the public web path of the application. @param mixed $path Path information for the asset type. @param array $config The configuration array of the library from which the asset is being loaded. @param array $options The array of options passed to `asset()` (see the `$options` parameter of `Media::asset()`). @return mixed Returns a modified path to a web asset, or `false`, if the path fails a check.
[ "Performs", "checks", "and", "applies", "transformations", "to", "asset", "paths", "including", "verifying", "that", "the", "virtual", "path", "exists", "on", "the", "filesystem", "appending", "a", "timestamp", "prepending", "an", "asset", "host", "or", "applying"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L538-L576
UnionOfRAD/lithium
net/http/Media.php
Media.webroot
public static function webroot($library = true, $scope = null) { if ($scope) { if ($config = static::attached($scope)) { return $config['path']; } return null; } if (!$config = Libraries::get($library)) { return null; } if (isset($config['webroot'])) { return $config['webroot']; } if (isset($config['path'])) { return $config['path'] . '/webroot'; } }
php
public static function webroot($library = true, $scope = null) { if ($scope) { if ($config = static::attached($scope)) { return $config['path']; } return null; } if (!$config = Libraries::get($library)) { return null; } if (isset($config['webroot'])) { return $config['webroot']; } if (isset($config['path'])) { return $config['path'] . '/webroot'; } }
[ "public", "static", "function", "webroot", "(", "$", "library", "=", "true", ",", "$", "scope", "=", "null", ")", "{", "if", "(", "$", "scope", ")", "{", "if", "(", "$", "config", "=", "static", "::", "attached", "(", "$", "scope", ")", ")", "{",...
Gets the physical path to the web assets (i.e. `/webroot`) directory of a library. @param string|boolean $library The name of the library for which to find the path, or `true` for the default library. @param string|boolean $scope The name of the to use to find the path. @return string Returns the physical path to the web assets directory.
[ "Gets", "the", "physical", "path", "to", "the", "web", "assets", "(", "i", ".", "e", ".", "/", "webroot", ")", "directory", "of", "a", "library", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L586-L602
UnionOfRAD/lithium
net/http/Media.php
Media.path
public static function path($path, $type, array $options = []) { $defaults = [ 'base' => null, 'paths' => [], 'suffix' => null, 'library' => true, 'scope' => false ]; if (!$base = static::_assets($type)) { $base = static::_assets('generic'); } $options += ($base + $defaults); $paths = $options['paths']; if ($options['scope']) { $root = static::webroot(false, $options['scope']); } else { $root = static::webroot($options['library']); Libraries::get(true, 'name') === $options['library'] ? end($paths) : reset($paths); } if ($qOffset = strpos($path, '?')) { $path = substr($path, 0, $qOffset); } if ($path[0] === '/') { $file = $root . $path; } else { $template = str_replace('{:library}/', '', key($paths)); $insert = ['base' => $root] + compact('path'); $file = Text::insert($template, $insert); } return realpath($file); }
php
public static function path($path, $type, array $options = []) { $defaults = [ 'base' => null, 'paths' => [], 'suffix' => null, 'library' => true, 'scope' => false ]; if (!$base = static::_assets($type)) { $base = static::_assets('generic'); } $options += ($base + $defaults); $paths = $options['paths']; if ($options['scope']) { $root = static::webroot(false, $options['scope']); } else { $root = static::webroot($options['library']); Libraries::get(true, 'name') === $options['library'] ? end($paths) : reset($paths); } if ($qOffset = strpos($path, '?')) { $path = substr($path, 0, $qOffset); } if ($path[0] === '/') { $file = $root . $path; } else { $template = str_replace('{:library}/', '', key($paths)); $insert = ['base' => $root] + compact('path'); $file = Text::insert($template, $insert); } return realpath($file); }
[ "public", "static", "function", "path", "(", "$", "path", ",", "$", "type", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'base'", "=>", "null", ",", "'paths'", "=>", "[", "]", ",", "'suffix'", "=>", "null", "...
Returns the physical path to an asset in the `/webroot` directory of an application or plugin. @param string $paths The path to a web asset, relative to the root path for its type. For example, for a JavaScript file in `/webroot/js/subpath/file.js`, the correct value for `$path` would be `'subpath/file.js'`. @param string $type A valid asset type, i.e. `'js'`, `'cs'`, `'image'`, or another type registered with `Media::assets()`, or `'generic'`. @param array $options The options used to calculate the path to the file. @return string Returns the physical filesystem path to an asset in the `/webroot` directory.
[ "Returns", "the", "physical", "path", "to", "an", "asset", "in", "the", "/", "webroot", "directory", "of", "an", "application", "or", "plugin", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L616-L649
UnionOfRAD/lithium
net/http/Media.php
Media.render
public static function render($response, $data = null, array $options = []) { $params = compact('response', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $types = static::_types(); $handlers = static::handlers(); $defaults = ['encode' => null, 'template' => null, 'layout' => '', 'view' => null]; $response = $params['response']; $data = $params['data']; $options = $params['options'] + ['type' => $response->type()]; $result = null; $type = $options['type']; if (!isset($handlers[$type])) { throw new MediaException("Unhandled media type `{$type}`."); } $handler = $options + $handlers[$type] + $defaults; $filter = function($v) { return $v !== null; }; $handler = array_filter($handler, $filter) + $handlers['default'] + $defaults; if (isset($types[$type])) { $mimeTypes = (array) $types[$type]; $header = current($mimeTypes); $header .= $response->encoding ? "; charset={$response->encoding}" : ''; $response->headers('Content-Type', $header); } $response->body(static::_handle($handler, $data, $response)); return $response; }); }
php
public static function render($response, $data = null, array $options = []) { $params = compact('response', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $types = static::_types(); $handlers = static::handlers(); $defaults = ['encode' => null, 'template' => null, 'layout' => '', 'view' => null]; $response = $params['response']; $data = $params['data']; $options = $params['options'] + ['type' => $response->type()]; $result = null; $type = $options['type']; if (!isset($handlers[$type])) { throw new MediaException("Unhandled media type `{$type}`."); } $handler = $options + $handlers[$type] + $defaults; $filter = function($v) { return $v !== null; }; $handler = array_filter($handler, $filter) + $handlers['default'] + $defaults; if (isset($types[$type])) { $mimeTypes = (array) $types[$type]; $header = current($mimeTypes); $header .= $response->encoding ? "; charset={$response->encoding}" : ''; $response->headers('Content-Type', $header); } $response->body(static::_handle($handler, $data, $response)); return $response; }); }
[ "public", "static", "function", "render", "(", "$", "response", ",", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'response'", ",", "'data'", ",", "'options'", ")", ";", "return...
Renders data (usually the result of a controller action) and generates a string representation of it, based on the type of expected output. @param object $response A Response object into which the operation will be rendered. The content of the render operation will be assigned to the `$body` property of the object, the `'Content-Type'` header will be set accordingly, and it will be returned. @param mixed $data The data (usually an associative array) to be rendered in the response. @param array $options Any options specific to the response being rendered, such as type information, keys (i.e. controller and action) used to generate template paths, etc. @return object Returns a modified `Response` object with headers and body defined. @filter
[ "Renders", "data", "(", "usually", "the", "result", "of", "a", "controller", "action", ")", "and", "generates", "a", "string", "representation", "of", "it", "based", "on", "the", "type", "of", "expected", "output", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L666-L699
UnionOfRAD/lithium
net/http/Media.php
Media.view
public static function view($handler, $data, &$response = null, array $options = []) { $params = ['response' => &$response] + compact('handler', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $handler = $params['handler']; $response =& $params['response']; $handler = is_array($handler) ? $handler : static::handlers($handler); $class = $handler['view']; unset($handler['view']); $config = $handler + ['response' => &$response]; return static::_instance($class, $config); }); }
php
public static function view($handler, $data, &$response = null, array $options = []) { $params = ['response' => &$response] + compact('handler', 'data', 'options'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $handler = $params['handler']; $response =& $params['response']; $handler = is_array($handler) ? $handler : static::handlers($handler); $class = $handler['view']; unset($handler['view']); $config = $handler + ['response' => &$response]; return static::_instance($class, $config); }); }
[ "public", "static", "function", "view", "(", "$", "handler", ",", "$", "data", ",", "&", "$", "response", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "[", "'response'", "=>", "&", "$", "response", "]", ...
Configures a template object instance, based on a media handler configuration. @see lithium\net\http\Media::type() @see lithium\template\View::render() @see lithium\action\Response @param mixed $handler Either a string specifying the name of a media type for which a handler is defined, or an array representing a handler configuration. For more on types and type handlers, see the `type()` method. @param mixed $data The data to be rendered. Usually an array. @param object $response The `Response` object associated with this dispatch cycle. Usually an instance of `lithium\action\Response`. @param array $options Any options that will be passed to the `render()` method of the templating object. @return object Returns an instance of a templating object, usually `lithium\template\View`. @filter
[ "Configures", "a", "template", "object", "instance", "based", "on", "a", "media", "handler", "configuration", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L718-L732
UnionOfRAD/lithium
net/http/Media.php
Media.encode
public static function encode($handler, $data, &$response = null) { $params = ['response' => &$response] + compact('handler', 'data'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $data = $params['data']; $handler = $params['handler']; $response =& $params['response']; $handler = is_array($handler) ? $handler : static::handlers($handler); if (!$handler || empty($handler['encode'])) { return null; } $cast = function($data) { if (!is_object($data)) { return $data; } return method_exists($data, 'to') ? $data->to('array') : get_object_vars($data); }; if (!isset($handler['cast']) || $handler['cast']) { $data = is_object($data) ? $cast($data) : $data; $data = is_array($data) ? array_map($cast, $data) : $data; } $method = $handler['encode']; return is_string($method) ? $method($data) : $method($data, $handler, $response); }); }
php
public static function encode($handler, $data, &$response = null) { $params = ['response' => &$response] + compact('handler', 'data'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $data = $params['data']; $handler = $params['handler']; $response =& $params['response']; $handler = is_array($handler) ? $handler : static::handlers($handler); if (!$handler || empty($handler['encode'])) { return null; } $cast = function($data) { if (!is_object($data)) { return $data; } return method_exists($data, 'to') ? $data->to('array') : get_object_vars($data); }; if (!isset($handler['cast']) || $handler['cast']) { $data = is_object($data) ? $cast($data) : $data; $data = is_array($data) ? array_map($cast, $data) : $data; } $method = $handler['encode']; return is_string($method) ? $method($data) : $method($data, $handler, $response); }); }
[ "public", "static", "function", "encode", "(", "$", "handler", ",", "$", "data", ",", "&", "$", "response", "=", "null", ")", "{", "$", "params", "=", "[", "'response'", "=>", "&", "$", "response", "]", "+", "compact", "(", "'handler'", ",", "'data'"...
For media types registered in `$_handlers` which include an `'encode'` setting, encodes data according to the specified media type. @see lithium\net\http\Media::type() @param mixed $handler Specifies the media type into which `$data` will be encoded. This media type must have an `'encode'` setting specified in `Media::$_handlers`. Alternatively, `$type` can be an array, in which case it is used as the type handler configuration. See the `type()` method for information on adding type handlers, and the available configuration keys. @param mixed $data Arbitrary data you wish to encode. Note that some encoders can only handle arrays or objects. @param object $response A reference to the `Response` object for this dispatch cycle. @return mixed Returns the result of `$data`, encoded with the encoding configuration specified by `$type`, the result of which is usually a string. @filter
[ "For", "media", "types", "registered", "in", "$_handlers", "which", "include", "an", "encode", "setting", "encodes", "data", "according", "to", "the", "specified", "media", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L751-L778
UnionOfRAD/lithium
net/http/Media.php
Media.decode
public static function decode($type, $data, array $options = []) { if ((!$handler = static::handlers($type)) || empty($handler['decode'])) { return null; } $method = $handler['decode']; return is_string($method) ? $method($data) : $method($data, $handler + $options); }
php
public static function decode($type, $data, array $options = []) { if ((!$handler = static::handlers($type)) || empty($handler['decode'])) { return null; } $method = $handler['decode']; return is_string($method) ? $method($data) : $method($data, $handler + $options); }
[ "public", "static", "function", "decode", "(", "$", "type", ",", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "(", "!", "$", "handler", "=", "static", "::", "handlers", "(", "$", "type", ")", ")", "||", "empty", ...
For media types registered in `$_handlers` which include an `'decode'` setting, decodes data according to the specified media type. @param string $type Specifies the media type into which `$data` will be encoded. This media type must have an `'encode'` setting specified in `Media::$_handlers`. @param mixed $data Arbitrary data you wish to encode. Note that some encoders can only handle arrays or objects. @param array $options Handler-specific options. @return mixed
[ "For", "media", "types", "registered", "in", "$_handlers", "which", "include", "an", "decode", "setting", "decodes", "data", "according", "to", "the", "specified", "media", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L791-L797
UnionOfRAD/lithium
net/http/Media.php
Media._handle
protected static function _handle($handler, $data, &$response) { $params = ['response' => &$response] + compact('handler', 'data'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $response = $params['response']; $handler = $params['handler']; $data = $params['data']; $options = $handler; if (isset($options['request'])) { $options += $options['request']->params; unset($options['request']); } switch (true) { case $handler['encode']: return static::encode($handler, $data, $response); case ($handler['template'] === false) && is_string($data): return $data; case $handler['view']: unset($options['view']); $instance = static::view($handler, $data, $response, $options); return $instance->render('all', (array) $data, $options); default: throw new MediaException("Could not interpret type settings for handler."); } }); }
php
protected static function _handle($handler, $data, &$response) { $params = ['response' => &$response] + compact('handler', 'data'); return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) { $response = $params['response']; $handler = $params['handler']; $data = $params['data']; $options = $handler; if (isset($options['request'])) { $options += $options['request']->params; unset($options['request']); } switch (true) { case $handler['encode']: return static::encode($handler, $data, $response); case ($handler['template'] === false) && is_string($data): return $data; case $handler['view']: unset($options['view']); $instance = static::view($handler, $data, $response, $options); return $instance->render('all', (array) $data, $options); default: throw new MediaException("Could not interpret type settings for handler."); } }); }
[ "protected", "static", "function", "_handle", "(", "$", "handler", ",", "$", "data", ",", "&", "$", "response", ")", "{", "$", "params", "=", "[", "'response'", "=>", "&", "$", "response", "]", "+", "compact", "(", "'handler'", ",", "'data'", ")", ";...
Called by `Media::render()` to render response content. Given a content handler and data, calls the content handler and passes in the data, receiving back a rendered content string. @see lithium\action\Response @param array $handler @param array $data @param object $response A reference to the `Response` object for this dispatch cycle. @return string @filter
[ "Called", "by", "Media", "::", "render", "()", "to", "render", "response", "content", ".", "Given", "a", "content", "handler", "and", "data", "calls", "the", "content", "handler", "and", "passes", "in", "the", "data", "receiving", "back", "a", "rendered", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L823-L850
UnionOfRAD/lithium
net/http/Media.php
Media._types
protected static function _types($type = null) { $types = static::$_types + [ 'html' => ['text/html', 'application/xhtml+xml', '*/*'], 'htm' => ['alias' => 'html'], 'form' => ['application/x-www-form-urlencoded', 'multipart/form-data'], 'json' => ['application/json'], 'rss' => ['application/rss+xml'], 'atom' => ['application/atom+xml'], 'css' => ['text/css'], 'js' => ['application/javascript', 'text/javascript'], 'text' => ['text/plain'], 'txt' => ['alias' => 'text'], 'xml' => ['application/xml', 'application/soap+xml', 'text/xml'] ]; if (!$type) { return $types; } if (strpos($type, '/') === false) { return isset($types[$type]) ? $types[$type] : null; } if (strpos($type, ';')) { list($type) = explode(';', $type, 2); } $result = []; foreach ($types as $name => $cTypes) { if ($type === $cTypes || (is_array($cTypes) && in_array($type, $cTypes))) { $result[] = $name; } } if (count($result) === 1) { return reset($result); } return $result ?: null; }
php
protected static function _types($type = null) { $types = static::$_types + [ 'html' => ['text/html', 'application/xhtml+xml', '*/*'], 'htm' => ['alias' => 'html'], 'form' => ['application/x-www-form-urlencoded', 'multipart/form-data'], 'json' => ['application/json'], 'rss' => ['application/rss+xml'], 'atom' => ['application/atom+xml'], 'css' => ['text/css'], 'js' => ['application/javascript', 'text/javascript'], 'text' => ['text/plain'], 'txt' => ['alias' => 'text'], 'xml' => ['application/xml', 'application/soap+xml', 'text/xml'] ]; if (!$type) { return $types; } if (strpos($type, '/') === false) { return isset($types[$type]) ? $types[$type] : null; } if (strpos($type, ';')) { list($type) = explode(';', $type, 2); } $result = []; foreach ($types as $name => $cTypes) { if ($type === $cTypes || (is_array($cTypes) && in_array($type, $cTypes))) { $result[] = $name; } } if (count($result) === 1) { return reset($result); } return $result ?: null; }
[ "protected", "static", "function", "_types", "(", "$", "type", "=", "null", ")", "{", "$", "types", "=", "static", "::", "$", "_types", "+", "[", "'html'", "=>", "[", "'text/html'", ",", "'application/xhtml+xml'", ",", "'*/*'", "]", ",", "'htm'", "=>", ...
Helper method for listing registered media types. Returns all types, or a single content type if a specific type is specified. @todo Use fnmatch() to support wildcards. @param string $type Type to return. @return mixed Array of types, or single type requested.
[ "Helper", "method", "for", "listing", "registered", "media", "types", ".", "Returns", "all", "types", "or", "a", "single", "content", "type", "if", "a", "specific", "type", "is", "specified", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L860-L895
UnionOfRAD/lithium
net/http/Media.php
Media.handlers
public static function handlers($type = null) { $handlers = static::$_handlers + [ 'default' => [ 'view' => 'lithium\template\View', 'encode' => false, 'decode' => false, 'cast' => false, 'paths' => [ 'template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php' ] ], 'html' => [], 'json' => [ 'cast' => true, 'encode' => 'json_encode', 'decode' => function($data) { return json_decode($data, true); } ], 'text' => ['cast' => false, 'encode' => function($s) { return $s; }], 'form' => [ 'cast' => true, 'encode' => 'http_build_query', 'decode' => function($data) { $decoded = []; parse_str($data, $decoded); return $decoded; } ] ]; if ($type) { return isset($handlers[$type]) ? $handlers[$type] : null; } return $handlers; }
php
public static function handlers($type = null) { $handlers = static::$_handlers + [ 'default' => [ 'view' => 'lithium\template\View', 'encode' => false, 'decode' => false, 'cast' => false, 'paths' => [ 'template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php' ] ], 'html' => [], 'json' => [ 'cast' => true, 'encode' => 'json_encode', 'decode' => function($data) { return json_decode($data, true); } ], 'text' => ['cast' => false, 'encode' => function($s) { return $s; }], 'form' => [ 'cast' => true, 'encode' => 'http_build_query', 'decode' => function($data) { $decoded = []; parse_str($data, $decoded); return $decoded; } ] ]; if ($type) { return isset($handlers[$type]) ? $handlers[$type] : null; } return $handlers; }
[ "public", "static", "function", "handlers", "(", "$", "type", "=", "null", ")", "{", "$", "handlers", "=", "static", "::", "$", "_handlers", "+", "[", "'default'", "=>", "[", "'view'", "=>", "'lithium\\template\\View'", ",", "'encode'", "=>", "false", ",",...
Helper method for listing registered type handlers. Returns all handlers, or the handler for a specific media type, if requested. @param string $type The type of handler to return. @return mixed Array of all handlers, or the handler for a specific type.
[ "Helper", "method", "for", "listing", "registered", "type", "handlers", ".", "Returns", "all", "handlers", "or", "the", "handler", "for", "a", "specific", "media", "type", "if", "requested", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L904-L941
UnionOfRAD/lithium
net/http/Media.php
Media._assets
protected static function _assets($type = null) { $assets = static::$_assets + [ 'js' => ['suffix' => '.js', 'filter' => null, 'paths' => [ '{:base}/{:library}/js/{:path}' => ['base', 'library', 'path'], '{:base}/js/{:path}' => ['base', 'path'] ]], 'css' => ['suffix' => '.css', 'filter' => null, 'paths' => [ '{:base}/{:library}/css/{:path}' => ['base', 'library', 'path'], '{:base}/css/{:path}' => ['base', 'path'] ]], 'image' => ['suffix' => null, 'filter' => null, 'paths' => [ '{:base}/{:library}/img/{:path}' => ['base', 'library', 'path'], '{:base}/img/{:path}' => ['base', 'path'] ]], 'generic' => ['suffix' => null, 'filter' => null, 'paths' => [ '{:base}/{:library}/{:path}' => ['base', 'library', 'path'], '{:base}/{:path}' => ['base', 'path'] ]] ]; if ($type) { return isset($assets[$type]) ? $assets[$type] : null; } return $assets; }
php
protected static function _assets($type = null) { $assets = static::$_assets + [ 'js' => ['suffix' => '.js', 'filter' => null, 'paths' => [ '{:base}/{:library}/js/{:path}' => ['base', 'library', 'path'], '{:base}/js/{:path}' => ['base', 'path'] ]], 'css' => ['suffix' => '.css', 'filter' => null, 'paths' => [ '{:base}/{:library}/css/{:path}' => ['base', 'library', 'path'], '{:base}/css/{:path}' => ['base', 'path'] ]], 'image' => ['suffix' => null, 'filter' => null, 'paths' => [ '{:base}/{:library}/img/{:path}' => ['base', 'library', 'path'], '{:base}/img/{:path}' => ['base', 'path'] ]], 'generic' => ['suffix' => null, 'filter' => null, 'paths' => [ '{:base}/{:library}/{:path}' => ['base', 'library', 'path'], '{:base}/{:path}' => ['base', 'path'] ]] ]; if ($type) { return isset($assets[$type]) ? $assets[$type] : null; } return $assets; }
[ "protected", "static", "function", "_assets", "(", "$", "type", "=", "null", ")", "{", "$", "assets", "=", "static", "::", "$", "_assets", "+", "[", "'js'", "=>", "[", "'suffix'", "=>", "'.js'", ",", "'filter'", "=>", "null", ",", "'paths'", "=>", "[...
Helper method to list all asset paths, or the path for a single type. @param string $type The type you wish to get paths for. @return mixed An array of all paths, or a single array of paths for the given type.
[ "Helper", "method", "to", "list", "all", "asset", "paths", "or", "the", "path", "for", "a", "single", "type", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L950-L973
UnionOfRAD/lithium
net/http/Media.php
Media.scope
public static function scope($name = null, Closure $closure = null) { if ($name === null) { return static::$_scope; } if ($closure === null) { $former = static::$_scope; static::$_scope = $name; return $former; } $former = static::$_scope; static::$_scope = $name; call_user_func($closure); static::$_scope = $former; }
php
public static function scope($name = null, Closure $closure = null) { if ($name === null) { return static::$_scope; } if ($closure === null) { $former = static::$_scope; static::$_scope = $name; return $former; } $former = static::$_scope; static::$_scope = $name; call_user_func($closure); static::$_scope = $former; }
[ "public", "static", "function", "scope", "(", "$", "name", "=", "null", ",", "Closure", "$", "closure", "=", "null", ")", "{", "if", "(", "$", "name", "===", "null", ")", "{", "return", "static", "::", "$", "_scope", ";", "}", "if", "(", "$", "cl...
Scope getter/setter. Special use case: If `$closure` is not null executing the closure inside the specified scope. @param string $name Name of the scope to use. @param \Closure $closure A closure to execute inside the scope. @return mixed Returns the previous scope if if `$name` is not null and `$closure` is null, returns the default used scope if `$name` is null, otherwise returns `null`.
[ "Scope", "getter", "/", "setter", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L986-L1001
UnionOfRAD/lithium
net/http/Media.php
Media.attach
public static function attach($name, $config = null) { if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === false) { $name = '__defaultScope__'; } if (is_array($config) || $config === false) { static::$_scopes->set($name, $config); } }
php
public static function attach($name, $config = null) { if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === false) { $name = '__defaultScope__'; } if (is_array($config) || $config === false) { static::$_scopes->set($name, $config); } }
[ "public", "static", "function", "attach", "(", "$", "name", ",", "$", "config", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "static", "::", "$", "_scopes", ")", ")", "{", "static", "::", "_initScopes", "(", ")", ";", "}", "if", "(", "$",...
Attach a scope to a mount point. Example: ``` Media::attach('app', [ 'path' => '/var/www/website/app/webroot/extradir', 'prefix' => 'extradir' ]); ``` ``` Media::attach('cdn', [ 'absolute' => true, 'path' => null, 'host' => 'http://my.cdn.com', 'prefix' => 'project1/assets' ]); ``` ``` Media::attach('cdn', [ 'absolute' => true, 'path' => null, 'host' => ['my.cdn.com', 'secure.cdn.com'], 'scheme' => ['http://', 'https://'], 'prefix' => 'project1/assets', ]); ``` ``` Media::attach('cdn', [ 'absolute' => true, 'path' => null, 'host' => ['my1.cdn.com', 'my2.cdn.com'], 'scheme' => 'http://', 'prefix' => 'project1/assets', ]); ``` @param string $name The name of the media you wish to attach. @param array $config Asset configuration options for the given scope. - `'path'` _string_: Path of the media. - `'prefix'` _string_: Contains the uri prefix. Such as `css`. - `'absolute'` _boolean_: Defaults to `false`. If you want to generate absolute URL's. - `'host'` _mixed_: String host, or array of hosts, of the media, if absolute is `true`. - `'scheme'` _mixed_: String scheme, or array of sc, of the media, if absolute is `true`. @return void
[ "Attach", "a", "scope", "to", "a", "mount", "point", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L1055-L1065
UnionOfRAD/lithium
net/http/Media.php
Media.attached
public static function attached($name = null) { if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === false) { $name = '__defaultScope__'; } return static::$_scopes->get($name); }
php
public static function attached($name = null) { if (!isset(static::$_scopes)) { static::_initScopes(); } if ($name === false) { $name = '__defaultScope__'; } return static::$_scopes->get($name); }
[ "public", "static", "function", "attached", "(", "$", "name", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "static", "::", "$", "_scopes", ")", ")", "{", "static", "::", "_initScopes", "(", ")", ";", "}", "if", "(", "$", "name", "===", "f...
Returns an attached mount point configuration.
[ "Returns", "an", "attached", "mount", "point", "configuration", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/http/Media.php#L1070-L1078
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php._init
protected function _init() { if ($this->isStarted()) { return true; } $config = $this->_config; unset($config['adapter'], $config['strategies'], $config['filters'], $config['init']); foreach ($config as $key => $value) { if (strpos($key, 'session.') === false) { continue; } if (ini_set($key, $value) === false) { throw new ConfigException('Could not initialize the session.'); } } }
php
protected function _init() { if ($this->isStarted()) { return true; } $config = $this->_config; unset($config['adapter'], $config['strategies'], $config['filters'], $config['init']); foreach ($config as $key => $value) { if (strpos($key, 'session.') === false) { continue; } if (ini_set($key, $value) === false) { throw new ConfigException('Could not initialize the session.'); } } }
[ "protected", "function", "_init", "(", ")", "{", "if", "(", "$", "this", "->", "isStarted", "(", ")", ")", "{", "return", "true", ";", "}", "$", "config", "=", "$", "this", "->", "_config", ";", "unset", "(", "$", "config", "[", "'adapter'", "]", ...
Initialization of the session. @todo Split up into an _initialize() and a _start().
[ "Initialization", "of", "the", "session", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L68-L83
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php.check
public function check($key, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { return Set::check($_SESSION, $params['key']); }; }
php
public function check($key, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { return Set::check($_SESSION, $params['key']); }; }
[ "public", "function", "check", "(", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", ")", "&&", "!", "$", "this", "->", "_start", "(", ")", ")", "{", "throw", "new", "Runtim...
Checks if a value has been set in the session. @param string $key Key of the entry to be checked. @param array $options Options array. Not used for this adapter method. @return \Closure Function returning boolean `true` if the key exists, `false` otherwise.
[ "Checks", "if", "a", "value", "has", "been", "set", "in", "the", "session", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L133-L140
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php.read
public function read($key = null, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { $key = $params['key']; if (!$key) { return $_SESSION; } if (strpos($key, '.') === false) { return isset($_SESSION[$key]) ? $_SESSION[$key] : null; } $filter = function($keys, $data) use (&$filter) { $key = array_shift($keys); if (isset($data[$key])) { return (empty($keys)) ? $data[$key] : $filter($keys, $data[$key]); } }; return $filter(explode('.', $key), $_SESSION); }; }
php
public function read($key = null, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { $key = $params['key']; if (!$key) { return $_SESSION; } if (strpos($key, '.') === false) { return isset($_SESSION[$key]) ? $_SESSION[$key] : null; } $filter = function($keys, $data) use (&$filter) { $key = array_shift($keys); if (isset($data[$key])) { return (empty($keys)) ? $data[$key] : $filter($keys, $data[$key]); } }; return $filter(explode('.', $key), $_SESSION); }; }
[ "public", "function", "read", "(", "$", "key", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", ")", "&&", "!", "$", "this", "->", "_start", "(", ")", ")", "{", "throw", ...
Read a value from the session. @param null|string $key Key of the entry to be read. If no key is passed, all current session data is returned. @param array $options Options array. Not used for this adapter method. @return \Closure Function returning data in the session if successful, `false` otherwise.
[ "Read", "a", "value", "from", "the", "session", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L150-L171
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php.write
public function write($key, $value, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { return $this->overwrite( $_SESSION, Set::insert($_SESSION, $params['key'], $params['value']) ); }; }
php
public function write($key, $value, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { return $this->overwrite( $_SESSION, Set::insert($_SESSION, $params['key'], $params['value']) ); }; }
[ "public", "function", "write", "(", "$", "key", ",", "$", "value", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", ")", "&&", "!", "$", "this", "->", "_start", "(", ")", ")", "{", "t...
Write a value to the session. @param string $key Key of the item to be stored. @param mixed $value The value to be stored. @param array $options Options array. Not used for this adapter method. @return \Closure Function returning boolean `true` on successful write, `false` otherwise.
[ "Write", "a", "value", "to", "the", "session", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L181-L190
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php.delete
public function delete($key, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { $key = $params['key']; $this->overwrite($_SESSION, Set::remove($_SESSION, $key)); return !Set::check($_SESSION, $key); }; }
php
public function delete($key, array $options = []) { if (!$this->isStarted() && !$this->_start()) { throw new RuntimeException('Could not start session.'); } return function($params) { $key = $params['key']; $this->overwrite($_SESSION, Set::remove($_SESSION, $key)); return !Set::check($_SESSION, $key); }; }
[ "public", "function", "delete", "(", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "isStarted", "(", ")", "&&", "!", "$", "this", "->", "_start", "(", ")", ")", "{", "throw", "new", "Runti...
Delete value from the session @param string $key The key to be deleted. @param array $options Options array. Not used for this adapter method. @return \Closure Function returning boolean `true` if the key no longer exists in the session, `false` otherwise
[ "Delete", "value", "from", "the", "session" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L200-L209
UnionOfRAD/lithium
storage/session/adapter/Php.php
Php.overwrite
public function overwrite(&$old, $new) { if (!empty($old)) { foreach ($old as $key => $value) { if (!isset($new[$key])) { unset($old[$key]); } } } foreach ($new as $key => $value) { $old[$key] = $value; } return true; }
php
public function overwrite(&$old, $new) { if (!empty($old)) { foreach ($old as $key => $value) { if (!isset($new[$key])) { unset($old[$key]); } } } foreach ($new as $key => $value) { $old[$key] = $value; } return true; }
[ "public", "function", "overwrite", "(", "&", "$", "old", ",", "$", "new", ")", "{", "if", "(", "!", "empty", "(", "$", "old", ")", ")", "{", "foreach", "(", "$", "old", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", ...
Overwrites session keys and values. @param array $old Reference to the array that needs to be overwritten. Will usually be `$_SESSION`. @param array $new The data that should overwrite the keys/values in `$old`. @return boolean Always `true`.
[ "Overwrites", "session", "keys", "and", "values", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/session/adapter/Php.php#L247-L259