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/source/Database.php
Database.read
public function read($query, array $options = []) { $defaults = [ 'return' => is_string($query) ? 'array' : 'item', 'schema' => null, 'quotes' => $this->_quotes ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $args = $params['options']; $return = $args['return']; unset($args['return']); $model = is_object($query) ? $query->model() : null; if (is_string($query)) { $sql = Text::insert($query, $this->value($args)); } else { if (!$data = $this->_queryExport($query)) { return false; } $sql = $this->renderCommand($data['type'], $data); } $result = $this->_execute($sql); if ($return === 'resource') { return $result; } if ($return === 'item') { return $model::create([], compact('query', 'result') + [ 'class' => 'set', 'defaults' => false ]); } $columns = $args['schema'] ?: $this->schema($query, $result); if (!is_array(reset($columns))) { $columns = ['' => $columns]; } $i = 0; $records = []; foreach ($result as $data) { $offset = 0; $records[$i] = []; foreach ($columns as $path => $cols) { $len = count($cols); $values = array_combine($cols, array_slice($data, $offset, $len)); ($path) ? $records[$i][$path] = $values : $records[$i] += $values; $offset += $len; } $i++; } return Set::expand($records); }); }
php
public function read($query, array $options = []) { $defaults = [ 'return' => is_string($query) ? 'array' : 'item', 'schema' => null, 'quotes' => $this->_quotes ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $args = $params['options']; $return = $args['return']; unset($args['return']); $model = is_object($query) ? $query->model() : null; if (is_string($query)) { $sql = Text::insert($query, $this->value($args)); } else { if (!$data = $this->_queryExport($query)) { return false; } $sql = $this->renderCommand($data['type'], $data); } $result = $this->_execute($sql); if ($return === 'resource') { return $result; } if ($return === 'item') { return $model::create([], compact('query', 'result') + [ 'class' => 'set', 'defaults' => false ]); } $columns = $args['schema'] ?: $this->schema($query, $result); if (!is_array(reset($columns))) { $columns = ['' => $columns]; } $i = 0; $records = []; foreach ($result as $data) { $offset = 0; $records[$i] = []; foreach ($columns as $path => $cols) { $len = count($cols); $values = array_combine($cols, array_slice($data, $offset, $len)); ($path) ? $records[$i][$path] = $values : $records[$i] += $values; $offset += $len; } $i++; } return Set::expand($records); }); }
[ "public", "function", "read", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'return'", "=>", "is_string", "(", "$", "query", ")", "?", "'array'", ":", "'item'", ",", "'schema'", "=>", "null", ...
Reads records from a database using a `lithium\data\model\Query` object or raw SQL string. @param string|object $query `lithium\data\model\Query` object or SQL string. @param array $options If `$query` is a raw string, contains the values that will be escaped and quoted. Other options: - `'return'` _string_: switch return between `'array'`, `'item'`, or `'resource'` _string_: Defaults to `'item'`. @return mixed Determined by `$options['return']`. @filter
[ "Reads", "records", "from", "a", "database", "using", "a", "lithium", "\\", "data", "\\", "model", "\\", "Query", "object", "or", "raw", "SQL", "string", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L573-L632
UnionOfRAD/lithium
data/source/Database.php
Database.&
protected function &_queryExport($query) { $data = $query->export($this); if (!$query->limit() || !($model = $query->model())) { return $data; } foreach ($query->relationships() as $relation) { if ($relation['type'] !== 'hasMany') { continue; } $pk = $this->name($model::meta('name') . '.' . $model::key()); $result = $this->_execute($this->renderCommand('read', [ 'fields' => "DISTINCT({$pk}) AS _ID_"] + $data )); $ids = []; foreach ($result as $row) { $ids[] = $row[0]; } if (!$ids) { $data = null; break; } $conditions = []; $relations = array_keys($query->relationships()); $pattern = '/^(' . implode('|', $relations) . ')\./'; foreach ($query->conditions() as $key => $value) { if (preg_match($pattern, $key)) { $conditions[$key] = $value; } } $data['conditions'] = $this->conditions( [$pk => $ids] + $conditions, $query ); $data['limit'] = ''; break; } return $data; }
php
protected function &_queryExport($query) { $data = $query->export($this); if (!$query->limit() || !($model = $query->model())) { return $data; } foreach ($query->relationships() as $relation) { if ($relation['type'] !== 'hasMany') { continue; } $pk = $this->name($model::meta('name') . '.' . $model::key()); $result = $this->_execute($this->renderCommand('read', [ 'fields' => "DISTINCT({$pk}) AS _ID_"] + $data )); $ids = []; foreach ($result as $row) { $ids[] = $row[0]; } if (!$ids) { $data = null; break; } $conditions = []; $relations = array_keys($query->relationships()); $pattern = '/^(' . implode('|', $relations) . ')\./'; foreach ($query->conditions() as $key => $value) { if (preg_match($pattern, $key)) { $conditions[$key] = $value; } } $data['conditions'] = $this->conditions( [$pk => $ids] + $conditions, $query ); $data['limit'] = ''; break; } return $data; }
[ "protected", "function", "&", "_queryExport", "(", "$", "query", ")", "{", "$", "data", "=", "$", "query", "->", "export", "(", "$", "this", ")", ";", "if", "(", "!", "$", "query", "->", "limit", "(", ")", "||", "!", "(", "$", "model", "=", "$"...
Helper method for `Database::read()` to export query while handling additional joins when using relationships and limited result sets. Filters conditions on subsequent queries to just the ones applying to the relation. @see lithium\data\source\Database::read() @param object $query The query object. @return array The exported query returned by reference.
[ "Helper", "method", "for", "Database", "::", "read", "()", "to", "export", "query", "while", "handling", "additional", "joins", "when", "using", "relationships", "and", "limited", "result", "sets", ".", "Filters", "conditions", "on", "subsequent", "queries", "to...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L643-L685
UnionOfRAD/lithium
data/source/Database.php
Database.update
public function update($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $exportedQuery = $query->export($this); if ($exportedQuery['fields'] === null) { return true; } $sql = $this->renderCommand('update', $exportedQuery, $query); $result = (boolean) $this->_execute($sql); if ($result && is_object($query) && $query->entity()) { $query->entity()->sync(); } return $result; }); }
php
public function update($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $exportedQuery = $query->export($this); if ($exportedQuery['fields'] === null) { return true; } $sql = $this->renderCommand('update', $exportedQuery, $query); $result = (boolean) $this->_execute($sql); if ($result && is_object($query) && $query->entity()) { $query->entity()->sync(); } return $result; }); }
[ "public", "function", "update", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "params", "=", "compact", "(", "'query'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ",", "__FUNCTION_...
Updates a record in the database based on the given `Query`. @param object $query A `lithium\data\model\Query` object @param array $options none @return boolean @filter
[ "Updates", "a", "record", "in", "the", "database", "based", "on", "the", "given", "Query", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L695-L714
UnionOfRAD/lithium
data/source/Database.php
Database.delete
public function delete($query, array $options = []) { $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $query = $params['query']; $isObject = is_object($query); if ($isObject) { $sql = $this->renderCommand('delete', $query->export($this), $query); } else { $sql = Text::insert($query, $this->value($params['options'])); } $result = (boolean) $this->_execute($sql); if ($result && $isObject && $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']; $isObject = is_object($query); if ($isObject) { $sql = $this->renderCommand('delete', $query->export($this), $query); } else { $sql = Text::insert($query, $this->value($params['options'])); } $result = (boolean) $this->_execute($sql); if ($result && $isObject && $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_...
Deletes a record in the database based on the given `Query`. @param object $query An SQL string, or `lithium\data\model\Query` object instance. @param array $options If `$query` is a string, `$options` is the array of quoted/escaped parameter values to be inserted into the query. @return boolean Returns `true` on successful query execution (not necessarily if records are deleted), otherwise `false`. @filter
[ "Deletes", "a", "record", "in", "the", "database", "based", "on", "the", "given", "Query", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L726-L745
UnionOfRAD/lithium
data/source/Database.php
Database.calculation
public function calculation($type, $query, array $options = []) { $query->calculate($type); switch ($type) { case 'count': if (strpos($fields = $this->fields($query->fields(), $query), ',') !== false) { $fields = "*"; } $query->fields("COUNT({$fields}) as count", true); $query->map([$query->alias() => ['count']]); $result = $this->read($query, $options)->data(); if (!$result || !isset($result[0]['count'])) { return null; } return (integer) $result[0]['count']; } }
php
public function calculation($type, $query, array $options = []) { $query->calculate($type); switch ($type) { case 'count': if (strpos($fields = $this->fields($query->fields(), $query), ',') !== false) { $fields = "*"; } $query->fields("COUNT({$fields}) as count", true); $query->map([$query->alias() => ['count']]); $result = $this->read($query, $options)->data(); if (!$result || !isset($result[0]['count'])) { return null; } return (integer) $result[0]['count']; } }
[ "public", "function", "calculation", "(", "$", "type", ",", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "query", "->", "calculate", "(", "$", "type", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'count'", ...
Executes calculation-related queries, such as those required for `count` and other aggregates. When building `count` queries and a single field is given, will use that to build the `COUNT()` fragment. When multiple fields are given forces a `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|null Result of the calculation or `null` if the calculation failed.
[ "Executes", "calculation", "-", "related", "queries", "such", "as", "those", "required", "for", "count", "and", "other", "aggregates", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L760-L778
UnionOfRAD/lithium
data/source/Database.php
Database.relationship
public function relationship($class, $type, $name, array $config = []) { $primary = $class::meta('key'); if (is_array($primary)) { $key = array_combine($primary, $primary); } elseif ($type === 'hasMany' || $type === 'hasOne') { $secondary = Inflector::underscore(Inflector::singularize($class::meta('name'))); $key = [$primary => "{$secondary}_id"]; } else { $key = Inflector::underscore(Inflector::singularize($name)) . '_id'; } $from = $class; $fieldName = $this->relationFieldName($type, $name); $config += compact('type', 'name', 'key', 'from', 'fieldName'); return $this->_instance('relationship', $config); }
php
public function relationship($class, $type, $name, array $config = []) { $primary = $class::meta('key'); if (is_array($primary)) { $key = array_combine($primary, $primary); } elseif ($type === 'hasMany' || $type === 'hasOne') { $secondary = Inflector::underscore(Inflector::singularize($class::meta('name'))); $key = [$primary => "{$secondary}_id"]; } else { $key = Inflector::underscore(Inflector::singularize($name)) . '_id'; } $from = $class; $fieldName = $this->relationFieldName($type, $name); $config += compact('type', 'name', 'key', 'from', 'fieldName'); return $this->_instance('relationship', $config); }
[ "public", "function", "relationship", "(", "$", "class", ",", "$", "type", ",", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "$", "primary", "=", "$", "class", "::", "meta", "(", "'key'", ")", ";", "if", "(", "is_array", "("...
Defines or modifies the default settings of a relationship between two models. @param string $class the primary model of the relationship @param string $type the type of the relationship (hasMany, hasOne, belongsTo) @param string $name the name of the relationship @param array $config relationship options @return array Returns an array containing the configuration for a model relationship.
[ "Defines", "or", "modifies", "the", "default", "settings", "of", "a", "relationship", "between", "two", "models", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L789-L805
UnionOfRAD/lithium
data/source/Database.php
Database.renderCommand
public function renderCommand($type, $data = null, $context = null) { if (is_object($type)) { $context = $type; $data = $context->export($this); $type = $context->type(); } if (!isset($this->_strings[$type])) { throw new InvalidArgumentException("Invalid query type `{$type}`."); } $template = $this->_strings[$type]; $data = array_filter($data); $placeholders = []; foreach ($data as $key => $value) { $placeholders[$key] = "{{$key}}"; } $template = Text::insert($template, $placeholders, ['clean' => true]); return trim(Text::insert($template, $data, ['before' => '{'])); }
php
public function renderCommand($type, $data = null, $context = null) { if (is_object($type)) { $context = $type; $data = $context->export($this); $type = $context->type(); } if (!isset($this->_strings[$type])) { throw new InvalidArgumentException("Invalid query type `{$type}`."); } $template = $this->_strings[$type]; $data = array_filter($data); $placeholders = []; foreach ($data as $key => $value) { $placeholders[$key] = "{{$key}}"; } $template = Text::insert($template, $placeholders, ['clean' => true]); return trim(Text::insert($template, $data, ['before' => '{'])); }
[ "public", "function", "renderCommand", "(", "$", "type", ",", "$", "data", "=", "null", ",", "$", "context", "=", "null", ")", "{", "if", "(", "is_object", "(", "$", "type", ")", ")", "{", "$", "context", "=", "$", "type", ";", "$", "data", "=", ...
Returns a given `type` statement for the given data, rendered from `Database::$_strings`. @param string $type One of `'create'`, `'read'`, `'update'`, `'delete'` or `'join'`. @param string $data The data to replace in the string. @param string $context @return string
[ "Returns", "a", "given", "type", "statement", "for", "the", "given", "data", "rendered", "from", "Database", "::", "$_strings", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L827-L844
UnionOfRAD/lithium
data/source/Database.php
Database.schema
public function schema($query, $resource = null, $context = null) { if (is_object($query)) { $query->applyStrategy($this); return $this->_schema($query, $this->_fields($query->fields(), $query)); } $result = []; if (!$resource || !$resource->resource()) { return $result; } $count = $resource->resource()->columnCount(); for ($i = 0; $i < $count; $i++) { $meta = $resource->resource()->getColumnMeta($i); $result[] = $meta['name']; } return $result; }
php
public function schema($query, $resource = null, $context = null) { if (is_object($query)) { $query->applyStrategy($this); return $this->_schema($query, $this->_fields($query->fields(), $query)); } $result = []; if (!$resource || !$resource->resource()) { return $result; } $count = $resource->resource()->columnCount(); for ($i = 0; $i < $count; $i++) { $meta = $resource->resource()->getColumnMeta($i); $result[] = $meta['name']; } return $result; }
[ "public", "function", "schema", "(", "$", "query", ",", "$", "resource", "=", "null", ",", "$", "context", "=", "null", ")", "{", "if", "(", "is_object", "(", "$", "query", ")", ")", "{", "$", "query", "->", "applyStrategy", "(", "$", "this", ")", ...
Builds an array of keyed on the fully-namespaced `Model` with array of fields as values for the given `Query` @param \lithium\data\model\Query $query A Query instance. @param \lithium\data\source\Result|null $resource An optional a result resource. @param object|null $context @return array
[ "Builds", "an", "array", "of", "keyed", "on", "the", "fully", "-", "namespaced", "Model", "with", "array", "of", "fields", "as", "values", "for", "the", "given", "Query" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L855-L872
UnionOfRAD/lithium
data/source/Database.php
Database._schema
protected function _schema($query, $fields = null) { $model = $query->model(); $paths = $query->paths($this); $models = $query->models($this); $alias = $query->alias(); $result = []; if (!$model) { foreach ($fields as $field => $value) { if (is_array($value)) { $result[$field] = array_keys($value); } else { $result[''][] = $field; } } return $result; } if (!$fields) { foreach ($paths as $alias => $relation) { $model = $models[$alias]; $result[$relation] = $model::schema()->names(); } return $result; } $unalias = function ($value) { if (is_object($value) && isset($value->scalar)) { $value = $value->scalar; } $aliasing = preg_split("/\s+as\s+/i", $value); return isset($aliasing[1]) ? $aliasing[1] : $value; }; if (isset($fields[0])) { $raw = array_map($unalias, $fields[0]); unset($fields[0]); } $fields = isset($fields[$alias]) ? [$alias => $fields[$alias]] + $fields : $fields; foreach ($fields as $field => $value) { if (is_array($value)) { if (isset($value['*'])) { $relModel = $models[$field]; $result[$paths[$field]] = $relModel::schema()->names(); } else { $result[$paths[$field]] = array_map($unalias, array_keys($value)); } } } if (isset($raw)) { $result[''] = isset($result['']) ? array_merge($raw, $result['']) : $raw; } return $result; }
php
protected function _schema($query, $fields = null) { $model = $query->model(); $paths = $query->paths($this); $models = $query->models($this); $alias = $query->alias(); $result = []; if (!$model) { foreach ($fields as $field => $value) { if (is_array($value)) { $result[$field] = array_keys($value); } else { $result[''][] = $field; } } return $result; } if (!$fields) { foreach ($paths as $alias => $relation) { $model = $models[$alias]; $result[$relation] = $model::schema()->names(); } return $result; } $unalias = function ($value) { if (is_object($value) && isset($value->scalar)) { $value = $value->scalar; } $aliasing = preg_split("/\s+as\s+/i", $value); return isset($aliasing[1]) ? $aliasing[1] : $value; }; if (isset($fields[0])) { $raw = array_map($unalias, $fields[0]); unset($fields[0]); } $fields = isset($fields[$alias]) ? [$alias => $fields[$alias]] + $fields : $fields; foreach ($fields as $field => $value) { if (is_array($value)) { if (isset($value['*'])) { $relModel = $models[$field]; $result[$paths[$field]] = $relModel::schema()->names(); } else { $result[$paths[$field]] = array_map($unalias, array_keys($value)); } } } if (isset($raw)) { $result[''] = isset($result['']) ? array_merge($raw, $result['']) : $raw; } return $result; }
[ "protected", "function", "_schema", "(", "$", "query", ",", "$", "fields", "=", "null", ")", "{", "$", "model", "=", "$", "query", "->", "model", "(", ")", ";", "$", "paths", "=", "$", "query", "->", "paths", "(", "$", "this", ")", ";", "$", "m...
Helper method for `data\model\Database::shema()` @param \lithium\data\model\Query $query A Query instance. @param array|null $fields Array of formatted fields. @return array
[ "Helper", "method", "for", "data", "\\", "model", "\\", "Database", "::", "shema", "()" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L881-L936
UnionOfRAD/lithium
data/source/Database.php
Database.conditions
public function conditions($conditions, $context, array $options = []) { $defaults = ['prepend' => 'WHERE']; $options += $defaults; return $this->_conditions($conditions, $context, $options); }
php
public function conditions($conditions, $context, array $options = []) { $defaults = ['prepend' => 'WHERE']; $options += $defaults; return $this->_conditions($conditions, $context, $options); }
[ "public", "function", "conditions", "(", "$", "conditions", ",", "$", "context", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'prepend'", "=>", "'WHERE'", "]", ";", "$", "options", "+=", "$", "defaults", ";", "re...
Returns a string of formatted conditions to be inserted into the query statement. If the query conditions are defined as an array, key pairs are converted to SQL strings. Conversion rules are as follows: - If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL fragment and returned. @param string|array $conditions The conditions for this query. @param object $context The current `lithium\data\model\Query` instance. @param array $options Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `'WHERE'`. @return string Returns the `WHERE` clause of an SQL query.
[ "Returns", "a", "string", "of", "formatted", "conditions", "to", "be", "inserted", "into", "the", "query", "statement", ".", "If", "the", "query", "conditions", "are", "defined", "as", "an", "array", "key", "pairs", "are", "converted", "to", "SQL", "strings"...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L954-L958
UnionOfRAD/lithium
data/source/Database.php
Database._conditions
protected function _conditions($conditions, $context, array $options = []) { $defaults = ['prepend' => false]; $options += $defaults; switch (true) { case empty($conditions): return ''; case is_string($conditions): return $options['prepend'] ? $options['prepend'] . " {$conditions}" : $conditions; case !is_array($conditions): return ''; } $result = []; foreach ($conditions as $key => $value) { $return = $this->_processConditions($key, $value, $context); if ($return) { $result[] = $return; } } $result = join(" AND ", $result); return ($options['prepend'] && $result) ? $options['prepend'] . " {$result}" : $result; }
php
protected function _conditions($conditions, $context, array $options = []) { $defaults = ['prepend' => false]; $options += $defaults; switch (true) { case empty($conditions): return ''; case is_string($conditions): return $options['prepend'] ? $options['prepend'] . " {$conditions}" : $conditions; case !is_array($conditions): return ''; } $result = []; foreach ($conditions as $key => $value) { $return = $this->_processConditions($key, $value, $context); if ($return) { $result[] = $return; } } $result = join(" AND ", $result); return ($options['prepend'] && $result) ? $options['prepend'] . " {$result}" : $result; }
[ "protected", "function", "_conditions", "(", "$", "conditions", ",", "$", "context", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'prepend'", "=>", "false", "]", ";", "$", "options", "+=", "$", "defaults", ";", "...
Returns a string of formatted conditions to be inserted into the query statement. If the query conditions are defined as an array, key pairs are converted to SQL strings. If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL fragment and returned. @param string|array $conditions The conditions for this query. @param object $context The current `lithium\data\model\Query` instance. @param array $options Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `false`. @return string Returns an SQL conditions clause.
[ "Returns", "a", "string", "of", "formatted", "conditions", "to", "be", "inserted", "into", "the", "query", "statement", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L996-L1019
UnionOfRAD/lithium
data/source/Database.php
Database._processOperator
protected function _processOperator($key, $value, $fieldMeta, $glue) { if (!is_string($key) || !is_array($value)) { return false; } $operator = strtoupper(key($value)); if (!is_numeric($operator)) { if (!isset($this->_operators[$operator])) { throw new QueryException("Unsupported operator `{$operator}`."); } foreach ($value as $op => $val) { $result[] = $this->_operator($key, [$op => $val], $fieldMeta); } return '(' . implode(' ' . $glue . ' ', $result) . ')'; } return false; }
php
protected function _processOperator($key, $value, $fieldMeta, $glue) { if (!is_string($key) || !is_array($value)) { return false; } $operator = strtoupper(key($value)); if (!is_numeric($operator)) { if (!isset($this->_operators[$operator])) { throw new QueryException("Unsupported operator `{$operator}`."); } foreach ($value as $op => $val) { $result[] = $this->_operator($key, [$op => $val], $fieldMeta); } return '(' . implode(' ' . $glue . ' ', $result) . ')'; } return false; }
[ "protected", "function", "_processOperator", "(", "$", "key", ",", "$", "value", ",", "$", "fieldMeta", ",", "$", "glue", ")", "{", "if", "(", "!", "is_string", "(", "$", "key", ")", "||", "!", "is_array", "(", "$", "value", ")", ")", "{", "return"...
Helper method used by `_processConditions`. @param string The field name string. @param array The operator to parse. @param array The schema of the field. @param string The glue operator (e.g `'AND'` or '`OR`'. @return mixed Returns the operator expression string or `false` if no operator is applicable. @throws A `QueryException` if the operator is not supported.
[ "Helper", "method", "used", "by", "_processConditions", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1085-L1100
UnionOfRAD/lithium
data/source/Database.php
Database.fields
public function fields($fields, $context) { $type = $context->type(); $schema = $context->schema()->fields(); $alias = $context->alias(); if (!is_array($fields)) { return $this->_fieldsReturn($type, $context, $fields, $schema); } $context->applyStrategy($this); $fields = $this->_fields($fields ? : $context->fields(), $context); $context->map($this->_schema($context, $fields)); $toMerge = []; if (isset($fields[0])) { foreach ($fields[0] as $val) { $toMerge[] = (is_object($val) && isset($val->scalar)) ? $val->scalar : $val; } unset($fields[0]); } $fields = isset($fields[$alias]) ? [$alias => $fields[$alias]] + $fields : $fields; foreach ($fields as $field => $value) { if (is_array($value)) { if (isset($value['*'])) { $toMerge[] = $this->name($field) . '.*'; continue; } foreach ($value as $fieldname => $mode) { $toMerge[] = $this->_fieldsQuote($field, $fieldname); } } } return $this->_fieldsReturn($type, $context, $toMerge, $schema); }
php
public function fields($fields, $context) { $type = $context->type(); $schema = $context->schema()->fields(); $alias = $context->alias(); if (!is_array($fields)) { return $this->_fieldsReturn($type, $context, $fields, $schema); } $context->applyStrategy($this); $fields = $this->_fields($fields ? : $context->fields(), $context); $context->map($this->_schema($context, $fields)); $toMerge = []; if (isset($fields[0])) { foreach ($fields[0] as $val) { $toMerge[] = (is_object($val) && isset($val->scalar)) ? $val->scalar : $val; } unset($fields[0]); } $fields = isset($fields[$alias]) ? [$alias => $fields[$alias]] + $fields : $fields; foreach ($fields as $field => $value) { if (is_array($value)) { if (isset($value['*'])) { $toMerge[] = $this->name($field) . '.*'; continue; } foreach ($value as $fieldname => $mode) { $toMerge[] = $this->_fieldsQuote($field, $fieldname); } } } return $this->_fieldsReturn($type, $context, $toMerge, $schema); }
[ "public", "function", "fields", "(", "$", "fields", ",", "$", "context", ")", "{", "$", "type", "=", "$", "context", "->", "type", "(", ")", ";", "$", "schema", "=", "$", "context", "->", "schema", "(", ")", "->", "fields", "(", ")", ";", "$", ...
Returns a string of formatted fields to be inserted into the query statement. @param array $fields Array of fields. @param object $context Generally a `data\model\Query` instance. @return string A SQL formatted string
[ "Returns", "a", "string", "of", "formatted", "fields", "to", "be", "inserted", "into", "the", "query", "statement", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1109-L1145
UnionOfRAD/lithium
data/source/Database.php
Database._fields
protected function _fields($fields, $context) { $alias = $context->alias(); $models = $context->models($this); $list = []; foreach ($fields as $key => $field) { if (!is_string($field)) { if (isset($models[$key])) { $field = array_fill_keys($field, true); $list[$key] = isset($list[$key]) ? array_merge($list[$key], $field) : $field; } else { $list[0][] = is_array($field) ? reset($field) : $field; } continue; } if (preg_match('/^([a-z0-9_-]+|\*)$/i', $field)) { isset($models[$field]) ? $list[$field]['*'] = true : $list[$alias][$field] = true; } elseif (preg_match('/^([a-z0-9_-]+)\.(.*)$/i', $field, $matches)) { $list[$matches[1]][$matches[2]] = true; } else { $list[0][] = $field; } } return $list; }
php
protected function _fields($fields, $context) { $alias = $context->alias(); $models = $context->models($this); $list = []; foreach ($fields as $key => $field) { if (!is_string($field)) { if (isset($models[$key])) { $field = array_fill_keys($field, true); $list[$key] = isset($list[$key]) ? array_merge($list[$key], $field) : $field; } else { $list[0][] = is_array($field) ? reset($field) : $field; } continue; } if (preg_match('/^([a-z0-9_-]+|\*)$/i', $field)) { isset($models[$field]) ? $list[$field]['*'] = true : $list[$alias][$field] = true; } elseif (preg_match('/^([a-z0-9_-]+)\.(.*)$/i', $field, $matches)) { $list[$matches[1]][$matches[2]] = true; } else { $list[0][] = $field; } } return $list; }
[ "protected", "function", "_fields", "(", "$", "fields", ",", "$", "context", ")", "{", "$", "alias", "=", "$", "context", "->", "alias", "(", ")", ";", "$", "models", "=", "$", "context", "->", "models", "(", "$", "this", ")", ";", "$", "list", "...
Reformats fields to be alias based. @see lithium\data\source\Database::fields() @see lithium\data\source\Database::schema() @param array $fields Array of fields. @param object $context Generally a `data\model\Query` instance. @return array Reformatted fields
[ "Reformats", "fields", "to", "be", "alias", "based", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1156-L1180
UnionOfRAD/lithium
data/source/Database.php
Database._fieldsQuote
protected function _fieldsQuote($alias, $field) { list($open, $close) = $this->_quotes; $aliasing = preg_split("/\s+as\s+/i", $field); if (isset($aliasing[1])) { list($aliasname, $fieldname) = $this->_splitFieldname($aliasing[0]); $alias = $aliasname ? : $alias; return "{$open}{$alias}{$close}.{$open}{$fieldname}{$close} as {$aliasing[1]}"; } elseif ($alias) { return "{$open}{$alias}{$close}.{$open}{$field}{$close}"; } else { return "{$open}{$field}{$close}"; } }
php
protected function _fieldsQuote($alias, $field) { list($open, $close) = $this->_quotes; $aliasing = preg_split("/\s+as\s+/i", $field); if (isset($aliasing[1])) { list($aliasname, $fieldname) = $this->_splitFieldname($aliasing[0]); $alias = $aliasname ? : $alias; return "{$open}{$alias}{$close}.{$open}{$fieldname}{$close} as {$aliasing[1]}"; } elseif ($alias) { return "{$open}{$alias}{$close}.{$open}{$field}{$close}"; } else { return "{$open}{$field}{$close}"; } }
[ "protected", "function", "_fieldsQuote", "(", "$", "alias", ",", "$", "field", ")", "{", "list", "(", "$", "open", ",", "$", "close", ")", "=", "$", "this", "->", "_quotes", ";", "$", "aliasing", "=", "preg_split", "(", "\"/\\s+as\\s+/i\"", ",", "$", ...
Quotes fields, also handles aliased fields. @see lithium\data\source\Database::fields() @param string $alias @param string $field @return string The quoted field.
[ "Quotes", "fields", "also", "handles", "aliased", "fields", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1190-L1203
UnionOfRAD/lithium
data/source/Database.php
Database._fieldsReturn
protected function _fieldsReturn($type, $context, $fields, $schema) { if ($type === 'create' || $type === 'update') { $data = $context->data(); if (isset($data['data']) && is_array($data['data']) && count($data) === 1) { $data = $data['data']; } if ($fields && is_array($fields) && is_int(key($fields))) { $data = array_intersect_key($data, array_combine($fields, $fields)); } $method = "_{$type}Fields"; return $this->{$method}($data, $schema, $context); } return empty($fields) ? '*' : join(', ', $fields); }
php
protected function _fieldsReturn($type, $context, $fields, $schema) { if ($type === 'create' || $type === 'update') { $data = $context->data(); if (isset($data['data']) && is_array($data['data']) && count($data) === 1) { $data = $data['data']; } if ($fields && is_array($fields) && is_int(key($fields))) { $data = array_intersect_key($data, array_combine($fields, $fields)); } $method = "_{$type}Fields"; return $this->{$method}($data, $schema, $context); } return empty($fields) ? '*' : join(', ', $fields); }
[ "protected", "function", "_fieldsReturn", "(", "$", "type", ",", "$", "context", ",", "$", "fields", ",", "$", "schema", ")", "{", "if", "(", "$", "type", "===", "'create'", "||", "$", "type", "===", "'update'", ")", "{", "$", "data", "=", "$", "co...
Renders the fields SQL fragment for queries. @see lithium\data\source\Database::fields() @param string $type Type of query i.e. `'create'` or `'update'`. @param object $context Generally a `data\model\Query` instance. @param array $fields @param array $schema An array defining the schema of the fields used in the criteria. @return string|array|null
[ "Renders", "the", "fields", "SQL", "fragment", "for", "queries", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1215-L1229
UnionOfRAD/lithium
data/source/Database.php
Database._createFields
protected function _createFields($data, $schema, $context) { $fields = []; $values = []; foreach ($data as $field => $value) { $fields[] = $this->name($field); $values[] = $this->value($value, isset($schema[$field]) ? $schema[$field] : []); } return [ 'fields' => join(', ', $fields), 'values' => join(', ', $values) ]; }
php
protected function _createFields($data, $schema, $context) { $fields = []; $values = []; foreach ($data as $field => $value) { $fields[] = $this->name($field); $values[] = $this->value($value, isset($schema[$field]) ? $schema[$field] : []); } return [ 'fields' => join(', ', $fields), 'values' => join(', ', $values) ]; }
[ "protected", "function", "_createFields", "(", "$", "data", ",", "$", "schema", ",", "$", "context", ")", "{", "$", "fields", "=", "[", "]", ";", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "field", "=>", "$", "valu...
Renders the fields part for _create_ queries. @see lithium\data\source\Database::_fieldsReturn() @param array $data @param array $schema An array defining the schema of the fields used in the criteria. @param object $context Generally a `data\model\Query` instance. @return array Array with `fields` and `values` keys which hold SQL fragments of fields an values separated by comma.
[ "Renders", "the", "fields", "part", "for", "_create_", "queries", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1241-L1253
UnionOfRAD/lithium
data/source/Database.php
Database._updateFields
protected function _updateFields($data, $schema, $context) { $fields = []; $increment = []; if ($entity = $context->entity()) { $export = $entity->export(); $increment = $export['increment']; array_map(function($key) use (&$data, $export){ if (!empty($data[$key]) && $export['data'][$key] === $data[$key]) { unset($data[$key]); } }, array_keys($export['data'])); if (!$data) { return null; } } foreach ($data as $field => $value) { $schema += [$field => ['default' => null]]; $name = $this->name($field); if (isset($increment[$field])) { $fields[] = $name . ' = ' . $name . ' + ' . $this->value($increment[$field], $schema[$field]); } else { $fields[] = $name . ' = ' . $this->value($value, $schema[$field]); } } return join(', ', $fields); }
php
protected function _updateFields($data, $schema, $context) { $fields = []; $increment = []; if ($entity = $context->entity()) { $export = $entity->export(); $increment = $export['increment']; array_map(function($key) use (&$data, $export){ if (!empty($data[$key]) && $export['data'][$key] === $data[$key]) { unset($data[$key]); } }, array_keys($export['data'])); if (!$data) { return null; } } foreach ($data as $field => $value) { $schema += [$field => ['default' => null]]; $name = $this->name($field); if (isset($increment[$field])) { $fields[] = $name . ' = ' . $name . ' + ' . $this->value($increment[$field], $schema[$field]); } else { $fields[] = $name . ' = ' . $this->value($value, $schema[$field]); } } return join(', ', $fields); }
[ "protected", "function", "_updateFields", "(", "$", "data", ",", "$", "schema", ",", "$", "context", ")", "{", "$", "fields", "=", "[", "]", ";", "$", "increment", "=", "[", "]", ";", "if", "(", "$", "entity", "=", "$", "context", "->", "entity", ...
Renders the fields part for _update_ queries. Will only include fields if they have been updated in the entity of the context. Also handles correct incremented/decremented fields. @see lithium\data\Entity::increment() @see lithium\data\source\Database::_fieldsReturn() @param array $data @param array $schema An array defining the schema of the fields used in the criteria. @param object $context Generally a `data\model\Query` instance. @return string|null SQL fragment, with fields separated by comma. Null when the fields haven't been changed.
[ "Renders", "the", "fields", "part", "for", "_update_", "queries", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1269-L1299
UnionOfRAD/lithium
data/source/Database.php
Database.joins
public function joins(array $joins, $context) { $result = null; foreach ($joins as $key => $join) { if ($result) { $result .= ' '; } $join = is_array($join) ? $this->_instance('query', $join) : $join; $options['keys'] = ['mode', 'source', 'alias', 'constraints']; $result .= $this->renderCommand('join', $join->export($this, $options)); } return $result; }
php
public function joins(array $joins, $context) { $result = null; foreach ($joins as $key => $join) { if ($result) { $result .= ' '; } $join = is_array($join) ? $this->_instance('query', $join) : $join; $options['keys'] = ['mode', 'source', 'alias', 'constraints']; $result .= $this->renderCommand('join', $join->export($this, $options)); } return $result; }
[ "public", "function", "joins", "(", "array", "$", "joins", ",", "$", "context", ")", "{", "$", "result", "=", "null", ";", "foreach", "(", "$", "joins", "as", "$", "key", "=>", "$", "join", ")", "{", "if", "(", "$", "result", ")", "{", "$", "re...
Returns a join statement for given array of query objects @param object|array $joins A single or array of `lithium\data\model\Query` objects @param \lithium\data\model\Query $context @return string
[ "Returns", "a", "join", "statement", "for", "given", "array", "of", "query", "objects" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1325-L1337
UnionOfRAD/lithium
data/source/Database.php
Database.constraints
public function constraints($constraints, $context, array $options = []) { $defaults = ['prepend' => 'ON']; $options += $defaults; if (is_array($constraints)) { $constraints = $this->_constraints($constraints); } return $this->_conditions($constraints, $context, $options); }
php
public function constraints($constraints, $context, array $options = []) { $defaults = ['prepend' => 'ON']; $options += $defaults; if (is_array($constraints)) { $constraints = $this->_constraints($constraints); } return $this->_conditions($constraints, $context, $options); }
[ "public", "function", "constraints", "(", "$", "constraints", ",", "$", "context", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'prepend'", "=>", "'ON'", "]", ";", "$", "options", "+=", "$", "defaults", ";", "if"...
Returns a string of formatted constraints to be inserted into the query statement. If the query constraints are defined as an array, key pairs are converted to SQL strings. If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL fragment and returned. @param string|array $constraints The constraints for a `ON` clause. @param \lithium\data\model\Query $context @param array $options Available options are: - `'prepend'` _boolean|string_: The string to prepend or `false` for no prepending. Defaults to `'ON'`. @return string Returns the `ON` clause of an SQL query.
[ "Returns", "a", "string", "of", "formatted", "constraints", "to", "be", "inserted", "into", "the", "query", "statement", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1353-L1361
UnionOfRAD/lithium
data/source/Database.php
Database._constraints
protected function _constraints(array $constraints) { foreach ($constraints as &$value) { if (is_string($value)) { $value = (object) $this->name($value); } elseif (is_array($value)) { $value = $this->_constraints($value); } } return $constraints; }
php
protected function _constraints(array $constraints) { foreach ($constraints as &$value) { if (is_string($value)) { $value = (object) $this->name($value); } elseif (is_array($value)) { $value = $this->_constraints($value); } } return $constraints; }
[ "protected", "function", "_constraints", "(", "array", "$", "constraints", ")", "{", "foreach", "(", "$", "constraints", "as", "&", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "value", "=", "(", "object", ")...
Auto escape string value to a field name value @param array $constraints The constraints array @return array The escaped constraints array
[ "Auto", "escape", "string", "value", "to", "a", "field", "name", "value" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1369-L1378
UnionOfRAD/lithium
data/source/Database.php
Database.order
public function order($order, $context) { if (!$order) { return null; } $model = $context->model(); $alias = $context->alias(); $normalized = []; if (is_string($order)) { if (preg_match('/^(.*?)\s+((?:A|DE)SC)$/i', $order, $match)) { $normalized[$match[1]] = strtoupper($match[2]); } else { $normalized[$order] = 'ASC'; } } else { foreach ($order as $field => $direction) { if (is_int($field)) { $normalized[$direction] = 'ASC'; } elseif (in_array($direction, ['ASC', 'DESC', 'asc', 'desc'])) { $normalized[$field] = strtoupper($direction); } else { $normalized[$field] = 'ASC'; } } } $escaped = []; foreach ($normalized as $field => $direction) { if (!$model || !$model::schema($field)) { $field = $this->name($field); } else { $field = $this->name($alias) . '.' . $this->name($field); } $escaped[] = "{$field} {$direction}"; } return 'ORDER BY ' . join(', ', $escaped); }
php
public function order($order, $context) { if (!$order) { return null; } $model = $context->model(); $alias = $context->alias(); $normalized = []; if (is_string($order)) { if (preg_match('/^(.*?)\s+((?:A|DE)SC)$/i', $order, $match)) { $normalized[$match[1]] = strtoupper($match[2]); } else { $normalized[$order] = 'ASC'; } } else { foreach ($order as $field => $direction) { if (is_int($field)) { $normalized[$direction] = 'ASC'; } elseif (in_array($direction, ['ASC', 'DESC', 'asc', 'desc'])) { $normalized[$field] = strtoupper($direction); } else { $normalized[$field] = 'ASC'; } } } $escaped = []; foreach ($normalized as $field => $direction) { if (!$model || !$model::schema($field)) { $field = $this->name($field); } else { $field = $this->name($alias) . '.' . $this->name($field); } $escaped[] = "{$field} {$direction}"; } return 'ORDER BY ' . join(', ', $escaped); }
[ "public", "function", "order", "(", "$", "order", ",", "$", "context", ")", "{", "if", "(", "!", "$", "order", ")", "{", "return", "null", ";", "}", "$", "model", "=", "$", "context", "->", "model", "(", ")", ";", "$", "alias", "=", "$", "conte...
Return formatted clause for `ORDER BY` with known fields escaped and directions normalized to uppercase. When order direction is missing or unrecognized defaults to `ASC`. @param string|array $order The clause to be formatted. @param object $context @return string|null Formatted clause, `null` if there is nothing to format.
[ "Return", "formatted", "clause", "for", "ORDER", "BY", "with", "known", "fields", "escaped", "and", "directions", "normalized", "to", "uppercase", ".", "When", "order", "direction", "is", "missing", "or", "unrecognized", "defaults", "to", "ASC", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1389-L1426
UnionOfRAD/lithium
data/source/Database.php
Database.group
public function group($group, $context) { if (!$group) { return null; } $self = $this; $model = $context->model(); $alias = $context->alias(); $escaped = array_map(function($field) use ($self, $model, $alias) { if (!$model || !$model::schema($field)) { return $self->name($field); } return $self->name($alias) . '.' . $self->name($field); }, (array) $group); return 'GROUP BY ' . join(', ', $escaped); }
php
public function group($group, $context) { if (!$group) { return null; } $self = $this; $model = $context->model(); $alias = $context->alias(); $escaped = array_map(function($field) use ($self, $model, $alias) { if (!$model || !$model::schema($field)) { return $self->name($field); } return $self->name($alias) . '.' . $self->name($field); }, (array) $group); return 'GROUP BY ' . join(', ', $escaped); }
[ "public", "function", "group", "(", "$", "group", ",", "$", "context", ")", "{", "if", "(", "!", "$", "group", ")", "{", "return", "null", ";", "}", "$", "self", "=", "$", "this", ";", "$", "model", "=", "$", "context", "->", "model", "(", ")",...
Return formatted clause for `GROUP BY` with known fields escaped. @param string|array $group The clause to be formatted. @param object $context @return string|null Formatted clause, `null` if there is nothing to format.
[ "Return", "formatted", "clause", "for", "GROUP", "BY", "with", "known", "fields", "escaped", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1435-L1451
UnionOfRAD/lithium
data/source/Database.php
Database._operator
protected function _operator($key, $value, array $schema = [], array $options = []) { $defaults = ['boolean' => 'AND']; $options += $defaults; $op = strtoupper(key($value)); $value = current($value); $config = $this->_operators[$op]; $key = $this->name($key); $values = []; if (!is_object($value)) { if ($value === null) { $value = [null]; } foreach ((array) $value as $val) { $values[] = $this->value($val, $schema); } } elseif (isset($value->scalar)) { return "{$key} {$op} {$value->scalar}"; } switch (true) { case (isset($config['format'])): return $key . ' ' . Text::insert($config['format'], $values); case (is_object($value) && isset($config['multiple'])): $op = $config['multiple']; $value = trim(rtrim($this->renderCommand($value), ';')); return "{$key} {$op} ({$value})"; case (count($values) > 1 && isset($config['multiple'])): $op = $config['multiple']; $values = join(', ', $values); return "{$key} {$op} ({$values})"; case (count($values) > 1): return join(" {$options['boolean']} ", array_map( function($v) use ($key, $op) { return "{$key} {$op} {$v}"; }, $values )); } return "{$key} {$op} {$values[0]}"; }
php
protected function _operator($key, $value, array $schema = [], array $options = []) { $defaults = ['boolean' => 'AND']; $options += $defaults; $op = strtoupper(key($value)); $value = current($value); $config = $this->_operators[$op]; $key = $this->name($key); $values = []; if (!is_object($value)) { if ($value === null) { $value = [null]; } foreach ((array) $value as $val) { $values[] = $this->value($val, $schema); } } elseif (isset($value->scalar)) { return "{$key} {$op} {$value->scalar}"; } switch (true) { case (isset($config['format'])): return $key . ' ' . Text::insert($config['format'], $values); case (is_object($value) && isset($config['multiple'])): $op = $config['multiple']; $value = trim(rtrim($this->renderCommand($value), ';')); return "{$key} {$op} ({$value})"; case (count($values) > 1 && isset($config['multiple'])): $op = $config['multiple']; $values = join(', ', $values); return "{$key} {$op} ({$values})"; case (count($values) > 1): return join(" {$options['boolean']} ", array_map( function($v) use ($key, $op) { return "{$key} {$op} {$v}"; }, $values )); } return "{$key} {$op} {$values[0]}"; }
[ "protected", "function", "_operator", "(", "$", "key", ",", "$", "value", ",", "array", "$", "schema", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'boolean'", "=>", "'AND'", "]", ";", "$", "op...
Handles conversion of SQL operator keys to SQL statements. @param string $key Key in a conditions array. Usually a field name. @param mixed $value An SQL operator or comparison value. @param array $schema An array defining the schema of the field used in the criteria. @param array $options @return string Returns an SQL string representing part of a `WHERE` clause of a query.
[ "Handles", "conversion", "of", "SQL", "operator", "keys", "to", "SQL", "statements", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1483-L1522
UnionOfRAD/lithium
data/source/Database.php
Database._entityName
protected function _entityName($entity, array $options = []) { $defaults = ['quoted' => false]; $options += $defaults; if (class_exists($entity, false) && method_exists($entity, 'meta')) { $entity = $entity::meta('source'); } return $options['quoted'] ? $this->name($entity) : $entity; }
php
protected function _entityName($entity, array $options = []) { $defaults = ['quoted' => false]; $options += $defaults; if (class_exists($entity, false) && method_exists($entity, 'meta')) { $entity = $entity::meta('source'); } return $options['quoted'] ? $this->name($entity) : $entity; }
[ "protected", "function", "_entityName", "(", "$", "entity", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'quoted'", "=>", "false", "]", ";", "$", "options", "+=", "$", "defaults", ";", "if", "(", "class_exists", ...
Returns a fully-qualified table name (i.e. with prefix), quoted. @param string $entity A table name or fully-namespaced model class name. @param array $options Available options: - `'quoted'` _boolean_: Indicates whether the name should be quoted. @return string Returns a quoted table name.
[ "Returns", "a", "fully", "-", "qualified", "table", "name", "(", "i", ".", "e", ".", "with", "prefix", ")", "quoted", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1532-L1540
UnionOfRAD/lithium
data/source/Database.php
Database._introspectType
protected function _introspectType($value) { switch (true) { case (is_bool($value)): return 'boolean'; case (is_float($value) || preg_match('/^\d+\.\d+$/', $value)): return 'float'; case (is_int($value) || preg_match('/^\d+$/', $value)): return 'integer'; case (is_string($value) && strlen($value) <= $this->_columns['string']['length']): return 'string'; default: return 'text'; } }
php
protected function _introspectType($value) { switch (true) { case (is_bool($value)): return 'boolean'; case (is_float($value) || preg_match('/^\d+\.\d+$/', $value)): return 'float'; case (is_int($value) || preg_match('/^\d+$/', $value)): return 'integer'; case (is_string($value) && strlen($value) <= $this->_columns['string']['length']): return 'string'; default: return 'text'; } }
[ "protected", "function", "_introspectType", "(", "$", "value", ")", "{", "switch", "(", "true", ")", "{", "case", "(", "is_bool", "(", "$", "value", ")", ")", ":", "return", "'boolean'", ";", "case", "(", "is_float", "(", "$", "value", ")", "||", "pr...
Attempts to automatically determine the column type of a value. Used by the `value()` method of various database adapters to determine how to prepare a value if the schema is not specified. @param mixed $value The value to be prepared for an SQL query. @return string Returns the name of the column type which `$value` most likely belongs to.
[ "Attempts", "to", "automatically", "determine", "the", "column", "type", "of", "a", "value", ".", "Used", "by", "the", "value", "()", "method", "of", "various", "database", "adapters", "to", "determine", "how", "to", "prepare", "a", "value", "if", "the", "...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1550-L1563
UnionOfRAD/lithium
data/source/Database.php
Database._toBoolean
protected function _toBoolean($value) { if (is_bool($value)) { return $value; } if (is_int($value) || is_float($value)) { return ($value !== 0); } if (is_string($value)) { return ($value === 't' || $value === 'T' || $value === 'true'); } return (boolean) $value; }
php
protected function _toBoolean($value) { if (is_bool($value)) { return $value; } if (is_int($value) || is_float($value)) { return ($value !== 0); } if (is_string($value)) { return ($value === 't' || $value === 'T' || $value === 'true'); } return (boolean) $value; }
[ "protected", "function", "_toBoolean", "(", "$", "value", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "is_int", "(", "$", "value", ")", "||", "is_float", "(", "$", "value", ")", "...
Casts a value which is being written or compared to a boolean-type database column. @param mixed $value A value of unknown type to be cast to boolean. Numeric values not equal to zero evaluate to `true`, otherwise `false`. String values equal to `'true'`, `'t'` or `'T'` evaluate to `true`, all others to `false`. In all other cases, uses PHP's default casting. @return boolean Returns a boolean representation of `$value`, based on the comparison rules specified above. Database adapters may override this method if boolean type coercion is required and falls outside the rules defined.
[ "Casts", "a", "value", "which", "is", "being", "written", "or", "compared", "to", "a", "boolean", "-", "type", "database", "column", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1576-L1587
UnionOfRAD/lithium
data/source/Database.php
Database._error
protected function _error($sql){ $params = compact('sql'); return Filters::run($this, __FUNCTION__, $params, function($params) { list($code, $error) = $this->error(); throw new QueryException("{$params['sql']}: {$error}", $code); }); }
php
protected function _error($sql){ $params = compact('sql'); return Filters::run($this, __FUNCTION__, $params, function($params) { list($code, $error) = $this->error(); throw new QueryException("{$params['sql']}: {$error}", $code); }); }
[ "protected", "function", "_error", "(", "$", "sql", ")", "{", "$", "params", "=", "compact", "(", "'sql'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ",", "__FUNCTION__", ",", "$", "params", ",", "function", "(", "$", "params", ")"...
Throw a `QueryException` error @param string $sql The offending SQL string @filter
[ "Throw", "a", "QueryException", "error" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1595-L1602
UnionOfRAD/lithium
data/source/Database.php
Database.applyStrategy
public function applyStrategy($options, $context) { if ($context->type() !== 'read') { return; } $options += ['strategy' => 'joined']; if (!$model = $context->model()) { throw new ConfigException('The `\'with\'` option need a valid `\'model\'` option.'); } $strategy = $options['strategy']; if (isset($this->_strategies[$strategy])) { $strategy = $this->_strategies[$strategy]; $strategy($model, $context); } else { throw new QueryException("Undefined query strategy `{$strategy}`."); } }
php
public function applyStrategy($options, $context) { if ($context->type() !== 'read') { return; } $options += ['strategy' => 'joined']; if (!$model = $context->model()) { throw new ConfigException('The `\'with\'` option need a valid `\'model\'` option.'); } $strategy = $options['strategy']; if (isset($this->_strategies[$strategy])) { $strategy = $this->_strategies[$strategy]; $strategy($model, $context); } else { throw new QueryException("Undefined query strategy `{$strategy}`."); } }
[ "public", "function", "applyStrategy", "(", "$", "options", ",", "$", "context", ")", "{", "if", "(", "$", "context", "->", "type", "(", ")", "!==", "'read'", ")", "{", "return", ";", "}", "$", "options", "+=", "[", "'strategy'", "=>", "'joined'", "]...
Applying a strategy to a `lithium\data\model\Query` object @param array $options The option array @param object $context A find query object to configure
[ "Applying", "a", "strategy", "to", "a", "lithium", "\\", "data", "\\", "model", "\\", "Query", "object" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1610-L1627
UnionOfRAD/lithium
data/source/Database.php
Database.join
public function join($context, $rel, $fromAlias = null, $toAlias = null, $constraints = []) { $model = $rel->to(); if ($fromAlias === null) { $fromAlias = $context->alias(); } if ($toAlias === null) { $toAlias = $context->alias(null, $rel->name()); } if (!is_object($constraints)) { $constraints = $this->on($rel, $fromAlias, $toAlias, $constraints); } else { $constraints = (array) $constraints; } $context->joins($toAlias, compact('constraints', 'model') + [ 'mode' => 'LEFT', 'alias' => $toAlias ]); }
php
public function join($context, $rel, $fromAlias = null, $toAlias = null, $constraints = []) { $model = $rel->to(); if ($fromAlias === null) { $fromAlias = $context->alias(); } if ($toAlias === null) { $toAlias = $context->alias(null, $rel->name()); } if (!is_object($constraints)) { $constraints = $this->on($rel, $fromAlias, $toAlias, $constraints); } else { $constraints = (array) $constraints; } $context->joins($toAlias, compact('constraints', 'model') + [ 'mode' => 'LEFT', 'alias' => $toAlias ]); }
[ "public", "function", "join", "(", "$", "context", ",", "$", "rel", ",", "$", "fromAlias", "=", "null", ",", "$", "toAlias", "=", "null", ",", "$", "constraints", "=", "[", "]", ")", "{", "$", "model", "=", "$", "rel", "->", "to", "(", ")", ";"...
Set a query's join according a Relationship. @param object $context A Query instance @param object $rel A Relationship instance @param string $fromAlias Set a specific alias for the `'from'` `Model`. @param string $toAlias Set a specific alias for `'to'` `Model`. @param mixed $constraints If `$constraints` is an array, it will be merged to defaults constraints. If `$constraints` is an object, defaults won't be merged.
[ "Set", "a", "query", "s", "join", "according", "a", "Relationship", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1639-L1658
UnionOfRAD/lithium
data/source/Database.php
Database._aliasing
protected function _aliasing($name, $alias, $map = []) { list($first, $second) = $this->_splitFieldname($name); if (!$first && preg_match('/^[a-z0-9_-]+$/i', $second)) { return $alias . "." . $second; } elseif (isset($map[$first])) { return $map[$first] . "." . $second; } return $name; }
php
protected function _aliasing($name, $alias, $map = []) { list($first, $second) = $this->_splitFieldname($name); if (!$first && preg_match('/^[a-z0-9_-]+$/i', $second)) { return $alias . "." . $second; } elseif (isset($map[$first])) { return $map[$first] . "." . $second; } return $name; }
[ "protected", "function", "_aliasing", "(", "$", "name", ",", "$", "alias", ",", "$", "map", "=", "[", "]", ")", "{", "list", "(", "$", "first", ",", "$", "second", ")", "=", "$", "this", "->", "_splitFieldname", "(", "$", "name", ")", ";", "if", ...
Helper which add an alias basename to a field name if necessary @param string $name The field name. @param string $alias The alias name @param array $map An array of `'modelname' => 'aliasname'` mapping @return string
[ "Helper", "which", "add", "an", "alias", "basename", "to", "a", "field", "name", "if", "necessary" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1668-L1676
UnionOfRAD/lithium
data/source/Database.php
Database.on
public function on($rel, $aliasFrom = null, $aliasTo = null, $constraints = []) { $model = $rel->from(); $aliasFrom = $aliasFrom ?: $model::meta('name'); $aliasTo = $aliasTo ?: $rel->name(); $keyConstraints = []; foreach ($rel->key() as $from => $to) { $keyConstraints["{$aliasFrom}.{$from}"] = "{$aliasTo}.{$to}"; } $mapAlias = [$model::meta('name') => $aliasFrom, $rel->name() => $aliasTo]; $relConstraints = $this->_on((array) $rel->constraints(), $aliasFrom, $aliasTo, $mapAlias); $constraints = $this->_on($constraints, $aliasFrom, $aliasTo, []); return $constraints + $relConstraints + $keyConstraints; }
php
public function on($rel, $aliasFrom = null, $aliasTo = null, $constraints = []) { $model = $rel->from(); $aliasFrom = $aliasFrom ?: $model::meta('name'); $aliasTo = $aliasTo ?: $rel->name(); $keyConstraints = []; foreach ($rel->key() as $from => $to) { $keyConstraints["{$aliasFrom}.{$from}"] = "{$aliasTo}.{$to}"; } $mapAlias = [$model::meta('name') => $aliasFrom, $rel->name() => $aliasTo]; $relConstraints = $this->_on((array) $rel->constraints(), $aliasFrom, $aliasTo, $mapAlias); $constraints = $this->_on($constraints, $aliasFrom, $aliasTo, []); return $constraints + $relConstraints + $keyConstraints; }
[ "public", "function", "on", "(", "$", "rel", ",", "$", "aliasFrom", "=", "null", ",", "$", "aliasTo", "=", "null", ",", "$", "constraints", "=", "[", "]", ")", "{", "$", "model", "=", "$", "rel", "->", "from", "(", ")", ";", "$", "aliasFrom", "...
Build the `ON` constraints from a `Relationship` instance @param object $rel A Relationship instance @param string $fromAlias Set a specific alias for the `'from'` `Model`. @param string $toAlias Set a specific alias for `'to'` `Model`. @param array $constraints Array of additionnal $constraints. @return array A constraints array.
[ "Build", "the", "ON", "constraints", "from", "a", "Relationship", "instance" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1687-L1704
UnionOfRAD/lithium
data/source/Database.php
Database._meta
protected function _meta($type, $name, $value) { $meta = isset($this->_metas[$type][$name]) ? $this->_metas[$type][$name] : null; if (!$meta || (isset($meta['options']) && !in_array($value, $meta['options']))) { return; } $meta += ['keyword' => '', 'escape' => false, 'join' => ' ']; if ($meta['escape'] === true) { $value = $this->value($value, ['type' => 'string']); } return ($result = "{$meta['keyword']}{$meta['join']}{$value}") !== ' ' ? $result : ''; }
php
protected function _meta($type, $name, $value) { $meta = isset($this->_metas[$type][$name]) ? $this->_metas[$type][$name] : null; if (!$meta || (isset($meta['options']) && !in_array($value, $meta['options']))) { return; } $meta += ['keyword' => '', 'escape' => false, 'join' => ' ']; if ($meta['escape'] === true) { $value = $this->value($value, ['type' => 'string']); } return ($result = "{$meta['keyword']}{$meta['join']}{$value}") !== ' ' ? $result : ''; }
[ "protected", "function", "_meta", "(", "$", "type", ",", "$", "name", ",", "$", "value", ")", "{", "$", "meta", "=", "isset", "(", "$", "this", "->", "_metas", "[", "$", "type", "]", "[", "$", "name", "]", ")", "?", "$", "this", "->", "_metas",...
Build a SQL column/table meta. @param string $type The type of the meta to build (possible values: `'table'` or `'column'`). @param string $name The name of the meta to build. @param mixed $value The value used for building the meta. @return string The SQL meta string.
[ "Build", "a", "SQL", "column", "/", "table", "meta", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1736-L1748
UnionOfRAD/lithium
data/source/Database.php
Database._constraint
protected function _constraint($name, $value, $schema = null) { $value += ['options' => []]; $meta = isset($this->_constraints[$name]) ? $this->_constraints[$name] : null; $template = isset($meta['template']) ? $meta['template'] : null; if (!$template) { return; } $data = []; foreach ($value as $name => $value) { switch ($name) { case 'key': case 'index': if (isset($meta[$name])) { $data['index'] = $meta[$name]; } break; case 'to': $data[$name] = $this->name($value); break; case 'on': $data[$name] = "ON {$value}"; break; case 'expr': if (is_array($value)) { $result = []; $context = new Query(['type' => 'none']); foreach ($value as $key => $val) { $return = $this->_processConditions($key, $val, $context, $schema); if ($return) { $result[] = $return; } } $data[$name] = join(" AND ", $result); } else { $data[$name] = $value; } break; case 'toColumn': case 'column': $data[$name] = join(', ', array_map([$this, 'name'], (array) $value)); break; } } return trim(Text::insert($template, $data, ['clean' => true])); }
php
protected function _constraint($name, $value, $schema = null) { $value += ['options' => []]; $meta = isset($this->_constraints[$name]) ? $this->_constraints[$name] : null; $template = isset($meta['template']) ? $meta['template'] : null; if (!$template) { return; } $data = []; foreach ($value as $name => $value) { switch ($name) { case 'key': case 'index': if (isset($meta[$name])) { $data['index'] = $meta[$name]; } break; case 'to': $data[$name] = $this->name($value); break; case 'on': $data[$name] = "ON {$value}"; break; case 'expr': if (is_array($value)) { $result = []; $context = new Query(['type' => 'none']); foreach ($value as $key => $val) { $return = $this->_processConditions($key, $val, $context, $schema); if ($return) { $result[] = $return; } } $data[$name] = join(" AND ", $result); } else { $data[$name] = $value; } break; case 'toColumn': case 'column': $data[$name] = join(', ', array_map([$this, 'name'], (array) $value)); break; } } return trim(Text::insert($template, $data, ['clean' => true])); }
[ "protected", "function", "_constraint", "(", "$", "name", ",", "$", "value", ",", "$", "schema", "=", "null", ")", "{", "$", "value", "+=", "[", "'options'", "=>", "[", "]", "]", ";", "$", "meta", "=", "isset", "(", "$", "this", "->", "_constraints...
Build a SQL column constraint @param string $name The name of the meta to build @param mixed $value The value used for building the meta @param object $schema A `Schema` instance. @return string The SQL meta string
[ "Build", "a", "SQL", "column", "constraint" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1758-L1804
UnionOfRAD/lithium
data/source/Database.php
Database.createSchema
public function createSchema($source, $schema) { if (!$schema instanceof $this->_classes['schema']) { throw new InvalidArgumentException("Passed schema is not a valid `{$class}` instance."); } $columns = []; $primary = null; $source = $this->name($source); foreach ($schema->fields() as $name => $field) { $field['name'] = $name; if ($field['type'] === 'id') { $primary = $name; } $columns[] = $this->column($field); } $columns = join(",\n", array_filter($columns)); $metas = $schema->meta() + ['table' => [], 'constraints' => []]; $constraints = $this->_buildConstraints($metas['constraints'], $schema, ",\n", $primary); $table = $this->_buildMetas('table', $metas['table']); $params = compact('source', 'columns', 'constraints', 'table'); return $this->_execute($this->renderCommand('schema', $params)); }
php
public function createSchema($source, $schema) { if (!$schema instanceof $this->_classes['schema']) { throw new InvalidArgumentException("Passed schema is not a valid `{$class}` instance."); } $columns = []; $primary = null; $source = $this->name($source); foreach ($schema->fields() as $name => $field) { $field['name'] = $name; if ($field['type'] === 'id') { $primary = $name; } $columns[] = $this->column($field); } $columns = join(",\n", array_filter($columns)); $metas = $schema->meta() + ['table' => [], 'constraints' => []]; $constraints = $this->_buildConstraints($metas['constraints'], $schema, ",\n", $primary); $table = $this->_buildMetas('table', $metas['table']); $params = compact('source', 'columns', 'constraints', 'table'); return $this->_execute($this->renderCommand('schema', $params)); }
[ "public", "function", "createSchema", "(", "$", "source", ",", "$", "schema", ")", "{", "if", "(", "!", "$", "schema", "instanceof", "$", "this", "->", "_classes", "[", "'schema'", "]", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Passed s...
Create a database-native schema @param string $source A table name. @param object $schema A `Schema` instance. @return boolean `true` on success, `true` otherwise
[ "Create", "a", "database", "-", "native", "schema" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1813-L1839
UnionOfRAD/lithium
data/source/Database.php
Database._buildMetas
protected function _buildMetas($type, array $metas, $names = null, $joiner = ' ') { $result = ''; $names = $names ? (array) $names : array_keys($metas); foreach ($names as $name) { $value = isset($metas[$name]) ? $metas[$name] : null; if ($value && $meta = $this->_meta($type, $name, $value)) { $result .= $joiner . $meta; } } return $result; }
php
protected function _buildMetas($type, array $metas, $names = null, $joiner = ' ') { $result = ''; $names = $names ? (array) $names : array_keys($metas); foreach ($names as $name) { $value = isset($metas[$name]) ? $metas[$name] : null; if ($value && $meta = $this->_meta($type, $name, $value)) { $result .= $joiner . $meta; } } return $result; }
[ "protected", "function", "_buildMetas", "(", "$", "type", ",", "array", "$", "metas", ",", "$", "names", "=", "null", ",", "$", "joiner", "=", "' '", ")", "{", "$", "result", "=", "''", ";", "$", "names", "=", "$", "names", "?", "(", "array", ")"...
Helper for building columns metas @see lithium\data\soure\Database::createSchema() @see lithium\data\soure\Database::column() @param array $metas The array of column metas. @param array $names If `$names` is not `null` only build meta present in `$names` @param type $joiner The join character @return string The SQL constraints
[ "Helper", "for", "building", "columns", "metas" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1851-L1861
UnionOfRAD/lithium
data/source/Database.php
Database._buildConstraints
protected function _buildConstraints(array $constraints, $schema = null, $joiner = ' ', $primary = false) { $result = ''; foreach ($constraints as $constraint) { if (isset($constraint['type'])) { $name = $constraint['type']; if ($meta = $this->_constraint($name, $constraint, $schema)) { $result .= $joiner . $meta; } if ($name === 'primary') { $primary = false; } } } if ($primary) { $result .= $joiner . $this->_constraint('primary', ['column' => $primary]); } return $result; }
php
protected function _buildConstraints(array $constraints, $schema = null, $joiner = ' ', $primary = false) { $result = ''; foreach ($constraints as $constraint) { if (isset($constraint['type'])) { $name = $constraint['type']; if ($meta = $this->_constraint($name, $constraint, $schema)) { $result .= $joiner . $meta; } if ($name === 'primary') { $primary = false; } } } if ($primary) { $result .= $joiner . $this->_constraint('primary', ['column' => $primary]); } return $result; }
[ "protected", "function", "_buildConstraints", "(", "array", "$", "constraints", ",", "$", "schema", "=", "null", ",", "$", "joiner", "=", "' '", ",", "$", "primary", "=", "false", ")", "{", "$", "result", "=", "''", ";", "foreach", "(", "$", "constrain...
Helper for building columns constraints @see lithium\data\soure\Database::createSchema() @param array $constraints The array of constraints @param type $schema The schema of the table @param type $joiner The join character @return string The SQL constraints
[ "Helper", "for", "building", "columns", "constraints" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1872-L1889
UnionOfRAD/lithium
data/source/Database.php
Database.dropSchema
public function dropSchema($source, $soft = true) { if ($source) { $source = $this->name($source); $exists = $soft ? 'IF EXISTS ' : ''; return $this->_execute($this->renderCommand('drop', compact('exists', 'source'))); } return false; }
php
public function dropSchema($source, $soft = true) { if ($source) { $source = $this->name($source); $exists = $soft ? 'IF EXISTS ' : ''; return $this->_execute($this->renderCommand('drop', compact('exists', 'source'))); } return false; }
[ "public", "function", "dropSchema", "(", "$", "source", ",", "$", "soft", "=", "true", ")", "{", "if", "(", "$", "source", ")", "{", "$", "source", "=", "$", "this", "->", "name", "(", "$", "source", ")", ";", "$", "exists", "=", "$", "soft", "...
Drops a table. @param string $source The table name to drop. @param boolean $soft With "soft dropping", the function will retrun `true` even if the table doesn't exists. @return boolean `true` on success, `false` otherwise
[ "Drops", "a", "table", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1899-L1906
UnionOfRAD/lithium
data/source/Database.php
Database.column
public function column($field) { if (!isset($field['type'])) { $field['type'] = 'string'; } if (!isset($field['name'])) { throw new InvalidArgumentException("Column name not defined."); } if (!isset($this->_columns[$field['type']])) { throw new UnexpectedValueException("Column type `{$field['type']}` does not exist."); } $field += $this->_columns[$field['type']] + [ 'name' => null, 'type' => null, 'length' => null, 'precision' => null, 'default' => null, 'null' => null ]; $isNumeric = preg_match('/^(integer|float|boolean)$/', $field['type']); if ($isNumeric && $field['default'] === '') { $field['default'] = null; } $field['use'] = strtolower($field['use']); return $this->_buildColumn($field); }
php
public function column($field) { if (!isset($field['type'])) { $field['type'] = 'string'; } if (!isset($field['name'])) { throw new InvalidArgumentException("Column name not defined."); } if (!isset($this->_columns[$field['type']])) { throw new UnexpectedValueException("Column type `{$field['type']}` does not exist."); } $field += $this->_columns[$field['type']] + [ 'name' => null, 'type' => null, 'length' => null, 'precision' => null, 'default' => null, 'null' => null ]; $isNumeric = preg_match('/^(integer|float|boolean)$/', $field['type']); if ($isNumeric && $field['default'] === '') { $field['default'] = null; } $field['use'] = strtolower($field['use']); return $this->_buildColumn($field); }
[ "public", "function", "column", "(", "$", "field", ")", "{", "if", "(", "!", "isset", "(", "$", "field", "[", "'type'", "]", ")", ")", "{", "$", "field", "[", "'type'", "]", "=", "'string'", ";", "}", "if", "(", "!", "isset", "(", "$", "field",...
Generate a database-native column schema string @param array $column A field array structured like the following: `array('name' => 'value', 'type' => 'value' [, options])`, where options can be `'default'`, `'null'`, `'length'` or `'precision'`. @return string SQL string
[ "Generate", "a", "database", "-", "native", "column", "schema", "string" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/Database.php#L1916-L1942
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb._init
protected function _init() { $hosts = []; foreach ((array) $this->_config['host'] as $host) { $host = HostString::parse($host) + [ 'host' => static::DEFAULT_HOST, 'port' => static::DEFAULT_PORT ]; $hosts[] = "{$host['host']}:{$host['port']}"; } if ($this->_config['login']) { $this->_config['dsn'] = sprintf( 'mongodb://%s:%s@%s/%s', $this->_config['login'], $this->_config['password'], implode(',', $hosts), $this->_config['database'] ); } else { $this->_config['dsn'] = sprintf( 'mongodb://%s', implode(',', $hosts) ); } parent::_init(); $this->_operators += [ 'like' => function($key, $value) { return new MongoRegex($value); }, '$exists' => function($key, $value) { return ['$exists' => (boolean) $value]; }, '$type' => function($key, $value) { return ['$type' => (integer) $value]; }, '$mod' => function($key, $value) { $value = (array) $value; return ['$mod' => [current($value), next($value) ?: 0]]; }, '$size' => function($key, $value) { return ['$size' => (integer) $value]; }, '$elemMatch' => function($operator, $values, $options = []) { $options += [ 'castOpts' => [], 'field' => '' ]; $options['castOpts'] += ['pathKey' => $options['field']]; $values = (array) $values; if (empty($options['castOpts']['schema'])) { return ['$elemMatch' => $values]; } foreach ($values as $key => &$value) { $value = $options['castOpts']['schema']->cast( null, $key, $value, $options['castOpts'] ); } return ['$elemMatch' => $values]; } ]; }
php
protected function _init() { $hosts = []; foreach ((array) $this->_config['host'] as $host) { $host = HostString::parse($host) + [ 'host' => static::DEFAULT_HOST, 'port' => static::DEFAULT_PORT ]; $hosts[] = "{$host['host']}:{$host['port']}"; } if ($this->_config['login']) { $this->_config['dsn'] = sprintf( 'mongodb://%s:%s@%s/%s', $this->_config['login'], $this->_config['password'], implode(',', $hosts), $this->_config['database'] ); } else { $this->_config['dsn'] = sprintf( 'mongodb://%s', implode(',', $hosts) ); } parent::_init(); $this->_operators += [ 'like' => function($key, $value) { return new MongoRegex($value); }, '$exists' => function($key, $value) { return ['$exists' => (boolean) $value]; }, '$type' => function($key, $value) { return ['$type' => (integer) $value]; }, '$mod' => function($key, $value) { $value = (array) $value; return ['$mod' => [current($value), next($value) ?: 0]]; }, '$size' => function($key, $value) { return ['$size' => (integer) $value]; }, '$elemMatch' => function($operator, $values, $options = []) { $options += [ 'castOpts' => [], 'field' => '' ]; $options['castOpts'] += ['pathKey' => $options['field']]; $values = (array) $values; if (empty($options['castOpts']['schema'])) { return ['$elemMatch' => $values]; } foreach ($values as $key => &$value) { $value = $options['castOpts']['schema']->cast( null, $key, $value, $options['castOpts'] ); } return ['$elemMatch' => $values]; } ]; }
[ "protected", "function", "_init", "(", ")", "{", "$", "hosts", "=", "[", "]", ";", "foreach", "(", "(", "array", ")", "$", "this", "->", "_config", "[", "'host'", "]", "as", "$", "host", ")", "{", "$", "host", "=", "HostString", "::", "parse", "(...
Initializer. Adds operator handlers which will later allow to correctly cast any values. Constructs a DSN from configuration. @see lithium\data\source\MongoDb::$_operators @see lithium\data\source\MongoDb::_operators() @return void
[ "Initializer", ".", "Adds", "operator", "handlers", "which", "will", "later", "allow", "to", "correctly", "cast", "any", "values", ".", "Constructs", "a", "DSN", "from", "configuration", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L272-L333
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.connect
public function connect() { $server = $this->_classes['server']; if ($this->server && $this->server->getConnections() && $this->connection) { return $this->_isConnected = true; } $this->_isConnected = false; $options = [ 'connect' => true, 'connectTimeoutMS' => $this->_config['timeout'], 'replicaSet' => $this->_config['replicaSet'], ]; try { $this->server = new $server($this->_config['dsn'], $options); if ($prefs = $this->_config['readPreference']) { $prefs = !is_array($prefs) ? [$prefs, []] : $prefs; $this->server->setReadPreference($prefs[0], $prefs[1]); } if ($this->connection = $this->server->{$this->_config['database']}) { $this->_isConnected = true; } } catch (Exception $e) { throw new NetworkException("Could not connect to the database.", 503, $e); } return $this->_isConnected; }
php
public function connect() { $server = $this->_classes['server']; if ($this->server && $this->server->getConnections() && $this->connection) { return $this->_isConnected = true; } $this->_isConnected = false; $options = [ 'connect' => true, 'connectTimeoutMS' => $this->_config['timeout'], 'replicaSet' => $this->_config['replicaSet'], ]; try { $this->server = new $server($this->_config['dsn'], $options); if ($prefs = $this->_config['readPreference']) { $prefs = !is_array($prefs) ? [$prefs, []] : $prefs; $this->server->setReadPreference($prefs[0], $prefs[1]); } if ($this->connection = $this->server->{$this->_config['database']}) { $this->_isConnected = true; } } catch (Exception $e) { throw new NetworkException("Could not connect to the database.", 503, $e); } return $this->_isConnected; }
[ "public", "function", "connect", "(", ")", "{", "$", "server", "=", "$", "this", "->", "_classes", "[", "'server'", "]", ";", "if", "(", "$", "this", "->", "server", "&&", "$", "this", "->", "server", "->", "getConnections", "(", ")", "&&", "$", "t...
Connects to the Mongo server. Matches up parameters from the constructor to create a Mongo database connection. @see lithium\data\source\MongoDb::__construct() @link http://php.net/mongo.construct.php PHP Manual: Mongo::__construct() @return boolean Returns `true` the connection attempt was successful, otherwise `false`.
[ "Connects", "to", "the", "Mongo", "server", ".", "Matches", "up", "parameters", "from", "the", "constructor", "to", "create", "a", "Mongo", "database", "connection", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L373-L402
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.disconnect
public function disconnect() { if ($this->server && $this->server->getConnections()) { $this->_isConnected = false; unset($this->connection, $this->server); } return true; }
php
public function disconnect() { if ($this->server && $this->server->getConnections()) { $this->_isConnected = false; unset($this->connection, $this->server); } return true; }
[ "public", "function", "disconnect", "(", ")", "{", "if", "(", "$", "this", "->", "server", "&&", "$", "this", "->", "server", "->", "getConnections", "(", ")", ")", "{", "$", "this", "->", "_isConnected", "=", "false", ";", "unset", "(", "$", "this",...
Disconnect from the Mongo server. Don't call the Mongo->close() method. The driver documentation states this should not be necessary since it auto disconnects when out of scope. With version 1.2.7, when using replica sets, close() can cause a segmentation fault. @return boolean True
[ "Disconnect", "from", "the", "Mongo", "server", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L413-L419
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.sources
public function sources($class = null) { $this->_checkConnection(); $conn = $this->connection; return array_map(function($col) { return $col->getName(); }, $conn->listCollections()); }
php
public function sources($class = null) { $this->_checkConnection(); $conn = $this->connection; return array_map(function($col) { return $col->getName(); }, $conn->listCollections()); }
[ "public", "function", "sources", "(", "$", "class", "=", "null", ")", "{", "$", "this", "->", "_checkConnection", "(", ")", ";", "$", "conn", "=", "$", "this", "->", "connection", ";", "return", "array_map", "(", "function", "(", "$", "col", ")", "{"...
Returns the list of collections in the currently-connected database. @param string $class The fully-name-spaced class name of the model object making the request. @return array Returns an array of objects to which models can connect.
[ "Returns", "the", "list", "of", "collections", "in", "the", "currently", "-", "connected", "database", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L427-L431
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.describe
public function describe($collection, $fields = [], array $meta = []) { if (!$fields && ($func = $this->_schema)) { $fields = $func($this, $collection, $meta); } return $this->_instance('schema', compact('fields')); }
php
public function describe($collection, $fields = [], array $meta = []) { if (!$fields && ($func = $this->_schema)) { $fields = $func($this, $collection, $meta); } return $this->_instance('schema', compact('fields')); }
[ "public", "function", "describe", "(", "$", "collection", ",", "$", "fields", "=", "[", "]", ",", "array", "$", "meta", "=", "[", "]", ")", "{", "if", "(", "!", "$", "fields", "&&", "(", "$", "func", "=", "$", "this", "->", "_schema", ")", ")",...
Gets the column 'schema' for a given MongoDB collection. Only returns a schema if the `'schema'` configuration flag has been set in the constructor. @see lithium\data\source\MongoDb::$_schema @param mixed $collection Specifies a collection name for which the schema should be queried. @param mixed $fields Any schema data pre-defined by the model. @param array $meta Any meta information pre-defined in the model. @return array Returns an associative array describing the given collection's schema.
[ "Gets", "the", "column", "schema", "for", "a", "given", "MongoDB", "collection", ".", "Only", "returns", "a", "schema", "if", "the", "schema", "configuration", "flag", "has", "been", "set", "in", "the", "constructor", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L443-L448
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.respondsTo
public function respondsTo($method, $internal = false) { $childRespondsTo = is_object($this->server) && is_callable([$this->server, $method]); return parent::respondsTo($method, $internal) || $childRespondsTo; }
php
public function respondsTo($method, $internal = false) { $childRespondsTo = is_object($this->server) && is_callable([$this->server, $method]); return parent::respondsTo($method, $internal) || $childRespondsTo; }
[ "public", "function", "respondsTo", "(", "$", "method", ",", "$", "internal", "=", "false", ")", "{", "$", "childRespondsTo", "=", "is_object", "(", "$", "this", "->", "server", ")", "&&", "is_callable", "(", "[", "$", "this", "->", "server", ",", "$",...
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/MongoDb.php#L493-L496
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.create
public function create($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $exporter = $this->_classes['exporter']; $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this, ['keys' => ['source', 'data']]); $data = $exporter::get('create', $args['data']); $source = $args['source']; if ($source === "{$prefix}.files" && isset($data['create']['file'])) { $result = ['ok' => true]; $data['create']['_id'] = $this->_saveFile($data['create']); } else { $result = $this->connection->{$source}->insert($data['create'], $options); $result = $this->_ok($result); } if ($result === true || isset($result['ok']) && (boolean) $result['ok'] === true) { if ($query->entity()) { $query->entity()->sync($data['create']['_id']); } return true; } return false; }); }
php
public function create($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $exporter = $this->_classes['exporter']; $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this, ['keys' => ['source', 'data']]); $data = $exporter::get('create', $args['data']); $source = $args['source']; if ($source === "{$prefix}.files" && isset($data['create']['file'])) { $result = ['ok' => true]; $data['create']['_id'] = $this->_saveFile($data['create']); } else { $result = $this->connection->{$source}->insert($data['create'], $options); $result = $this->_ok($result); } if ($result === true || isset($result['ok']) && (boolean) $result['ok'] === true) { if ($query->entity()) { $query->entity()->sync($data['create']['_id']); } return true; } return false; }); }
[ "public", "function", "create", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "_checkConnection", "(", ")", ";", "$", "defaults", "=", "[", "'w'", "=>", "$", "this", "->", "_config", "[", "'w'", "]", ...
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/MongoDb.php#L520-L559
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.read
public function read($query, array $options = []) { $this->_checkConnection(); $defaults = ['return' => 'resource']; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this); $source = $args['source']; $model = $query->model(); if ($group = $args['group']) { $result = $this->_group($group, $args, $options); $config = ['class' => 'set', 'defaults' => false] + compact('query') + $result; return $model::create($config['data'], $config); } $collection = $this->connection->{$source}; if ($source === "{$prefix}.files") { $collection = $this->connection->getGridFS($prefix); } $result = $collection->find($args['conditions'], $args['fields']); if ($query->calculate()) { return $result; } $resource = $result->sort($args['order'])->limit($args['limit'])->skip($args['offset']); $result = $this->_instance('result', compact('resource')); $config = compact('result', 'query') + ['class' => 'set', 'defaults' => false]; return $model::create([], $config); }); }
php
public function read($query, array $options = []) { $this->_checkConnection(); $defaults = ['return' => 'resource']; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this); $source = $args['source']; $model = $query->model(); if ($group = $args['group']) { $result = $this->_group($group, $args, $options); $config = ['class' => 'set', 'defaults' => false] + compact('query') + $result; return $model::create($config['data'], $config); } $collection = $this->connection->{$source}; if ($source === "{$prefix}.files") { $collection = $this->connection->getGridFS($prefix); } $result = $collection->find($args['conditions'], $args['fields']); if ($query->calculate()) { return $result; } $resource = $result->sort($args['order'])->limit($args['limit'])->skip($args['offset']); $result = $this->_instance('result', compact('resource')); $config = compact('result', 'query') + ['class' => 'set', 'defaults' => false]; return $model::create([], $config); }); }
[ "public", "function", "read", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "_checkConnection", "(", ")", ";", "$", "defaults", "=", "[", "'return'", "=>", "'resource'", "]", ";", "$", "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/MongoDb.php#L601-L639
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.update
public function update($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'upsert' => false, 'multiple' => true, 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $exporter = $this->_classes['exporter']; $prefix = $this->_config['gridPrefix']; $options = $params['options']; $query = $params['query']; $args = $query->export($this, ['keys' => ['conditions', 'source', 'data']]); $source = $args['source']; $data = $args['data']; if ($query->entity()) { $data = $exporter::get('update', $data); } if ($source === "{$prefix}.files" && isset($data['update']['file'])) { $args['data']['_id'] = $this->_saveFile($data['update']); } $update = $query->entity() ? $exporter::toCommand($data) : $data; if (empty($update)) { return true; } if ($options['multiple'] && !preg_grep('/^\$/', array_keys($update))) { $update = ['$set' => $update]; } $result = $this->connection->{$source}->update($args['conditions'], $update, $options); if ($this->_ok($result)) { $query->entity() ? $query->entity()->sync() : null; return true; } return false; }); }
php
public function update($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'upsert' => false, 'multiple' => true, 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options += $defaults; $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $exporter = $this->_classes['exporter']; $prefix = $this->_config['gridPrefix']; $options = $params['options']; $query = $params['query']; $args = $query->export($this, ['keys' => ['conditions', 'source', 'data']]); $source = $args['source']; $data = $args['data']; if ($query->entity()) { $data = $exporter::get('update', $data); } if ($source === "{$prefix}.files" && isset($data['update']['file'])) { $args['data']['_id'] = $this->_saveFile($data['update']); } $update = $query->entity() ? $exporter::toCommand($data) : $data; if (empty($update)) { return true; } if ($options['multiple'] && !preg_grep('/^\$/', array_keys($update))) { $update = ['$set' => $update]; } $result = $this->connection->{$source}->update($args['conditions'], $update, $options); if ($this->_ok($result)) { $query->entity() ? $query->entity()->sync() : null; return true; } return false; }); }
[ "public", "function", "update", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "_checkConnection", "(", ")", ";", "$", "defaults", "=", "[", "'upsert'", "=>", "false", ",", "'multiple'", "=>", "true", ","...
Update document @param string $query @param array $options @return boolean @filter
[ "Update", "document" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L660-L707
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.delete
public function delete($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'justOne' => false, 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options = array_intersect_key($options + $defaults, $defaults); $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this, ['keys' => ['source', 'conditions']]); $source = $args['source']; $conditions = $args['conditions']; if ($source === "{$prefix}.files") { $result = $this->_deleteFile($conditions); } else { $result = $this->connection->{$args['source']}->remove($conditions, $options); $result = $this->_ok($result); } if ($result && $query->entity()) { $query->entity()->sync(null, [], ['dematerialize' => true]); } return $result; }); }
php
public function delete($query, array $options = []) { $this->_checkConnection(); $defaults = [ 'justOne' => false, 'w' => $this->_config['w'], 'wTimeoutMS' => $this->_config['wTimeoutMS'], 'fsync' => false ]; $options = array_intersect_key($options + $defaults, $defaults); $params = compact('query', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $prefix = $this->_config['gridPrefix']; $query = $params['query']; $options = $params['options']; $args = $query->export($this, ['keys' => ['source', 'conditions']]); $source = $args['source']; $conditions = $args['conditions']; if ($source === "{$prefix}.files") { $result = $this->_deleteFile($conditions); } else { $result = $this->connection->{$args['source']}->remove($conditions, $options); $result = $this->_ok($result); } if ($result && $query->entity()) { $query->entity()->sync(null, [], ['dematerialize' => true]); } return $result; }); }
[ "public", "function", "delete", "(", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "_checkConnection", "(", ")", ";", "$", "defaults", "=", "[", "'justOne'", "=>", "false", ",", "'w'", "=>", "$", "this", "-...
Delete document @param string $query @param array $options @return boolean @filter
[ "Delete", "document" ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L717-L749
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.calculation
public function calculation($type, $query, array $options = []) { $query->calculate($type); switch ($type) { case 'count': return $this->read($query, $options)->count(); } }
php
public function calculation($type, $query, array $options = []) { $query->calculate($type); switch ($type) { case 'count': return $this->read($query, $options)->count(); } }
[ "public", "function", "calculation", "(", "$", "type", ",", "$", "query", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "query", "->", "calculate", "(", "$", "type", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'count'", ...
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/MongoDb.php#L780-L787
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.relationship
public function relationship($class, $type, $name, array $config = []) { $fieldName = $this->relationFieldName($type, $name); $config += compact('name', 'type', 'key', 'fieldName'); $config['from'] = $class; return $this->_instance('relationship', $config + [ 'strategy' => function($rel) use ($config, $class, $name, $type) { if (isset($config['key'])) { return []; } $link = null; $hasLink = isset($config['link']); $result = []; $to = $rel->to(); $local = $class::key(); $className = $class::meta('name'); $keys = [ [$class, $name], [$class, Inflector::singularize($name)], [$to, Inflector::singularize($className)], [$to, $className] ]; foreach ($keys as $map) { list($on, $key) = $map; $key = lcfirst(Inflector::camelize($key)); if (!$on::hasField($key)) { continue; } $join = ($on === $class) ? [$key => $on::key()] : [$local => $key]; $result['key'] = $join; if (isset($config['link'])) { return $result; } $fieldType = $on::schema()->type($key); if ($fieldType === 'id' || $fieldType === 'MongoId') { $isArray = $on::schema()->is('array', $key); $link = $isArray ? $rel::LINK_KEY_LIST : $rel::LINK_KEY; break; } } if (!$link && !$hasLink) { $link = ($type === "belongsTo") ? $rel::LINK_CONTAINED : $rel::LINK_EMBEDDED; } return $result + ($hasLink ? [] : compact('link')); } ]); }
php
public function relationship($class, $type, $name, array $config = []) { $fieldName = $this->relationFieldName($type, $name); $config += compact('name', 'type', 'key', 'fieldName'); $config['from'] = $class; return $this->_instance('relationship', $config + [ 'strategy' => function($rel) use ($config, $class, $name, $type) { if (isset($config['key'])) { return []; } $link = null; $hasLink = isset($config['link']); $result = []; $to = $rel->to(); $local = $class::key(); $className = $class::meta('name'); $keys = [ [$class, $name], [$class, Inflector::singularize($name)], [$to, Inflector::singularize($className)], [$to, $className] ]; foreach ($keys as $map) { list($on, $key) = $map; $key = lcfirst(Inflector::camelize($key)); if (!$on::hasField($key)) { continue; } $join = ($on === $class) ? [$key => $on::key()] : [$local => $key]; $result['key'] = $join; if (isset($config['link'])) { return $result; } $fieldType = $on::schema()->type($key); if ($fieldType === 'id' || $fieldType === 'MongoId') { $isArray = $on::schema()->is('array', $key); $link = $isArray ? $rel::LINK_KEY_LIST : $rel::LINK_KEY; break; } } if (!$link && !$hasLink) { $link = ($type === "belongsTo") ? $rel::LINK_CONTAINED : $rel::LINK_EMBEDDED; } return $result + ($hasLink ? [] : compact('link')); } ]); }
[ "public", "function", "relationship", "(", "$", "class", ",", "$", "type", ",", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "$", "fieldName", "=", "$", "this", "->", "relationFieldName", "(", "$", "type", ",", "$", "name", ")...
Document relationships. @param string $class @param string $type Relationship type, e.g. `belongsTo`. @param string $name @param array $config @return array
[ "Document", "relationships", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L798-L849
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.group
public function group($group, $context) { if (!$group) { return; } if (is_string($group) && strpos($group, 'function') === 0) { return ['$keyf' => new MongoCode($group)]; } $group = (array) $group; foreach ($group as $i => $field) { if (is_int($i)) { $group[$field] = true; unset($group[$i]); } } return ['key' => $group]; }
php
public function group($group, $context) { if (!$group) { return; } if (is_string($group) && strpos($group, 'function') === 0) { return ['$keyf' => new MongoCode($group)]; } $group = (array) $group; foreach ($group as $i => $field) { if (is_int($i)) { $group[$field] = true; unset($group[$i]); } } return ['key' => $group]; }
[ "public", "function", "group", "(", "$", "group", ",", "$", "context", ")", "{", "if", "(", "!", "$", "group", ")", "{", "return", ";", "}", "if", "(", "is_string", "(", "$", "group", ")", "&&", "strpos", "(", "$", "group", ",", "'function'", ")"...
Formats `group` clauses for MongoDB. @param string|array $group The group clause. @param object $context @return array Formatted `group` clause.
[ "Formats", "group", "clauses", "for", "MongoDB", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L858-L874
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.conditions
public function conditions($conditions, $context) { if (!$conditions) { return []; } if ($code = $this->_isMongoCode($conditions)) { return $code; } $schema = null; $model = null; if ($context) { $schema = $context->schema(); $model = $context->model(); } return $this->_conditions($conditions, $model, $schema, $context); }
php
public function conditions($conditions, $context) { if (!$conditions) { return []; } if ($code = $this->_isMongoCode($conditions)) { return $code; } $schema = null; $model = null; if ($context) { $schema = $context->schema(); $model = $context->model(); } return $this->_conditions($conditions, $model, $schema, $context); }
[ "public", "function", "conditions", "(", "$", "conditions", ",", "$", "context", ")", "{", "if", "(", "!", "$", "conditions", ")", "{", "return", "[", "]", ";", "}", "if", "(", "$", "code", "=", "$", "this", "->", "_isMongoCode", "(", "$", "conditi...
Maps incoming conditions with their corresponding MongoDB-native operators. @param array $conditions Array of conditions @param object $context Context with which this method was called; currently inspects the return value of `$context->type()`. @return array Transformed conditions
[ "Maps", "incoming", "conditions", "with", "their", "corresponding", "MongoDB", "-", "native", "operators", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L884-L899
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb._conditions
protected function _conditions(array $conditions, $model, $schema, $context) { $ops = $this->_operators; $castOpts = [ 'first' => true, 'database' => $this, 'wrap' => false, 'asContent' => true ]; $cast = function($key, $value) use (&$schema, &$castOpts) { return $schema ? $schema->cast(null, $key, $value, $castOpts) : $value; }; foreach ($conditions as $key => $value) { if (in_array($key, $this->_boolean)) { $operator = isset($ops[$key]) ? $ops[$key] : $key; foreach ($value as $i => $compare) { $value[$i] = $this->_conditions($compare, $model, $schema, $context); } unset($conditions[$key]); $conditions[$operator] = $value; continue; } if (is_object($value)) { continue; } if (!is_array($value)) { $conditions[$key] = $cast($key, $value); continue; } $current = key($value); if (!isset($ops[$current]) && $current[0] !== '$') { $conditions[$key] = ['$in' => $cast($key, $value)]; continue; } $conditions[$key] = $this->_operators($key, $value, $schema); } return $conditions; }
php
protected function _conditions(array $conditions, $model, $schema, $context) { $ops = $this->_operators; $castOpts = [ 'first' => true, 'database' => $this, 'wrap' => false, 'asContent' => true ]; $cast = function($key, $value) use (&$schema, &$castOpts) { return $schema ? $schema->cast(null, $key, $value, $castOpts) : $value; }; foreach ($conditions as $key => $value) { if (in_array($key, $this->_boolean)) { $operator = isset($ops[$key]) ? $ops[$key] : $key; foreach ($value as $i => $compare) { $value[$i] = $this->_conditions($compare, $model, $schema, $context); } unset($conditions[$key]); $conditions[$operator] = $value; continue; } if (is_object($value)) { continue; } if (!is_array($value)) { $conditions[$key] = $cast($key, $value); continue; } $current = key($value); if (!isset($ops[$current]) && $current[0] !== '$') { $conditions[$key] = ['$in' => $cast($key, $value)]; continue; } $conditions[$key] = $this->_operators($key, $value, $schema); } return $conditions; }
[ "protected", "function", "_conditions", "(", "array", "$", "conditions", ",", "$", "model", ",", "$", "schema", ",", "$", "context", ")", "{", "$", "ops", "=", "$", "this", "->", "_operators", ";", "$", "castOpts", "=", "[", "'first'", "=>", "true", ...
Protected helper method used to format conditions. @todo Catch Document/Array objects used in conditions and extract their values. @param array $conditions The conditions array to be processed. @param string $model The name of the model class used in the query. @param object $schema The object containing the schema definition. @param object $context The `Query` object. @return array Processed query conditions.
[ "Protected", "helper", "method", "used", "to", "format", "conditions", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L911-L948
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.order
public function order($order, $context) { if (!$order) { return []; } if (is_string($order)) { return [$order => 1]; } if (!is_array($order)) { return []; } foreach ($order as $key => $value) { if (!is_string($key)) { unset($order[$key]); $order[$value] = 1; continue; } if (is_string($value)) { $order[$key] = strtolower($value) === 'asc' ? 1 : -1; } } return $order; }
php
public function order($order, $context) { if (!$order) { return []; } if (is_string($order)) { return [$order => 1]; } if (!is_array($order)) { return []; } foreach ($order as $key => $value) { if (!is_string($key)) { unset($order[$key]); $order[$value] = 1; continue; } if (is_string($value)) { $order[$key] = strtolower($value) === 'asc' ? 1 : -1; } } return $order; }
[ "public", "function", "order", "(", "$", "order", ",", "$", "context", ")", "{", "if", "(", "!", "$", "order", ")", "{", "return", "[", "]", ";", "}", "if", "(", "is_string", "(", "$", "order", ")", ")", "{", "return", "[", "$", "order", "=>", ...
Return formatted clause for order. @param mixed $order The `order` clause to be formatted @param object $context @return mixed Formatted `order` clause.
[ "Return", "formatted", "clause", "for", "order", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L1021-L1042
UnionOfRAD/lithium
data/source/MongoDb.php
MongoDb.relationFieldName
public function relationFieldName($type, $name) { $fieldName = Inflector::camelize($name, false); if (preg_match('/Many$/', $type)) { $fieldName = Inflector::pluralize($fieldName); } else { $fieldName = Inflector::singularize($fieldName); } return $fieldName; }
php
public function relationFieldName($type, $name) { $fieldName = Inflector::camelize($name, false); if (preg_match('/Many$/', $type)) { $fieldName = Inflector::pluralize($fieldName); } else { $fieldName = Inflector::singularize($fieldName); } return $fieldName; }
[ "public", "function", "relationFieldName", "(", "$", "type", ",", "$", "name", ")", "{", "$", "fieldName", "=", "Inflector", "::", "camelize", "(", "$", "name", ",", "false", ")", ";", "if", "(", "preg_match", "(", "'/Many$/'", ",", "$", "type", ")", ...
Returns the field name of a relation name (camelBack). @param string The type of the relation. @param string The name of the relation. @return string
[ "Returns", "the", "field", "name", "of", "a", "relation", "name", "(", "camelBack", ")", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/data/source/MongoDb.php#L1057-L1065
UnionOfRAD/lithium
g11n/Locale.php
Locale.respondsTo
public static function respondsTo($method, $internal = false) { return isset(static::$_tags[$method]) || parent::respondsTo($method, $internal); }
php
public static function respondsTo($method, $internal = false) { return isset(static::$_tags[$method]) || parent::respondsTo($method, $internal); }
[ "public", "static", "function", "respondsTo", "(", "$", "method", ",", "$", "internal", "=", "false", ")", "{", "return", "isset", "(", "static", "::", "$", "_tags", "[", "$", "method", "]", ")", "||", "parent", "::", "respondsTo", "(", "$", "method", ...
Determines if a given method can be called. @param string $method Name of the method. @param boolean $internal Provide `true` to perform check from inside the class/object. When `false` checks also for public visibility; defaults to `false`. @return boolean Returns `true` if the method can be called, `false` otherwise.
[ "Determines", "if", "a", "given", "method", "can", "be", "called", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L94-L96
UnionOfRAD/lithium
g11n/Locale.php
Locale.compose
public static function compose($tags) { $result = []; foreach (static::$_tags as $name => $tag) { if (isset($tags[$name])) { $result[] = $tags[$name]; } } if ($result) { return implode('_', $result); } }
php
public static function compose($tags) { $result = []; foreach (static::$_tags as $name => $tag) { if (isset($tags[$name])) { $result[] = $tags[$name]; } } if ($result) { return implode('_', $result); } }
[ "public", "static", "function", "compose", "(", "$", "tags", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "static", "::", "$", "_tags", "as", "$", "name", "=>", "$", "tag", ")", "{", "if", "(", "isset", "(", "$", "tags", "[", "$...
Composes a locale from locale tags. This is the pendant to `Locale::decompose()`. @param array $tags An array as obtained from `Locale::decompose()`. @return string A locale with tags separated by underscores or `null` if none of the passed tags could be used to compose a locale.
[ "Composes", "a", "locale", "from", "locale", "tags", ".", "This", "is", "the", "pendant", "to", "Locale", "::", "decompose", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L105-L116
UnionOfRAD/lithium
g11n/Locale.php
Locale.decompose
public static function decompose($locale) { $regex = '(?P<language>[a-z]{2,3})'; $regex .= '(?:[_-](?P<script>[a-z]{4}))?'; $regex .= '(?:[_-](?P<territory>[a-z]{2}))?'; $regex .= '(?:[_-](?P<variant>[a-z]{5,}))?'; if (!preg_match("/^{$regex}$/i", $locale, $matches)) { throw new InvalidArgumentException("Locale `{$locale}` could not be parsed."); } return array_filter(array_intersect_key($matches, static::$_tags)); }
php
public static function decompose($locale) { $regex = '(?P<language>[a-z]{2,3})'; $regex .= '(?:[_-](?P<script>[a-z]{4}))?'; $regex .= '(?:[_-](?P<territory>[a-z]{2}))?'; $regex .= '(?:[_-](?P<variant>[a-z]{5,}))?'; if (!preg_match("/^{$regex}$/i", $locale, $matches)) { throw new InvalidArgumentException("Locale `{$locale}` could not be parsed."); } return array_filter(array_intersect_key($matches, static::$_tags)); }
[ "public", "static", "function", "decompose", "(", "$", "locale", ")", "{", "$", "regex", "=", "'(?P<language>[a-z]{2,3})'", ";", "$", "regex", ".=", "'(?:[_-](?P<script>[a-z]{4}))?'", ";", "$", "regex", ".=", "'(?:[_-](?P<territory>[a-z]{2}))?'", ";", "$", "regex", ...
Parses a locale into locale tags. This is the pendant to `Locale::compose()``. @param string $locale A locale in an arbitrary form (i.e. `'en_US'` or `'EN-US'`). @return array Parsed language, script, territory and variant tags. @throws InvalidArgumentException
[ "Parses", "a", "locale", "into", "locale", "tags", ".", "This", "is", "the", "pendant", "to", "Locale", "::", "compose", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L125-L135
UnionOfRAD/lithium
g11n/Locale.php
Locale.canonicalize
public static function canonicalize($locale) { $tags = static::decompose($locale); foreach ($tags as $name => &$tag) { foreach ((array) static::$_tags[$name]['formatter'] as $formatter) { $tag = $formatter($tag); } } return static::compose($tags); }
php
public static function canonicalize($locale) { $tags = static::decompose($locale); foreach ($tags as $name => &$tag) { foreach ((array) static::$_tags[$name]['formatter'] as $formatter) { $tag = $formatter($tag); } } return static::compose($tags); }
[ "public", "static", "function", "canonicalize", "(", "$", "locale", ")", "{", "$", "tags", "=", "static", "::", "decompose", "(", "$", "locale", ")", ";", "foreach", "(", "$", "tags", "as", "$", "name", "=>", "&", "$", "tag", ")", "{", "foreach", "...
Returns a locale in its canonical form with tags formatted properly. @param string $locale A locale in an arbitrary form (i.e. `'ZH-HANS-HK_REVISED'`). @return string A locale in its canonical form (i.e. `'zh_Hans_HK_REVISED'`).
[ "Returns", "a", "locale", "in", "its", "canonical", "form", "with", "tags", "formatted", "properly", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L143-L152
UnionOfRAD/lithium
g11n/Locale.php
Locale.cascade
public static function cascade($locale) { $locales[] = $locale; if ($locale === 'root') { return $locales; } $tags = static::decompose($locale); while (count($tags) > 1) { array_pop($tags); $locales[] = static::compose($tags); } $locales[] = 'root'; return $locales; }
php
public static function cascade($locale) { $locales[] = $locale; if ($locale === 'root') { return $locales; } $tags = static::decompose($locale); while (count($tags) > 1) { array_pop($tags); $locales[] = static::compose($tags); } $locales[] = 'root'; return $locales; }
[ "public", "static", "function", "cascade", "(", "$", "locale", ")", "{", "$", "locales", "[", "]", "=", "$", "locale", ";", "if", "(", "$", "locale", "===", "'root'", ")", "{", "return", "$", "locales", ";", "}", "$", "tags", "=", "static", "::", ...
Cascades a locale. Usage: ``` Locale::cascade('en_US'); // returns ['en_US', 'en', 'root'] Locale::cascade('zh_Hans_HK_REVISED'); // returns ['zh_Hans_HK_REVISED', 'zh_Hans_HK', 'zh_Hans', 'zh', 'root'] ``` @link http://www.unicode.org/reports/tr35/tr35-13.html#Locale_Inheritance @param string $locale A locale in an arbitrary form (i.e. `'en_US'` or `'EN-US'`). @return array Indexed array of locales (starting with the most specific one).
[ "Cascades", "a", "locale", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L170-L184
UnionOfRAD/lithium
g11n/Locale.php
Locale.lookup
public static function lookup($locales, $locale) { $tags = static::decompose($locale); while (($count = count($tags)) > 0) { if (($key = array_search(static::compose($tags), $locales)) !== false) { return $locales[$key]; } if ($count === 1) { foreach ($locales as $current) { if (strpos($current, current($tags) . '_') === 0) { return $current; } } } if (($key = array_search(static::compose($tags), $locales)) !== false) { return $locales[$key]; } array_pop($tags); } }
php
public static function lookup($locales, $locale) { $tags = static::decompose($locale); while (($count = count($tags)) > 0) { if (($key = array_search(static::compose($tags), $locales)) !== false) { return $locales[$key]; } if ($count === 1) { foreach ($locales as $current) { if (strpos($current, current($tags) . '_') === 0) { return $current; } } } if (($key = array_search(static::compose($tags), $locales)) !== false) { return $locales[$key]; } array_pop($tags); } }
[ "public", "static", "function", "lookup", "(", "$", "locales", ",", "$", "locale", ")", "{", "$", "tags", "=", "static", "::", "decompose", "(", "$", "locale", ")", ";", "while", "(", "(", "$", "count", "=", "count", "(", "$", "tags", ")", ")", "...
Searches an array of locales for the best match to a locale. The locale is iteratively simplified until either it matches one of the locales in the list or the locale can't be further simplified. This method partially implements the lookup matching scheme as described in RFC 4647, section 3.4 and thus does not strictly conform to the specification. Differences to specification: - No support for wildcards in the to-be-matched locales. - No support for locales with private subtags. - No support for a default return value. - Passed locales are required to be in canonical form (i.e. `'ja_JP'`). @link http://www.ietf.org/rfc/rfc4647.txt @param array $locales Locales to match against `$locale`. @param string $locale A locale in its canonical form (i.e. `'zh_Hans_HK_REVISED'`). @return string The matched locale.
[ "Searches", "an", "array", "of", "locales", "for", "the", "best", "match", "to", "a", "locale", ".", "The", "locale", "is", "iteratively", "simplified", "until", "either", "it", "matches", "one", "of", "the", "locales", "in", "the", "list", "or", "the", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L206-L225
UnionOfRAD/lithium
g11n/Locale.php
Locale.preferred
public static function preferred($request, $available = null) { if (is_array($request)) { $result = $request; } elseif ($request instanceof ActionRequest) { $result = static::_preferredAction($request); } elseif ($request instanceof ConsoleRequest) { $result = static::_preferredConsole($request); } else { return null; } if (!$available) { return array_shift($result); } foreach ((array) $result as $locale) { if ($match = static::lookup($available, $locale)) { return $match; } } }
php
public static function preferred($request, $available = null) { if (is_array($request)) { $result = $request; } elseif ($request instanceof ActionRequest) { $result = static::_preferredAction($request); } elseif ($request instanceof ConsoleRequest) { $result = static::_preferredConsole($request); } else { return null; } if (!$available) { return array_shift($result); } foreach ((array) $result as $locale) { if ($match = static::lookup($available, $locale)) { return $match; } } }
[ "public", "static", "function", "preferred", "(", "$", "request", ",", "$", "available", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "request", ")", ")", "{", "$", "result", "=", "$", "request", ";", "}", "elseif", "(", "$", "request", ...
Determines the preferred locale from a request or array. Optionally negotiates the preferred locale with available locales. @see lithium\g11n\Locale::_preferredAction() @see lithium\g11n\Locale::_preferredConsole() @see lithium\g11n\Locale::lookup() @param object|array $request An action or console request object or an array of locales. @param array $available A list of locales to negotiate the preferred locale with. @return string The preferred locale in its canonical form (i.e. `'fr_CA'`). @todo Rewrite this to remove hard-coded class names.
[ "Determines", "the", "preferred", "locale", "from", "a", "request", "or", "array", ".", "Optionally", "negotiates", "the", "preferred", "locale", "with", "available", "locales", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L239-L257
UnionOfRAD/lithium
g11n/Locale.php
Locale._preferredAction
protected static function _preferredAction($request) { $result = []; $regex = "/^\s*(?P<locale>\w\w(?:[-]\w\w)?)(?:;q=(?P<quality>(0|1|0\.\d+)))?\s*$/"; foreach (explode(',', $request->env('HTTP_ACCEPT_LANGUAGE')) as $part) { if (preg_match($regex, $part, $matches)) { $locale = static::canonicalize($matches['locale']); $quality = isset($matches['quality']) ? $matches['quality'] : 1; $result[$quality][] = $locale; } } krsort($result); return array_reduce($result, function($carry, $item) { return array_merge($carry, array_values($item)); }, []); }
php
protected static function _preferredAction($request) { $result = []; $regex = "/^\s*(?P<locale>\w\w(?:[-]\w\w)?)(?:;q=(?P<quality>(0|1|0\.\d+)))?\s*$/"; foreach (explode(',', $request->env('HTTP_ACCEPT_LANGUAGE')) as $part) { if (preg_match($regex, $part, $matches)) { $locale = static::canonicalize($matches['locale']); $quality = isset($matches['quality']) ? $matches['quality'] : 1; $result[$quality][] = $locale; } } krsort($result); return array_reduce($result, function($carry, $item) { return array_merge($carry, array_values($item)); }, []); }
[ "protected", "static", "function", "_preferredAction", "(", "$", "request", ")", "{", "$", "result", "=", "[", "]", ";", "$", "regex", "=", "\"/^\\s*(?P<locale>\\w\\w(?:[-]\\w\\w)?)(?:;q=(?P<quality>(0|1|0\\.\\d+)))?\\s*$/\"", ";", "foreach", "(", "explode", "(", "','...
Detects preferred locales from an action request by looking at the `'Accept-Language'` header as described by RFC 2616, section 14.4. @link http://www.ietf.org/rfc/rfc2616.txt @param \lithium\action\Request $request @return array Preferred locales in their canonical form (i.e. `'fr_CA'`).
[ "Detects", "preferred", "locales", "from", "an", "action", "request", "by", "looking", "at", "the", "Accept", "-", "Language", "header", "as", "described", "by", "RFC", "2616", "section", "14", ".", "4", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L267-L283
UnionOfRAD/lithium
g11n/Locale.php
Locale._preferredConsole
protected static function _preferredConsole($request) { $regex = '(?P<locale>[\w\_]+)(\.|@|$)+'; $result = []; if ($value = $request->env('LANGUAGE')) { return explode(':', $value); } foreach (['LC_ALL', 'LANG'] as $variable) { $value = $request->env($variable); if (!$value || $value === 'C' || $value === 'POSIX') { continue; } if (preg_match("/{$regex}/", $value, $matches)) { return (array) $matches['locale']; } } return $result; }
php
protected static function _preferredConsole($request) { $regex = '(?P<locale>[\w\_]+)(\.|@|$)+'; $result = []; if ($value = $request->env('LANGUAGE')) { return explode(':', $value); } foreach (['LC_ALL', 'LANG'] as $variable) { $value = $request->env($variable); if (!$value || $value === 'C' || $value === 'POSIX') { continue; } if (preg_match("/{$regex}/", $value, $matches)) { return (array) $matches['locale']; } } return $result; }
[ "protected", "static", "function", "_preferredConsole", "(", "$", "request", ")", "{", "$", "regex", "=", "'(?P<locale>[\\w\\_]+)(\\.|@|$)+'", ";", "$", "result", "=", "[", "]", ";", "if", "(", "$", "value", "=", "$", "request", "->", "env", "(", "'LANGUAG...
Detects preferred locales from a console request by looking at certain environment variables. The environment variables may be present or not depending on your system. If multiple variables are present the following hierarchy is used: `'LANGUAGE'`, `'LC_ALL'`, `'LANG'`. The locales of the `'LC_ALL'` and the `'LANG'` are formatted according to the posix standard: `language(_territory)(.encoding)(@modifier)`. Locales having such a format are automatically canonicalized and transformed into the `Locale` class' format. @link http://www.linux.com/archive/feature/53781 @param \lithium\console\Request $request @return array Preferred locales in their canonical form (i.e. `'fr_CA'`).
[ "Detects", "preferred", "locales", "from", "a", "console", "request", "by", "looking", "at", "certain", "environment", "variables", ".", "The", "environment", "variables", "may", "be", "present", "or", "not", "depending", "on", "your", "system", ".", "If", "mu...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/g11n/Locale.php#L300-L318
UnionOfRAD/lithium
security/Hash.php
Hash.calculate
public static function calculate($data, array $options = []) { if (!is_scalar($data)) { $data = ($data instanceof Closure) ? spl_object_hash($data) : serialize($data); } $defaults = [ 'type' => 'sha512', 'salt' => false, 'key' => false, 'raw' => false ]; $options += $defaults; if ($options['salt']) { $data = "{$options['salt']}{$data}"; } if ($options['key']) { return hash_hmac($options['type'], $data, $options['key'], $options['raw']); } return hash($options['type'], $data, $options['raw']); }
php
public static function calculate($data, array $options = []) { if (!is_scalar($data)) { $data = ($data instanceof Closure) ? spl_object_hash($data) : serialize($data); } $defaults = [ 'type' => 'sha512', 'salt' => false, 'key' => false, 'raw' => false ]; $options += $defaults; if ($options['salt']) { $data = "{$options['salt']}{$data}"; } if ($options['key']) { return hash_hmac($options['type'], $data, $options['key'], $options['raw']); } return hash($options['type'], $data, $options['raw']); }
[ "public", "static", "function", "calculate", "(", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "data", ")", ")", "{", "$", "data", "=", "(", "$", "data", "instanceof", "Closure", ")", ...
Uses PHP's hashing functions to calculate a hash over the data provided, using the options specified. The default hash algorithm is SHA-512. Examples: ``` // Calculates a secure hash over string `'foo'`. Hash::calculate('foo'); // It is possible to hash non-scalar data, too. Hash::calculate(['foo' => 'bar']); // serializes before hashing Hash::calculate(new Foo()); // -- " -- Hash::calculate(function() { return 'bar'; }); // uses `spl_object_hash()` // Also allows for quick - non secure - hashing of arbitrary data. Hash::calculate(['foo' => 'bar'], ['type' => 'crc32b']); ``` @link http://php.net/hash @link http://php.net/hash_hmac @link http://php.net/hash_algos @param mixed $data The arbitrary data to hash. Non-scalar data will be serialized, before being hashed. For anonymous functions the object hash will be used. @param array $options Supported options: - `'type'` _string_: Any valid hashing algorithm. See the `hash_algos()` function to determine which are available on your system. - `'salt'` _string_: A _salt_ value which, if specified, will be prepended to the data. - `'key'` _string_: If specified generates a keyed hash using `hash_hmac()` instead of `hash()`, with `'key'` being used as the message key. - `'raw'` _boolean_: If `true`, outputs the raw binary result of the hash operation. Defaults to `false`. @return string Returns a hash calculated over given data.
[ "Uses", "PHP", "s", "hashing", "functions", "to", "calculate", "a", "hash", "over", "the", "data", "provided", "using", "the", "options", "specified", ".", "The", "default", "hash", "algorithm", "is", "SHA", "-", "512", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Hash.php#L54-L73
UnionOfRAD/lithium
security/Hash.php
Hash.compare
public static function compare($known, $user) { if (function_exists('hash_equals')) { return hash_equals($known, $user); } if (!is_string($known) || !is_string($user)) { trigger_error('Expected `$known` & `$user` parameters to be strings.', E_USER_WARNING); return false; } if (($length = strlen($known)) !== strlen($user)) { return false; } for ($i = 0, $result = 0; $i < $length; $i++) { $result |= ord($known[$i]) ^ ord($user[$i]); } return $result === 0; }
php
public static function compare($known, $user) { if (function_exists('hash_equals')) { return hash_equals($known, $user); } if (!is_string($known) || !is_string($user)) { trigger_error('Expected `$known` & `$user` parameters to be strings.', E_USER_WARNING); return false; } if (($length = strlen($known)) !== strlen($user)) { return false; } for ($i = 0, $result = 0; $i < $length; $i++) { $result |= ord($known[$i]) ^ ord($user[$i]); } return $result === 0; }
[ "public", "static", "function", "compare", "(", "$", "known", ",", "$", "user", ")", "{", "if", "(", "function_exists", "(", "'hash_equals'", ")", ")", "{", "return", "hash_equals", "(", "$", "known", ",", "$", "user", ")", ";", "}", "if", "(", "!", ...
Compares two hashes in constant time to prevent timing attacks. To successfully mitigate timing attacks and not leak the actual length of the known hash, it is important that _both provided hash strings have the same length_ and that the _user-supplied hash string is passed as a second parameter_ rather than first. This function has the same signature and behavior as the native `hash_equals()` function and will use that function if available (PHP >= 5.6). An E_USER_WARNING will be emitted when either of the supplied parameters is not a string. @link http://php.net/hash_equals @link http://codahale.com/a-lesson-in-timing-attacks/ More about timing attacks. @param string $known The hash string of known length to compare against. @param string $user The user-supplied hash string. @return boolean Returns a boolean indicating whether the two hash strings are equal.
[ "Compares", "two", "hashes", "in", "constant", "time", "to", "prevent", "timing", "attacks", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/security/Hash.php#L93-L109
UnionOfRAD/lithium
util/Text.php
Text.uuid
public static function uuid() { $uuid = Random::generate(16); $uuid[6] = chr(ord($uuid[6]) & static::UUID_CLEAR_VER | static::UUID_VERSION_4); $uuid[8] = chr(ord($uuid[8]) & static::UUID_CLEAR_VAR | static::UUID_VAR_RFC); return join('-', [ bin2hex(substr($uuid, 0, 4)), bin2hex(substr($uuid, 4, 2)), bin2hex(substr($uuid, 6, 2)), bin2hex(substr($uuid, 8, 2)), bin2hex(substr($uuid, 10, 6)) ]); }
php
public static function uuid() { $uuid = Random::generate(16); $uuid[6] = chr(ord($uuid[6]) & static::UUID_CLEAR_VER | static::UUID_VERSION_4); $uuid[8] = chr(ord($uuid[8]) & static::UUID_CLEAR_VAR | static::UUID_VAR_RFC); return join('-', [ bin2hex(substr($uuid, 0, 4)), bin2hex(substr($uuid, 4, 2)), bin2hex(substr($uuid, 6, 2)), bin2hex(substr($uuid, 8, 2)), bin2hex(substr($uuid, 10, 6)) ]); }
[ "public", "static", "function", "uuid", "(", ")", "{", "$", "uuid", "=", "Random", "::", "generate", "(", "16", ")", ";", "$", "uuid", "[", "6", "]", "=", "chr", "(", "ord", "(", "$", "uuid", "[", "6", "]", ")", "&", "static", "::", "UUID_CLEAR...
Generates an RFC 4122-compliant version 4 UUID. @return string The string representation of an RFC 4122-compliant, version 4 UUID. @link http://www.ietf.org/rfc/rfc4122.txt RFC 4122: UUID URN Namespace
[ "Generates", "an", "RFC", "4122", "-", "compliant", "version", "4", "UUID", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Text.php#L46-L58
UnionOfRAD/lithium
util/Text.php
Text.insert
public static function insert($str, array $data, array $options = []) { $defaults = [ 'before' => '{:', 'after' => '}', 'escape' => null, 'format' => null, 'clean' => false ]; $options += $defaults; $format = $options['format']; if ($format === 'regex' || (!$format && $options['escape'])) { $format = sprintf( '/(?<!%s)%s%%s%s/', preg_quote($options['escape'], '/'), str_replace('%', '%%', preg_quote($options['before'], '/')), str_replace('%', '%%', preg_quote($options['after'], '/')) ); } if (!$format && key($data) !== 0) { $replace = []; foreach ($data as $key => $value) { if (!is_scalar($value)) { if (is_object($value) && method_exists($value, '__toString')) { $value = (string) $value; } else { $value = ''; } } $replace["{$options['before']}{$key}{$options['after']}"] = $value; } $str = strtr($str, $replace); return $options['clean'] ? static::clean($str, $options) : $str; } if (strpos($str, '?') !== false && isset($data[0])) { $offset = 0; while (($pos = strpos($str, '?', $offset)) !== false) { $val = array_shift($data); $offset = $pos + strlen($val); $str = substr_replace($str, $val, $pos, 1); } return $options['clean'] ? static::clean($str, $options) : $str; } foreach ($data as $key => $value) { if (!$key = sprintf($format, preg_quote($key, '/'))) { continue; } $hash = crc32($key); $str = preg_replace($key, $hash, $str); $str = str_replace($hash, $value, $str); } if (!isset($options['format']) && isset($options['before'])) { $str = str_replace($options['escape'] . $options['before'], $options['before'], $str); } return $options['clean'] ? static::clean($str, $options) : $str; }
php
public static function insert($str, array $data, array $options = []) { $defaults = [ 'before' => '{:', 'after' => '}', 'escape' => null, 'format' => null, 'clean' => false ]; $options += $defaults; $format = $options['format']; if ($format === 'regex' || (!$format && $options['escape'])) { $format = sprintf( '/(?<!%s)%s%%s%s/', preg_quote($options['escape'], '/'), str_replace('%', '%%', preg_quote($options['before'], '/')), str_replace('%', '%%', preg_quote($options['after'], '/')) ); } if (!$format && key($data) !== 0) { $replace = []; foreach ($data as $key => $value) { if (!is_scalar($value)) { if (is_object($value) && method_exists($value, '__toString')) { $value = (string) $value; } else { $value = ''; } } $replace["{$options['before']}{$key}{$options['after']}"] = $value; } $str = strtr($str, $replace); return $options['clean'] ? static::clean($str, $options) : $str; } if (strpos($str, '?') !== false && isset($data[0])) { $offset = 0; while (($pos = strpos($str, '?', $offset)) !== false) { $val = array_shift($data); $offset = $pos + strlen($val); $str = substr_replace($str, $val, $pos, 1); } return $options['clean'] ? static::clean($str, $options) : $str; } foreach ($data as $key => $value) { if (!$key = sprintf($format, preg_quote($key, '/'))) { continue; } $hash = crc32($key); $str = preg_replace($key, $hash, $str); $str = str_replace($hash, $value, $str); } if (!isset($options['format']) && isset($options['before'])) { $str = str_replace($options['escape'] . $options['before'], $options['before'], $str); } return $options['clean'] ? static::clean($str, $options) : $str; }
[ "public", "static", "function", "insert", "(", "$", "str", ",", "array", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'before'", "=>", "'{:'", ",", "'after'", "=>", "'}'", ",", "'escape'", "=>", "n...
Replaces variable placeholders inside a string with any given data. Each key in the `$data` array corresponds to a variable placeholder name in `$str`. Usage: ``` Text::insert( 'My name is {:name} and I am {:age} years old.', ['name' => 'Bob', 'age' => '65'] ); // returns 'My name is Bob and I am 65 years old.' ``` Please note that optimization have applied to this method and parts of the code may look like it can refactored or removed but in fact this is part of the applied optimization. Please check the history for this section of code before refactoring @param string $str A string containing variable place-holders. @param array $data A key, value array where each key stands for a place-holder variable name to be replaced with value. @param array $options Available options are: - `'after'`: The character or string after the name of the variable place-holder (defaults to `}`). - `'before'`: The character or string in front of the name of the variable place-holder (defaults to `'{:'`). - `'clean'`: A boolean or array with instructions for `Text::clean()`. - `'escape'`: The character or string used to escape the before character or string (defaults to `'\'`). - `'format'`: A regular expression to use for matching variable place-holders (defaults to `'/(?<!\\)\:%s/'`. Please note that this option takes precedence over all other options except `'clean'`. @return string
[ "Replaces", "variable", "placeholders", "inside", "a", "string", "with", "any", "given", "data", ".", "Each", "key", "in", "the", "$data", "array", "corresponds", "to", "a", "variable", "placeholder", "name", "in", "$str", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Text.php#L92-L154
UnionOfRAD/lithium
util/Text.php
Text.clean
public static function clean($str, array $options = []) { if (is_array($options['clean'])) { $clean = $options['clean']; } else { $clean = [ 'method' => is_bool($options['clean']) ? 'text' : $options['clean'] ]; } switch ($clean['method']) { case 'text': $clean += [ 'word' => '[\w,.]+', 'gap' => '[\s]*(?:(?:and|or|,)[\s]*)?', 'replacement' => '' ]; $before = preg_quote($options['before'], '/'); $after = preg_quote($options['after'], '/'); $kleenex = sprintf( '/(%s%s%s%s|%s%s%s%s|%s%s%s%s%s)/', $before, $clean['word'], $after, $clean['gap'], $clean['gap'], $before, $clean['word'], $after, $clean['gap'], $before, $clean['word'], $after, $clean['gap'] ); $str = preg_replace($kleenex, $clean['replacement'], $str); break; case 'html': $clean += [ 'word' => '[\w,.]+', 'andText' => true, 'replacement' => '' ]; $kleenex = sprintf( '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i', preg_quote($options['before'], '/'), $clean['word'], preg_quote($options['after'], '/') ); $str = preg_replace($kleenex, $clean['replacement'], $str); if ($clean['andText']) { return static::clean($str, [ 'clean' => ['method' => 'text'] ] + $options); } break; } return $str; }
php
public static function clean($str, array $options = []) { if (is_array($options['clean'])) { $clean = $options['clean']; } else { $clean = [ 'method' => is_bool($options['clean']) ? 'text' : $options['clean'] ]; } switch ($clean['method']) { case 'text': $clean += [ 'word' => '[\w,.]+', 'gap' => '[\s]*(?:(?:and|or|,)[\s]*)?', 'replacement' => '' ]; $before = preg_quote($options['before'], '/'); $after = preg_quote($options['after'], '/'); $kleenex = sprintf( '/(%s%s%s%s|%s%s%s%s|%s%s%s%s%s)/', $before, $clean['word'], $after, $clean['gap'], $clean['gap'], $before, $clean['word'], $after, $clean['gap'], $before, $clean['word'], $after, $clean['gap'] ); $str = preg_replace($kleenex, $clean['replacement'], $str); break; case 'html': $clean += [ 'word' => '[\w,.]+', 'andText' => true, 'replacement' => '' ]; $kleenex = sprintf( '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i', preg_quote($options['before'], '/'), $clean['word'], preg_quote($options['after'], '/') ); $str = preg_replace($kleenex, $clean['replacement'], $str); if ($clean['andText']) { return static::clean($str, [ 'clean' => ['method' => 'text'] ] + $options); } break; } return $str; }
[ "public", "static", "function", "clean", "(", "$", "str", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_array", "(", "$", "options", "[", "'clean'", "]", ")", ")", "{", "$", "clean", "=", "$", "options", "[", "'clean'", "]...
Cleans up a `Text::insert()` formatted string with given `$options` depending on the `'clean'` option. The goal of this function is to replace all whitespace and unneeded mark-up around place-holders that did not get replaced by `Text::insert()`. @param string $str The string to clean. @param array $options Available options are: - `'after'`: characters marking the end of targeted substring. - `'andText'`: (defaults to `true`). - `'before'`: characters marking the start of targeted substring. - `'clean'`: `true` or an array of clean options: - `'gap'`: Regular expression matching gaps. - `'method'`: Either `'text'` or `'html'` (defaults to `'text'`). - `'replacement'`: Text to use for cleaned substrings (defaults to `''`). - `'word'`: Regular expression matching words. @return string The cleaned string.
[ "Cleans", "up", "a", "Text", "::", "insert", "()", "formatted", "string", "with", "given", "$options", "depending", "on", "the", "clean", "option", ".", "The", "goal", "of", "this", "function", "is", "to", "replace", "all", "whitespace", "and", "unneeded", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Text.php#L173-L222
UnionOfRAD/lithium
util/Text.php
Text.extract
public static function extract($regex, $str, $index = 0) { if (!preg_match($regex, $str, $match)) { return false; } return isset($match[$index]) ? $match[$index] : null; }
php
public static function extract($regex, $str, $index = 0) { if (!preg_match($regex, $str, $match)) { return false; } return isset($match[$index]) ? $match[$index] : null; }
[ "public", "static", "function", "extract", "(", "$", "regex", ",", "$", "str", ",", "$", "index", "=", "0", ")", "{", "if", "(", "!", "preg_match", "(", "$", "regex", ",", "$", "str", ",", "$", "match", ")", ")", "{", "return", "false", ";", "}...
Extract a part of a string based on a regular expression `$regex`. @param string $regex The regular expression to use. @param string $str The string to run the extraction on. @param integer $index The number of the part to return based on the regex. @return mixed
[ "Extract", "a", "part", "of", "a", "string", "based", "on", "a", "regular", "expression", "$regex", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Text.php#L232-L237
UnionOfRAD/lithium
util/Text.php
Text.tokenize
public static function tokenize($data, array $options = []) { $options += ['separator' => ',', 'leftBound' => '(', 'rightBound' => ')']; if (!$data || is_array($data)) { return $data; } $depth = 0; $offset = 0; $buffer = ''; $results = []; $length = strlen($data); $open = false; while ($offset <= $length) { $tmpOffset = -1; $offsets = [ strpos($data, $options['separator'], $offset), strpos($data, $options['leftBound'], $offset), strpos($data, $options['rightBound'], $offset) ]; for ($i = 0; $i < 3; $i++) { if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset === -1)) { $tmpOffset = $offsets[$i]; } } if ($tmpOffset === -1) { $results[] = $buffer . substr($data, $offset); $offset = $length + 1; continue; } $buffer .= substr($data, $offset, ($tmpOffset - $offset)); if ($data[$tmpOffset] === $options['separator'] && $depth === 0) { $results[] = $buffer; $buffer = ''; } else { $buffer .= $data{$tmpOffset}; } if ($options['leftBound'] !== $options['rightBound']) { if ($data[$tmpOffset] === $options['leftBound']) { $depth++; } if ($data[$tmpOffset] === $options['rightBound']) { $depth--; } $offset = ++$tmpOffset; continue; } if ($data[$tmpOffset] === $options['leftBound']) { ($open) ? $depth-- : $depth++; $open = !$open; } $offset = ++$tmpOffset; } if (!$results && $buffer) { $results[] = $buffer; } return $results ? array_map('trim', $results) : []; }
php
public static function tokenize($data, array $options = []) { $options += ['separator' => ',', 'leftBound' => '(', 'rightBound' => ')']; if (!$data || is_array($data)) { return $data; } $depth = 0; $offset = 0; $buffer = ''; $results = []; $length = strlen($data); $open = false; while ($offset <= $length) { $tmpOffset = -1; $offsets = [ strpos($data, $options['separator'], $offset), strpos($data, $options['leftBound'], $offset), strpos($data, $options['rightBound'], $offset) ]; for ($i = 0; $i < 3; $i++) { if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset === -1)) { $tmpOffset = $offsets[$i]; } } if ($tmpOffset === -1) { $results[] = $buffer . substr($data, $offset); $offset = $length + 1; continue; } $buffer .= substr($data, $offset, ($tmpOffset - $offset)); if ($data[$tmpOffset] === $options['separator'] && $depth === 0) { $results[] = $buffer; $buffer = ''; } else { $buffer .= $data{$tmpOffset}; } if ($options['leftBound'] !== $options['rightBound']) { if ($data[$tmpOffset] === $options['leftBound']) { $depth++; } if ($data[$tmpOffset] === $options['rightBound']) { $depth--; } $offset = ++$tmpOffset; continue; } if ($data[$tmpOffset] === $options['leftBound']) { ($open) ? $depth-- : $depth++; $open = !$open; } $offset = ++$tmpOffset; } if (!$results && $buffer) { $results[] = $buffer; } return $results ? array_map('trim', $results) : []; }
[ "public", "static", "function", "tokenize", "(", "$", "data", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "+=", "[", "'separator'", "=>", "','", ",", "'leftBound'", "=>", "'('", ",", "'rightBound'", "=>", "')'", "]", ";", "...
Tokenizes a string using `$options['separator']`, ignoring any instances of `$options['separator']` that appear between `$options['leftBound']` and `$options['rightBound']`. @param string $data The data to tokenize. @param array $options Options to use when tokenizing: -`'separator'` _string_: The token to split the data on. -`'leftBound'` _string_: Left scope-enclosing boundary. -`'rightBound'` _string_: Right scope-enclosing boundary. @return array Returns an array of tokens.
[ "Tokenizes", "a", "string", "using", "$options", "[", "separator", "]", "ignoring", "any", "instances", "of", "$options", "[", "separator", "]", "that", "appear", "between", "$options", "[", "leftBound", "]", "and", "$options", "[", "rightBound", "]", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/util/Text.php#L251-L315
UnionOfRAD/lithium
analysis/logger/adapter/File.php
File.write
public function write($priority, $message) { return function($params) { $path = $this->_config['path'] . '/' . $this->_config['file']($params, $this->_config); $params['timestamp'] = date($this->_config['timestamp']); $message = Text::insert($this->_config['format'], $params); return file_put_contents($path, $message, FILE_APPEND); }; }
php
public function write($priority, $message) { return function($params) { $path = $this->_config['path'] . '/' . $this->_config['file']($params, $this->_config); $params['timestamp'] = date($this->_config['timestamp']); $message = Text::insert($this->_config['format'], $params); return file_put_contents($path, $message, FILE_APPEND); }; }
[ "public", "function", "write", "(", "$", "priority", ",", "$", "message", ")", "{", "return", "function", "(", "$", "params", ")", "{", "$", "path", "=", "$", "this", "->", "_config", "[", "'path'", "]", ".", "'/'", ".", "$", "this", "->", "_config...
Appends a message to a log file. @see lithium\analysis\Logger::$_priorities @param string $priority The message priority. See `Logger::$_priorities`. @param string $message The message to write to the log. @return \Closure Function returning boolean `true` on successful write, `false` otherwise.
[ "Appends", "a", "message", "to", "a", "log", "file", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/logger/adapter/File.php#L73-L80
UnionOfRAD/lithium
aop/Chain.php
Chain.run
public function run(array $params, $implementation) { $this->_implementation = $implementation; $filter = reset($this->_filters); $result = $filter($params, $this); $this->_implementation = null; return $result; }
php
public function run(array $params, $implementation) { $this->_implementation = $implementation; $filter = reset($this->_filters); $result = $filter($params, $this); $this->_implementation = null; return $result; }
[ "public", "function", "run", "(", "array", "$", "params", ",", "$", "implementation", ")", "{", "$", "this", "->", "_implementation", "=", "$", "implementation", ";", "$", "filter", "=", "reset", "(", "$", "this", "->", "_filters", ")", ";", "$", "resu...
Runs the chain causing any queued callables and finally the implementation to be executed. Before each run the implementation is made available to `Chain::__invoke()` and the chain rewinded, after each run the implementation is unset. An example implementation which is bound to an instance receives exactly one argument (the named parameters). ``` function($params) { $foo = $this->_bar; return $foo . 'baz'; } ``` @param array $params An array of named parameters. @param callable $implementation @return mixed The end result of the chain.
[ "Runs", "the", "chain", "causing", "any", "queued", "callables", "and", "finally", "the", "implementation", "to", "be", "executed", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Chain.php#L119-L127
UnionOfRAD/lithium
aop/Chain.php
Chain.next
public function next(/* array */ $params) { $message = '`$chain->next()` has been deprecated in favor of `$chain($params)`.'; trigger_error($message, E_USER_DEPRECATED); return $this($this->_bcNext(func_get_args())); }
php
public function next(/* array */ $params) { $message = '`$chain->next()` has been deprecated in favor of `$chain($params)`.'; trigger_error($message, E_USER_DEPRECATED); return $this($this->_bcNext(func_get_args())); }
[ "public", "function", "next", "(", "/* array */", "$", "params", ")", "{", "$", "message", "=", "'`$chain->next()` has been deprecated in favor of `$chain($params)`.'", ";", "trigger_error", "(", "$", "message", ",", "E_USER_DEPRECATED", ")", ";", "return", "$", "this...
Advances the chain by one and executes the next filter in line. This method is usually accessed from within a filter function. ``` function($params, $chain) { return $chain->next($params); } ``` @deprecated @param array $params An array of named parameters. @return mixed The return value of the next filter. If there is no next filter, the return value of the implementation.
[ "Advances", "the", "chain", "by", "one", "and", "executes", "the", "next", "filter", "in", "line", ".", "This", "method", "is", "usually", "accessed", "from", "within", "a", "filter", "function", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Chain.php#L195-L200
UnionOfRAD/lithium
aop/Chain.php
Chain.method
public function method($full = false) { $message = '`$chain->method()` has been deprecated.'; trigger_error($message, E_USER_DEPRECATED); $class = is_string($this->_class) ? $this->_class : get_class($this->_class); return $full ? $class . '::' . $this->_method : $this->_method; }
php
public function method($full = false) { $message = '`$chain->method()` has been deprecated.'; trigger_error($message, E_USER_DEPRECATED); $class = is_string($this->_class) ? $this->_class : get_class($this->_class); return $full ? $class . '::' . $this->_method : $this->_method; }
[ "public", "function", "method", "(", "$", "full", "=", "false", ")", "{", "$", "message", "=", "'`$chain->method()` has been deprecated.'", ";", "trigger_error", "(", "$", "message", ",", "E_USER_DEPRECATED", ")", ";", "$", "class", "=", "is_string", "(", "$",...
Gets the method name associated with this filter chain. This is the method being filtered. @deprecated @param boolean $full Whether to include the class name, defaults to `false`. @return string When $full is `true` returns a string with pattern `<CLASS>::<METHOD>`, else returns just the method name.
[ "Gets", "the", "method", "name", "associated", "with", "this", "filter", "chain", ".", "This", "is", "the", "method", "being", "filtered", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/aop/Chain.php#L211-L217
UnionOfRAD/lithium
storage/cache/adapter/Apc.php
Apc.write
public function write(array $keys, $expiry = null) { $expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry']; if (!$expiry || $expiry === Cache::PERSIST) { $ttl = 0; } elseif (is_int($expiry)) { $ttl = $expiry; } else { $ttl = strtotime($expiry) - time(); } if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys); } return apc_store($keys, null, $ttl) === []; }
php
public function write(array $keys, $expiry = null) { $expiry = $expiry || $expiry === Cache::PERSIST ? $expiry : $this->_config['expiry']; if (!$expiry || $expiry === Cache::PERSIST) { $ttl = 0; } elseif (is_int($expiry)) { $ttl = $expiry; } else { $ttl = strtotime($expiry) - time(); } if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys); } return apc_store($keys, null, $ttl) === []; }
[ "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/Apc.php#L86-L100
UnionOfRAD/lithium
storage/cache/adapter/Apc.php
Apc.read
public function read(array $keys) { if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys); } $results = apc_fetch($keys); 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 = apc_fetch($keys); 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. @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/Apc.php#L111-L121
UnionOfRAD/lithium
storage/cache/adapter/Apc.php
Apc.delete
public function delete(array $keys) { if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys); } return apc_delete($keys) === []; }
php
public function delete(array $keys) { if ($this->_config['scope']) { $keys = $this->_addScopePrefix($this->_config['scope'], $keys); } return apc_delete($keys) === []; }
[ "public", "function", "delete", "(", "array", "$", "keys", ")", "{", "if", "(", "$", "this", "->", "_config", "[", "'scope'", "]", ")", "{", "$", "keys", "=", "$", "this", "->", "_addScopePrefix", "(", "$", "this", "->", "_config", "[", "'scope'", ...
Will attempt to remove specified keys from the user space cache. @param array $keys Keys to uniquely identify the cached items. @return boolean `true` on successful delete, `false` otherwise.
[ "Will", "attempt", "to", "remove", "specified", "keys", "from", "the", "user", "space", "cache", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Apc.php#L129-L134
UnionOfRAD/lithium
storage/cache/adapter/Apc.php
Apc.enabled
public static function enabled() { $loaded = extension_loaded('apc'); $isCli = (php_sapi_name() === 'cli'); $enabled = (!$isCli && ini_get('apc.enabled')) || ($isCli && ini_get('apc.enable_cli')); return ($loaded && $enabled); }
php
public static function enabled() { $loaded = extension_loaded('apc'); $isCli = (php_sapi_name() === 'cli'); $enabled = (!$isCli && ini_get('apc.enabled')) || ($isCli && ini_get('apc.enable_cli')); return ($loaded && $enabled); }
[ "public", "static", "function", "enabled", "(", ")", "{", "$", "loaded", "=", "extension_loaded", "(", "'apc'", ")", ";", "$", "isCli", "=", "(", "php_sapi_name", "(", ")", "===", "'cli'", ")", ";", "$", "enabled", "=", "(", "!", "$", "isCli", "&&", ...
Determines if the APC extension has been installed and if the userspace cache is available. @return boolean `true` if enabled, `false` otherwise.
[ "Determines", "if", "the", "APC", "extension", "has", "been", "installed", "and", "if", "the", "userspace", "cache", "is", "available", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/storage/cache/adapter/Apc.php#L189-L194
UnionOfRAD/lithium
template/helper/Form.php
Form.config
public function config(array $config = []) { if (!$config) { $keys = ['base' => '', 'text' => '', 'textarea' => '', 'attributes' => '']; return ['templates' => $this->_templateMap] + array_intersect_key( $this->_config, $keys ); } if (isset($config['templates'])) { $this->_templateMap = $config['templates'] + $this->_templateMap; unset($config['templates']); } return ($this->_config = Set::merge($this->_config, $config)) + [ 'templates' => $this->_templateMap ]; }
php
public function config(array $config = []) { if (!$config) { $keys = ['base' => '', 'text' => '', 'textarea' => '', 'attributes' => '']; return ['templates' => $this->_templateMap] + array_intersect_key( $this->_config, $keys ); } if (isset($config['templates'])) { $this->_templateMap = $config['templates'] + $this->_templateMap; unset($config['templates']); } return ($this->_config = Set::merge($this->_config, $config)) + [ 'templates' => $this->_templateMap ]; }
[ "public", "function", "config", "(", "array", "$", "config", "=", "[", "]", ")", "{", "if", "(", "!", "$", "config", ")", "{", "$", "keys", "=", "[", "'base'", "=>", "''", ",", "'text'", "=>", "''", ",", "'textarea'", "=>", "''", ",", "'attribute...
Allows you to configure a default set of options which are included on a per-method basis, and configure method template overrides. To force all `<label />` elements to have a default `class` attribute value of `"foo"`, simply do the following: ``` $this->form->config(['label' => ['class' => 'foo']]); ``` Note that this can be overridden on a case-by-case basis, and when overriding, values are not merged or combined. Therefore, if you wanted a particular `<label />` to have both `foo` and `bar` as classes, you would have to specify `'class' => 'foo bar'`. You can also use this method to change the string template that a method uses to render its content. For example, the default template for rendering a checkbox is `'<input type="checkbox" name="{:name}"{:options} />'`. However, suppose you implemented your own custom UI elements, and you wanted to change the markup used, you could do the following: ``` $this->form->config(['templates' => [ 'checkbox' => '<div id="{:name}" class="ui-checkbox-element"{:options}></div>' ]]); ``` Now, for any calls to `$this->form->checkbox()`, your custom markup template will be applied. This works for any `Form` method that renders HTML elements. @see lithium\template\helper\Form::$_templateMap @param array $config An associative array where the keys are `Form` method names (or `'templates'`, to include a template-overriding sub-array), and the values are arrays of configuration options to be included in the `$options` parameter of each method specified. @return array Returns an array containing the currently set per-method configurations, and an array of the currently set template overrides (in the `'templates'` array key).
[ "Allows", "you", "to", "configure", "a", "default", "set", "of", "options", "which", "are", "included", "on", "a", "per", "-", "method", "basis", "and", "configure", "method", "template", "overrides", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L236-L250
UnionOfRAD/lithium
template/helper/Form.php
Form.create
public function create($bindings = null, array $options = []) { $request = $this->_context ? $this->_context->request() : null; $binding = is_array($bindings) ? reset($bindings) : $bindings; $defaults = [ 'url' => $request ? $request->params : [], 'type' => null, 'action' => null, 'method' => $binding ? ($binding->exists() ? 'put' : 'post') : 'post' ]; list(, $options, $tpl) = $this->_defaults(__FUNCTION__, null, $options); list($scope, $options) = $this->_options($defaults, $options); $params = compact('scope', 'options', 'bindings'); $extra = ['method' => __METHOD__] + compact('tpl', 'defaults'); return Filters::run($this, __FUNCTION__, $params, function($params) use ($extra) { $scope = $params['scope']; $options = $params['options']; $this->_binding = $params['bindings']; $append = null; $scope['method'] = strtolower($scope['method']); if ($scope['type'] === 'file') { if ($scope['method'] === 'get') { $scope['method'] = 'post'; } $options['enctype'] = 'multipart/form-data'; } if (!($scope['method'] === 'get' || $scope['method'] === 'post')) { $append = $this->hidden('_method', ['value' => strtoupper($scope['method'])]); $scope['method'] = 'post'; } $url = $scope['action'] ? ['action' => $scope['action']] : $scope['url']; $options['method'] = strtolower($scope['method']); $this->_bindingOptions = $scope + $options; return $this->_render($extra['method'], $extra['tpl'], compact('url', 'options', 'append') ); }); }
php
public function create($bindings = null, array $options = []) { $request = $this->_context ? $this->_context->request() : null; $binding = is_array($bindings) ? reset($bindings) : $bindings; $defaults = [ 'url' => $request ? $request->params : [], 'type' => null, 'action' => null, 'method' => $binding ? ($binding->exists() ? 'put' : 'post') : 'post' ]; list(, $options, $tpl) = $this->_defaults(__FUNCTION__, null, $options); list($scope, $options) = $this->_options($defaults, $options); $params = compact('scope', 'options', 'bindings'); $extra = ['method' => __METHOD__] + compact('tpl', 'defaults'); return Filters::run($this, __FUNCTION__, $params, function($params) use ($extra) { $scope = $params['scope']; $options = $params['options']; $this->_binding = $params['bindings']; $append = null; $scope['method'] = strtolower($scope['method']); if ($scope['type'] === 'file') { if ($scope['method'] === 'get') { $scope['method'] = 'post'; } $options['enctype'] = 'multipart/form-data'; } if (!($scope['method'] === 'get' || $scope['method'] === 'post')) { $append = $this->hidden('_method', ['value' => strtoupper($scope['method'])]); $scope['method'] = 'post'; } $url = $scope['action'] ? ['action' => $scope['action']] : $scope['url']; $options['method'] = strtolower($scope['method']); $this->_bindingOptions = $scope + $options; return $this->_render($extra['method'], $extra['tpl'], compact('url', 'options', 'append') ); }); }
[ "public", "function", "create", "(", "$", "bindings", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "request", "=", "$", "this", "->", "_context", "?", "$", "this", "->", "_context", "->", "request", "(", ")", ":", "null"...
Creates an HTML form, and optionally binds it to a data object which contains information on how to render form fields, any data to pre-populate the form with, and any validation errors. Typically, a data object will be a `Record` object returned from a `Model`, but you can define your own custom objects as well. For more information on custom data objects, see `lithium\template\helper\Form::$_binding`. @see lithium\template\helper\Form::$_binding @see lithium\data\Entity @param mixed $bindings List of objects, or the object to bind the form to. This is usually an instance of `Record` or `Document`, or some other class that extends `lithium\data\Entity`. @param array $options Other parameters for creating the form. Available options are: - `'url'` _mixed_: A string URL or URL array parameters defining where in the application the form should be submitted to. - `'action'` _string_: This is a shortcut to be used if you wish to only specify the name of the action to submit to, and use the default URL parameters (i.e. the current controller, etc.) for generating the remainder of the URL. Ignored if the `'url'` key is set. - `'type'` _string_: Currently the only valid option is `'file'`. Set this if the form will be used for file uploads. - `'method'` _string_: Represents the HTTP method with which the form will be submitted (`'get'`, `'post'`, `'put'` or `'delete'`). If `'put'` or `'delete'`, the request method is simulated using a hidden input field. @return string Returns a `<form />` open tag with the `action` attribute defined by either the `'action'` or `'url'` options (defaulting to the current page if none is specified), the HTTP method is defined by the `'method'` option, and any HTML attributes passed in `$options`. @filter
[ "Creates", "an", "HTML", "form", "and", "optionally", "binds", "it", "to", "a", "data", "object", "which", "contains", "information", "on", "how", "to", "render", "form", "fields", "any", "data", "to", "pre", "-", "populate", "the", "form", "with", "and", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L282-L326
UnionOfRAD/lithium
template/helper/Form.php
Form.end
public function end() { list(, $options, $template) = $this->_defaults(__FUNCTION__, null, []); $params = compact('options', 'template'); $result = Filters::run($this, __FUNCTION__, $params, function($params) { $this->_bindingOptions = []; return $this->_render('end', $params['template'], []); }); unset($this->_binding); $this->_binding = null; return $result; }
php
public function end() { list(, $options, $template) = $this->_defaults(__FUNCTION__, null, []); $params = compact('options', 'template'); $result = Filters::run($this, __FUNCTION__, $params, function($params) { $this->_bindingOptions = []; return $this->_render('end', $params['template'], []); }); unset($this->_binding); $this->_binding = null; return $result; }
[ "public", "function", "end", "(", ")", "{", "list", "(", ",", "$", "options", ",", "$", "template", ")", "=", "$", "this", "->", "_defaults", "(", "__FUNCTION__", ",", "null", ",", "[", "]", ")", ";", "$", "params", "=", "compact", "(", "'options'"...
Echoes a closing `</form>` tag and unbinds the `Form` helper from any `Record` or `Document` object used to generate the corresponding form. @return string Returns a closing `</form>` tag. @filter
[ "Echoes", "a", "closing", "<", "/", "form", ">", "tag", "and", "unbinds", "the", "Form", "helper", "from", "any", "Record", "or", "Document", "object", "used", "to", "generate", "the", "corresponding", "form", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L335-L346
UnionOfRAD/lithium
template/helper/Form.php
Form.binding
public function binding($name = null) { if (!$this->_binding) { return $this->_config['binding'](null, $name); } $binding = $this->_binding; $model = null; $key = $name; if (is_array($binding)) { switch (true) { case strpos($name, '.'): list($model, $key) = explode('.', $name, 2); $binding = isset($binding[$model]) ? $binding[$model] : reset($binding); break; case isset($binding[$name]): $binding = $binding[$name]; $key = null; break; default: $binding = reset($binding); break; } } return $key ? $this->_config['binding']($binding, $key) : $binding; }
php
public function binding($name = null) { if (!$this->_binding) { return $this->_config['binding'](null, $name); } $binding = $this->_binding; $model = null; $key = $name; if (is_array($binding)) { switch (true) { case strpos($name, '.'): list($model, $key) = explode('.', $name, 2); $binding = isset($binding[$model]) ? $binding[$model] : reset($binding); break; case isset($binding[$name]): $binding = $binding[$name]; $key = null; break; default: $binding = reset($binding); break; } } return $key ? $this->_config['binding']($binding, $key) : $binding; }
[ "public", "function", "binding", "(", "$", "name", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "_binding", ")", "{", "return", "$", "this", "->", "_config", "[", "'binding'", "]", "(", "null", ",", "$", "name", ")", ";", "}", "$", ...
Returns the entity that the `Form` helper is currently bound to. @see lithium\template\helper\Form::$_binding @param string $name If specified, match this field name against the list of bindings @param string $key If $name specified, where to store relevant $_binding key @return object Returns an object, usually an instance of `lithium\data\Entity`.
[ "Returns", "the", "entity", "that", "the", "Form", "helper", "is", "currently", "bound", "to", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L356-L381
UnionOfRAD/lithium
template/helper/Form.php
Form.field
public function field($name, array $options = []) { if (is_array($name)) { return $this->_fields($name, $options); } $method = __FUNCTION__; if (isset($options['type']) && !empty($this->_config['field-' . $options['type']])) { $method = 'field-' . $options['type']; } list(, $options, $template) = $this->_defaults($method, $name, $options); $defaults = [ 'label' => null, 'type' => isset($options['list']) ? 'select' : 'text', 'template' => $template, 'wrap' => [], 'list' => null, 'error' => [] ]; list($options, $field) = $this->_options($defaults, $options); $label = $input = null; $wrap = $options['wrap']; $type = $options['type']; $list = $options['list']; $error = $options['error']; $template = $options['template']; $notText = $template === 'field' && $type !== 'text'; if ($notText && $this->_context->strings('field-' . $type)) { $template = 'field-' . $type; } if (($options['label'] === null || $options['label']) && $options['type'] !== 'hidden') { if (!$options['label']) { $options['label'] = Inflector::humanize(preg_replace('/[\[\]\.]/', '_', $name)); } $label = $this->label(isset($options['id']) ? $options['id'] : '', $options['label']); } if ($type === 'text' && $list) { if (is_array($list)) { list($list, $datalist) = $this->_datalist($list, $options); } $field['list'] = $list; } else { $datalist = null; } $call = ($type === 'select') ? [$name, $list, $field] : [$name, $field]; $input = call_user_func_array([$this, $type], $call); if ($error !== false && $this->_binding) { $error = $this->error($name, null, ['messages' => $error]); } else { $error = null; } return $this->_render(__METHOD__, $template, compact( 'wrap', 'label', 'input', 'datalist', 'error' )); }
php
public function field($name, array $options = []) { if (is_array($name)) { return $this->_fields($name, $options); } $method = __FUNCTION__; if (isset($options['type']) && !empty($this->_config['field-' . $options['type']])) { $method = 'field-' . $options['type']; } list(, $options, $template) = $this->_defaults($method, $name, $options); $defaults = [ 'label' => null, 'type' => isset($options['list']) ? 'select' : 'text', 'template' => $template, 'wrap' => [], 'list' => null, 'error' => [] ]; list($options, $field) = $this->_options($defaults, $options); $label = $input = null; $wrap = $options['wrap']; $type = $options['type']; $list = $options['list']; $error = $options['error']; $template = $options['template']; $notText = $template === 'field' && $type !== 'text'; if ($notText && $this->_context->strings('field-' . $type)) { $template = 'field-' . $type; } if (($options['label'] === null || $options['label']) && $options['type'] !== 'hidden') { if (!$options['label']) { $options['label'] = Inflector::humanize(preg_replace('/[\[\]\.]/', '_', $name)); } $label = $this->label(isset($options['id']) ? $options['id'] : '', $options['label']); } if ($type === 'text' && $list) { if (is_array($list)) { list($list, $datalist) = $this->_datalist($list, $options); } $field['list'] = $list; } else { $datalist = null; } $call = ($type === 'select') ? [$name, $list, $field] : [$name, $field]; $input = call_user_func_array([$this, $type], $call); if ($error !== false && $this->_binding) { $error = $this->error($name, null, ['messages' => $error]); } else { $error = null; } return $this->_render(__METHOD__, $template, compact( 'wrap', 'label', 'input', 'datalist', 'error' )); }
[ "public", "function", "field", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "return", "$", "this", "->", "_fields", "(", "$", "name", ",", "$", "options", ")", ...
Generates a form field with a label, input, and error message (if applicable), all contained within a wrapping element. ``` echo $this->form->field('name'); echo $this->form->field('present', ['type' => 'checkbox']); echo $this->form->field(['email' => 'Enter a valid email']); echo $this->form->field(['name','email','phone'], ['div' => false]); ``` @param mixed $name The name of the field to render. If the form was bound to an object passed in `create()`, `$name` should be the name of a field in that object. Otherwise, can be any arbitrary field name, as it will appear in POST data. Alternatively supply an array of fields that will use the same options [$field1 => $label1, $field2, $field3 => $label3] @param array $options Rendering options for the form field. The available options are as follows: - `'label'` _mixed_: A string or array defining the label text and / or parameters. By default, the label text is a human-friendly version of `$name`. However, you can specify the label manually as a string, or both the label text and options as an array, i.e.: `array('Your Label Title' => ['class' => 'foo', 'other' => 'options'])`. - `'type'` _string_: The type of form field to render. Available default options are: `'text'`, `'textarea'`, `'select'`, `'checkbox'`, `'password'` or `'hidden'`, as well as any arbitrary type (i.e. HTML5 form fields). - `'template'` _string_: Defaults to `'template'`, but can be set to any named template string, or an arbitrary HTML fragment. For example, to change the default wrapper tag from `<div />` to `<li />`, you can pass the following: `'<li{:wrap}>{:label}{:input}{:error}</li>'`. - `'wrap'` _array_: An array of HTML attributes which will be embedded in the wrapper tag. - `list` _array|string_: If `'type'` is set to `'select'`, `'list'` is an array of key/value pairs representing the `$list` parameter of the `select()` method. If `'type'` is set to `'text'`, `'list'` is used to render/reference a corresponding `<datalist>` element. It then can either be an array of option values or a string to reference an existing `<datalist>`. - `error` _array|string|boolean_: Allows to control rendering of error messages. By setting this option to `false` any messages are disabled. When an array mapping failed rule names to messages, will use these alternative message instead of the ones provided when the validation was originally defined (i.e inside the model). The array may contain a `'default'` key which value will be used as a fallback message. In absence of a default message, the original messages get rendered instead. When providing a string it will be used for any error messages. @return string Returns a form input (the input type is based on the `'type'` option), with label and error message, wrapped in a `<div />` element.
[ "Generates", "a", "form", "field", "with", "a", "label", "input", "and", "error", "message", "(", "if", "applicable", ")", "all", "contained", "within", "a", "wrapping", "element", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L465-L522
UnionOfRAD/lithium
template/helper/Form.php
Form._fields
protected function _fields(array $fields, array $options = []) { $result = []; foreach ($fields as $field => $label) { if (is_numeric($field)) { $field = $label; unset($label); } $result[] = $this->field($field, compact('label') + $options); } return join("\n", $result); }
php
protected function _fields(array $fields, array $options = []) { $result = []; foreach ($fields as $field => $label) { if (is_numeric($field)) { $field = $label; unset($label); } $result[] = $this->field($field, compact('label') + $options); } return join("\n", $result); }
[ "protected", "function", "_fields", "(", "array", "$", "fields", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", "=>", "$", "label", ")", "{", "if", "(",...
Helper method used by `Form::field()` for iterating over an array of multiple fields. @see lithium\template\helper\Form::field() @param array $fields An array of fields to render. @param array $options The array of options to apply to all fields in the `$fields` array. See the `$options` parameter of the `field` method for more information. @return string Returns the fields rendered by `field()`, each separated by a newline.
[ "Helper", "method", "used", "by", "Form", "::", "field", "()", "for", "iterating", "over", "an", "array", "of", "multiple", "fields", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L533-L544
UnionOfRAD/lithium
template/helper/Form.php
Form.button
public function button($title = null, array $options = []) { $defaults = ['escape' => true]; list($scope, $options) = $this->_options($defaults, $options); list($title, $options, $template) = $this->_defaults(__METHOD__, $title, $options); $arguments = compact('type', 'title', 'options', 'value'); return $this->_render(__METHOD__, 'button', $arguments, $scope); }
php
public function button($title = null, array $options = []) { $defaults = ['escape' => true]; list($scope, $options) = $this->_options($defaults, $options); list($title, $options, $template) = $this->_defaults(__METHOD__, $title, $options); $arguments = compact('type', 'title', 'options', 'value'); return $this->_render(__METHOD__, 'button', $arguments, $scope); }
[ "public", "function", "button", "(", "$", "title", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'escape'", "=>", "true", "]", ";", "list", "(", "$", "scope", ",", "$", "options", ")", "=", "$", ...
Generates an HTML button `<button></button>`. @param string $title The title of the button. @param array $options Any options passed are converted to HTML attributes within the `<button></button>` tag. @return string Returns a `<button></button>` tag with the given title and HTML attributes.
[ "Generates", "an", "HTML", "button", "<button", ">", "<", "/", "button", ">", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L554-L561
UnionOfRAD/lithium
template/helper/Form.php
Form.submit
public function submit($title = null, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, null, $options); return $this->_render(__METHOD__, $template, compact('title', 'options')); }
php
public function submit($title = null, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, null, $options); return $this->_render(__METHOD__, $template, compact('title', 'options')); }
[ "public", "function", "submit", "(", "$", "title", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "list", "(", "$", "name", ",", "$", "options", ",", "$", "template", ")", "=", "$", "this", "->", "_defaults", "(", "__FUNCTION__...
Generates an HTML `<input type="submit" />` object. @param string $title The title of the submit button. @param array $options Any options passed are converted to HTML attributes within the `<input />` tag. @return string Returns a submit `<input />` tag with the given title and HTML attributes.
[ "Generates", "an", "HTML", "<input", "type", "=", "submit", "/", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L571-L574
UnionOfRAD/lithium
template/helper/Form.php
Form.textarea
public function textarea($name, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options(['value' => null], $options); $value = isset($scope['value']) ? $scope['value'] : ''; return $this->_render(__METHOD__, $template, compact('name', 'options', 'value')); }
php
public function textarea($name, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options(['value' => null], $options); $value = isset($scope['value']) ? $scope['value'] : ''; return $this->_render(__METHOD__, $template, compact('name', 'options', 'value')); }
[ "public", "function", "textarea", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "list", "(", "$", "name", ",", "$", "options", ",", "$", "template", ")", "=", "$", "this", "->", "_defaults", "(", "__FUNCTION__", ",", "$",...
Generates an HTML `<textarea>...</textarea>` object. @param string $name The name of the field. @param array $options The options to be used when generating the `<textarea />` tag pair, which are as follows: - `'value'` _string_: The content value of the field. - Any other options specified are rendered as HTML attributes of the element. @return string Returns a `<textarea>` tag with the given name and HTML attributes.
[ "Generates", "an", "HTML", "<textarea", ">", "...", "<", "/", "textarea", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L586-L591
UnionOfRAD/lithium
template/helper/Form.php
Form._datalist
protected function _datalist(array $list, array $scope) { $options = []; if (isset($scope['id'])) { $id = $options['id'] = $scope['id'] . 'List'; } $raw = array_reduce($list, function($carry, $value) { return $carry .= $this->_render(__METHOD__, 'datalist-option', compact('value')); }, ''); return [ isset($options['id']) ? $options['id'] : null, $this->_render(__METHOD__, 'datalist', compact('options', 'raw')) ]; }
php
protected function _datalist(array $list, array $scope) { $options = []; if (isset($scope['id'])) { $id = $options['id'] = $scope['id'] . 'List'; } $raw = array_reduce($list, function($carry, $value) { return $carry .= $this->_render(__METHOD__, 'datalist-option', compact('value')); }, ''); return [ isset($options['id']) ? $options['id'] : null, $this->_render(__METHOD__, 'datalist', compact('options', 'raw')) ]; }
[ "protected", "function", "_datalist", "(", "array", "$", "list", ",", "array", "$", "scope", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "scope", "[", "'id'", "]", ")", ")", "{", "$", "id", "=", "$", "options", "...
Generates an HTML `<datalist></datalist>` object with `<option>` elements. @link https://www.w3.org/wiki/HTML/Elements/datalist @param array $list Valuues, which will be used to render the options of the datalist. @param array $scope An array of options passed to the parent scope. @return string Returns a `<datalist>` tag with `<option>` elements.
[ "Generates", "an", "HTML", "<datalist", ">", "<", "/", "datalist", ">", "object", "with", "<option", ">", "elements", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L613-L627
UnionOfRAD/lithium
template/helper/Form.php
Form.select
public function select($name, $list = [], array $options = []) { $defaults = ['empty' => false, 'value' => null]; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if ($scope['empty']) { $list = ['' => ($scope['empty'] === true) ? '' : $scope['empty']] + $list; } if ($template === __FUNCTION__ && $scope['multiple']) { $template = 'select-multi'; } $raw = $this->_selectOptions($list, $scope); return $this->_render(__METHOD__, $template, compact('name', 'options', 'raw')); }
php
public function select($name, $list = [], array $options = []) { $defaults = ['empty' => false, 'value' => null]; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if ($scope['empty']) { $list = ['' => ($scope['empty'] === true) ? '' : $scope['empty']] + $list; } if ($template === __FUNCTION__ && $scope['multiple']) { $template = 'select-multi'; } $raw = $this->_selectOptions($list, $scope); return $this->_render(__METHOD__, $template, compact('name', 'options', 'raw')); }
[ "public", "function", "select", "(", "$", "name", ",", "$", "list", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'empty'", "=>", "false", ",", "'value'", "=>", "null", "]", ";", "list", "(", ...
Generates a `<select />` list using the `$list` parameter for the `<option />` tags. The default selection will be set to the value of `$options['value']`, if specified. For example: ``` $this->form->select('colors', [1 => 'red', 2 => 'green', 3 => 'blue'], [ 'id' => 'Colors', 'value' => 2 ]); // Renders a '<select />' list with options 'red', 'green' and 'blue', with the 'green' // option as the selection ``` @param string $name The `name` attribute of the `<select />` element. @param array $list An associative array of key/value pairs, which will be used to render the list of options. @param array $options Any HTML attributes that should be associated with the `<select />` element. If the `'value'` key is set, this will be the value of the option that is selected by default. @return string Returns an HTML `<select />` element.
[ "Generates", "a", "<select", "/", ">", "list", "using", "the", "$list", "parameter", "for", "the", "<option", "/", ">", "tags", ".", "The", "default", "selection", "will", "be", "set", "to", "the", "value", "of", "$options", "[", "value", "]", "if", "s...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L650-L663
UnionOfRAD/lithium
template/helper/Form.php
Form._selectOptions
protected function _selectOptions(array $list, array $scope) { $result = ""; foreach ($list as $value => $title) { if (is_array($title)) { $label = $value; $options = []; $raw = $this->_selectOptions($title, $scope); $params = compact('label', 'options', 'raw'); $result .= $this->_render('select', 'option-group', $params); continue; } $selected = ( (is_array($scope['value']) && in_array($value, $scope['value'])) || ($scope['empty'] && empty($scope['value']) && $value === '') || (is_scalar($scope['value']) && ((string) $scope['value'] === (string) $value)) ); $options = $selected ? ['selected' => true] : []; $params = compact('value', 'title', 'options'); $result .= $this->_render('select', 'select-option', $params); } return $result; }
php
protected function _selectOptions(array $list, array $scope) { $result = ""; foreach ($list as $value => $title) { if (is_array($title)) { $label = $value; $options = []; $raw = $this->_selectOptions($title, $scope); $params = compact('label', 'options', 'raw'); $result .= $this->_render('select', 'option-group', $params); continue; } $selected = ( (is_array($scope['value']) && in_array($value, $scope['value'])) || ($scope['empty'] && empty($scope['value']) && $value === '') || (is_scalar($scope['value']) && ((string) $scope['value'] === (string) $value)) ); $options = $selected ? ['selected' => true] : []; $params = compact('value', 'title', 'options'); $result .= $this->_render('select', 'select-option', $params); } return $result; }
[ "protected", "function", "_selectOptions", "(", "array", "$", "list", ",", "array", "$", "scope", ")", "{", "$", "result", "=", "\"\"", ";", "foreach", "(", "$", "list", "as", "$", "value", "=>", "$", "title", ")", "{", "if", "(", "is_array", "(", ...
Generator method used by `select()` to produce `<option />` and `<optgroup />` elements. Generally, this method should not need to be called directly, but through `select()`. @param array $list Either a flat key/value array of select menu options, or an array which contains key/value elements and/or elements where the keys are `<optgroup />` titles and the values are sub-arrays of key/value pairs representing nested `<option />` elements. @param array $scope An array of options passed to the parent scope, including the currently selected value of the associated form element. @return string Returns a string of `<option />` and (optionally) `<optgroup />` tags to be embedded in a select element.
[ "Generator", "method", "used", "by", "select", "()", "to", "produce", "<option", "/", ">", "and", "<optgroup", "/", ">", "elements", ".", "Generally", "this", "method", "should", "not", "need", "to", "be", "called", "directly", "but", "through", "select", ...
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L678-L701
UnionOfRAD/lithium
template/helper/Form.php
Form.checkbox
public function checkbox($name, array $options = []) { $defaults = ['value' => '1', 'hidden' => true]; $options += $defaults; $default = $options['value']; $key = $name; $out = ''; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if (!isset($options['checked'])) { $options['checked'] = ($this->binding($key)->data == $default); } if ($scope['hidden']) { $out = $this->hidden($name, ['value' => '', 'id' => false]); } $options['value'] = $scope['value']; return $out . $this->_render(__METHOD__, $template, compact('name', 'options')); }
php
public function checkbox($name, array $options = []) { $defaults = ['value' => '1', 'hidden' => true]; $options += $defaults; $default = $options['value']; $key = $name; $out = ''; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if (!isset($options['checked'])) { $options['checked'] = ($this->binding($key)->data == $default); } if ($scope['hidden']) { $out = $this->hidden($name, ['value' => '', 'id' => false]); } $options['value'] = $scope['value']; return $out . $this->_render(__METHOD__, $template, compact('name', 'options')); }
[ "public", "function", "checkbox", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'value'", "=>", "'1'", ",", "'hidden'", "=>", "true", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$", ...
Generates an HTML `<input type="checkbox" />` object. @param string $name The name of the field. @param array $options Options to be used when generating the checkbox `<input />` element: - `'checked'` _boolean_: Whether or not the field should be checked by default. - `'value'` _mixed_: if specified, it will be used as the 'value' html attribute and no hidden input field will be added. - Any other options specified are rendered as HTML attributes of the element. @return string Returns a `<input />` tag with the given name and HTML attributes.
[ "Generates", "an", "HTML", "<input", "type", "=", "checkbox", "/", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L714-L732
UnionOfRAD/lithium
template/helper/Form.php
Form.radio
public function radio($name, array $options = []) { $defaults = ['value' => '1']; $options += $defaults; $default = $options['value']; $key = $name; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if (!isset($options['checked'])) { $options['checked'] = ($this->binding($key)->data == $default); } $options['value'] = $scope['value']; return $this->_render(__METHOD__, $template, compact('name', 'options')); }
php
public function radio($name, array $options = []) { $defaults = ['value' => '1']; $options += $defaults; $default = $options['value']; $key = $name; list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); list($scope, $options) = $this->_options($defaults, $options); if (!isset($options['checked'])) { $options['checked'] = ($this->binding($key)->data == $default); } $options['value'] = $scope['value']; return $this->_render(__METHOD__, $template, compact('name', 'options')); }
[ "public", "function", "radio", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'value'", "=>", "'1'", "]", ";", "$", "options", "+=", "$", "defaults", ";", "$", "default", "=", "$", "options", ...
Generates an HTML `<input type="radio" />` object. @param string $name The name of the field @param array $options All options to be used when generating the radio `<input />` element: - `'checked'` _boolean_: Whether or not the field should be selected by default. - `'value'` _mixed_: if specified, it will be used as the 'value' html attribute. Defaults to `1` - Any other options specified are rendered as HTML attributes of the element. @return string Returns a `<input />` tag with the given name and attributes
[ "Generates", "an", "HTML", "<input", "type", "=", "radio", "/", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L745-L760
UnionOfRAD/lithium
template/helper/Form.php
Form.password
public function password($name, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); unset($options['value']); return $this->_render(__METHOD__, $template, compact('name', 'options')); }
php
public function password($name, array $options = []) { list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); unset($options['value']); return $this->_render(__METHOD__, $template, compact('name', 'options')); }
[ "public", "function", "password", "(", "$", "name", ",", "array", "$", "options", "=", "[", "]", ")", "{", "list", "(", "$", "name", ",", "$", "options", ",", "$", "template", ")", "=", "$", "this", "->", "_defaults", "(", "__FUNCTION__", ",", "$",...
Generates an HTML `<input type="password" />` object. @param string $name The name of the field. @param array $options An array of HTML attributes with which the field should be rendered. @return string Returns a `<input />` tag with the given name and HTML attributes.
[ "Generates", "an", "HTML", "<input", "type", "=", "password", "/", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L769-L773
UnionOfRAD/lithium
template/helper/Form.php
Form.label
public function label($id, $title = null, array $options = []) { $defaults = ['escape' => true]; if (is_array($title)) { $options = current($title); $title = key($title); } $title = $title ?: Inflector::humanize(str_replace('.', '_', $id)); list($name, $options, $template) = $this->_defaults(__FUNCTION__, $id, $options); list($scope, $options) = $this->_options($defaults, $options); if (strpos($id, '.')) { $generator = $this->_config['attributes']['id']; $id = $generator(__METHOD__, $id, $options); } return $this->_render(__METHOD__, $template, compact('id', 'title', 'options'), $scope); }
php
public function label($id, $title = null, array $options = []) { $defaults = ['escape' => true]; if (is_array($title)) { $options = current($title); $title = key($title); } $title = $title ?: Inflector::humanize(str_replace('.', '_', $id)); list($name, $options, $template) = $this->_defaults(__FUNCTION__, $id, $options); list($scope, $options) = $this->_options($defaults, $options); if (strpos($id, '.')) { $generator = $this->_config['attributes']['id']; $id = $generator(__METHOD__, $id, $options); } return $this->_render(__METHOD__, $template, compact('id', 'title', 'options'), $scope); }
[ "public", "function", "label", "(", "$", "id", ",", "$", "title", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'escape'", "=>", "true", "]", ";", "if", "(", "is_array", "(", "$", "title", ")", ...
Generates an HTML `<label></label>` object. @param string $id The DOM ID of the field that the label is for. @param string $title The content inside the `<label></label>` object. @param array $options Besides HTML attributes, this parameter allows one additional flag: - `'escape'` _boolean_: Defaults to `true`. Indicates whether the title of the label should be escaped. If `false`, it will be treated as raw HTML. @return string Returns a `<label>` tag for the name and with HTML attributes.
[ "Generates", "an", "HTML", "<label", ">", "<", "/", "label", ">", "object", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L797-L814
UnionOfRAD/lithium
template/helper/Form.php
Form.error
public function error($name, $key = null, array $options = []) { $defaults = ['class' => 'error', 'messages' => []]; list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); $options += $defaults; if (is_array($options['messages'])) { $messages = $options['messages'] + ['default' => null]; } else { $messages = ['default' => $options['messages']]; } unset($options['messages']); $params = compact('name', 'key', 'messages', 'options', 'template'); return Filters::run($this, __FUNCTION__, $params, function($params) { $options = $params['options']; $template = $params['template']; $messages = $params['messages']; if (isset($options['value'])) { unset($options['value']); } if (!$content = $this->binding($params['name'])->errors) { return null; } $result = ''; if (!is_array($content)) { return $this->_render(__METHOD__, $template, compact('content', 'options')); } $errors = $content; if ($params['key'] === null) { foreach ($errors as $rule => $content) { if (isset($messages[$rule])) { $content = $messages[$rule]; } elseif ($messages['default']) { $content = $messages['default']; } $result .= $this->_render(__METHOD__, $template, compact('content', 'options')); } return $result; } $key = $params['key']; $content = !isset($errors[$key]) || $key === true ? reset($errors) : $errors[$key]; return $this->_render(__METHOD__, $template, compact('content', 'options')); }); }
php
public function error($name, $key = null, array $options = []) { $defaults = ['class' => 'error', 'messages' => []]; list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options); $options += $defaults; if (is_array($options['messages'])) { $messages = $options['messages'] + ['default' => null]; } else { $messages = ['default' => $options['messages']]; } unset($options['messages']); $params = compact('name', 'key', 'messages', 'options', 'template'); return Filters::run($this, __FUNCTION__, $params, function($params) { $options = $params['options']; $template = $params['template']; $messages = $params['messages']; if (isset($options['value'])) { unset($options['value']); } if (!$content = $this->binding($params['name'])->errors) { return null; } $result = ''; if (!is_array($content)) { return $this->_render(__METHOD__, $template, compact('content', 'options')); } $errors = $content; if ($params['key'] === null) { foreach ($errors as $rule => $content) { if (isset($messages[$rule])) { $content = $messages[$rule]; } elseif ($messages['default']) { $content = $messages['default']; } $result .= $this->_render(__METHOD__, $template, compact('content', 'options')); } return $result; } $key = $params['key']; $content = !isset($errors[$key]) || $key === true ? reset($errors) : $errors[$key]; return $this->_render(__METHOD__, $template, compact('content', 'options')); }); }
[ "public", "function", "error", "(", "$", "name", ",", "$", "key", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "defaults", "=", "[", "'class'", "=>", "'error'", ",", "'messages'", "=>", "[", "]", "]", ";", "list", "(",...
Generates an error message for a field which is part of an object bound to a form in `create()`. @param string $name The name of the field for which to render an error. @param mixed $key If more than one error is present for `$name`, a key may be specified. If `$key` is not set in the array of errors, or if `$key` is `true`, the first available error is used. @param array $options Any rendering options or HTML attributes to be used when rendering the error. @return string Returns a rendered error message based on the `'error'` string template.
[ "Generates", "an", "error", "message", "for", "a", "field", "which", "is", "part", "of", "an", "object", "bound", "to", "a", "form", "in", "create", "()", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L828-L876
UnionOfRAD/lithium
template/helper/Form.php
Form._defaults
protected function _defaults($method, $name, $options) { $params = compact('method', 'name', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $method = $params['method']; $name = $params['name']; $options = $params['options']; $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : []; $options += $methodConfig + $this->_config['base']; $options = $this->_generators($method, $name, $options); $hasValue = ( (!isset($options['value']) || $options['value'] === null) && $name && $value = $this->binding($name)->data ); $isZero = (isset($value) && ($value === 0 || $value === "0")); if ($hasValue || $isZero) { $options['value'] = $value; } if (isset($options['value']) && !$isZero) { $isZero = ($options['value'] === 0 || $options['value'] === "0"); } if (isset($options['default']) && empty($options['value']) && !$isZero) { $options['value'] = $options['default']; } unset($options['default']); $generator = $this->_config['attributes']['name']; $name = $generator($method, $name, $options); $tplKey = isset($options['template']) ? $options['template'] : $method; $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey; return [$name, $options, $template]; }); }
php
protected function _defaults($method, $name, $options) { $params = compact('method', 'name', 'options'); return Filters::run($this, __FUNCTION__, $params, function($params) { $method = $params['method']; $name = $params['name']; $options = $params['options']; $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : []; $options += $methodConfig + $this->_config['base']; $options = $this->_generators($method, $name, $options); $hasValue = ( (!isset($options['value']) || $options['value'] === null) && $name && $value = $this->binding($name)->data ); $isZero = (isset($value) && ($value === 0 || $value === "0")); if ($hasValue || $isZero) { $options['value'] = $value; } if (isset($options['value']) && !$isZero) { $isZero = ($options['value'] === 0 || $options['value'] === "0"); } if (isset($options['default']) && empty($options['value']) && !$isZero) { $options['value'] = $options['default']; } unset($options['default']); $generator = $this->_config['attributes']['name']; $name = $generator($method, $name, $options); $tplKey = isset($options['template']) ? $options['template'] : $method; $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey; return [$name, $options, $template]; }); }
[ "protected", "function", "_defaults", "(", "$", "method", ",", "$", "name", ",", "$", "options", ")", "{", "$", "params", "=", "compact", "(", "'method'", ",", "'name'", ",", "'options'", ")", ";", "return", "Filters", "::", "run", "(", "$", "this", ...
Builds the defaults array for a method by name, according to the config. @param string $method The name of the method to create defaults for. @param string $name The `$name` supplied to the original method. @param string $options `$options` from the original method. @return array Defaults array contents.
[ "Builds", "the", "defaults", "array", "for", "a", "method", "by", "name", "according", "to", "the", "config", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L886-L922
UnionOfRAD/lithium
template/helper/Form.php
Form._generators
protected function _generators($method, $name, $options) { foreach ($this->_config['attributes'] as $key => $generator) { if ($key === 'name') { continue; } if ($generator && !isset($options[$key])) { if (($attr = $generator($method, $name, $options)) !== null) { $options[$key] = $attr; } continue; } if ($generator && $options[$key] === false) { unset($options[$key]); } } return $options; }
php
protected function _generators($method, $name, $options) { foreach ($this->_config['attributes'] as $key => $generator) { if ($key === 'name') { continue; } if ($generator && !isset($options[$key])) { if (($attr = $generator($method, $name, $options)) !== null) { $options[$key] = $attr; } continue; } if ($generator && $options[$key] === false) { unset($options[$key]); } } return $options; }
[ "protected", "function", "_generators", "(", "$", "method", ",", "$", "name", ",", "$", "options", ")", "{", "foreach", "(", "$", "this", "->", "_config", "[", "'attributes'", "]", "as", "$", "key", "=>", "$", "generator", ")", "{", "if", "(", "$", ...
Iterates over the configured attribute generators, and modifies the settings for a tag. @param string $method The name of the helper method which was called, i.e. `'text'`, `'select'`, etc. @param string $name The name of the field whose attributes are being generated. Some helper methods, such as `create()` and `end()`, are not field-based, and therefore will have no name. @param array $options The options and HTML attributes that will be used to generate the helper output. @return array Returns the value of the `$options` array, modified by the attribute generators added in the `'attributes'` key of the helper's configuration. Note that if a generator is present for a field whose value is `false`, that field will be removed from the array.
[ "Iterates", "over", "the", "configured", "attribute", "generators", "and", "modifies", "the", "settings", "for", "a", "tag", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Form.php#L939-L955
UnionOfRAD/lithium
template/View.php
View._init
protected function _init() { parent::_init(); $encoding = 'UTF-8'; if ($this->_response) { $encoding =& $this->_response->encoding; } $h = function($data) use (&$encoding) { return htmlspecialchars((string) $data, ENT_QUOTES, $encoding); }; $this->outputFilters += compact('h') + $this->_config['outputFilters']; foreach (['loader', 'renderer'] as $key) { if (is_object($this->_config[$key])) { $this->{'_' . $key} = $this->_config[$key]; continue; } $class = $this->_config[$key]; $config = ['view' => $this] + $this->_config; $this->{'_' . $key} = Libraries::instance($this->_adapters, $class, $config); } }
php
protected function _init() { parent::_init(); $encoding = 'UTF-8'; if ($this->_response) { $encoding =& $this->_response->encoding; } $h = function($data) use (&$encoding) { return htmlspecialchars((string) $data, ENT_QUOTES, $encoding); }; $this->outputFilters += compact('h') + $this->_config['outputFilters']; foreach (['loader', 'renderer'] as $key) { if (is_object($this->_config[$key])) { $this->{'_' . $key} = $this->_config[$key]; continue; } $class = $this->_config[$key]; $config = ['view' => $this] + $this->_config; $this->{'_' . $key} = Libraries::instance($this->_adapters, $class, $config); } }
[ "protected", "function", "_init", "(", ")", "{", "parent", "::", "_init", "(", ")", ";", "$", "encoding", "=", "'UTF-8'", ";", "if", "(", "$", "this", "->", "_response", ")", "{", "$", "encoding", "=", "&", "$", "this", "->", "_response", "->", "en...
Perform initialization of the View. Looks up and initializes loader and renderer classes, and initializes the output escape handler, matching the encoding from the `Response` object. @return void
[ "Perform", "initialization", "of", "the", "View", "." ]
train
https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L246-L268