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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
eghojansu/moe
src/AbstractModel.php
AbstractModel.copyfrom
public function copyfrom($key,$func=NULL) { $var=is_array($key)?$key:Instance::get($key); if ($func) $var=call_user_func($func,$var); foreach ($var as $key=>$val) !isset($this->_properties['fields'][$key]) || $this->set($key, $val); return $this; }
php
public function copyfrom($key,$func=NULL) { $var=is_array($key)?$key:Instance::get($key); if ($func) $var=call_user_func($func,$var); foreach ($var as $key=>$val) !isset($this->_properties['fields'][$key]) || $this->set($key, $val); return $this; }
[ "public", "function", "copyfrom", "(", "$", "key", ",", "$", "func", "=", "NULL", ")", "{", "$", "var", "=", "is_array", "(", "$", "key", ")", "?", "$", "key", ":", "Instance", "::", "get", "(", "$", "key", ")", ";", "if", "(", "$", "func", ")", "$", "var", "=", "call_user_func", "(", "$", "func", ",", "$", "var", ")", ";", "foreach", "(", "$", "var", "as", "$", "key", "=>", "$", "val", ")", "!", "isset", "(", "$", "this", "->", "_properties", "[", "'fields'", "]", "[", "$", "key", "]", ")", "||", "$", "this", "->", "set", "(", "$", "key", ",", "$", "val", ")", ";", "return", "$", "this", ";", "}" ]
Hydrate mapper object using hive array variable @return NULL @param $key string @param $func callback
[ "Hydrate", "mapper", "object", "using", "hive", "array", "variable" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L301-L310
eghojansu/moe
src/AbstractModel.php
AbstractModel.copyto
public function copyto($key) { $var=&Base::instance()->ref($key); foreach (array_merge($this->_schema['init'], array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule'))) as $key=>$val) $var[$key]=$val; return $this; }
php
public function copyto($key) { $var=&Base::instance()->ref($key); foreach (array_merge($this->_schema['init'], array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule'))) as $key=>$val) $var[$key]=$val; return $this; }
[ "public", "function", "copyto", "(", "$", "key", ")", "{", "$", "var", "=", "&", "Base", "::", "instance", "(", ")", "->", "ref", "(", "$", "key", ")", ";", "foreach", "(", "array_merge", "(", "$", "this", "->", "_schema", "[", "'init'", "]", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'values'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'others'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ")", "as", "$", "key", "=>", "$", "val", ")", "$", "var", "[", "$", "key", "]", "=", "$", "val", ";", "return", "$", "this", ";", "}" ]
Populate hive array variable with mapper fields @return NULL @param $key string
[ "Populate", "hive", "array", "variable", "with", "mapper", "fields" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L317-L326
eghojansu/moe
src/AbstractModel.php
AbstractModel.get
public function get($var) { return isset($this->_schema['values'][$var])? $this->_schema['values'][$var]:( isset($this->_schema['others'][$var])? $this->_schema['others'][$var]:null); }
php
public function get($var) { return isset($this->_schema['values'][$var])? $this->_schema['values'][$var]:( isset($this->_schema['others'][$var])? $this->_schema['others'][$var]:null); }
[ "public", "function", "get", "(", "$", "var", ")", "{", "return", "isset", "(", "$", "this", "->", "_schema", "[", "'values'", "]", "[", "$", "var", "]", ")", "?", "$", "this", "->", "_schema", "[", "'values'", "]", "[", "$", "var", "]", ":", "(", "isset", "(", "$", "this", "->", "_schema", "[", "'others'", "]", "[", "$", "var", "]", ")", "?", "$", "this", "->", "_schema", "[", "'others'", "]", "[", "$", "var", "]", ":", "null", ")", ";", "}" ]
Get fields value
[ "Get", "fields", "value" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L351-L357
eghojansu/moe
src/AbstractModel.php
AbstractModel.findByPK
public function findByPK() { $pk = func_get_args(); if (!$this->_properties['primary_key'] || !$pk) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); !is_array(reset($pk)) || $pk = array_shift($pk); $criteria = $values = array(); foreach ($this->_properties['primary_key'] as $field) { $token = ':pk_'.$field; $criteria[] = '{table}.'.$field.'='.$token; $values[$token] = isset($pk[$field])?$pk[$field]:array_shift($pk); } return $this->limit(1)->find(implode(' and ', $criteria), $values); }
php
public function findByPK() { $pk = func_get_args(); if (!$this->_properties['primary_key'] || !$pk) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); !is_array(reset($pk)) || $pk = array_shift($pk); $criteria = $values = array(); foreach ($this->_properties['primary_key'] as $field) { $token = ':pk_'.$field; $criteria[] = '{table}.'.$field.'='.$token; $values[$token] = isset($pk[$field])?$pk[$field]:array_shift($pk); } return $this->limit(1)->find(implode(' and ', $criteria), $values); }
[ "public", "function", "findByPK", "(", ")", "{", "$", "pk", "=", "func_get_args", "(", ")", ";", "if", "(", "!", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "||", "!", "$", "pk", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_PrimaryKey", ",", "get_called_class", "(", ")", ")", ",", "1", ")", ";", "!", "is_array", "(", "reset", "(", "$", "pk", ")", ")", "||", "$", "pk", "=", "array_shift", "(", "$", "pk", ")", ";", "$", "criteria", "=", "$", "values", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "as", "$", "field", ")", "{", "$", "token", "=", "':pk_'", ".", "$", "field", ";", "$", "criteria", "[", "]", "=", "'{table}.'", ".", "$", "field", ".", "'='", ".", "$", "token", ";", "$", "values", "[", "$", "token", "]", "=", "isset", "(", "$", "pk", "[", "$", "field", "]", ")", "?", "$", "pk", "[", "$", "field", "]", ":", "array_shift", "(", "$", "pk", ")", ";", "}", "return", "$", "this", "->", "limit", "(", "1", ")", "->", "find", "(", "implode", "(", "' and '", ",", "$", "criteria", ")", ",", "$", "values", ")", ";", "}" ]
Find by PK
[ "Find", "by", "PK" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L476-L491
eghojansu/moe
src/AbstractModel.php
AbstractModel.pkValue
public function pkValue() { if ($args = func_get_args()) { !is_array($args[0]) || $args = array_shift($args); $args = array_values($args); foreach ($args as $key=>$arg) $this->{$this->_properties['primary_key'][$key]} = $arg; return $this; } $pk = array_intersect_key($this->_schema['values'], array_fill_keys($this->_properties['primary_key'], null)); return count($pk)==0?null:(count($pk)==1?array_shift($pk):$pk); }
php
public function pkValue() { if ($args = func_get_args()) { !is_array($args[0]) || $args = array_shift($args); $args = array_values($args); foreach ($args as $key=>$arg) $this->{$this->_properties['primary_key'][$key]} = $arg; return $this; } $pk = array_intersect_key($this->_schema['values'], array_fill_keys($this->_properties['primary_key'], null)); return count($pk)==0?null:(count($pk)==1?array_shift($pk):$pk); }
[ "public", "function", "pkValue", "(", ")", "{", "if", "(", "$", "args", "=", "func_get_args", "(", ")", ")", "{", "!", "is_array", "(", "$", "args", "[", "0", "]", ")", "||", "$", "args", "=", "array_shift", "(", "$", "args", ")", ";", "$", "args", "=", "array_values", "(", "$", "args", ")", ";", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "arg", ")", "$", "this", "->", "{", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "[", "$", "key", "]", "}", "=", "$", "arg", ";", "return", "$", "this", ";", "}", "$", "pk", "=", "array_intersect_key", "(", "$", "this", "->", "_schema", "[", "'values'", "]", ",", "array_fill_keys", "(", "$", "this", "->", "_properties", "[", "'primary_key'", "]", ",", "null", ")", ")", ";", "return", "count", "(", "$", "pk", ")", "==", "0", "?", "null", ":", "(", "count", "(", "$", "pk", ")", "==", "1", "?", "array_shift", "(", "$", "pk", ")", ":", "$", "pk", ")", ";", "}" ]
Get PK Value @return mixed pk value
[ "Get", "PK", "Value" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L497-L512
eghojansu/moe
src/AbstractModel.php
AbstractModel.pkCompare
public function pkCompare($pk) { $pkThis = $this->pkValue(); is_array($pkThis) || $pkThis = array($pkThis); is_array($pk) || $pk = array($pk); if (count($pkThis)!=count($pk)) return false; foreach ($pkThis as $key => $value) if (!isset($pk[$key]) || $pk[$key]!=$value) return false; return true; }
php
public function pkCompare($pk) { $pkThis = $this->pkValue(); is_array($pkThis) || $pkThis = array($pkThis); is_array($pk) || $pk = array($pk); if (count($pkThis)!=count($pk)) return false; foreach ($pkThis as $key => $value) if (!isset($pk[$key]) || $pk[$key]!=$value) return false; return true; }
[ "public", "function", "pkCompare", "(", "$", "pk", ")", "{", "$", "pkThis", "=", "$", "this", "->", "pkValue", "(", ")", ";", "is_array", "(", "$", "pkThis", ")", "||", "$", "pkThis", "=", "array", "(", "$", "pkThis", ")", ";", "is_array", "(", "$", "pk", ")", "||", "$", "pk", "=", "array", "(", "$", "pk", ")", ";", "if", "(", "count", "(", "$", "pkThis", ")", "!=", "count", "(", "$", "pk", ")", ")", "return", "false", ";", "foreach", "(", "$", "pkThis", "as", "$", "key", "=>", "$", "value", ")", "if", "(", "!", "isset", "(", "$", "pk", "[", "$", "key", "]", ")", "||", "$", "pk", "[", "$", "key", "]", "!=", "$", "value", ")", "return", "false", ";", "return", "true", ";", "}" ]
Compare PK
[ "Compare", "PK" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L517-L532
eghojansu/moe
src/AbstractModel.php
AbstractModel.generatePK
public function generatePK() { $format = $this->pkFormat; $pk = $this->_properties['primary_key']; if (isset($pk[1])) throw new Exception(sprintf(self::E_Composit, get_called_class(), __FUNCTION__), 1); $pk = array_shift($pk); if (!$pk) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $last = (int) $this ->select(($format['serial']? 'right('.$pk.', '.$format['serial'].')': $pk).' as last') ->order($pk.' desc') ->read(1) ->last; // compile prefix format if (preg_match('/\{(?<date>.+)\}/', $format['prefix'], $match)) $newPK = preg_replace('/\{.+\}/', date($match['date']), $format['prefix']); else $newPK = $format['prefix']; $newPK .= trim(str_pad($last+1, $format['serial'], $format['prefix']?'0':' ', STR_PAD_LEFT)); return $newPK; }
php
public function generatePK() { $format = $this->pkFormat; $pk = $this->_properties['primary_key']; if (isset($pk[1])) throw new Exception(sprintf(self::E_Composit, get_called_class(), __FUNCTION__), 1); $pk = array_shift($pk); if (!$pk) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $last = (int) $this ->select(($format['serial']? 'right('.$pk.', '.$format['serial'].')': $pk).' as last') ->order($pk.' desc') ->read(1) ->last; // compile prefix format if (preg_match('/\{(?<date>.+)\}/', $format['prefix'], $match)) $newPK = preg_replace('/\{.+\}/', date($match['date']), $format['prefix']); else $newPK = $format['prefix']; $newPK .= trim(str_pad($last+1, $format['serial'], $format['prefix']?'0':' ', STR_PAD_LEFT)); return $newPK; }
[ "public", "function", "generatePK", "(", ")", "{", "$", "format", "=", "$", "this", "->", "pkFormat", ";", "$", "pk", "=", "$", "this", "->", "_properties", "[", "'primary_key'", "]", ";", "if", "(", "isset", "(", "$", "pk", "[", "1", "]", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Composit", ",", "get_called_class", "(", ")", ",", "__FUNCTION__", ")", ",", "1", ")", ";", "$", "pk", "=", "array_shift", "(", "$", "pk", ")", ";", "if", "(", "!", "$", "pk", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_PrimaryKey", ",", "get_called_class", "(", ")", ")", ",", "1", ")", ";", "$", "last", "=", "(", "int", ")", "$", "this", "->", "select", "(", "(", "$", "format", "[", "'serial'", "]", "?", "'right('", ".", "$", "pk", ".", "', '", ".", "$", "format", "[", "'serial'", "]", ".", "')'", ":", "$", "pk", ")", ".", "' as last'", ")", "->", "order", "(", "$", "pk", ".", "' desc'", ")", "->", "read", "(", "1", ")", "->", "last", ";", "// compile prefix format", "if", "(", "preg_match", "(", "'/\\{(?<date>.+)\\}/'", ",", "$", "format", "[", "'prefix'", "]", ",", "$", "match", ")", ")", "$", "newPK", "=", "preg_replace", "(", "'/\\{.+\\}/'", ",", "date", "(", "$", "match", "[", "'date'", "]", ")", ",", "$", "format", "[", "'prefix'", "]", ")", ";", "else", "$", "newPK", "=", "$", "format", "[", "'prefix'", "]", ";", "$", "newPK", ".=", "trim", "(", "str_pad", "(", "$", "last", "+", "1", ",", "$", "format", "[", "'serial'", "]", ",", "$", "format", "[", "'prefix'", "]", "?", "'0'", ":", "' '", ",", "STR_PAD_LEFT", ")", ")", ";", "return", "$", "newPK", ";", "}" ]
Generate PK only if pk count = 1 @return string Next PK
[ "Generate", "PK", "only", "if", "pk", "count", "=", "1" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L548-L576
eghojansu/moe
src/AbstractModel.php
AbstractModel.exists
public function exists($criteria = null, array $values = array()) { if (!$this->_properties['primary_key'] || (!$values && !$criteria)) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $that = clone $this; $values ? $that->find($criteria, $values) : $that->findByPK($criteria); return $that->wet(); }
php
public function exists($criteria = null, array $values = array()) { if (!$this->_properties['primary_key'] || (!$values && !$criteria)) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $that = clone $this; $values ? $that->find($criteria, $values) : $that->findByPK($criteria); return $that->wet(); }
[ "public", "function", "exists", "(", "$", "criteria", "=", "null", ",", "array", "$", "values", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "||", "(", "!", "$", "values", "&&", "!", "$", "criteria", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_PrimaryKey", ",", "get_called_class", "(", ")", ")", ",", "1", ")", ";", "$", "that", "=", "clone", "$", "this", ";", "$", "values", "?", "$", "that", "->", "find", "(", "$", "criteria", ",", "$", "values", ")", ":", "$", "that", "->", "findByPK", "(", "$", "criteria", ")", ";", "return", "$", "that", "->", "wet", "(", ")", ";", "}" ]
Check existance
[ "Check", "existance" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L581-L590
eghojansu/moe
src/AbstractModel.php
AbstractModel.unique
public function unique($criteria = null, array $values = array()) { if (!$this->_properties['primary_key'] || (!$values && !$criteria)) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $that = clone $this; $values ? $that->find($criteria, $values) : $that->findByPK($criteria); return ($that->dry() || $this->pkCompare($that->pkValue())); }
php
public function unique($criteria = null, array $values = array()) { if (!$this->_properties['primary_key'] || (!$values && !$criteria)) throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1); $that = clone $this; $values ? $that->find($criteria, $values) : $that->findByPK($criteria); return ($that->dry() || $this->pkCompare($that->pkValue())); }
[ "public", "function", "unique", "(", "$", "criteria", "=", "null", ",", "array", "$", "values", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "||", "(", "!", "$", "values", "&&", "!", "$", "criteria", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_PrimaryKey", ",", "get_called_class", "(", ")", ")", ",", "1", ")", ";", "$", "that", "=", "clone", "$", "this", ";", "$", "values", "?", "$", "that", "->", "find", "(", "$", "criteria", ",", "$", "values", ")", ":", "$", "that", "->", "findByPK", "(", "$", "criteria", ")", ";", "return", "(", "$", "that", "->", "dry", "(", ")", "||", "$", "this", "->", "pkCompare", "(", "$", "that", "->", "pkValue", "(", ")", ")", ")", ";", "}" ]
Check not existance
[ "Check", "not", "existance" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L595-L604
eghojansu/moe
src/AbstractModel.php
AbstractModel.cast
public function cast($init = true) { return array_merge($init?$this->_schema['init']:array(), array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule'))); }
php
public function cast($init = true) { return array_merge($init?$this->_schema['init']:array(), array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule'))); }
[ "public", "function", "cast", "(", "$", "init", "=", "true", ")", "{", "return", "array_merge", "(", "$", "init", "?", "$", "this", "->", "_schema", "[", "'init'", "]", ":", "array", "(", ")", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'values'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'others'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ")", ";", "}" ]
Get data
[ "Get", "data" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L609-L614
eghojansu/moe
src/AbstractModel.php
AbstractModel.page
public function page($page = 1, $limit = 10) { $query = $this ->disableResetAfterBuild() ->limit($limit) ->offset($page*$limit-$limit) ->buildSelect(); return [ 'data'=>$this->run($query['query'], $query['param'])? $this->_stmt->fetchAll($this->_schema['fetch']):[], 'recordsTotal'=>($total = $this ->enableResetAfterBuild() ->limit(0) ->offset(0) ->count(true)), 'totalPage'=>$limit>0?ceil($total/$limit):0, ]; }
php
public function page($page = 1, $limit = 10) { $query = $this ->disableResetAfterBuild() ->limit($limit) ->offset($page*$limit-$limit) ->buildSelect(); return [ 'data'=>$this->run($query['query'], $query['param'])? $this->_stmt->fetchAll($this->_schema['fetch']):[], 'recordsTotal'=>($total = $this ->enableResetAfterBuild() ->limit(0) ->offset(0) ->count(true)), 'totalPage'=>$limit>0?ceil($total/$limit):0, ]; }
[ "public", "function", "page", "(", "$", "page", "=", "1", ",", "$", "limit", "=", "10", ")", "{", "$", "query", "=", "$", "this", "->", "disableResetAfterBuild", "(", ")", "->", "limit", "(", "$", "limit", ")", "->", "offset", "(", "$", "page", "*", "$", "limit", "-", "$", "limit", ")", "->", "buildSelect", "(", ")", ";", "return", "[", "'data'", "=>", "$", "this", "->", "run", "(", "$", "query", "[", "'query'", "]", ",", "$", "query", "[", "'param'", "]", ")", "?", "$", "this", "->", "_stmt", "->", "fetchAll", "(", "$", "this", "->", "_schema", "[", "'fetch'", "]", ")", ":", "[", "]", ",", "'recordsTotal'", "=>", "(", "$", "total", "=", "$", "this", "->", "enableResetAfterBuild", "(", ")", "->", "limit", "(", "0", ")", "->", "offset", "(", "0", ")", "->", "count", "(", "true", ")", ")", ",", "'totalPage'", "=>", "$", "limit", ">", "0", "?", "ceil", "(", "$", "total", "/", "$", "limit", ")", ":", "0", ",", "]", ";", "}" ]
Paging
[ "Paging" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L619-L637
eghojansu/moe
src/AbstractModel.php
AbstractModel.next
public function next() { if (!$this->hasError()) { $row = $this->_stmt->fetch($this->_schema['fetch']); $this->assign($row?:array_fill_keys(array_keys( $this->_properties['fields']), null)); } return $this; }
php
public function next() { if (!$this->hasError()) { $row = $this->_stmt->fetch($this->_schema['fetch']); $this->assign($row?:array_fill_keys(array_keys( $this->_properties['fields']), null)); } return $this; }
[ "public", "function", "next", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasError", "(", ")", ")", "{", "$", "row", "=", "$", "this", "->", "_stmt", "->", "fetch", "(", "$", "this", "->", "_schema", "[", "'fetch'", "]", ")", ";", "$", "this", "->", "assign", "(", "$", "row", "?", ":", "array_fill_keys", "(", "array_keys", "(", "$", "this", "->", "_properties", "[", "'fields'", "]", ")", ",", "null", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
get next row and assign row to schema values
[ "get", "next", "row", "and", "assign", "row", "to", "schema", "values" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L655-L664
eghojansu/moe
src/AbstractModel.php
AbstractModel.read
public function read($limit = 0) { $this->limit($limit); $query = $this->buildSelect(); $this->run($query['query'], $query['param']); return $this->next(); }
php
public function read($limit = 0) { $this->limit($limit); $query = $this->buildSelect(); $this->run($query['query'], $query['param']); return $this->next(); }
[ "public", "function", "read", "(", "$", "limit", "=", "0", ")", "{", "$", "this", "->", "limit", "(", "$", "limit", ")", ";", "$", "query", "=", "$", "this", "->", "buildSelect", "(", ")", ";", "$", "this", "->", "run", "(", "$", "query", "[", "'query'", "]", ",", "$", "query", "[", "'param'", "]", ")", ";", "return", "$", "this", "->", "next", "(", ")", ";", "}" ]
perform select query
[ "perform", "select", "query" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L669-L676
eghojansu/moe
src/AbstractModel.php
AbstractModel.readAll
public function readAll($limit = 0) { $this->limit($limit); $query = $this->buildSelect($params); return $this->run($query['query'], $query['param'])?$this->_stmt->fetchAll($this->_schema['fetch']):array(); }
php
public function readAll($limit = 0) { $this->limit($limit); $query = $this->buildSelect($params); return $this->run($query['query'], $query['param'])?$this->_stmt->fetchAll($this->_schema['fetch']):array(); }
[ "public", "function", "readAll", "(", "$", "limit", "=", "0", ")", "{", "$", "this", "->", "limit", "(", "$", "limit", ")", ";", "$", "query", "=", "$", "this", "->", "buildSelect", "(", "$", "params", ")", ";", "return", "$", "this", "->", "run", "(", "$", "query", "[", "'query'", "]", ",", "$", "query", "[", "'param'", "]", ")", "?", "$", "this", "->", "_stmt", "->", "fetchAll", "(", "$", "this", "->", "_schema", "[", "'fetch'", "]", ")", ":", "array", "(", ")", ";", "}" ]
Get all
[ "Get", "all" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L681-L687
eghojansu/moe
src/AbstractModel.php
AbstractModel.count
public function count($force = false) { if ($this->_stmt && !$force) return $this->_stmt->rowCount(); $this->select('count(*)', true); $query = $this->buildSelect($params); return $this->run($query['query'], $query['param'])?$this->_stmt->fetchColumn(0):0; }
php
public function count($force = false) { if ($this->_stmt && !$force) return $this->_stmt->rowCount(); $this->select('count(*)', true); $query = $this->buildSelect($params); return $this->run($query['query'], $query['param'])?$this->_stmt->fetchColumn(0):0; }
[ "public", "function", "count", "(", "$", "force", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_stmt", "&&", "!", "$", "force", ")", "return", "$", "this", "->", "_stmt", "->", "rowCount", "(", ")", ";", "$", "this", "->", "select", "(", "'count(*)'", ",", "true", ")", ";", "$", "query", "=", "$", "this", "->", "buildSelect", "(", "$", "params", ")", ";", "return", "$", "this", "->", "run", "(", "$", "query", "[", "'query'", "]", ",", "$", "query", "[", "'param'", "]", ")", "?", "$", "this", "->", "_stmt", "->", "fetchColumn", "(", "0", ")", ":", "0", ";", "}" ]
Get count
[ "Get", "count" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L692-L701
eghojansu/moe
src/AbstractModel.php
AbstractModel.save
public function save(array $data = array(), $update = false) { $this->viewCheck(__FUNCTION__); return $this->dry()?$this->insert($data, $update):$this->update($data); }
php
public function save(array $data = array(), $update = false) { $this->viewCheck(__FUNCTION__); return $this->dry()?$this->insert($data, $update):$this->update($data); }
[ "public", "function", "save", "(", "array", "$", "data", "=", "array", "(", ")", ",", "$", "update", "=", "false", ")", "{", "$", "this", "->", "viewCheck", "(", "__FUNCTION__", ")", ";", "return", "$", "this", "->", "dry", "(", ")", "?", "$", "this", "->", "insert", "(", "$", "data", ",", "$", "update", ")", ":", "$", "this", "->", "update", "(", "$", "data", ")", ";", "}" ]
Save
[ "Save" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L706-L711
eghojansu/moe
src/AbstractModel.php
AbstractModel.insert
public function insert(array $data = array(), $update = false) { $this->viewCheck(__FUNCTION__); $data = array_merge($this->_schema['init'], array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule')), $data); $params = array(); foreach ($data as $key => $value) if (in_array($key, $this->_properties['primary_key']) && !$value) continue; elseif (is_array($value)) return false; elseif (isset($this->_properties['fields'][$key])) $params[':'.$key] = $value; if (empty($params) || ($update && !$this->_properties['primary_key'])) return false; $query = $this->buildInsert($params, $update); if (!($query && $this->validate($params))) return false; $old = clone $this; if (!$this->beforeInsert($params)) return false; if ($result = $this->run($query, $params)) $this->assign($params); if (!$this->afterInsert($old)) return false; return $result; }
php
public function insert(array $data = array(), $update = false) { $this->viewCheck(__FUNCTION__); $data = array_merge($this->_schema['init'], array_filter($this->_schema['values'], array($this, 'filterRule')), array_filter($this->_schema['others'], array($this, 'filterRule')), $data); $params = array(); foreach ($data as $key => $value) if (in_array($key, $this->_properties['primary_key']) && !$value) continue; elseif (is_array($value)) return false; elseif (isset($this->_properties['fields'][$key])) $params[':'.$key] = $value; if (empty($params) || ($update && !$this->_properties['primary_key'])) return false; $query = $this->buildInsert($params, $update); if (!($query && $this->validate($params))) return false; $old = clone $this; if (!$this->beforeInsert($params)) return false; if ($result = $this->run($query, $params)) $this->assign($params); if (!$this->afterInsert($old)) return false; return $result; }
[ "public", "function", "insert", "(", "array", "$", "data", "=", "array", "(", ")", ",", "$", "update", "=", "false", ")", "{", "$", "this", "->", "viewCheck", "(", "__FUNCTION__", ")", ";", "$", "data", "=", "array_merge", "(", "$", "this", "->", "_schema", "[", "'init'", "]", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'values'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ",", "array_filter", "(", "$", "this", "->", "_schema", "[", "'others'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ",", "$", "data", ")", ";", "$", "params", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "if", "(", "in_array", "(", "$", "key", ",", "$", "this", "->", "_properties", "[", "'primary_key'", "]", ")", "&&", "!", "$", "value", ")", "continue", ";", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "return", "false", ";", "elseif", "(", "isset", "(", "$", "this", "->", "_properties", "[", "'fields'", "]", "[", "$", "key", "]", ")", ")", "$", "params", "[", "':'", ".", "$", "key", "]", "=", "$", "value", ";", "if", "(", "empty", "(", "$", "params", ")", "||", "(", "$", "update", "&&", "!", "$", "this", "->", "_properties", "[", "'primary_key'", "]", ")", ")", "return", "false", ";", "$", "query", "=", "$", "this", "->", "buildInsert", "(", "$", "params", ",", "$", "update", ")", ";", "if", "(", "!", "(", "$", "query", "&&", "$", "this", "->", "validate", "(", "$", "params", ")", ")", ")", "return", "false", ";", "$", "old", "=", "clone", "$", "this", ";", "if", "(", "!", "$", "this", "->", "beforeInsert", "(", "$", "params", ")", ")", "return", "false", ";", "if", "(", "$", "result", "=", "$", "this", "->", "run", "(", "$", "query", ",", "$", "params", ")", ")", "$", "this", "->", "assign", "(", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "afterInsert", "(", "$", "old", ")", ")", "return", "false", ";", "return", "$", "result", ";", "}" ]
Insert, on duplicate key update
[ "Insert", "on", "duplicate", "key", "update" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L716-L753
eghojansu/moe
src/AbstractModel.php
AbstractModel.update
public function update(array $data = array(), array $criteria = array()) { $this->viewCheck(__FUNCTION__); $data = array_merge( array_filter($this->_schema['others'], array($this, 'filterRule')), $data); $params = array(); $values = array_filter($this->_schema['values']); $others = array_filter($this->_schema['others']); foreach ($data as $key => $value) if (is_array($value)) return false; elseif (isset($this->_properties['fields'][$key])) if (isset($values[$key]) && isset($others[$key]) && $values[$key]==$others[$key] ) continue; else $params[':'.$key] = $value; if (empty($params)) return true; $query = $this->buildUpdate($params, $criteria); if (!($query && $this->validate($params))) return false; $old = clone $this; if (!$this->beforeUpdate($params)) return false; if ($result = $this->run($query, $params)) $this->assign($params); if (!$this->afterUpdate($old)) return false; return $result; }
php
public function update(array $data = array(), array $criteria = array()) { $this->viewCheck(__FUNCTION__); $data = array_merge( array_filter($this->_schema['others'], array($this, 'filterRule')), $data); $params = array(); $values = array_filter($this->_schema['values']); $others = array_filter($this->_schema['others']); foreach ($data as $key => $value) if (is_array($value)) return false; elseif (isset($this->_properties['fields'][$key])) if (isset($values[$key]) && isset($others[$key]) && $values[$key]==$others[$key] ) continue; else $params[':'.$key] = $value; if (empty($params)) return true; $query = $this->buildUpdate($params, $criteria); if (!($query && $this->validate($params))) return false; $old = clone $this; if (!$this->beforeUpdate($params)) return false; if ($result = $this->run($query, $params)) $this->assign($params); if (!$this->afterUpdate($old)) return false; return $result; }
[ "public", "function", "update", "(", "array", "$", "data", "=", "array", "(", ")", ",", "array", "$", "criteria", "=", "array", "(", ")", ")", "{", "$", "this", "->", "viewCheck", "(", "__FUNCTION__", ")", ";", "$", "data", "=", "array_merge", "(", "array_filter", "(", "$", "this", "->", "_schema", "[", "'others'", "]", ",", "array", "(", "$", "this", ",", "'filterRule'", ")", ")", ",", "$", "data", ")", ";", "$", "params", "=", "array", "(", ")", ";", "$", "values", "=", "array_filter", "(", "$", "this", "->", "_schema", "[", "'values'", "]", ")", ";", "$", "others", "=", "array_filter", "(", "$", "this", "->", "_schema", "[", "'others'", "]", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "if", "(", "is_array", "(", "$", "value", ")", ")", "return", "false", ";", "elseif", "(", "isset", "(", "$", "this", "->", "_properties", "[", "'fields'", "]", "[", "$", "key", "]", ")", ")", "if", "(", "isset", "(", "$", "values", "[", "$", "key", "]", ")", "&&", "isset", "(", "$", "others", "[", "$", "key", "]", ")", "&&", "$", "values", "[", "$", "key", "]", "==", "$", "others", "[", "$", "key", "]", ")", "continue", ";", "else", "$", "params", "[", "':'", ".", "$", "key", "]", "=", "$", "value", ";", "if", "(", "empty", "(", "$", "params", ")", ")", "return", "true", ";", "$", "query", "=", "$", "this", "->", "buildUpdate", "(", "$", "params", ",", "$", "criteria", ")", ";", "if", "(", "!", "(", "$", "query", "&&", "$", "this", "->", "validate", "(", "$", "params", ")", ")", ")", "return", "false", ";", "$", "old", "=", "clone", "$", "this", ";", "if", "(", "!", "$", "this", "->", "beforeUpdate", "(", "$", "params", ")", ")", "return", "false", ";", "if", "(", "$", "result", "=", "$", "this", "->", "run", "(", "$", "query", ",", "$", "params", ")", ")", "$", "this", "->", "assign", "(", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "afterUpdate", "(", "$", "old", ")", ")", "return", "false", ";", "return", "$", "result", ";", "}" ]
Update, only when there is primary key
[ "Update", "only", "when", "there", "is", "primary", "key" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L758-L799
eghojansu/moe
src/AbstractModel.php
AbstractModel.delete
public function delete(array $criteria = []) { $this->viewCheck(__FUNCTION__); $query = $this->buildDelete($criteria); $old = clone $this; if (!$this->beforeDelete($criteria)) return false; if ($result = $this->run($query, $criteria)) $this->next(); if (!$this->afterDelete($old)) return false; return $result; }
php
public function delete(array $criteria = []) { $this->viewCheck(__FUNCTION__); $query = $this->buildDelete($criteria); $old = clone $this; if (!$this->beforeDelete($criteria)) return false; if ($result = $this->run($query, $criteria)) $this->next(); if (!$this->afterDelete($old)) return false; return $result; }
[ "public", "function", "delete", "(", "array", "$", "criteria", "=", "[", "]", ")", "{", "$", "this", "->", "viewCheck", "(", "__FUNCTION__", ")", ";", "$", "query", "=", "$", "this", "->", "buildDelete", "(", "$", "criteria", ")", ";", "$", "old", "=", "clone", "$", "this", ";", "if", "(", "!", "$", "this", "->", "beforeDelete", "(", "$", "criteria", ")", ")", "return", "false", ";", "if", "(", "$", "result", "=", "$", "this", "->", "run", "(", "$", "query", ",", "$", "criteria", ")", ")", "$", "this", "->", "next", "(", ")", ";", "if", "(", "!", "$", "this", "->", "afterDelete", "(", "$", "old", ")", ")", "return", "false", ";", "return", "$", "result", ";", "}" ]
delete, only when there is primary key
[ "delete", "only", "when", "there", "is", "primary", "key" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L804-L821
eghojansu/moe
src/AbstractModel.php
AbstractModel.fetchMode
public function fetchMode($mode) { if ($mode = @constant('PDO::FETCH_'.strtoupper($mode))) $this->_schema['fetch'] = $mode; return $this; }
php
public function fetchMode($mode) { if ($mode = @constant('PDO::FETCH_'.strtoupper($mode))) $this->_schema['fetch'] = $mode; return $this; }
[ "public", "function", "fetchMode", "(", "$", "mode", ")", "{", "if", "(", "$", "mode", "=", "@", "constant", "(", "'PDO::FETCH_'", ".", "strtoupper", "(", "$", "mode", ")", ")", ")", "$", "this", "->", "_schema", "[", "'fetch'", "]", "=", "$", "mode", ";", "return", "$", "this", ";", "}" ]
Fetch mode
[ "Fetch", "mode" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L854-L860
eghojansu/moe
src/AbstractModel.php
AbstractModel.buildInsert
public function buildInsert(&$params, $update = false) { $values = implode(',', array_keys($params)); $query = 'insert into '.$this->table().' ('. str_replace(':', '', $values).') values'.PHP_EOL.' ('. $values.')'; if ($update) { $update = array(); foreach ($params as $token=>$value) { $field = str_replace(':', '', $token); in_array($field, $this->_properties['primary_key']) || $update[] = $field.'='.$token; } !$update || $query .= PHP_EOL.' on duplicate key update '.implode(',', $update); } return $query; }
php
public function buildInsert(&$params, $update = false) { $values = implode(',', array_keys($params)); $query = 'insert into '.$this->table().' ('. str_replace(':', '', $values).') values'.PHP_EOL.' ('. $values.')'; if ($update) { $update = array(); foreach ($params as $token=>$value) { $field = str_replace(':', '', $token); in_array($field, $this->_properties['primary_key']) || $update[] = $field.'='.$token; } !$update || $query .= PHP_EOL.' on duplicate key update '.implode(',', $update); } return $query; }
[ "public", "function", "buildInsert", "(", "&", "$", "params", ",", "$", "update", "=", "false", ")", "{", "$", "values", "=", "implode", "(", "','", ",", "array_keys", "(", "$", "params", ")", ")", ";", "$", "query", "=", "'insert into '", ".", "$", "this", "->", "table", "(", ")", ".", "' ('", ".", "str_replace", "(", "':'", ",", "''", ",", "$", "values", ")", ".", "') values'", ".", "PHP_EOL", ".", "' ('", ".", "$", "values", ".", "')'", ";", "if", "(", "$", "update", ")", "{", "$", "update", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "token", "=>", "$", "value", ")", "{", "$", "field", "=", "str_replace", "(", "':'", ",", "''", ",", "$", "token", ")", ";", "in_array", "(", "$", "field", ",", "$", "this", "->", "_properties", "[", "'primary_key'", "]", ")", "||", "$", "update", "[", "]", "=", "$", "field", ".", "'='", ".", "$", "token", ";", "}", "!", "$", "update", "||", "$", "query", ".=", "PHP_EOL", ".", "' on duplicate key update '", ".", "implode", "(", "','", ",", "$", "update", ")", ";", "}", "return", "$", "query", ";", "}" ]
insert Builder
[ "insert", "Builder" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L875-L892
eghojansu/moe
src/AbstractModel.php
AbstractModel.buildUpdate
public function buildUpdate(&$params, array $criteria = array()) { $set = ''; foreach ($params as $token=>$value) { $field = str_replace(':', '', $token); $set .= $field.'='.$token.','; } $where = $where_param = array(); if ($criteria) { foreach ($criteria as $field=>$value) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $value; } } elseif ($this->wet()) { foreach ($this->_properties['primary_key'] as $field) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $this->_schema['values'][$field]; } } if (!$where || !$set) return; $params = array_merge($params, $where_param); $query = 'update '.$this->table().' set '.PHP_EOL.rtrim($set, ',').PHP_EOL.' where '.implode(' and ', $where); return $query; }
php
public function buildUpdate(&$params, array $criteria = array()) { $set = ''; foreach ($params as $token=>$value) { $field = str_replace(':', '', $token); $set .= $field.'='.$token.','; } $where = $where_param = array(); if ($criteria) { foreach ($criteria as $field=>$value) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $value; } } elseif ($this->wet()) { foreach ($this->_properties['primary_key'] as $field) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $this->_schema['values'][$field]; } } if (!$where || !$set) return; $params = array_merge($params, $where_param); $query = 'update '.$this->table().' set '.PHP_EOL.rtrim($set, ',').PHP_EOL.' where '.implode(' and ', $where); return $query; }
[ "public", "function", "buildUpdate", "(", "&", "$", "params", ",", "array", "$", "criteria", "=", "array", "(", ")", ")", "{", "$", "set", "=", "''", ";", "foreach", "(", "$", "params", "as", "$", "token", "=>", "$", "value", ")", "{", "$", "field", "=", "str_replace", "(", "':'", ",", "''", ",", "$", "token", ")", ";", "$", "set", ".=", "$", "field", ".", "'='", ".", "$", "token", ".", "','", ";", "}", "$", "where", "=", "$", "where_param", "=", "array", "(", ")", ";", "if", "(", "$", "criteria", ")", "{", "foreach", "(", "$", "criteria", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "token", "=", "':'", ".", "$", "field", ".", "'_where'", ";", "$", "where", "[", "]", "=", "$", "field", ".", "'='", ".", "$", "token", ";", "$", "where_param", "[", "$", "token", "]", "=", "$", "value", ";", "}", "}", "elseif", "(", "$", "this", "->", "wet", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "as", "$", "field", ")", "{", "$", "token", "=", "':'", ".", "$", "field", ".", "'_where'", ";", "$", "where", "[", "]", "=", "$", "field", ".", "'='", ".", "$", "token", ";", "$", "where_param", "[", "$", "token", "]", "=", "$", "this", "->", "_schema", "[", "'values'", "]", "[", "$", "field", "]", ";", "}", "}", "if", "(", "!", "$", "where", "||", "!", "$", "set", ")", "return", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "where_param", ")", ";", "$", "query", "=", "'update '", ".", "$", "this", "->", "table", "(", ")", ".", "' set '", ".", "PHP_EOL", ".", "rtrim", "(", "$", "set", ",", "','", ")", ".", "PHP_EOL", ".", "' where '", ".", "implode", "(", "' and '", ",", "$", "where", ")", ";", "return", "$", "query", ";", "}" ]
update Builder
[ "update", "Builder" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L897-L927
eghojansu/moe
src/AbstractModel.php
AbstractModel.buildDelete
public function buildDelete(array &$criteria = array()) { $where = $where_param = array(); if ($criteria) { foreach ($criteria as $field=>$value) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $value; } } elseif ($this->wet()) { foreach ($this->_properties['primary_key'] as $field) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $this->_schema['values'][$field]; } } if (!$where) return; $criteria = $where_param; $query = 'delete from '.$this->table().' where '.implode(' and ', $where); return $query; }
php
public function buildDelete(array &$criteria = array()) { $where = $where_param = array(); if ($criteria) { foreach ($criteria as $field=>$value) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $value; } } elseif ($this->wet()) { foreach ($this->_properties['primary_key'] as $field) { $token = ':'.$field.'_where'; $where[] = $field.'='.$token; $where_param[$token] = $this->_schema['values'][$field]; } } if (!$where) return; $criteria = $where_param; $query = 'delete from '.$this->table().' where '.implode(' and ', $where); return $query; }
[ "public", "function", "buildDelete", "(", "array", "&", "$", "criteria", "=", "array", "(", ")", ")", "{", "$", "where", "=", "$", "where_param", "=", "array", "(", ")", ";", "if", "(", "$", "criteria", ")", "{", "foreach", "(", "$", "criteria", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "token", "=", "':'", ".", "$", "field", ".", "'_where'", ";", "$", "where", "[", "]", "=", "$", "field", ".", "'='", ".", "$", "token", ";", "$", "where_param", "[", "$", "token", "]", "=", "$", "value", ";", "}", "}", "elseif", "(", "$", "this", "->", "wet", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "_properties", "[", "'primary_key'", "]", "as", "$", "field", ")", "{", "$", "token", "=", "':'", ".", "$", "field", ".", "'_where'", ";", "$", "where", "[", "]", "=", "$", "field", ".", "'='", ".", "$", "token", ";", "$", "where_param", "[", "$", "token", "]", "=", "$", "this", "->", "_schema", "[", "'values'", "]", "[", "$", "field", "]", ";", "}", "}", "if", "(", "!", "$", "where", ")", "return", ";", "$", "criteria", "=", "$", "where_param", ";", "$", "query", "=", "'delete from '", ".", "$", "this", "->", "table", "(", ")", ".", "' where '", ".", "implode", "(", "' and '", ",", "$", "where", ")", ";", "return", "$", "query", ";", "}" ]
delete Builder
[ "delete", "Builder" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L932-L956
eghojansu/moe
src/AbstractModel.php
AbstractModel.performValidate
protected function performValidate($key, &$value) { if (!$filter = $this->_schema['filter'][$key]) return true; $validation = Validation::instance(); $moe = Base::instance(); $field = $this->_properties['fields'][$key]; foreach ($filter as $func => $param) { if (is_numeric($func)) { $func = $param; $args = array(); } else $args = [$param]; $function = $func; if (method_exists($validation, $func)) $func = array($validation, $func); elseif (method_exists($this, $func) || preg_match('/^('.self::Magic.')/', $func)) $func = array($this, $func); elseif (method_exists($moe, $func)) $func = array($moe, $func); array_unshift($args, $value); if (false === $result = $moe->call($func, $args)) { $this->_messages[] = $validation->message($function, $field, $value, $param); return false; } else is_bool($result) || $value = $result; } return true; }
php
protected function performValidate($key, &$value) { if (!$filter = $this->_schema['filter'][$key]) return true; $validation = Validation::instance(); $moe = Base::instance(); $field = $this->_properties['fields'][$key]; foreach ($filter as $func => $param) { if (is_numeric($func)) { $func = $param; $args = array(); } else $args = [$param]; $function = $func; if (method_exists($validation, $func)) $func = array($validation, $func); elseif (method_exists($this, $func) || preg_match('/^('.self::Magic.')/', $func)) $func = array($this, $func); elseif (method_exists($moe, $func)) $func = array($moe, $func); array_unshift($args, $value); if (false === $result = $moe->call($func, $args)) { $this->_messages[] = $validation->message($function, $field, $value, $param); return false; } else is_bool($result) || $value = $result; } return true; }
[ "protected", "function", "performValidate", "(", "$", "key", ",", "&", "$", "value", ")", "{", "if", "(", "!", "$", "filter", "=", "$", "this", "->", "_schema", "[", "'filter'", "]", "[", "$", "key", "]", ")", "return", "true", ";", "$", "validation", "=", "Validation", "::", "instance", "(", ")", ";", "$", "moe", "=", "Base", "::", "instance", "(", ")", ";", "$", "field", "=", "$", "this", "->", "_properties", "[", "'fields'", "]", "[", "$", "key", "]", ";", "foreach", "(", "$", "filter", "as", "$", "func", "=>", "$", "param", ")", "{", "if", "(", "is_numeric", "(", "$", "func", ")", ")", "{", "$", "func", "=", "$", "param", ";", "$", "args", "=", "array", "(", ")", ";", "}", "else", "$", "args", "=", "[", "$", "param", "]", ";", "$", "function", "=", "$", "func", ";", "if", "(", "method_exists", "(", "$", "validation", ",", "$", "func", ")", ")", "$", "func", "=", "array", "(", "$", "validation", ",", "$", "func", ")", ";", "elseif", "(", "method_exists", "(", "$", "this", ",", "$", "func", ")", "||", "preg_match", "(", "'/^('", ".", "self", "::", "Magic", ".", "')/'", ",", "$", "func", ")", ")", "$", "func", "=", "array", "(", "$", "this", ",", "$", "func", ")", ";", "elseif", "(", "method_exists", "(", "$", "moe", ",", "$", "func", ")", ")", "$", "func", "=", "array", "(", "$", "moe", ",", "$", "func", ")", ";", "array_unshift", "(", "$", "args", ",", "$", "value", ")", ";", "if", "(", "false", "===", "$", "result", "=", "$", "moe", "->", "call", "(", "$", "func", ",", "$", "args", ")", ")", "{", "$", "this", "->", "_messages", "[", "]", "=", "$", "validation", "->", "message", "(", "$", "function", ",", "$", "field", ",", "$", "value", ",", "$", "param", ")", ";", "return", "false", ";", "}", "else", "is_bool", "(", "$", "result", ")", "||", "$", "value", "=", "$", "result", ";", "}", "return", "true", ";", "}" ]
Perform validation We can use method in Base class or any method with full name call but you need to define a message to override default message Be aware when use a method
[ "Perform", "validation", "We", "can", "use", "method", "in", "Base", "class", "or", "any", "method", "with", "full", "name", "call", "but", "you", "need", "to", "define", "a", "message", "to", "override", "default", "message", "Be", "aware", "when", "use", "a", "method" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L972-L1005
eghojansu/moe
src/AbstractModel.php
AbstractModel.assign
protected function assign(array $data) { foreach ($data as $key => $value) { $key = str_replace(':', '', $key); if (isset($this->_properties['fields'][$key])) $this->_schema['values'][$key] = $value; else $this->_schema['others'][$key] = $value; } return $this; }
php
protected function assign(array $data) { foreach ($data as $key => $value) { $key = str_replace(':', '', $key); if (isset($this->_properties['fields'][$key])) $this->_schema['values'][$key] = $value; else $this->_schema['others'][$key] = $value; } return $this; }
[ "protected", "function", "assign", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", "str_replace", "(", "':'", ",", "''", ",", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "_properties", "[", "'fields'", "]", "[", "$", "key", "]", ")", ")", "$", "this", "->", "_schema", "[", "'values'", "]", "[", "$", "key", "]", "=", "$", "value", ";", "else", "$", "this", "->", "_schema", "[", "'others'", "]", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
Assign
[ "Assign" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L1010-L1021
eghojansu/moe
src/AbstractModel.php
AbstractModel.run
protected function run($query, array $params) { if (!$query) return; $query = str_replace('{table}', $this->table(), $query); $pdo = $this->db()->pdo; if ($this->_schema['config']['log']) { $quoted = $params; foreach ($quoted as $key => $value) $quoted[$key] = $pdo->quote($value); $this->_logs[] = str_replace(array_keys($quoted), array_values($quoted), $query); $this->_queries[] = $query; unset($quoted); } if (!($this->_schema['config']['reUseStatement'] && $this->_stmt)) $this->_stmt = $pdo->prepare($query); $this->_stmt->execute($params); if ($this->_stmt->errorCode()!='00000') { $this->_errors[] = Instance::stringify($this->_stmt->errorInfo()); return false; } return true; }
php
protected function run($query, array $params) { if (!$query) return; $query = str_replace('{table}', $this->table(), $query); $pdo = $this->db()->pdo; if ($this->_schema['config']['log']) { $quoted = $params; foreach ($quoted as $key => $value) $quoted[$key] = $pdo->quote($value); $this->_logs[] = str_replace(array_keys($quoted), array_values($quoted), $query); $this->_queries[] = $query; unset($quoted); } if (!($this->_schema['config']['reUseStatement'] && $this->_stmt)) $this->_stmt = $pdo->prepare($query); $this->_stmt->execute($params); if ($this->_stmt->errorCode()!='00000') { $this->_errors[] = Instance::stringify($this->_stmt->errorInfo()); return false; } return true; }
[ "protected", "function", "run", "(", "$", "query", ",", "array", "$", "params", ")", "{", "if", "(", "!", "$", "query", ")", "return", ";", "$", "query", "=", "str_replace", "(", "'{table}'", ",", "$", "this", "->", "table", "(", ")", ",", "$", "query", ")", ";", "$", "pdo", "=", "$", "this", "->", "db", "(", ")", "->", "pdo", ";", "if", "(", "$", "this", "->", "_schema", "[", "'config'", "]", "[", "'log'", "]", ")", "{", "$", "quoted", "=", "$", "params", ";", "foreach", "(", "$", "quoted", "as", "$", "key", "=>", "$", "value", ")", "$", "quoted", "[", "$", "key", "]", "=", "$", "pdo", "->", "quote", "(", "$", "value", ")", ";", "$", "this", "->", "_logs", "[", "]", "=", "str_replace", "(", "array_keys", "(", "$", "quoted", ")", ",", "array_values", "(", "$", "quoted", ")", ",", "$", "query", ")", ";", "$", "this", "->", "_queries", "[", "]", "=", "$", "query", ";", "unset", "(", "$", "quoted", ")", ";", "}", "if", "(", "!", "(", "$", "this", "->", "_schema", "[", "'config'", "]", "[", "'reUseStatement'", "]", "&&", "$", "this", "->", "_stmt", ")", ")", "$", "this", "->", "_stmt", "=", "$", "pdo", "->", "prepare", "(", "$", "query", ")", ";", "$", "this", "->", "_stmt", "->", "execute", "(", "$", "params", ")", ";", "if", "(", "$", "this", "->", "_stmt", "->", "errorCode", "(", ")", "!=", "'00000'", ")", "{", "$", "this", "->", "_errors", "[", "]", "=", "Instance", "::", "stringify", "(", "$", "this", "->", "_stmt", "->", "errorInfo", "(", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Run query
[ "Run", "query" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L1026-L1053
eghojansu/moe
src/AbstractModel.php
AbstractModel.buildRelation
protected function buildRelation() { if (!($this->relation && $relation = $this->relation())) return ''; if (isset($relation[$this->relation])) $relation = [$this->relation=>$relation[$this->relation]]; elseif (strpos($this->relation, ',')!==false) { $tmp = explode(',', $this->relation); foreach ($relation as $key => $value) if (!in_array($key, $tmp)) unset($relation[$key]); } elseif ($this->relation!='all') throw new Exception(sprintf(self::E_NoRelation, get_called_class(), $this->relation), 1); $rel = array(); foreach ($relation as $key => $value) { if (is_numeric($key)) throw new Exception(sprintf(self::E_Relation, get_called_class()), 1); $tmp = explode(' ', $key); $table = $tmp[0]; $alias = isset($tmp[1])?$tmp[1]:null; if (strpos($value, 'select')!==false) { $alias = $table; $table = null; } $rel[] = str_replace(array('{join}', '{j}'), array($table, $alias), $value); } return implode(PHP_EOL, $rel); }
php
protected function buildRelation() { if (!($this->relation && $relation = $this->relation())) return ''; if (isset($relation[$this->relation])) $relation = [$this->relation=>$relation[$this->relation]]; elseif (strpos($this->relation, ',')!==false) { $tmp = explode(',', $this->relation); foreach ($relation as $key => $value) if (!in_array($key, $tmp)) unset($relation[$key]); } elseif ($this->relation!='all') throw new Exception(sprintf(self::E_NoRelation, get_called_class(), $this->relation), 1); $rel = array(); foreach ($relation as $key => $value) { if (is_numeric($key)) throw new Exception(sprintf(self::E_Relation, get_called_class()), 1); $tmp = explode(' ', $key); $table = $tmp[0]; $alias = isset($tmp[1])?$tmp[1]:null; if (strpos($value, 'select')!==false) { $alias = $table; $table = null; } $rel[] = str_replace(array('{join}', '{j}'), array($table, $alias), $value); } return implode(PHP_EOL, $rel); }
[ "protected", "function", "buildRelation", "(", ")", "{", "if", "(", "!", "(", "$", "this", "->", "relation", "&&", "$", "relation", "=", "$", "this", "->", "relation", "(", ")", ")", ")", "return", "''", ";", "if", "(", "isset", "(", "$", "relation", "[", "$", "this", "->", "relation", "]", ")", ")", "$", "relation", "=", "[", "$", "this", "->", "relation", "=>", "$", "relation", "[", "$", "this", "->", "relation", "]", "]", ";", "elseif", "(", "strpos", "(", "$", "this", "->", "relation", ",", "','", ")", "!==", "false", ")", "{", "$", "tmp", "=", "explode", "(", "','", ",", "$", "this", "->", "relation", ")", ";", "foreach", "(", "$", "relation", "as", "$", "key", "=>", "$", "value", ")", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "tmp", ")", ")", "unset", "(", "$", "relation", "[", "$", "key", "]", ")", ";", "}", "elseif", "(", "$", "this", "->", "relation", "!=", "'all'", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_NoRelation", ",", "get_called_class", "(", ")", ",", "$", "this", "->", "relation", ")", ",", "1", ")", ";", "$", "rel", "=", "array", "(", ")", ";", "foreach", "(", "$", "relation", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Relation", ",", "get_called_class", "(", ")", ")", ",", "1", ")", ";", "$", "tmp", "=", "explode", "(", "' '", ",", "$", "key", ")", ";", "$", "table", "=", "$", "tmp", "[", "0", "]", ";", "$", "alias", "=", "isset", "(", "$", "tmp", "[", "1", "]", ")", "?", "$", "tmp", "[", "1", "]", ":", "null", ";", "if", "(", "strpos", "(", "$", "value", ",", "'select'", ")", "!==", "false", ")", "{", "$", "alias", "=", "$", "table", ";", "$", "table", "=", "null", ";", "}", "$", "rel", "[", "]", "=", "str_replace", "(", "array", "(", "'{join}'", ",", "'{j}'", ")", ",", "array", "(", "$", "table", ",", "$", "alias", ")", ",", "$", "value", ")", ";", "}", "return", "implode", "(", "PHP_EOL", ",", "$", "rel", ")", ";", "}" ]
Build relation
[ "Build", "relation" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L1058-L1090
eghojansu/moe
src/AbstractModel.php
AbstractModel.translateParam
protected function translateParam($method, array $args) { $params = array(); foreach ($this->translateColumn($method) as $column) if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); else $params[$column] = array_shift($args); return $params; }
php
protected function translateParam($method, array $args) { $params = array(); foreach ($this->translateColumn($method) as $column) if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); else $params[$column] = array_shift($args); return $params; }
[ "protected", "function", "translateParam", "(", "$", "method", ",", "array", "$", "args", ")", "{", "$", "params", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "translateColumn", "(", "$", "method", ")", "as", "$", "column", ")", "if", "(", "!", "$", "args", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Param", ",", "get_called_class", "(", ")", ",", "$", "column", ")", ",", "1", ")", ";", "else", "$", "params", "[", "$", "column", "]", "=", "array_shift", "(", "$", "args", ")", ";", "return", "$", "params", ";", "}" ]
Translate param
[ "Translate", "param" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L1095-L1105
eghojansu/moe
src/AbstractModel.php
AbstractModel.translateCriteria
protected function translateCriteria($method, array $args) { $result = [ 'criteria'=>'', 'params'=>[] ]; $columns = $this->translateColumn($method); $n_token = '{not}'; $p_token = '{and}{or}'; $o_token = '{in}{between}{like}{begin}{end}{null}'; $last = count($columns); for ($pointer = 0; $pointer < $last; $pointer++) { $column = $columns[$pointer]; if ($this->inToken($column, $n_token)) continue; $negation = (isset($columns[$pointer-1]) && $this->inToken($columns[$pointer-1], $n_token)); $punc = 'and'; $operator = ($negation?'!':'').'='; $params = array(); $token = ':'.$column; $skip = 0; if (isset($columns[$pointer+1])) { // bisa jadi punc or opr $next = $columns[$pointer+1]; ++$skip; if ($this->inToken($next, $p_token)) { $punc = $next; } elseif ($this->inToken($next, $o_token)) { switch ($next) { case 'in': # in (:field1, :field2, ..., :fieldn) if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').$next; $arg = array_shift($args); is_array($arg) || $arg = [$arg]; $i = 1; $token = '('; foreach ($arg as $value) { $t = ':'.$column.$i++; $token .= $t.','; $params[$t] = $value; } $token = rtrim($token,',').')'; break; case 'between': # between :field1 and :field2 if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').$next; $arg = array_shift($args); is_array($arg) || $arg = [$arg]; if (count($arg)<2) throw new Exception(sprintf(self::E_Param, $column), 1); $token = ':'.$column.'1 and :'.$column.'2'; $params[':'.$column.'1'] = array_shift($arg); $params[':'.$column.'2'] = array_shift($arg); break; case 'like': # %:field% case 'begin': # :field% case 'end': # %:field if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').'like'; $params[$token] = ($next=='begin'?'':'%'). array_shift($args). ($next=='end'?'':'%'); break; case 'null': $token = ''; $operator = 'is '.($negation?'not ':'').$next; break; } } else --$skip; if (isset($columns[$pointer+2]) && $this->inToken($columns[$pointer+2], $p_token) ) { $punc = $columns[$pointer+2]; ++$skip; } } else $params[$token] = array_shift($args); $result['criteria'] .= rtrim(' {table}.'.$column.' '.$operator.' '.$token.' '.$punc); $result['params'] = array_merge($result['params'], $params); $pointer += $skip; } $result['criteria'] = preg_replace('/ (and|or)$/i', '', $result['criteria']); return $result; }
php
protected function translateCriteria($method, array $args) { $result = [ 'criteria'=>'', 'params'=>[] ]; $columns = $this->translateColumn($method); $n_token = '{not}'; $p_token = '{and}{or}'; $o_token = '{in}{between}{like}{begin}{end}{null}'; $last = count($columns); for ($pointer = 0; $pointer < $last; $pointer++) { $column = $columns[$pointer]; if ($this->inToken($column, $n_token)) continue; $negation = (isset($columns[$pointer-1]) && $this->inToken($columns[$pointer-1], $n_token)); $punc = 'and'; $operator = ($negation?'!':'').'='; $params = array(); $token = ':'.$column; $skip = 0; if (isset($columns[$pointer+1])) { // bisa jadi punc or opr $next = $columns[$pointer+1]; ++$skip; if ($this->inToken($next, $p_token)) { $punc = $next; } elseif ($this->inToken($next, $o_token)) { switch ($next) { case 'in': # in (:field1, :field2, ..., :fieldn) if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').$next; $arg = array_shift($args); is_array($arg) || $arg = [$arg]; $i = 1; $token = '('; foreach ($arg as $value) { $t = ':'.$column.$i++; $token .= $t.','; $params[$t] = $value; } $token = rtrim($token,',').')'; break; case 'between': # between :field1 and :field2 if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').$next; $arg = array_shift($args); is_array($arg) || $arg = [$arg]; if (count($arg)<2) throw new Exception(sprintf(self::E_Param, $column), 1); $token = ':'.$column.'1 and :'.$column.'2'; $params[':'.$column.'1'] = array_shift($arg); $params[':'.$column.'2'] = array_shift($arg); break; case 'like': # %:field% case 'begin': # :field% case 'end': # %:field if (!$args) throw new Exception(sprintf(self::E_Param, get_called_class(), $column), 1); $operator = ($negation?'not ':'').'like'; $params[$token] = ($next=='begin'?'':'%'). array_shift($args). ($next=='end'?'':'%'); break; case 'null': $token = ''; $operator = 'is '.($negation?'not ':'').$next; break; } } else --$skip; if (isset($columns[$pointer+2]) && $this->inToken($columns[$pointer+2], $p_token) ) { $punc = $columns[$pointer+2]; ++$skip; } } else $params[$token] = array_shift($args); $result['criteria'] .= rtrim(' {table}.'.$column.' '.$operator.' '.$token.' '.$punc); $result['params'] = array_merge($result['params'], $params); $pointer += $skip; } $result['criteria'] = preg_replace('/ (and|or)$/i', '', $result['criteria']); return $result; }
[ "protected", "function", "translateCriteria", "(", "$", "method", ",", "array", "$", "args", ")", "{", "$", "result", "=", "[", "'criteria'", "=>", "''", ",", "'params'", "=>", "[", "]", "]", ";", "$", "columns", "=", "$", "this", "->", "translateColumn", "(", "$", "method", ")", ";", "$", "n_token", "=", "'{not}'", ";", "$", "p_token", "=", "'{and}{or}'", ";", "$", "o_token", "=", "'{in}{between}{like}{begin}{end}{null}'", ";", "$", "last", "=", "count", "(", "$", "columns", ")", ";", "for", "(", "$", "pointer", "=", "0", ";", "$", "pointer", "<", "$", "last", ";", "$", "pointer", "++", ")", "{", "$", "column", "=", "$", "columns", "[", "$", "pointer", "]", ";", "if", "(", "$", "this", "->", "inToken", "(", "$", "column", ",", "$", "n_token", ")", ")", "continue", ";", "$", "negation", "=", "(", "isset", "(", "$", "columns", "[", "$", "pointer", "-", "1", "]", ")", "&&", "$", "this", "->", "inToken", "(", "$", "columns", "[", "$", "pointer", "-", "1", "]", ",", "$", "n_token", ")", ")", ";", "$", "punc", "=", "'and'", ";", "$", "operator", "=", "(", "$", "negation", "?", "'!'", ":", "''", ")", ".", "'='", ";", "$", "params", "=", "array", "(", ")", ";", "$", "token", "=", "':'", ".", "$", "column", ";", "$", "skip", "=", "0", ";", "if", "(", "isset", "(", "$", "columns", "[", "$", "pointer", "+", "1", "]", ")", ")", "{", "// bisa jadi punc or opr", "$", "next", "=", "$", "columns", "[", "$", "pointer", "+", "1", "]", ";", "++", "$", "skip", ";", "if", "(", "$", "this", "->", "inToken", "(", "$", "next", ",", "$", "p_token", ")", ")", "{", "$", "punc", "=", "$", "next", ";", "}", "elseif", "(", "$", "this", "->", "inToken", "(", "$", "next", ",", "$", "o_token", ")", ")", "{", "switch", "(", "$", "next", ")", "{", "case", "'in'", ":", "# in (:field1, :field2, ..., :fieldn)", "if", "(", "!", "$", "args", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Param", ",", "get_called_class", "(", ")", ",", "$", "column", ")", ",", "1", ")", ";", "$", "operator", "=", "(", "$", "negation", "?", "'not '", ":", "''", ")", ".", "$", "next", ";", "$", "arg", "=", "array_shift", "(", "$", "args", ")", ";", "is_array", "(", "$", "arg", ")", "||", "$", "arg", "=", "[", "$", "arg", "]", ";", "$", "i", "=", "1", ";", "$", "token", "=", "'('", ";", "foreach", "(", "$", "arg", "as", "$", "value", ")", "{", "$", "t", "=", "':'", ".", "$", "column", ".", "$", "i", "++", ";", "$", "token", ".=", "$", "t", ".", "','", ";", "$", "params", "[", "$", "t", "]", "=", "$", "value", ";", "}", "$", "token", "=", "rtrim", "(", "$", "token", ",", "','", ")", ".", "')'", ";", "break", ";", "case", "'between'", ":", "# between :field1 and :field2", "if", "(", "!", "$", "args", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Param", ",", "get_called_class", "(", ")", ",", "$", "column", ")", ",", "1", ")", ";", "$", "operator", "=", "(", "$", "negation", "?", "'not '", ":", "''", ")", ".", "$", "next", ";", "$", "arg", "=", "array_shift", "(", "$", "args", ")", ";", "is_array", "(", "$", "arg", ")", "||", "$", "arg", "=", "[", "$", "arg", "]", ";", "if", "(", "count", "(", "$", "arg", ")", "<", "2", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Param", ",", "$", "column", ")", ",", "1", ")", ";", "$", "token", "=", "':'", ".", "$", "column", ".", "'1 and :'", ".", "$", "column", ".", "'2'", ";", "$", "params", "[", "':'", ".", "$", "column", ".", "'1'", "]", "=", "array_shift", "(", "$", "arg", ")", ";", "$", "params", "[", "':'", ".", "$", "column", ".", "'2'", "]", "=", "array_shift", "(", "$", "arg", ")", ";", "break", ";", "case", "'like'", ":", "# %:field%", "case", "'begin'", ":", "# :field%", "case", "'end'", ":", "# %:field", "if", "(", "!", "$", "args", ")", "throw", "new", "Exception", "(", "sprintf", "(", "self", "::", "E_Param", ",", "get_called_class", "(", ")", ",", "$", "column", ")", ",", "1", ")", ";", "$", "operator", "=", "(", "$", "negation", "?", "'not '", ":", "''", ")", ".", "'like'", ";", "$", "params", "[", "$", "token", "]", "=", "(", "$", "next", "==", "'begin'", "?", "''", ":", "'%'", ")", ".", "array_shift", "(", "$", "args", ")", ".", "(", "$", "next", "==", "'end'", "?", "''", ":", "'%'", ")", ";", "break", ";", "case", "'null'", ":", "$", "token", "=", "''", ";", "$", "operator", "=", "'is '", ".", "(", "$", "negation", "?", "'not '", ":", "''", ")", ".", "$", "next", ";", "break", ";", "}", "}", "else", "--", "$", "skip", ";", "if", "(", "isset", "(", "$", "columns", "[", "$", "pointer", "+", "2", "]", ")", "&&", "$", "this", "->", "inToken", "(", "$", "columns", "[", "$", "pointer", "+", "2", "]", ",", "$", "p_token", ")", ")", "{", "$", "punc", "=", "$", "columns", "[", "$", "pointer", "+", "2", "]", ";", "++", "$", "skip", ";", "}", "}", "else", "$", "params", "[", "$", "token", "]", "=", "array_shift", "(", "$", "args", ")", ";", "$", "result", "[", "'criteria'", "]", ".=", "rtrim", "(", "' {table}.'", ".", "$", "column", ".", "' '", ".", "$", "operator", ".", "' '", ".", "$", "token", ".", "' '", ".", "$", "punc", ")", ";", "$", "result", "[", "'params'", "]", "=", "array_merge", "(", "$", "result", "[", "'params'", "]", ",", "$", "params", ")", ";", "$", "pointer", "+=", "$", "skip", ";", "}", "$", "result", "[", "'criteria'", "]", "=", "preg_replace", "(", "'/ (and|or)$/i'", ",", "''", ",", "$", "result", "[", "'criteria'", "]", ")", ";", "return", "$", "result", ";", "}" ]
Translate Criteria
[ "Translate", "Criteria" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/AbstractModel.php#L1110-L1201
highday/glitter
src/Audit/Listeners/Member/LogFailedLogin.php
LogFailedLogin.handle
public function handle(Failed $event) { if ($event->user) { $model = snake_case(class_basename($event->user)); $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), 'credentials' => $event->credentials, // 'credentials' => array_except($event->credentials, ['password']), ]; $event->user->log("{$model}.failed_login", $data); } }
php
public function handle(Failed $event) { if ($event->user) { $model = snake_case(class_basename($event->user)); $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), 'credentials' => $event->credentials, // 'credentials' => array_except($event->credentials, ['password']), ]; $event->user->log("{$model}.failed_login", $data); } }
[ "public", "function", "handle", "(", "Failed", "$", "event", ")", "{", "if", "(", "$", "event", "->", "user", ")", "{", "$", "model", "=", "snake_case", "(", "class_basename", "(", "$", "event", "->", "user", ")", ")", ";", "$", "data", "=", "[", "'ip'", "=>", "request", "(", ")", "->", "ip", "(", ")", ",", "'ua'", "=>", "request", "(", ")", "->", "header", "(", "'User-Agent'", ")", ",", "'credentials'", "=>", "$", "event", "->", "credentials", ",", "// 'credentials' => array_except($event->credentials, ['password']),", "]", ";", "$", "event", "->", "user", "->", "log", "(", "\"{$model}.failed_login\"", ",", "$", "data", ")", ";", "}", "}" ]
Handle the event. @param Failed $event @return void
[ "Handle", "the", "event", "." ]
train
https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Audit/Listeners/Member/LogFailedLogin.php#L26-L38
chippyash/Assembly-Builder
src/chippyash/Assembler/Traits/ParameterGrabable.php
ParameterGrabable.grabFunctionParameters
static function grabFunctionParameters($class, $function, array $paramValues) { $declaredParams = (new \ReflectionMethod($class, $function))->getParameters(); $paramNames = array_map(function(\ReflectionParameter $v) { return $v->getName(); }, $declaredParams ); $paramDefaults = array_map(function(\ReflectionParameter $v) { return $v->isOptional() ? $v->getDefaultValue() : null; }, $declaredParams ); return array_combine($paramNames, array_replace($paramDefaults, $paramValues)); }
php
static function grabFunctionParameters($class, $function, array $paramValues) { $declaredParams = (new \ReflectionMethod($class, $function))->getParameters(); $paramNames = array_map(function(\ReflectionParameter $v) { return $v->getName(); }, $declaredParams ); $paramDefaults = array_map(function(\ReflectionParameter $v) { return $v->isOptional() ? $v->getDefaultValue() : null; }, $declaredParams ); return array_combine($paramNames, array_replace($paramDefaults, $paramValues)); }
[ "static", "function", "grabFunctionParameters", "(", "$", "class", ",", "$", "function", ",", "array", "$", "paramValues", ")", "{", "$", "declaredParams", "=", "(", "new", "\\", "ReflectionMethod", "(", "$", "class", ",", "$", "function", ")", ")", "->", "getParameters", "(", ")", ";", "$", "paramNames", "=", "array_map", "(", "function", "(", "\\", "ReflectionParameter", "$", "v", ")", "{", "return", "$", "v", "->", "getName", "(", ")", ";", "}", ",", "$", "declaredParams", ")", ";", "$", "paramDefaults", "=", "array_map", "(", "function", "(", "\\", "ReflectionParameter", "$", "v", ")", "{", "return", "$", "v", "->", "isOptional", "(", ")", "?", "$", "v", "->", "getDefaultValue", "(", ")", ":", "null", ";", "}", ",", "$", "declaredParams", ")", ";", "return", "array_combine", "(", "$", "paramNames", ",", "array_replace", "(", "$", "paramDefaults", ",", "$", "paramValues", ")", ")", ";", "}" ]
Return array keyed by parameter name of values passed into a class static function @param string $class Name of class that has the method usually via __CLASS__ @param string $function Name of function to inspect usually via __FUNCTION__ @param array $paramValues array of actual values usually via func_get_args @return array
[ "Return", "array", "keyed", "by", "parameter", "name", "of", "values", "passed", "into", "a", "class", "static", "function" ]
train
https://github.com/chippyash/Assembly-Builder/blob/be477306b7a1c09b48ce9e100f9f6680035d0df3/src/chippyash/Assembler/Traits/ParameterGrabable.php#L45-L60
glynnforrest/blockade
src/Blockade/EventListener/FirewallListener.php
FirewallListener.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); foreach ($this->firewalls as $firewall) { //firewalls returns true for an exemption, so skip others if (true === $firewall->check($request)) { return; } } }
php
public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); foreach ($this->firewalls as $firewall) { //firewalls returns true for an exemption, so skip others if (true === $firewall->check($request)) { return; } } }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "foreach", "(", "$", "this", "->", "firewalls", "as", "$", "firewall", ")", "{", "//firewalls returns true for an exemption, so skip others", "if", "(", "true", "===", "$", "firewall", "->", "check", "(", "$", "request", ")", ")", "{", "return", ";", "}", "}", "}" ]
Respond to a REQUEST KernelEvent by validating the request against the registered firewalls.
[ "Respond", "to", "a", "REQUEST", "KernelEvent", "by", "validating", "the", "request", "against", "the", "registered", "firewalls", "." ]
train
https://github.com/glynnforrest/blockade/blob/5dfc8b2fa7b9f7029a1bdaa7c50e32ee8665ab3b/src/Blockade/EventListener/FirewallListener.php#L61-L70
ekuiter/feature-php
FeaturePhp/Aspect/Aspect.php
Aspect.getRelativeFileTarget
public function getRelativeFileTarget($aspectKernelTarget) { return fphp\Helper\Path::join(fphp\Helper\Path::rootPath(dirname($aspectKernelTarget)), $this->fileSpecification->getTarget()); }
php
public function getRelativeFileTarget($aspectKernelTarget) { return fphp\Helper\Path::join(fphp\Helper\Path::rootPath(dirname($aspectKernelTarget)), $this->fileSpecification->getTarget()); }
[ "public", "function", "getRelativeFileTarget", "(", "$", "aspectKernelTarget", ")", "{", "return", "fphp", "\\", "Helper", "\\", "Path", "::", "join", "(", "fphp", "\\", "Helper", "\\", "Path", "::", "rootPath", "(", "dirname", "(", "$", "aspectKernelTarget", ")", ")", ",", "$", "this", "->", "fileSpecification", "->", "getTarget", "(", ")", ")", ";", "}" ]
Returns the path of the aspect's target file relative to the aspect kernel's target file. @param string $aspectKernelTarget @return string
[ "Returns", "the", "path", "of", "the", "aspect", "s", "target", "file", "relative", "to", "the", "aspect", "kernel", "s", "target", "file", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Aspect/Aspect.php#L68-L71
ekuiter/feature-php
FeaturePhp/Aspect/Aspect.php
Aspect.getClassName
public function getClassName() { $fileSource = $this->fileSpecification->getSource(); return (new fphp\Helper\PhpParser())->parseFile($fileSource)->getExactlyOneClass($fileSource)->name; }
php
public function getClassName() { $fileSource = $this->fileSpecification->getSource(); return (new fphp\Helper\PhpParser())->parseFile($fileSource)->getExactlyOneClass($fileSource)->name; }
[ "public", "function", "getClassName", "(", ")", "{", "$", "fileSource", "=", "$", "this", "->", "fileSpecification", "->", "getSource", "(", ")", ";", "return", "(", "new", "fphp", "\\", "Helper", "\\", "PhpParser", "(", ")", ")", "->", "parseFile", "(", "$", "fileSource", ")", "->", "getExactlyOneClass", "(", "$", "fileSource", ")", "->", "name", ";", "}" ]
Returns the aspect's class name. For this, the aspect's file has to be parsed. @return string
[ "Returns", "the", "aspect", "s", "class", "name", ".", "For", "this", "the", "aspect", "s", "file", "has", "to", "be", "parsed", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Aspect/Aspect.php#L78-L81
php-lug/lug
src/Component/Grid/Filter/Type/AbstractType.php
AbstractType.filter
public function filter($data, array $options) { if (!$this->validate($data, $options)) { return; } $expressions = []; foreach ($options['fields'] as $field) { if (($expression = $this->process($field, $data, $options)) !== null) { $expressions[] = $expression; } } if (empty($expressions)) { return; } $builder = $options['builder']; $expression = $options['fields_condition'] === self::CONDITION_OR ? $builder->getExpressionBuilder()->orX($expressions) : $builder->getExpressionBuilder()->andX($expressions); if ($options['builder_condition'] === self::CONDITION_OR) { $builder->orWhere($expression); } else { $builder->andWhere($expression); } }
php
public function filter($data, array $options) { if (!$this->validate($data, $options)) { return; } $expressions = []; foreach ($options['fields'] as $field) { if (($expression = $this->process($field, $data, $options)) !== null) { $expressions[] = $expression; } } if (empty($expressions)) { return; } $builder = $options['builder']; $expression = $options['fields_condition'] === self::CONDITION_OR ? $builder->getExpressionBuilder()->orX($expressions) : $builder->getExpressionBuilder()->andX($expressions); if ($options['builder_condition'] === self::CONDITION_OR) { $builder->orWhere($expression); } else { $builder->andWhere($expression); } }
[ "public", "function", "filter", "(", "$", "data", ",", "array", "$", "options", ")", "{", "if", "(", "!", "$", "this", "->", "validate", "(", "$", "data", ",", "$", "options", ")", ")", "{", "return", ";", "}", "$", "expressions", "=", "[", "]", ";", "foreach", "(", "$", "options", "[", "'fields'", "]", "as", "$", "field", ")", "{", "if", "(", "(", "$", "expression", "=", "$", "this", "->", "process", "(", "$", "field", ",", "$", "data", ",", "$", "options", ")", ")", "!==", "null", ")", "{", "$", "expressions", "[", "]", "=", "$", "expression", ";", "}", "}", "if", "(", "empty", "(", "$", "expressions", ")", ")", "{", "return", ";", "}", "$", "builder", "=", "$", "options", "[", "'builder'", "]", ";", "$", "expression", "=", "$", "options", "[", "'fields_condition'", "]", "===", "self", "::", "CONDITION_OR", "?", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "orX", "(", "$", "expressions", ")", ":", "$", "builder", "->", "getExpressionBuilder", "(", ")", "->", "andX", "(", "$", "expressions", ")", ";", "if", "(", "$", "options", "[", "'builder_condition'", "]", "===", "self", "::", "CONDITION_OR", ")", "{", "$", "builder", "->", "orWhere", "(", "$", "expression", ")", ";", "}", "else", "{", "$", "builder", "->", "andWhere", "(", "$", "expression", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/AbstractType.php#L28-L57
php-lug/lug
src/Component/Grid/Filter/Type/AbstractType.php
AbstractType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'builder_condition' => self::CONDITION_AND, 'fields_condition' => self::CONDITION_OR, 'fields' => function (Options $options, $fields) { return $fields ?: [$options['filter']->getName()]; }, ]) ->setAllowedValues('builder_condition', $conditions = [self::CONDITION_AND, self::CONDITION_OR]) ->setAllowedValues('fields_condition', $conditions) ->setAllowedTypes('fields', 'array'); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'builder_condition' => self::CONDITION_AND, 'fields_condition' => self::CONDITION_OR, 'fields' => function (Options $options, $fields) { return $fields ?: [$options['filter']->getName()]; }, ]) ->setAllowedValues('builder_condition', $conditions = [self::CONDITION_AND, self::CONDITION_OR]) ->setAllowedValues('fields_condition', $conditions) ->setAllowedTypes('fields', 'array'); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'builder_condition'", "=>", "self", "::", "CONDITION_AND", ",", "'fields_condition'", "=>", "self", "::", "CONDITION_OR", ",", "'fields'", "=>", "function", "(", "Options", "$", "options", ",", "$", "fields", ")", "{", "return", "$", "fields", "?", ":", "[", "$", "options", "[", "'filter'", "]", "->", "getName", "(", ")", "]", ";", "}", ",", "]", ")", "->", "setAllowedValues", "(", "'builder_condition'", ",", "$", "conditions", "=", "[", "self", "::", "CONDITION_AND", ",", "self", "::", "CONDITION_OR", "]", ")", "->", "setAllowedValues", "(", "'fields_condition'", ",", "$", "conditions", ")", "->", "setAllowedTypes", "(", "'fields'", ",", "'array'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/AbstractType.php#L62-L75
technote-space/wordpress-plugin-base
src/classes/models/lib/loader/controller/api.php
Api.register_ajax_script
private function register_ajax_script() { return $this->register_script_common( function () { return [ 'endpoint' => $this->apply_filters( 'admin_ajax', admin_url( 'admin-ajax.php' ) ), 'nonce_key' => $this->get_nonce_key(), 'nonce_value' => $this->create_nonce(), 'is_admin_ajax' => true, ]; } ); }
php
private function register_ajax_script() { return $this->register_script_common( function () { return [ 'endpoint' => $this->apply_filters( 'admin_ajax', admin_url( 'admin-ajax.php' ) ), 'nonce_key' => $this->get_nonce_key(), 'nonce_value' => $this->create_nonce(), 'is_admin_ajax' => true, ]; } ); }
[ "private", "function", "register_ajax_script", "(", ")", "{", "return", "$", "this", "->", "register_script_common", "(", "function", "(", ")", "{", "return", "[", "'endpoint'", "=>", "$", "this", "->", "apply_filters", "(", "'admin_ajax'", ",", "admin_url", "(", "'admin-ajax.php'", ")", ")", ",", "'nonce_key'", "=>", "$", "this", "->", "get_nonce_key", "(", ")", ",", "'nonce_value'", "=>", "$", "this", "->", "create_nonce", "(", ")", ",", "'is_admin_ajax'", "=>", "true", ",", "]", ";", "}", ")", ";", "}" ]
register script for admin-ajax.php
[ "register", "script", "for", "admin", "-", "ajax", ".", "php" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/loader/controller/api.php#L177-L186
technote-space/wordpress-plugin-base
src/classes/models/lib/loader/controller/api.php
Api.error_to_response
private function error_to_response( $error ) { $error_data = $error->get_error_data(); if ( is_array( $error_data ) && isset( $error_data['status'] ) ) { $status = $error_data['status']; } else { $status = 500; } $errors = []; foreach ( (array) $error->errors as $code => $messages ) { foreach ( (array) $messages as $message ) { $errors[] = [ 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) ]; } } $data = $errors[0]; if ( count( $errors ) > 1 ) { array_shift( $errors ); $data['additional_errors'] = $errors; } $response = new \WP_REST_Response( $data, $status ); return $response; }
php
private function error_to_response( $error ) { $error_data = $error->get_error_data(); if ( is_array( $error_data ) && isset( $error_data['status'] ) ) { $status = $error_data['status']; } else { $status = 500; } $errors = []; foreach ( (array) $error->errors as $code => $messages ) { foreach ( (array) $messages as $message ) { $errors[] = [ 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) ]; } } $data = $errors[0]; if ( count( $errors ) > 1 ) { array_shift( $errors ); $data['additional_errors'] = $errors; } $response = new \WP_REST_Response( $data, $status ); return $response; }
[ "private", "function", "error_to_response", "(", "$", "error", ")", "{", "$", "error_data", "=", "$", "error", "->", "get_error_data", "(", ")", ";", "if", "(", "is_array", "(", "$", "error_data", ")", "&&", "isset", "(", "$", "error_data", "[", "'status'", "]", ")", ")", "{", "$", "status", "=", "$", "error_data", "[", "'status'", "]", ";", "}", "else", "{", "$", "status", "=", "500", ";", "}", "$", "errors", "=", "[", "]", ";", "foreach", "(", "(", "array", ")", "$", "error", "->", "errors", "as", "$", "code", "=>", "$", "messages", ")", "{", "foreach", "(", "(", "array", ")", "$", "messages", "as", "$", "message", ")", "{", "$", "errors", "[", "]", "=", "[", "'code'", "=>", "$", "code", ",", "'message'", "=>", "$", "message", ",", "'data'", "=>", "$", "error", "->", "get_error_data", "(", "$", "code", ")", "]", ";", "}", "}", "$", "data", "=", "$", "errors", "[", "0", "]", ";", "if", "(", "count", "(", "$", "errors", ")", ">", "1", ")", "{", "array_shift", "(", "$", "errors", ")", ";", "$", "data", "[", "'additional_errors'", "]", "=", "$", "errors", ";", "}", "$", "response", "=", "new", "\\", "WP_REST_Response", "(", "$", "data", ",", "$", "status", ")", ";", "return", "$", "response", ";", "}" ]
@param \WP_Error $error @return \WP_REST_Response
[ "@param", "\\", "WP_Error", "$error" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/loader/controller/api.php#L225-L248
technote-space/wordpress-plugin-base
src/classes/models/lib/loader/controller/api.php
Api.get_ajax_action_result
private function get_ajax_action_result( $api ) { if ( ! $this->nonce_check() ) { return new \WP_Error( 'rest_forbidden', 'Forbidden', [ 'status' => 403 ] ); } if ( ! $this->app->user_can( $api->get_capability() ) ) { return new \WP_Error( 'rest_forbidden', 'Forbidden', [ 'status' => 403 ] ); } if ( strtoupper( $api->get_method() ) !== $this->app->input->method() ) { return new \WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), [ 'status' => 404 ] ); } if ( in_array( $this->app->input->method(), [ 'GET', 'HEAD', ] ) ) { $params = $this->app->input->get(); } else { $params = $this->app->input->post(); } $args = $api->get_args_setting(); $required = []; $invalid_params = []; $request = new \WP_REST_Request( $_SERVER['REQUEST_METHOD'] ); $request->set_query_params( wp_unslash( $_GET ) ); $request->set_body_params( wp_unslash( $_POST ) ); foreach ( $args as $name => $setting ) { if ( array_key_exists( 'default', $setting ) && ! array_key_exists( $name, $params ) ) { $params[ $name ] = $setting['default']; } if ( ! isset( $params[ $name ] ) ) { if ( ! empty( $setting['required'] ) ) { $required[] = $name; } continue; } if ( ! empty( $setting['validate_callback'] ) ) { $valid_check = call_user_func( $setting['validate_callback'], $params[ $name ], $request, $name ); if ( false === $valid_check ) { $invalid_params[ $name ] = __( 'Invalid parameter.' ); continue; } if ( is_wp_error( $valid_check ) ) { $invalid_params[ $name ] = $valid_check->get_error_message(); continue; } } if ( ! empty( $setting['sanitize_callback'] ) && is_callable( $setting['sanitize_callback'] ) ) { $sanitized_value = call_user_func( $setting['sanitize_callback'], $params[ $name ], $request, $name ); if ( is_wp_error( $sanitized_value ) ) { $invalid_params[ $name ] = $sanitized_value->get_error_message(); } else { $params[ $name ] = $sanitized_value; } } } if ( ! empty( $required ) ) { return new \WP_Error( 'rest_missing_callback_param', sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ), [ 'status' => 400, 'params' => $required, ] ); } if ( $invalid_params ) { return new \WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ), [ 'status' => 400, 'params' => $invalid_params, ] ); } return $api->callback( $params ); }
php
private function get_ajax_action_result( $api ) { if ( ! $this->nonce_check() ) { return new \WP_Error( 'rest_forbidden', 'Forbidden', [ 'status' => 403 ] ); } if ( ! $this->app->user_can( $api->get_capability() ) ) { return new \WP_Error( 'rest_forbidden', 'Forbidden', [ 'status' => 403 ] ); } if ( strtoupper( $api->get_method() ) !== $this->app->input->method() ) { return new \WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), [ 'status' => 404 ] ); } if ( in_array( $this->app->input->method(), [ 'GET', 'HEAD', ] ) ) { $params = $this->app->input->get(); } else { $params = $this->app->input->post(); } $args = $api->get_args_setting(); $required = []; $invalid_params = []; $request = new \WP_REST_Request( $_SERVER['REQUEST_METHOD'] ); $request->set_query_params( wp_unslash( $_GET ) ); $request->set_body_params( wp_unslash( $_POST ) ); foreach ( $args as $name => $setting ) { if ( array_key_exists( 'default', $setting ) && ! array_key_exists( $name, $params ) ) { $params[ $name ] = $setting['default']; } if ( ! isset( $params[ $name ] ) ) { if ( ! empty( $setting['required'] ) ) { $required[] = $name; } continue; } if ( ! empty( $setting['validate_callback'] ) ) { $valid_check = call_user_func( $setting['validate_callback'], $params[ $name ], $request, $name ); if ( false === $valid_check ) { $invalid_params[ $name ] = __( 'Invalid parameter.' ); continue; } if ( is_wp_error( $valid_check ) ) { $invalid_params[ $name ] = $valid_check->get_error_message(); continue; } } if ( ! empty( $setting['sanitize_callback'] ) && is_callable( $setting['sanitize_callback'] ) ) { $sanitized_value = call_user_func( $setting['sanitize_callback'], $params[ $name ], $request, $name ); if ( is_wp_error( $sanitized_value ) ) { $invalid_params[ $name ] = $sanitized_value->get_error_message(); } else { $params[ $name ] = $sanitized_value; } } } if ( ! empty( $required ) ) { return new \WP_Error( 'rest_missing_callback_param', sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ), [ 'status' => 400, 'params' => $required, ] ); } if ( $invalid_params ) { return new \WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ), [ 'status' => 400, 'params' => $invalid_params, ] ); } return $api->callback( $params ); }
[ "private", "function", "get_ajax_action_result", "(", "$", "api", ")", "{", "if", "(", "!", "$", "this", "->", "nonce_check", "(", ")", ")", "{", "return", "new", "\\", "WP_Error", "(", "'rest_forbidden'", ",", "'Forbidden'", ",", "[", "'status'", "=>", "403", "]", ")", ";", "}", "if", "(", "!", "$", "this", "->", "app", "->", "user_can", "(", "$", "api", "->", "get_capability", "(", ")", ")", ")", "{", "return", "new", "\\", "WP_Error", "(", "'rest_forbidden'", ",", "'Forbidden'", ",", "[", "'status'", "=>", "403", "]", ")", ";", "}", "if", "(", "strtoupper", "(", "$", "api", "->", "get_method", "(", ")", ")", "!==", "$", "this", "->", "app", "->", "input", "->", "method", "(", ")", ")", "{", "return", "new", "\\", "WP_Error", "(", "'rest_no_route'", ",", "__", "(", "'No route was found matching the URL and request method'", ")", ",", "[", "'status'", "=>", "404", "]", ")", ";", "}", "if", "(", "in_array", "(", "$", "this", "->", "app", "->", "input", "->", "method", "(", ")", ",", "[", "'GET'", ",", "'HEAD'", ",", "]", ")", ")", "{", "$", "params", "=", "$", "this", "->", "app", "->", "input", "->", "get", "(", ")", ";", "}", "else", "{", "$", "params", "=", "$", "this", "->", "app", "->", "input", "->", "post", "(", ")", ";", "}", "$", "args", "=", "$", "api", "->", "get_args_setting", "(", ")", ";", "$", "required", "=", "[", "]", ";", "$", "invalid_params", "=", "[", "]", ";", "$", "request", "=", "new", "\\", "WP_REST_Request", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", ";", "$", "request", "->", "set_query_params", "(", "wp_unslash", "(", "$", "_GET", ")", ")", ";", "$", "request", "->", "set_body_params", "(", "wp_unslash", "(", "$", "_POST", ")", ")", ";", "foreach", "(", "$", "args", "as", "$", "name", "=>", "$", "setting", ")", "{", "if", "(", "array_key_exists", "(", "'default'", ",", "$", "setting", ")", "&&", "!", "array_key_exists", "(", "$", "name", ",", "$", "params", ")", ")", "{", "$", "params", "[", "$", "name", "]", "=", "$", "setting", "[", "'default'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "params", "[", "$", "name", "]", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "setting", "[", "'required'", "]", ")", ")", "{", "$", "required", "[", "]", "=", "$", "name", ";", "}", "continue", ";", "}", "if", "(", "!", "empty", "(", "$", "setting", "[", "'validate_callback'", "]", ")", ")", "{", "$", "valid_check", "=", "call_user_func", "(", "$", "setting", "[", "'validate_callback'", "]", ",", "$", "params", "[", "$", "name", "]", ",", "$", "request", ",", "$", "name", ")", ";", "if", "(", "false", "===", "$", "valid_check", ")", "{", "$", "invalid_params", "[", "$", "name", "]", "=", "__", "(", "'Invalid parameter.'", ")", ";", "continue", ";", "}", "if", "(", "is_wp_error", "(", "$", "valid_check", ")", ")", "{", "$", "invalid_params", "[", "$", "name", "]", "=", "$", "valid_check", "->", "get_error_message", "(", ")", ";", "continue", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "setting", "[", "'sanitize_callback'", "]", ")", "&&", "is_callable", "(", "$", "setting", "[", "'sanitize_callback'", "]", ")", ")", "{", "$", "sanitized_value", "=", "call_user_func", "(", "$", "setting", "[", "'sanitize_callback'", "]", ",", "$", "params", "[", "$", "name", "]", ",", "$", "request", ",", "$", "name", ")", ";", "if", "(", "is_wp_error", "(", "$", "sanitized_value", ")", ")", "{", "$", "invalid_params", "[", "$", "name", "]", "=", "$", "sanitized_value", "->", "get_error_message", "(", ")", ";", "}", "else", "{", "$", "params", "[", "$", "name", "]", "=", "$", "sanitized_value", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "required", ")", ")", "{", "return", "new", "\\", "WP_Error", "(", "'rest_missing_callback_param'", ",", "sprintf", "(", "__", "(", "'Missing parameter(s): %s'", ")", ",", "implode", "(", "', '", ",", "$", "required", ")", ")", ",", "[", "'status'", "=>", "400", ",", "'params'", "=>", "$", "required", ",", "]", ")", ";", "}", "if", "(", "$", "invalid_params", ")", "{", "return", "new", "\\", "WP_Error", "(", "'rest_invalid_param'", ",", "sprintf", "(", "__", "(", "'Invalid parameter(s): %s'", ")", ",", "implode", "(", "', '", ",", "array_keys", "(", "$", "invalid_params", ")", ")", ")", ",", "[", "'status'", "=>", "400", ",", "'params'", "=>", "$", "invalid_params", ",", "]", ")", ";", "}", "return", "$", "api", "->", "callback", "(", "$", "params", ")", ";", "}" ]
@param \Technote\Classes\Controllers\Api\Base $api @return int|\WP_Error|\WP_REST_Response
[ "@param", "\\", "Technote", "\\", "Classes", "\\", "Controllers", "\\", "Api", "\\", "Base", "$api" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/loader/controller/api.php#L255-L327
Eresus/EresusCMS
src/core/framework/core/Template/Template.php
TemplateSettings.getGlobalValue
public static function getGlobalValue($name) { return array_key_exists($name, self::$globalValues) ? self::$globalValues[$name] : null; }
php
public static function getGlobalValue($name) { return array_key_exists($name, self::$globalValues) ? self::$globalValues[$name] : null; }
[ "public", "static", "function", "getGlobalValue", "(", "$", "name", ")", "{", "return", "array_key_exists", "(", "$", "name", ",", "self", "::", "$", "globalValues", ")", "?", "self", "::", "$", "globalValues", "[", "$", "name", "]", ":", "null", ";", "}" ]
Get global substitution value @param string $name @return null|mixed Null will be returned if value not set
[ "Get", "global", "substitution", "value" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/Template/Template.php#L61-L64
Visithor/visithor
src/Visithor/Renderer/DotRenderer.php
DotRenderer.render
public function render( OutputInterface $output, Url $url, $HTTPCode, $success ) { $content = $success ? '<fg=green>.</fg=green>' : '<fg=red>F</fg=red>'; $output->write($content); return $this; }
php
public function render( OutputInterface $output, Url $url, $HTTPCode, $success ) { $content = $success ? '<fg=green>.</fg=green>' : '<fg=red>F</fg=red>'; $output->write($content); return $this; }
[ "public", "function", "render", "(", "OutputInterface", "$", "output", ",", "Url", "$", "url", ",", "$", "HTTPCode", ",", "$", "success", ")", "{", "$", "content", "=", "$", "success", "?", "'<fg=green>.</fg=green>'", ":", "'<fg=red>F</fg=red>'", ";", "$", "output", "->", "write", "(", "$", "content", ")", ";", "return", "$", "this", ";", "}" ]
Renders an URL execution @param OutputInterface $output Output @param Url $url Url @param string $HTTPCode Returned HTTP Code @param boolean $success Successfully executed @return $this Self object
[ "Renders", "an", "URL", "execution" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Renderer/DotRenderer.php#L37-L50
artscorestudio/document-bundle
Controller/PageController.php
PageController.deleteAction
public function deleteAction($id) { $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page !'); $pageManager = $this->get('asf_document.page.manager'); $page = $pageManager->getRepository()->findOneBy(array('id' => $id)); try { if ( is_null($page) ) throw new \Exception($this->get('translator')->trans('An error occurs when deleting the page', array(), 'asf_document')); $pageManager->getEntityManager()->remove($page); $pageManager->getEntityManager()->flush(); if ( $this->has('asf_layout.flash_message') ) { $this->get('asf_layout.flash_message')->success($this->getTranslator()->trans('The page "%name%" successfully deleted', array('%name%' => $page->getTitle()), 'asf_document')); } } catch (\Exception $e) { $this->get('asf_layout.flash_message')->danger($e->getMessage()); } return $this->redirect($this->get('router')->generate('asf_document_page_list')); }
php
public function deleteAction($id) { $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page !'); $pageManager = $this->get('asf_document.page.manager'); $page = $pageManager->getRepository()->findOneBy(array('id' => $id)); try { if ( is_null($page) ) throw new \Exception($this->get('translator')->trans('An error occurs when deleting the page', array(), 'asf_document')); $pageManager->getEntityManager()->remove($page); $pageManager->getEntityManager()->flush(); if ( $this->has('asf_layout.flash_message') ) { $this->get('asf_layout.flash_message')->success($this->getTranslator()->trans('The page "%name%" successfully deleted', array('%name%' => $page->getTitle()), 'asf_document')); } } catch (\Exception $e) { $this->get('asf_layout.flash_message')->danger($e->getMessage()); } return $this->redirect($this->get('router')->generate('asf_document_page_list')); }
[ "public", "function", "deleteAction", "(", "$", "id", ")", "{", "$", "this", "->", "denyAccessUnlessGranted", "(", "'ROLE_ADMIN'", ",", "null", ",", "'Unable to access this page !'", ")", ";", "$", "pageManager", "=", "$", "this", "->", "get", "(", "'asf_document.page.manager'", ")", ";", "$", "page", "=", "$", "pageManager", "->", "getRepository", "(", ")", "->", "findOneBy", "(", "array", "(", "'id'", "=>", "$", "id", ")", ")", ";", "try", "{", "if", "(", "is_null", "(", "$", "page", ")", ")", "throw", "new", "\\", "Exception", "(", "$", "this", "->", "get", "(", "'translator'", ")", "->", "trans", "(", "'An error occurs when deleting the page'", ",", "array", "(", ")", ",", "'asf_document'", ")", ")", ";", "$", "pageManager", "->", "getEntityManager", "(", ")", "->", "remove", "(", "$", "page", ")", ";", "$", "pageManager", "->", "getEntityManager", "(", ")", "->", "flush", "(", ")", ";", "if", "(", "$", "this", "->", "has", "(", "'asf_layout.flash_message'", ")", ")", "{", "$", "this", "->", "get", "(", "'asf_layout.flash_message'", ")", "->", "success", "(", "$", "this", "->", "getTranslator", "(", ")", "->", "trans", "(", "'The page \"%name%\" successfully deleted'", ",", "array", "(", "'%name%'", "=>", "$", "page", "->", "getTitle", "(", ")", ")", ",", "'asf_document'", ")", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "get", "(", "'asf_layout.flash_message'", ")", "->", "danger", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "get", "(", "'router'", ")", "->", "generate", "(", "'asf_document_page_list'", ")", ")", ";", "}" ]
Delete a page @param integer $id ASFDocumentBundle:Page Entity ID @throws AccessDeniedException If user does not have ACL's rights for delete the page @throws \Exception Error on page not found or on removing element from DB @return \Symfony\Component\HttpFoundation\RedirectResponse
[ "Delete", "a", "page" ]
train
https://github.com/artscorestudio/document-bundle/blob/3aceab0f75de8f7dd0fad0d0db83d7940bf565c8/Controller/PageController.php#L203-L226
zhouyl/mellivora
Mellivora/Database/Query/Grammars/SqlServerGrammar.php
SqlServerGrammar.parseUpdateTable
protected function parseUpdateTable($table) { $table = $alias = $this->wrapTable($table); if (strpos(strtolower($table), '] as [') !== false) { $alias = '[' . explode('] as [', $table)[1]; } return [$table, $alias]; }
php
protected function parseUpdateTable($table) { $table = $alias = $this->wrapTable($table); if (strpos(strtolower($table), '] as [') !== false) { $alias = '[' . explode('] as [', $table)[1]; } return [$table, $alias]; }
[ "protected", "function", "parseUpdateTable", "(", "$", "table", ")", "{", "$", "table", "=", "$", "alias", "=", "$", "this", "->", "wrapTable", "(", "$", "table", ")", ";", "if", "(", "strpos", "(", "strtolower", "(", "$", "table", ")", ",", "'] as ['", ")", "!==", "false", ")", "{", "$", "alias", "=", "'['", ".", "explode", "(", "'] as ['", ",", "$", "table", ")", "[", "1", "]", ";", "}", "return", "[", "$", "table", ",", "$", "alias", "]", ";", "}" ]
Get the table and alias for the given table. @param string $table @return array
[ "Get", "the", "table", "and", "alias", "for", "the", "given", "table", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Query/Grammars/SqlServerGrammar.php#L350-L359
hametuha/wpametu
src/WPametu/API/RewriteParser.php
RewriteParser.parse_request
public function parse_request($uri, \WP_Query &$wp_query = null){ // Set wp_query if exists if( !is_null($wp_query) ){ $this->wp_query = $wp_query; } // Parse URI $uri = explode('/', trim($uri, '/')); $method = array_shift($uri); $request_method = $this->input->request_method(); $this->handle_request($method, $request_method, $uri); }
php
public function parse_request($uri, \WP_Query &$wp_query = null){ // Set wp_query if exists if( !is_null($wp_query) ){ $this->wp_query = $wp_query; } // Parse URI $uri = explode('/', trim($uri, '/')); $method = array_shift($uri); $request_method = $this->input->request_method(); $this->handle_request($method, $request_method, $uri); }
[ "public", "function", "parse_request", "(", "$", "uri", ",", "\\", "WP_Query", "&", "$", "wp_query", "=", "null", ")", "{", "// Set wp_query if exists", "if", "(", "!", "is_null", "(", "$", "wp_query", ")", ")", "{", "$", "this", "->", "wp_query", "=", "$", "wp_query", ";", "}", "// Parse URI", "$", "uri", "=", "explode", "(", "'/'", ",", "trim", "(", "$", "uri", ",", "'/'", ")", ")", ";", "$", "method", "=", "array_shift", "(", "$", "uri", ")", ";", "$", "request_method", "=", "$", "this", "->", "input", "->", "request_method", "(", ")", ";", "$", "this", "->", "handle_request", "(", "$", "method", ",", "$", "request_method", ",", "$", "uri", ")", ";", "}" ]
Parse request @param string $uri @param \WP_Query $wp_query
[ "Parse", "request" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/API/RewriteParser.php#L29-L39
hametuha/wpametu
src/WPametu/API/RewriteParser.php
RewriteParser.invoke
protected function invoke($method_name, $request_method, array $arguments = []){ $method_name = strtolower($request_method).'_'.$this->str->to_snake_case($method_name); // Check if method exists if( !is_callable([$this, $method_name]) ){ return false; } // Check accessibility $reflection = new \ReflectionMethod($this, $method_name); if( !$reflection->isPublic() || $reflection->isStatic() ){ return false; } // Check required arguments length if( $reflection->getNumberOfRequiredParameters() > count($arguments) ){ return false; } // O.K. It's public method. Call it. $this->handle_result(call_user_func_array([$this, $method_name], $arguments)); return true; }
php
protected function invoke($method_name, $request_method, array $arguments = []){ $method_name = strtolower($request_method).'_'.$this->str->to_snake_case($method_name); // Check if method exists if( !is_callable([$this, $method_name]) ){ return false; } // Check accessibility $reflection = new \ReflectionMethod($this, $method_name); if( !$reflection->isPublic() || $reflection->isStatic() ){ return false; } // Check required arguments length if( $reflection->getNumberOfRequiredParameters() > count($arguments) ){ return false; } // O.K. It's public method. Call it. $this->handle_result(call_user_func_array([$this, $method_name], $arguments)); return true; }
[ "protected", "function", "invoke", "(", "$", "method_name", ",", "$", "request_method", ",", "array", "$", "arguments", "=", "[", "]", ")", "{", "$", "method_name", "=", "strtolower", "(", "$", "request_method", ")", ".", "'_'", ".", "$", "this", "->", "str", "->", "to_snake_case", "(", "$", "method_name", ")", ";", "// Check if method exists", "if", "(", "!", "is_callable", "(", "[", "$", "this", ",", "$", "method_name", "]", ")", ")", "{", "return", "false", ";", "}", "// Check accessibility", "$", "reflection", "=", "new", "\\", "ReflectionMethod", "(", "$", "this", ",", "$", "method_name", ")", ";", "if", "(", "!", "$", "reflection", "->", "isPublic", "(", ")", "||", "$", "reflection", "->", "isStatic", "(", ")", ")", "{", "return", "false", ";", "}", "// Check required arguments length", "if", "(", "$", "reflection", "->", "getNumberOfRequiredParameters", "(", ")", ">", "count", "(", "$", "arguments", ")", ")", "{", "return", "false", ";", "}", "// O.K. It's public method. Call it.", "$", "this", "->", "handle_result", "(", "call_user_func_array", "(", "[", "$", "this", ",", "$", "method_name", "]", ",", "$", "arguments", ")", ")", ";", "return", "true", ";", "}" ]
Search method and execute if exists. @param string $method_name @param string $request_method @param array $arguments @return bool
[ "Search", "method", "and", "execute", "if", "exists", "." ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/API/RewriteParser.php#L61-L79
OpenBuildings/monetary
src/OpenBuildings/Monetary/Source/ECB.php
Source_ECB.convert_to_array
public function convert_to_array($raw_data) { $xml = new \SimpleXMLElement($raw_data); $xml->registerXPathNamespace( self::XML_NAMESPACE, self::XML_NAMESPACE_URL ); $data = $xml->xpath(self::XPATH_CURRENCY); $currencies = array(); foreach ($data as $currency) { $currencies[ (string) $currency->attributes()->currency] = (string) $currency->attributes()->rate; } return $currencies; }
php
public function convert_to_array($raw_data) { $xml = new \SimpleXMLElement($raw_data); $xml->registerXPathNamespace( self::XML_NAMESPACE, self::XML_NAMESPACE_URL ); $data = $xml->xpath(self::XPATH_CURRENCY); $currencies = array(); foreach ($data as $currency) { $currencies[ (string) $currency->attributes()->currency] = (string) $currency->attributes()->rate; } return $currencies; }
[ "public", "function", "convert_to_array", "(", "$", "raw_data", ")", "{", "$", "xml", "=", "new", "\\", "SimpleXMLElement", "(", "$", "raw_data", ")", ";", "$", "xml", "->", "registerXPathNamespace", "(", "self", "::", "XML_NAMESPACE", ",", "self", "::", "XML_NAMESPACE_URL", ")", ";", "$", "data", "=", "$", "xml", "->", "xpath", "(", "self", "::", "XPATH_CURRENCY", ")", ";", "$", "currencies", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "currency", ")", "{", "$", "currencies", "[", "(", "string", ")", "$", "currency", "->", "attributes", "(", ")", "->", "currency", "]", "=", "(", "string", ")", "$", "currency", "->", "attributes", "(", ")", "->", "rate", ";", "}", "return", "$", "currencies", ";", "}" ]
Convert raw currency data to array of currencies @param string $raw_data currency data in XML format @return array currencies
[ "Convert", "raw", "currency", "data", "to", "array", "of", "currencies" ]
train
https://github.com/OpenBuildings/monetary/blob/f7831ab055eaba7105f3f3530506b96de7fedd29/src/OpenBuildings/Monetary/Source/ECB.php#L30-L47
FriendsOfApi/phraseapp
src/Api/Translation.php
Translation.indexLocale
public function indexLocale(string $projectKey, string $localeId, array $params = []) { if (isset($params['tags'])) { $params['q'] = 'tags:'.$params['tags']; unset($params['tags']); } $response = $this->httpGet(sprintf('/api/v2/projects/%s/locales/%s/translations', $projectKey, $localeId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, Index::class); }
php
public function indexLocale(string $projectKey, string $localeId, array $params = []) { if (isset($params['tags'])) { $params['q'] = 'tags:'.$params['tags']; unset($params['tags']); } $response = $this->httpGet(sprintf('/api/v2/projects/%s/locales/%s/translations', $projectKey, $localeId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, Index::class); }
[ "public", "function", "indexLocale", "(", "string", "$", "projectKey", ",", "string", "$", "localeId", ",", "array", "$", "params", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "'tags'", "]", ")", ")", "{", "$", "params", "[", "'q'", "]", "=", "'tags:'", ".", "$", "params", "[", "'tags'", "]", ";", "unset", "(", "$", "params", "[", "'tags'", "]", ")", ";", "}", "$", "response", "=", "$", "this", "->", "httpGet", "(", "sprintf", "(", "'/api/v2/projects/%s/locales/%s/translations'", ",", "$", "projectKey", ",", "$", "localeId", ")", ",", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "hydrator", ")", "{", "return", "$", "response", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "!==", "201", ")", "{", "$", "this", "->", "handleErrors", "(", "$", "response", ")", ";", "}", "return", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "response", ",", "Index", "::", "class", ")", ";", "}" ]
Index a locale. @param string $projectKey @param string $localeId @param array $params @return Index|ResponseInterface
[ "Index", "a", "locale", "." ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Api/Translation.php#L31-L49
FriendsOfApi/phraseapp
src/Api/Translation.php
Translation.create
public function create(string $projectKey, string $localeId, string $keyId, string $content, array $params = []) { $params['locale_id'] = $localeId; $params['key_id'] = $keyId; $params['content'] = $content; $response = $this->httpPost(sprintf('/api/v2/projects/%s/translations', $projectKey), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, TranslationCreated::class); }
php
public function create(string $projectKey, string $localeId, string $keyId, string $content, array $params = []) { $params['locale_id'] = $localeId; $params['key_id'] = $keyId; $params['content'] = $content; $response = $this->httpPost(sprintf('/api/v2/projects/%s/translations', $projectKey), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, TranslationCreated::class); }
[ "public", "function", "create", "(", "string", "$", "projectKey", ",", "string", "$", "localeId", ",", "string", "$", "keyId", ",", "string", "$", "content", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "params", "[", "'locale_id'", "]", "=", "$", "localeId", ";", "$", "params", "[", "'key_id'", "]", "=", "$", "keyId", ";", "$", "params", "[", "'content'", "]", "=", "$", "content", ";", "$", "response", "=", "$", "this", "->", "httpPost", "(", "sprintf", "(", "'/api/v2/projects/%s/translations'", ",", "$", "projectKey", ")", ",", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "hydrator", ")", "{", "return", "$", "response", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "!==", "201", ")", "{", "$", "this", "->", "handleErrors", "(", "$", "response", ")", ";", "}", "return", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "response", ",", "TranslationCreated", "::", "class", ")", ";", "}" ]
Create a translation. @param string $projectKey @param string $keyId @param string $content @param array $params @return TranslationCreated|ResponseInterface
[ "Create", "a", "translation", "." ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Api/Translation.php#L61-L78
FriendsOfApi/phraseapp
src/Api/Translation.php
Translation.update
public function update(string $projectKey, string $translationId, string $content, array $params = []) { $params['content'] = $content; $response = $this->httpPatch(sprintf('/api/v2/projects/%s/translations/%s', $projectKey, $translationId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, TranslationUpdated::class); }
php
public function update(string $projectKey, string $translationId, string $content, array $params = []) { $params['content'] = $content; $response = $this->httpPatch(sprintf('/api/v2/projects/%s/translations/%s', $projectKey, $translationId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, TranslationUpdated::class); }
[ "public", "function", "update", "(", "string", "$", "projectKey", ",", "string", "$", "translationId", ",", "string", "$", "content", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "params", "[", "'content'", "]", "=", "$", "content", ";", "$", "response", "=", "$", "this", "->", "httpPatch", "(", "sprintf", "(", "'/api/v2/projects/%s/translations/%s'", ",", "$", "projectKey", ",", "$", "translationId", ")", ",", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "hydrator", ")", "{", "return", "$", "response", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "!==", "201", ")", "{", "$", "this", "->", "handleErrors", "(", "$", "response", ")", ";", "}", "return", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "response", ",", "TranslationUpdated", "::", "class", ")", ";", "}" ]
Update a translation. @param string $projectKey @param string $translationId @param string $content @param array $params @return TranslationUpdated|ResponseInterface
[ "Update", "a", "translation", "." ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Api/Translation.php#L90-L105
FriendsOfApi/phraseapp
src/Api/Translation.php
Translation.indexKey
public function indexKey(string $projectKey, string $keyId, array $params = []) { if (isset($params['tags'])) { $params['q'] = 'tags:'.$params['tags']; unset($params['tags']); } $response = $this->httpGet(sprintf('/api/v2/projects/%s/keys/%s/translations', $projectKey, $keyId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, Index::class); }
php
public function indexKey(string $projectKey, string $keyId, array $params = []) { if (isset($params['tags'])) { $params['q'] = 'tags:'.$params['tags']; unset($params['tags']); } $response = $this->httpGet(sprintf('/api/v2/projects/%s/keys/%s/translations', $projectKey, $keyId), $params); if (!$this->hydrator) { return $response; } if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) { $this->handleErrors($response); } return $this->hydrator->hydrate($response, Index::class); }
[ "public", "function", "indexKey", "(", "string", "$", "projectKey", ",", "string", "$", "keyId", ",", "array", "$", "params", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "'tags'", "]", ")", ")", "{", "$", "params", "[", "'q'", "]", "=", "'tags:'", ".", "$", "params", "[", "'tags'", "]", ";", "unset", "(", "$", "params", "[", "'tags'", "]", ")", ";", "}", "$", "response", "=", "$", "this", "->", "httpGet", "(", "sprintf", "(", "'/api/v2/projects/%s/keys/%s/translations'", ",", "$", "projectKey", ",", "$", "keyId", ")", ",", "$", "params", ")", ";", "if", "(", "!", "$", "this", "->", "hydrator", ")", "{", "return", "$", "response", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", "&&", "$", "response", "->", "getStatusCode", "(", ")", "!==", "201", ")", "{", "$", "this", "->", "handleErrors", "(", "$", "response", ")", ";", "}", "return", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "response", ",", "Index", "::", "class", ")", ";", "}" ]
List translations for a specific key. @param string $projectKey @param string $keyId @param array $params @return Index|ResponseInterface
[ "List", "translations", "for", "a", "specific", "key", "." ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Api/Translation.php#L116-L134
j-d/draggy
src/Draggy/Autocode/Entity.php
Entity.&
public function &getAttributeByName($name) { if (!isset( $this->attributes[$name] )) { throw new \RuntimeException( 'An attribute by the name of \'' . $name . '\' could not be located on the \'' . $this->getName() . '\' entity.' ); } return $this->attributes[$name]; }
php
public function &getAttributeByName($name) { if (!isset( $this->attributes[$name] )) { throw new \RuntimeException( 'An attribute by the name of \'' . $name . '\' could not be located on the \'' . $this->getName() . '\' entity.' ); } return $this->attributes[$name]; }
[ "public", "function", "&", "getAttributeByName", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'An attribute by the name of \\''", ".", "$", "name", ".", "'\\' could not be located on the \\''", ".", "$", "this", "->", "getName", "(", ")", ".", "'\\' entity.'", ")", ";", "}", "return", "$", "this", "->", "attributes", "[", "$", "name", "]", ";", "}" ]
@param $name @return Attribute @throws \RuntimeException
[ "@param", "$name" ]
train
https://github.com/j-d/draggy/blob/97ffc66e1aacb5f685d7aac5251c4abb8888d4bb/src/Draggy/Autocode/Entity.php#L254-L261
j-d/draggy
src/Draggy/Autocode/Entity.php
Entity.&
public function &getPrimaryAttribute() { if (count($this->primaryAttributes) != 1) { throw new \RuntimeException( 'There is not one primary attribute on the \'' . $this->getName() . '\' entity. (There are ' . count($this->getPrimaryAttributes()) . ')' ); } return $this->primaryAttributes[array_keys($this->primaryAttributes)[0]]; }
php
public function &getPrimaryAttribute() { if (count($this->primaryAttributes) != 1) { throw new \RuntimeException( 'There is not one primary attribute on the \'' . $this->getName() . '\' entity. (There are ' . count($this->getPrimaryAttributes()) . ')' ); } return $this->primaryAttributes[array_keys($this->primaryAttributes)[0]]; }
[ "public", "function", "&", "getPrimaryAttribute", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "primaryAttributes", ")", "!=", "1", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'There is not one primary attribute on the \\''", ".", "$", "this", "->", "getName", "(", ")", ".", "'\\' entity. (There are '", ".", "count", "(", "$", "this", "->", "getPrimaryAttributes", "(", ")", ")", ".", "')'", ")", ";", "}", "return", "$", "this", "->", "primaryAttributes", "[", "array_keys", "(", "$", "this", "->", "primaryAttributes", ")", "[", "0", "]", "]", ";", "}" ]
@return Attribute @throws \RuntimeException
[ "@return", "Attribute" ]
train
https://github.com/j-d/draggy/blob/97ffc66e1aacb5f685d7aac5251c4abb8888d4bb/src/Draggy/Autocode/Entity.php#L268-L275
WellCommerce/AppBundle
Form/DataTransformer/TranslationTransformer.php
TranslationTransformer.transform
public function transform($modelData) { $values = []; if ($modelData instanceof PersistentCollection) { $mapping = $modelData->getMapping(); $metaData = $this->getClassMetadata($mapping['targetEntity']); $fields = $metaData->getFieldNames(); foreach ($modelData as $translation) { $this->transformTranslation($translation, $fields, $values); } } return $values; }
php
public function transform($modelData) { $values = []; if ($modelData instanceof PersistentCollection) { $mapping = $modelData->getMapping(); $metaData = $this->getClassMetadata($mapping['targetEntity']); $fields = $metaData->getFieldNames(); foreach ($modelData as $translation) { $this->transformTranslation($translation, $fields, $values); } } return $values; }
[ "public", "function", "transform", "(", "$", "modelData", ")", "{", "$", "values", "=", "[", "]", ";", "if", "(", "$", "modelData", "instanceof", "PersistentCollection", ")", "{", "$", "mapping", "=", "$", "modelData", "->", "getMapping", "(", ")", ";", "$", "metaData", "=", "$", "this", "->", "getClassMetadata", "(", "$", "mapping", "[", "'targetEntity'", "]", ")", ";", "$", "fields", "=", "$", "metaData", "->", "getFieldNames", "(", ")", ";", "foreach", "(", "$", "modelData", "as", "$", "translation", ")", "{", "$", "this", "->", "transformTranslation", "(", "$", "translation", ",", "$", "fields", ",", "$", "values", ")", ";", "}", "}", "return", "$", "values", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Form/DataTransformer/TranslationTransformer.php#L31-L46
WellCommerce/AppBundle
Form/DataTransformer/TranslationTransformer.php
TranslationTransformer.transformTranslation
protected function transformTranslation(LocaleAwareInterface $translation, $fields, &$values) { foreach ($fields as $field) { $values[$translation->getLocale()][$field] = $this->propertyAccessor->getValue($translation, $field); } }
php
protected function transformTranslation(LocaleAwareInterface $translation, $fields, &$values) { foreach ($fields as $field) { $values[$translation->getLocale()][$field] = $this->propertyAccessor->getValue($translation, $field); } }
[ "protected", "function", "transformTranslation", "(", "LocaleAwareInterface", "$", "translation", ",", "$", "fields", ",", "&", "$", "values", ")", "{", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "values", "[", "$", "translation", "->", "getLocale", "(", ")", "]", "[", "$", "field", "]", "=", "$", "this", "->", "propertyAccessor", "->", "getValue", "(", "$", "translation", ",", "$", "field", ")", ";", "}", "}" ]
Transforms single translation @param LocaleAwareInterface $translation @param array $fields @param array $values
[ "Transforms", "single", "translation" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Form/DataTransformer/TranslationTransformer.php#L55-L60
WellCommerce/AppBundle
Form/DataTransformer/TranslationTransformer.php
TranslationTransformer.reverseTransform
public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $value) { foreach ($value as $locale => $fields) { $translation = $modelData->translate($locale); foreach ($fields as $fieldName => $fieldValue) { $this->propertyAccessor->setValue($translation, $fieldName, $fieldValue); } } $modelData->mergeNewTranslations(); }
php
public function reverseTransform($modelData, PropertyPathInterface $propertyPath, $value) { foreach ($value as $locale => $fields) { $translation = $modelData->translate($locale); foreach ($fields as $fieldName => $fieldValue) { $this->propertyAccessor->setValue($translation, $fieldName, $fieldValue); } } $modelData->mergeNewTranslations(); }
[ "public", "function", "reverseTransform", "(", "$", "modelData", ",", "PropertyPathInterface", "$", "propertyPath", ",", "$", "value", ")", "{", "foreach", "(", "$", "value", "as", "$", "locale", "=>", "$", "fields", ")", "{", "$", "translation", "=", "$", "modelData", "->", "translate", "(", "$", "locale", ")", ";", "foreach", "(", "$", "fields", "as", "$", "fieldName", "=>", "$", "fieldValue", ")", "{", "$", "this", "->", "propertyAccessor", "->", "setValue", "(", "$", "translation", ",", "$", "fieldName", ",", "$", "fieldValue", ")", ";", "}", "}", "$", "modelData", "->", "mergeNewTranslations", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Form/DataTransformer/TranslationTransformer.php#L65-L75
InactiveProjects/limoncello-illuminate
app/Api/RolesApi.php
RolesApi.createInstance
protected function createInstance(JsonApiRequest $request, ErrorCollection $errors) { // for Roles allowed to define ID on creation that's why we don't use default (parent) method $instance = $this->getModel()->newInstance(); $instance->setAttribute($instance->getKeyName(), $request->getId()); return $instance; }
php
protected function createInstance(JsonApiRequest $request, ErrorCollection $errors) { // for Roles allowed to define ID on creation that's why we don't use default (parent) method $instance = $this->getModel()->newInstance(); $instance->setAttribute($instance->getKeyName(), $request->getId()); return $instance; }
[ "protected", "function", "createInstance", "(", "JsonApiRequest", "$", "request", ",", "ErrorCollection", "$", "errors", ")", "{", "// for Roles allowed to define ID on creation that's why we don't use default (parent) method", "$", "instance", "=", "$", "this", "->", "getModel", "(", ")", "->", "newInstance", "(", ")", ";", "$", "instance", "->", "setAttribute", "(", "$", "instance", "->", "getKeyName", "(", ")", ",", "$", "request", "->", "getId", "(", ")", ")", ";", "return", "$", "instance", ";", "}" ]
@noinspection PhpMissingParentCallCommonInspection @inheritDoc
[ "@noinspection", "PhpMissingParentCallCommonInspection" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Api/RolesApi.php#L25-L34
webignition/url-health-checker
src/UrlHealthChecker.php
UrlHealthChecker.check
public function check(string $url): LinkState { $response = null; try { $requests = $this->createRequestSet($url); foreach ($requests as $request) { $response = $this->getHttpResponse($request); if ($response->getStatusCode() === self::HTTP_STATUS_CODE_OK) { return new LinkState(LinkState::TYPE_HTTP, $response->getStatusCode()); } } } catch (\InvalidArgumentException $invalidArgumentException) { if (substr_count($invalidArgumentException->getMessage(), 'Unable to parse URI')) { return new LinkState(LinkState::TYPE_CURL, Configuration::CURL_MALFORMED_URL_CODE); } } catch (HttpConnectException $connectException) { $curlExceptionFactory = new CurlExceptionFactory(); if ($curlExceptionFactory::isCurlException($connectException)) { $curlException = $curlExceptionFactory::fromConnectException($connectException); return new LinkState(LinkState::TYPE_CURL, $curlException->getCurlCode()); } } catch (GuzzleException $guzzleException) { // Cannot happen return new LinkState(LinkState::TYPE_CURL, 0); } return new LinkState(LinkState::TYPE_HTTP, $response->getStatusCode()); }
php
public function check(string $url): LinkState { $response = null; try { $requests = $this->createRequestSet($url); foreach ($requests as $request) { $response = $this->getHttpResponse($request); if ($response->getStatusCode() === self::HTTP_STATUS_CODE_OK) { return new LinkState(LinkState::TYPE_HTTP, $response->getStatusCode()); } } } catch (\InvalidArgumentException $invalidArgumentException) { if (substr_count($invalidArgumentException->getMessage(), 'Unable to parse URI')) { return new LinkState(LinkState::TYPE_CURL, Configuration::CURL_MALFORMED_URL_CODE); } } catch (HttpConnectException $connectException) { $curlExceptionFactory = new CurlExceptionFactory(); if ($curlExceptionFactory::isCurlException($connectException)) { $curlException = $curlExceptionFactory::fromConnectException($connectException); return new LinkState(LinkState::TYPE_CURL, $curlException->getCurlCode()); } } catch (GuzzleException $guzzleException) { // Cannot happen return new LinkState(LinkState::TYPE_CURL, 0); } return new LinkState(LinkState::TYPE_HTTP, $response->getStatusCode()); }
[ "public", "function", "check", "(", "string", "$", "url", ")", ":", "LinkState", "{", "$", "response", "=", "null", ";", "try", "{", "$", "requests", "=", "$", "this", "->", "createRequestSet", "(", "$", "url", ")", ";", "foreach", "(", "$", "requests", "as", "$", "request", ")", "{", "$", "response", "=", "$", "this", "->", "getHttpResponse", "(", "$", "request", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "===", "self", "::", "HTTP_STATUS_CODE_OK", ")", "{", "return", "new", "LinkState", "(", "LinkState", "::", "TYPE_HTTP", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}", "}", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "invalidArgumentException", ")", "{", "if", "(", "substr_count", "(", "$", "invalidArgumentException", "->", "getMessage", "(", ")", ",", "'Unable to parse URI'", ")", ")", "{", "return", "new", "LinkState", "(", "LinkState", "::", "TYPE_CURL", ",", "Configuration", "::", "CURL_MALFORMED_URL_CODE", ")", ";", "}", "}", "catch", "(", "HttpConnectException", "$", "connectException", ")", "{", "$", "curlExceptionFactory", "=", "new", "CurlExceptionFactory", "(", ")", ";", "if", "(", "$", "curlExceptionFactory", "::", "isCurlException", "(", "$", "connectException", ")", ")", "{", "$", "curlException", "=", "$", "curlExceptionFactory", "::", "fromConnectException", "(", "$", "connectException", ")", ";", "return", "new", "LinkState", "(", "LinkState", "::", "TYPE_CURL", ",", "$", "curlException", "->", "getCurlCode", "(", ")", ")", ";", "}", "}", "catch", "(", "GuzzleException", "$", "guzzleException", ")", "{", "// Cannot happen", "return", "new", "LinkState", "(", "LinkState", "::", "TYPE_CURL", ",", "0", ")", ";", "}", "return", "new", "LinkState", "(", "LinkState", "::", "TYPE_HTTP", ",", "$", "response", "->", "getStatusCode", "(", ")", ")", ";", "}" ]
@param string $url @return LinkState
[ "@param", "string", "$url" ]
train
https://github.com/webignition/url-health-checker/blob/17efa3a4cb6f112c5dfcf10392676e71b623811f/src/UrlHealthChecker.php#L84-L115
webignition/url-health-checker
src/UrlHealthChecker.php
UrlHealthChecker.getHttpResponse
private function getHttpResponse(RequestInterface $request): ?ResponseInterface { try { return $this->httpClient->send($request); } catch (TooManyRedirectsException $tooManyRedirectsException) { return $this->httpHistoryContainer->getLastResponse(); } catch (BadResponseException $badResponseException) { $this->badRequestCount++; if ($this->isBadRequestLimitReached()) { return $badResponseException->getResponse(); } return $this->getHttpResponse($request); } catch (HttpConnectException $connectException) { throw $connectException; } catch (RequestException $requestException) { if ($this->isCurlException($requestException)) { throw new HttpConnectException( $requestException->getMessage(), $requestException->getRequest(), $requestException->getPrevious() ); } $this->badRequestCount++; if ($this->isBadRequestLimitReached()) { return $requestException->getResponse(); } return $this->getHttpResponse($request); } }
php
private function getHttpResponse(RequestInterface $request): ?ResponseInterface { try { return $this->httpClient->send($request); } catch (TooManyRedirectsException $tooManyRedirectsException) { return $this->httpHistoryContainer->getLastResponse(); } catch (BadResponseException $badResponseException) { $this->badRequestCount++; if ($this->isBadRequestLimitReached()) { return $badResponseException->getResponse(); } return $this->getHttpResponse($request); } catch (HttpConnectException $connectException) { throw $connectException; } catch (RequestException $requestException) { if ($this->isCurlException($requestException)) { throw new HttpConnectException( $requestException->getMessage(), $requestException->getRequest(), $requestException->getPrevious() ); } $this->badRequestCount++; if ($this->isBadRequestLimitReached()) { return $requestException->getResponse(); } return $this->getHttpResponse($request); } }
[ "private", "function", "getHttpResponse", "(", "RequestInterface", "$", "request", ")", ":", "?", "ResponseInterface", "{", "try", "{", "return", "$", "this", "->", "httpClient", "->", "send", "(", "$", "request", ")", ";", "}", "catch", "(", "TooManyRedirectsException", "$", "tooManyRedirectsException", ")", "{", "return", "$", "this", "->", "httpHistoryContainer", "->", "getLastResponse", "(", ")", ";", "}", "catch", "(", "BadResponseException", "$", "badResponseException", ")", "{", "$", "this", "->", "badRequestCount", "++", ";", "if", "(", "$", "this", "->", "isBadRequestLimitReached", "(", ")", ")", "{", "return", "$", "badResponseException", "->", "getResponse", "(", ")", ";", "}", "return", "$", "this", "->", "getHttpResponse", "(", "$", "request", ")", ";", "}", "catch", "(", "HttpConnectException", "$", "connectException", ")", "{", "throw", "$", "connectException", ";", "}", "catch", "(", "RequestException", "$", "requestException", ")", "{", "if", "(", "$", "this", "->", "isCurlException", "(", "$", "requestException", ")", ")", "{", "throw", "new", "HttpConnectException", "(", "$", "requestException", "->", "getMessage", "(", ")", ",", "$", "requestException", "->", "getRequest", "(", ")", ",", "$", "requestException", "->", "getPrevious", "(", ")", ")", ";", "}", "$", "this", "->", "badRequestCount", "++", ";", "if", "(", "$", "this", "->", "isBadRequestLimitReached", "(", ")", ")", "{", "return", "$", "requestException", "->", "getResponse", "(", ")", ";", "}", "return", "$", "this", "->", "getHttpResponse", "(", "$", "request", ")", ";", "}", "}" ]
@param RequestInterface $request @return ResponseInterface @throws GuzzleException
[ "@param", "RequestInterface", "$request" ]
train
https://github.com/webignition/url-health-checker/blob/17efa3a4cb6f112c5dfcf10392676e71b623811f/src/UrlHealthChecker.php#L123-L156
webignition/url-health-checker
src/UrlHealthChecker.php
UrlHealthChecker.createRequestSet
private function createRequestSet(string $url): array { $httpMethodList = $this->configuration->getHttpMethodList(); $userAgentSelection = $this->getUserAgentSelection(); $referrer = $this->configuration->getReferrer(); $requests = []; foreach ($userAgentSelection as $userAgent) { foreach ($httpMethodList as $methodIndex => $method) { $headers = [ 'user-agent' => $userAgent, ]; if (!empty($referrer)) { $headers['referer'] = $referrer; } $requests[] = new Request($method, $url, $headers); } } return $requests; }
php
private function createRequestSet(string $url): array { $httpMethodList = $this->configuration->getHttpMethodList(); $userAgentSelection = $this->getUserAgentSelection(); $referrer = $this->configuration->getReferrer(); $requests = []; foreach ($userAgentSelection as $userAgent) { foreach ($httpMethodList as $methodIndex => $method) { $headers = [ 'user-agent' => $userAgent, ]; if (!empty($referrer)) { $headers['referer'] = $referrer; } $requests[] = new Request($method, $url, $headers); } } return $requests; }
[ "private", "function", "createRequestSet", "(", "string", "$", "url", ")", ":", "array", "{", "$", "httpMethodList", "=", "$", "this", "->", "configuration", "->", "getHttpMethodList", "(", ")", ";", "$", "userAgentSelection", "=", "$", "this", "->", "getUserAgentSelection", "(", ")", ";", "$", "referrer", "=", "$", "this", "->", "configuration", "->", "getReferrer", "(", ")", ";", "$", "requests", "=", "[", "]", ";", "foreach", "(", "$", "userAgentSelection", "as", "$", "userAgent", ")", "{", "foreach", "(", "$", "httpMethodList", "as", "$", "methodIndex", "=>", "$", "method", ")", "{", "$", "headers", "=", "[", "'user-agent'", "=>", "$", "userAgent", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "referrer", ")", ")", "{", "$", "headers", "[", "'referer'", "]", "=", "$", "referrer", ";", "}", "$", "requests", "[", "]", "=", "new", "Request", "(", "$", "method", ",", "$", "url", ",", "$", "headers", ")", ";", "}", "}", "return", "$", "requests", ";", "}" ]
@param string $url @return RequestInterface[]
[ "@param", "string", "$url" ]
train
https://github.com/webignition/url-health-checker/blob/17efa3a4cb6f112c5dfcf10392676e71b623811f/src/UrlHealthChecker.php#L181-L204
platformsh/platformsh-oauth2-php
src/GuzzleMiddleware.php
GuzzleMiddleware.isOAuth2
private function isOAuth2(RequestInterface $request, array $options) { // The 'auth' option must be set to 'oauth2'. if (!isset($options['auth']) || $options['auth'] !== 'oauth2') { return false; } // The request must be not for an access token endpoint. if ($this->provider->getBaseAccessTokenUrl([]) === $request->getUri()) { return false; } return true; }
php
private function isOAuth2(RequestInterface $request, array $options) { // The 'auth' option must be set to 'oauth2'. if (!isset($options['auth']) || $options['auth'] !== 'oauth2') { return false; } // The request must be not for an access token endpoint. if ($this->provider->getBaseAccessTokenUrl([]) === $request->getUri()) { return false; } return true; }
[ "private", "function", "isOAuth2", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", ")", "{", "// The 'auth' option must be set to 'oauth2'.", "if", "(", "!", "isset", "(", "$", "options", "[", "'auth'", "]", ")", "||", "$", "options", "[", "'auth'", "]", "!==", "'oauth2'", ")", "{", "return", "false", ";", "}", "// The request must be not for an access token endpoint.", "if", "(", "$", "this", "->", "provider", "->", "getBaseAccessTokenUrl", "(", "[", "]", ")", "===", "$", "request", "->", "getUri", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if a request is configured to use OAuth2. @param RequestInterface $request @param array $options @return bool
[ "Check", "if", "a", "request", "is", "configured", "to", "use", "OAuth2", "." ]
train
https://github.com/platformsh/platformsh-oauth2-php/blob/c5056b818f326e8ee358521224ac7f803d1e9d6b/src/GuzzleMiddleware.php#L101-L114
platformsh/platformsh-oauth2-php
src/GuzzleMiddleware.php
GuzzleMiddleware.authenticateRequest
private function authenticateRequest(RequestInterface $request, AccessToken $token) { foreach ($this->provider->getHeaders($token->getToken()) as $name => $value) { $request = $request->withHeader($name, $value); } return $request; }
php
private function authenticateRequest(RequestInterface $request, AccessToken $token) { foreach ($this->provider->getHeaders($token->getToken()) as $name => $value) { $request = $request->withHeader($name, $value); } return $request; }
[ "private", "function", "authenticateRequest", "(", "RequestInterface", "$", "request", ",", "AccessToken", "$", "token", ")", "{", "foreach", "(", "$", "this", "->", "provider", "->", "getHeaders", "(", "$", "token", "->", "getToken", "(", ")", ")", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "request", "=", "$", "request", "->", "withHeader", "(", "$", "name", ",", "$", "value", ")", ";", "}", "return", "$", "request", ";", "}" ]
Add authentication to an HTTP request. @param \Psr\Http\Message\RequestInterface $request @param \League\OAuth2\Client\Token\AccessToken $token @return \Psr\Http\Message\RequestInterface
[ "Add", "authentication", "to", "an", "HTTP", "request", "." ]
train
https://github.com/platformsh/platformsh-oauth2-php/blob/c5056b818f326e8ee358521224ac7f803d1e9d6b/src/GuzzleMiddleware.php#L124-L131
platformsh/platformsh-oauth2-php
src/GuzzleMiddleware.php
GuzzleMiddleware.getAccessToken
private function getAccessToken(AccessToken $invalid = null) { if (!isset($this->accessToken) || $this->accessToken->hasExpired() || ($invalid && $this->accessToken === $invalid)) { $this->accessToken = $this->acquireAccessToken(); if (is_callable($this->tokenSave)) { call_user_func($this->tokenSave, $this->accessToken); } } return $this->accessToken; }
php
private function getAccessToken(AccessToken $invalid = null) { if (!isset($this->accessToken) || $this->accessToken->hasExpired() || ($invalid && $this->accessToken === $invalid)) { $this->accessToken = $this->acquireAccessToken(); if (is_callable($this->tokenSave)) { call_user_func($this->tokenSave, $this->accessToken); } } return $this->accessToken; }
[ "private", "function", "getAccessToken", "(", "AccessToken", "$", "invalid", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "accessToken", ")", "||", "$", "this", "->", "accessToken", "->", "hasExpired", "(", ")", "||", "(", "$", "invalid", "&&", "$", "this", "->", "accessToken", "===", "$", "invalid", ")", ")", "{", "$", "this", "->", "accessToken", "=", "$", "this", "->", "acquireAccessToken", "(", ")", ";", "if", "(", "is_callable", "(", "$", "this", "->", "tokenSave", ")", ")", "{", "call_user_func", "(", "$", "this", "->", "tokenSave", ",", "$", "this", "->", "accessToken", ")", ";", "}", "}", "return", "$", "this", "->", "accessToken", ";", "}" ]
Get the current access token. @param AccessToken|null $invalid A token to consider invalid. @return \League\OAuth2\Client\Token\AccessToken The OAuth2 access token.
[ "Get", "the", "current", "access", "token", "." ]
train
https://github.com/platformsh/platformsh-oauth2-php/blob/c5056b818f326e8ee358521224ac7f803d1e9d6b/src/GuzzleMiddleware.php#L142-L152
platformsh/platformsh-oauth2-php
src/GuzzleMiddleware.php
GuzzleMiddleware.acquireAccessToken
private function acquireAccessToken() { if (isset($this->accessToken) && $this->accessToken->getRefreshToken()) { return $this->provider->getAccessToken(new RefreshToken(), ['refresh_token' => $this->accessToken->getRefreshToken()]); } return $this->provider->getAccessToken($this->grant, $this->grantOptions); }
php
private function acquireAccessToken() { if (isset($this->accessToken) && $this->accessToken->getRefreshToken()) { return $this->provider->getAccessToken(new RefreshToken(), ['refresh_token' => $this->accessToken->getRefreshToken()]); } return $this->provider->getAccessToken($this->grant, $this->grantOptions); }
[ "private", "function", "acquireAccessToken", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "accessToken", ")", "&&", "$", "this", "->", "accessToken", "->", "getRefreshToken", "(", ")", ")", "{", "return", "$", "this", "->", "provider", "->", "getAccessToken", "(", "new", "RefreshToken", "(", ")", ",", "[", "'refresh_token'", "=>", "$", "this", "->", "accessToken", "->", "getRefreshToken", "(", ")", "]", ")", ";", "}", "return", "$", "this", "->", "provider", "->", "getAccessToken", "(", "$", "this", "->", "grant", ",", "$", "this", "->", "grantOptions", ")", ";", "}" ]
Acquire a new access token using a refresh token or the configured grant. @return AccessToken
[ "Acquire", "a", "new", "access", "token", "using", "a", "refresh", "token", "or", "the", "configured", "grant", "." ]
train
https://github.com/platformsh/platformsh-oauth2-php/blob/c5056b818f326e8ee358521224ac7f803d1e9d6b/src/GuzzleMiddleware.php#L159-L166
antaresproject/notifications
src/Console/NotificationCategoriesCommand.php
NotificationCategoriesCommand.fire
public function fire() { $categories = NotificationCategory::all(); $flatten = []; foreach ($categories as $category) { $flatten[] = ['<info>' . $category->id . '</info>', '<fg=red>' . $category->name . '</fg=red>', '<info>' . $category->title . '</info>']; } if (count($flatten) > 0) { $this->table(['Id', 'Name', 'Title'], $flatten); } else { $this->error('No categories found'); } }
php
public function fire() { $categories = NotificationCategory::all(); $flatten = []; foreach ($categories as $category) { $flatten[] = ['<info>' . $category->id . '</info>', '<fg=red>' . $category->name . '</fg=red>', '<info>' . $category->title . '</info>']; } if (count($flatten) > 0) { $this->table(['Id', 'Name', 'Title'], $flatten); } else { $this->error('No categories found'); } }
[ "public", "function", "fire", "(", ")", "{", "$", "categories", "=", "NotificationCategory", "::", "all", "(", ")", ";", "$", "flatten", "=", "[", "]", ";", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "$", "flatten", "[", "]", "=", "[", "'<info>'", ".", "$", "category", "->", "id", ".", "'</info>'", ",", "'<fg=red>'", ".", "$", "category", "->", "name", ".", "'</fg=red>'", ",", "'<info>'", ".", "$", "category", "->", "title", ".", "'</info>'", "]", ";", "}", "if", "(", "count", "(", "$", "flatten", ")", ">", "0", ")", "{", "$", "this", "->", "table", "(", "[", "'Id'", ",", "'Name'", ",", "'Title'", "]", ",", "$", "flatten", ")", ";", "}", "else", "{", "$", "this", "->", "error", "(", "'No categories found'", ")", ";", "}", "}" ]
Execute the console command. @return void
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Console/NotificationCategoriesCommand.php#L49-L62
php-lug/lug
src/Component/Locale/Negotiator/LocaleNegotiator.php
LocaleNegotiator.parse
public function parse($header) { $header = trim($header); if (empty($header)) { throw new InvalidArgument('The header string should not be empty.'); } preg_match_all('/(?:[^,"]*+(?:"[^"]*+")?)+[^,"]*+/', $header, $matches); return $this->sort(array_map( [$this, 'acceptFactory'], array_values(array_filter(array_map('trim', $matches[0]))) )); }
php
public function parse($header) { $header = trim($header); if (empty($header)) { throw new InvalidArgument('The header string should not be empty.'); } preg_match_all('/(?:[^,"]*+(?:"[^"]*+")?)+[^,"]*+/', $header, $matches); return $this->sort(array_map( [$this, 'acceptFactory'], array_values(array_filter(array_map('trim', $matches[0]))) )); }
[ "public", "function", "parse", "(", "$", "header", ")", "{", "$", "header", "=", "trim", "(", "$", "header", ")", ";", "if", "(", "empty", "(", "$", "header", ")", ")", "{", "throw", "new", "InvalidArgument", "(", "'The header string should not be empty.'", ")", ";", "}", "preg_match_all", "(", "'/(?:[^,\"]*+(?:\"[^\"]*+\")?)+[^,\"]*+/'", ",", "$", "header", ",", "$", "matches", ")", ";", "return", "$", "this", "->", "sort", "(", "array_map", "(", "[", "$", "this", ",", "'acceptFactory'", "]", ",", "array_values", "(", "array_filter", "(", "array_map", "(", "'trim'", ",", "$", "matches", "[", "0", "]", ")", ")", ")", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Locale/Negotiator/LocaleNegotiator.php#L26-L40
php-lug/lug
src/Component/Locale/Negotiator/LocaleNegotiator.php
LocaleNegotiator.sort
private function sort(array $acceptLanguages) { $topAcceptLanguages = []; $sortedAcceptLanguages = []; foreach ($acceptLanguages as $acceptLanguage) { if ($acceptLanguage->getQuality() === 1.0) { $topAcceptLanguages[] = $acceptLanguage; } else { $sortedAcceptLanguages[] = $acceptLanguage; } } usort($sortedAcceptLanguages, function (AcceptLanguage $a, AcceptLanguage $b) { return $a->getQuality() > $b->getQuality() ? -1 : 1; }); return array_merge($topAcceptLanguages, $sortedAcceptLanguages); }
php
private function sort(array $acceptLanguages) { $topAcceptLanguages = []; $sortedAcceptLanguages = []; foreach ($acceptLanguages as $acceptLanguage) { if ($acceptLanguage->getQuality() === 1.0) { $topAcceptLanguages[] = $acceptLanguage; } else { $sortedAcceptLanguages[] = $acceptLanguage; } } usort($sortedAcceptLanguages, function (AcceptLanguage $a, AcceptLanguage $b) { return $a->getQuality() > $b->getQuality() ? -1 : 1; }); return array_merge($topAcceptLanguages, $sortedAcceptLanguages); }
[ "private", "function", "sort", "(", "array", "$", "acceptLanguages", ")", "{", "$", "topAcceptLanguages", "=", "[", "]", ";", "$", "sortedAcceptLanguages", "=", "[", "]", ";", "foreach", "(", "$", "acceptLanguages", "as", "$", "acceptLanguage", ")", "{", "if", "(", "$", "acceptLanguage", "->", "getQuality", "(", ")", "===", "1.0", ")", "{", "$", "topAcceptLanguages", "[", "]", "=", "$", "acceptLanguage", ";", "}", "else", "{", "$", "sortedAcceptLanguages", "[", "]", "=", "$", "acceptLanguage", ";", "}", "}", "usort", "(", "$", "sortedAcceptLanguages", ",", "function", "(", "AcceptLanguage", "$", "a", ",", "AcceptLanguage", "$", "b", ")", "{", "return", "$", "a", "->", "getQuality", "(", ")", ">", "$", "b", "->", "getQuality", "(", ")", "?", "-", "1", ":", "1", ";", "}", ")", ";", "return", "array_merge", "(", "$", "topAcceptLanguages", ",", "$", "sortedAcceptLanguages", ")", ";", "}" ]
@param AcceptLanguage[] $acceptLanguages @return AcceptLanguage[]
[ "@param", "AcceptLanguage", "[]", "$acceptLanguages" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Locale/Negotiator/LocaleNegotiator.php#L47-L65
php-lug/lug
src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php
RegisterDriverMappingPass.process
public function process(ContainerBuilder $container) { foreach (array_keys($container->findTaggedServiceIds('lug.resource')) as $id) { if (($compiler = $this->getCompilerPass($container->getDefinition($id))) !== null) { $compiler->process($container); } } }
php
public function process(ContainerBuilder $container) { foreach (array_keys($container->findTaggedServiceIds('lug.resource')) as $id) { if (($compiler = $this->getCompilerPass($container->getDefinition($id))) !== null) { $compiler->process($container); } } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "foreach", "(", "array_keys", "(", "$", "container", "->", "findTaggedServiceIds", "(", "'lug.resource'", ")", ")", "as", "$", "id", ")", "{", "if", "(", "(", "$", "compiler", "=", "$", "this", "->", "getCompilerPass", "(", "$", "container", "->", "getDefinition", "(", "$", "id", ")", ")", ")", "!==", "null", ")", "{", "$", "compiler", "->", "process", "(", "$", "container", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php#L30-L37
php-lug/lug
src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php
RegisterDriverMappingPass.getCompilerPass
private function getCompilerPass(Definition $definition) { $driver = $this->getResourceDriver($definition); if ($driver === null) { return; } $class = $this->getCompilerPassClass($driver); $method = $this->getCompilerPassMethod($this->getResourceDriverMappingFormat($definition)); $path = $this->getResourceDriverMappingPath($definition); $model = $this->getResourceModel($definition); return $class::$method([$path => ClassUtils::getRealNamespace($model)], []); }
php
private function getCompilerPass(Definition $definition) { $driver = $this->getResourceDriver($definition); if ($driver === null) { return; } $class = $this->getCompilerPassClass($driver); $method = $this->getCompilerPassMethod($this->getResourceDriverMappingFormat($definition)); $path = $this->getResourceDriverMappingPath($definition); $model = $this->getResourceModel($definition); return $class::$method([$path => ClassUtils::getRealNamespace($model)], []); }
[ "private", "function", "getCompilerPass", "(", "Definition", "$", "definition", ")", "{", "$", "driver", "=", "$", "this", "->", "getResourceDriver", "(", "$", "definition", ")", ";", "if", "(", "$", "driver", "===", "null", ")", "{", "return", ";", "}", "$", "class", "=", "$", "this", "->", "getCompilerPassClass", "(", "$", "driver", ")", ";", "$", "method", "=", "$", "this", "->", "getCompilerPassMethod", "(", "$", "this", "->", "getResourceDriverMappingFormat", "(", "$", "definition", ")", ")", ";", "$", "path", "=", "$", "this", "->", "getResourceDriverMappingPath", "(", "$", "definition", ")", ";", "$", "model", "=", "$", "this", "->", "getResourceModel", "(", "$", "definition", ")", ";", "return", "$", "class", "::", "$", "method", "(", "[", "$", "path", "=>", "ClassUtils", "::", "getRealNamespace", "(", "$", "model", ")", "]", ",", "[", "]", ")", ";", "}" ]
@param Definition $definition @return CompilerPassInterface|null
[ "@param", "Definition", "$definition" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php#L44-L58
php-lug/lug
src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php
RegisterDriverMappingPass.getResourceMetadata
private function getResourceMetadata(Definition $definition, $method) { foreach ($definition->getMethodCalls() as $methodCall) { if ($methodCall[0] === $method) { return $methodCall[1][0]; } } }
php
private function getResourceMetadata(Definition $definition, $method) { foreach ($definition->getMethodCalls() as $methodCall) { if ($methodCall[0] === $method) { return $methodCall[1][0]; } } }
[ "private", "function", "getResourceMetadata", "(", "Definition", "$", "definition", ",", "$", "method", ")", "{", "foreach", "(", "$", "definition", "->", "getMethodCalls", "(", ")", "as", "$", "methodCall", ")", "{", "if", "(", "$", "methodCall", "[", "0", "]", "===", "$", "method", ")", "{", "return", "$", "methodCall", "[", "1", "]", "[", "0", "]", ";", "}", "}", "}" ]
@param Definition $definition @param string $method @return string
[ "@param", "Definition", "$definition", "@param", "string", "$method" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/DependencyInjection/Compiler/RegisterDriverMappingPass.php#L106-L113
CradlePHP/packages
src/Curl/CurlHandler.php
CurlHandler.getResponse
public function getResponse() { $this->addParameters()->addHeaders(); $this->options[CURLOPT_RETURNTRANSFER] = true; $this->meta = call_user_func($this->map, $this->options); return $this->meta['response']; }
php
public function getResponse() { $this->addParameters()->addHeaders(); $this->options[CURLOPT_RETURNTRANSFER] = true; $this->meta = call_user_func($this->map, $this->options); return $this->meta['response']; }
[ "public", "function", "getResponse", "(", ")", "{", "$", "this", "->", "addParameters", "(", ")", "->", "addHeaders", "(", ")", ";", "$", "this", "->", "options", "[", "CURLOPT_RETURNTRANSFER", "]", "=", "true", ";", "$", "this", "->", "meta", "=", "call_user_func", "(", "$", "this", "->", "map", ",", "$", "this", "->", "options", ")", ";", "return", "$", "this", "->", "meta", "[", "'response'", "]", ";", "}" ]
Send the curl off and returns the results @return string
[ "Send", "the", "curl", "off", "and", "returns", "the", "results" ]
train
https://github.com/CradlePHP/packages/blob/c4f52201337090f65cb8d5e2e15515cb9372ae4b/src/Curl/CurlHandler.php#L207-L215
CradlePHP/packages
src/Curl/CurlHandler.php
CurlHandler.setPostFields
public function setPostFields($fields, string $type = 'query') { if (is_array($fields)) { if ($type === 'json') { $fields = json_encode($fields); } else { $fields = http_build_query($fields); } } $this->options[CURLOPT_POSTFIELDS] = $fields; return $this; }
php
public function setPostFields($fields, string $type = 'query') { if (is_array($fields)) { if ($type === 'json') { $fields = json_encode($fields); } else { $fields = http_build_query($fields); } } $this->options[CURLOPT_POSTFIELDS] = $fields; return $this; }
[ "public", "function", "setPostFields", "(", "$", "fields", ",", "string", "$", "type", "=", "'query'", ")", "{", "if", "(", "is_array", "(", "$", "fields", ")", ")", "{", "if", "(", "$", "type", "===", "'json'", ")", "{", "$", "fields", "=", "json_encode", "(", "$", "fields", ")", ";", "}", "else", "{", "$", "fields", "=", "http_build_query", "(", "$", "fields", ")", ";", "}", "}", "$", "this", "->", "options", "[", "CURLOPT_POSTFIELDS", "]", "=", "$", "fields", ";", "return", "$", "this", ";", "}" ]
CURLOPT_POSTFIELDS accepts array and string arguments, this is a special case that __call does not handle @param *string|array $fields the post data to send @param string $type query or json @return CurlHandler
[ "CURLOPT_POSTFIELDS", "accepts", "array", "and", "string", "arguments", "this", "is", "a", "special", "case", "that", "__call", "does", "not", "handle" ]
train
https://github.com/CradlePHP/packages/blob/c4f52201337090f65cb8d5e2e15515cb9372ae4b/src/Curl/CurlHandler.php#L411-L424
JBZoo/Assets
src/Asset/Callback.php
Callback.load
public function load(array $filters = []) { $result = call_user_func_array($this->_source, [$this, $this->_params, $filters]); return [Asset::TYPE_CALLBACK, $result]; }
php
public function load(array $filters = []) { $result = call_user_func_array($this->_source, [$this, $this->_params, $filters]); return [Asset::TYPE_CALLBACK, $result]; }
[ "public", "function", "load", "(", "array", "$", "filters", "=", "[", "]", ")", "{", "$", "result", "=", "call_user_func_array", "(", "$", "this", "->", "_source", ",", "[", "$", "this", ",", "$", "this", "->", "_params", ",", "$", "filters", "]", ")", ";", "return", "[", "Asset", "::", "TYPE_CALLBACK", ",", "$", "result", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/JBZoo/Assets/blob/134a109378f5b5e955dfb15e6ed2821581564991/src/Asset/Callback.php#L32-L37
Innmind/neo4j-dbal
src/Query/Cypher.php
Cypher.withParameters
public function withParameters(array $parameters): self { $query = $this; foreach ($parameters as $key => $parameter) { $query = $query->withParameter($key, $parameter); } return $query; }
php
public function withParameters(array $parameters): self { $query = $this; foreach ($parameters as $key => $parameter) { $query = $query->withParameter($key, $parameter); } return $query; }
[ "public", "function", "withParameters", "(", "array", "$", "parameters", ")", ":", "self", "{", "$", "query", "=", "$", "this", ";", "foreach", "(", "$", "parameters", "as", "$", "key", "=>", "$", "parameter", ")", "{", "$", "query", "=", "$", "query", "->", "withParameter", "(", "$", "key", ",", "$", "parameter", ")", ";", "}", "return", "$", "query", ";", "}" ]
Attach parameters to this query @param array $parameters @throws NonParametrableClause @return self
[ "Attach", "parameters", "to", "this", "query" ]
train
https://github.com/Innmind/neo4j-dbal/blob/12cb71e698cc0f4d55b7f2eb40f7b353c778a20b/src/Query/Cypher.php#L72-L81
Innmind/neo4j-dbal
src/Query/Cypher.php
Cypher.withParameter
public function withParameter(string $key, $parameter): self { if (Str::of($key)->empty()) { throw new DomainException; } $query = new self($this->cypher); $query->parameters = $this->parameters->put( $key, new Parameter($key, $parameter) ); return $query; }
php
public function withParameter(string $key, $parameter): self { if (Str::of($key)->empty()) { throw new DomainException; } $query = new self($this->cypher); $query->parameters = $this->parameters->put( $key, new Parameter($key, $parameter) ); return $query; }
[ "public", "function", "withParameter", "(", "string", "$", "key", ",", "$", "parameter", ")", ":", "self", "{", "if", "(", "Str", "::", "of", "(", "$", "key", ")", "->", "empty", "(", ")", ")", "{", "throw", "new", "DomainException", ";", "}", "$", "query", "=", "new", "self", "(", "$", "this", "->", "cypher", ")", ";", "$", "query", "->", "parameters", "=", "$", "this", "->", "parameters", "->", "put", "(", "$", "key", ",", "new", "Parameter", "(", "$", "key", ",", "$", "parameter", ")", ")", ";", "return", "$", "query", ";", "}" ]
Attach the given parameter to this query @param string $key @param mixed $parameter @throws NonParametrableClause @return self
[ "Attach", "the", "given", "parameter", "to", "this", "query" ]
train
https://github.com/Innmind/neo4j-dbal/blob/12cb71e698cc0f4d55b7f2eb40f7b353c778a20b/src/Query/Cypher.php#L93-L106
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php
ConfigRepository.get
public function get($key, $default = null) { return isset($this->repository[$key]) ? $this->repository[$key] : $default; }
php
public function get($key, $default = null) { return isset($this->repository[$key]) ? $this->repository[$key] : $default; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "repository", "[", "$", "key", "]", ")", "?", "$", "this", "->", "repository", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosymfony/ConfigServiceProvider/blob/f6cb9a9fc707b6c92e0d03201e5ecc17eaee3114/src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php#L42-L45
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php
ConfigRepository.union
public function union(ConfigRepositoryInterface $repository) { $union = function($main, $second) { $result = new ConfigRepository(); foreach($main as $key => $value) { $result[$key] = $value; } foreach($second as $key => $value) { if(!isset($main[$key])) { $result[$key] = $value; } } return $result; }; return $union($this, $repository); }
php
public function union(ConfigRepositoryInterface $repository) { $union = function($main, $second) { $result = new ConfigRepository(); foreach($main as $key => $value) { $result[$key] = $value; } foreach($second as $key => $value) { if(!isset($main[$key])) { $result[$key] = $value; } } return $result; }; return $union($this, $repository); }
[ "public", "function", "union", "(", "ConfigRepositoryInterface", "$", "repository", ")", "{", "$", "union", "=", "function", "(", "$", "main", ",", "$", "second", ")", "{", "$", "result", "=", "new", "ConfigRepository", "(", ")", ";", "foreach", "(", "$", "main", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "}", "foreach", "(", "$", "second", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "main", "[", "$", "key", "]", ")", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "result", ";", "}", ";", "return", "$", "union", "(", "$", "this", ",", "$", "repository", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosymfony/ConfigServiceProvider/blob/f6cb9a9fc707b6c92e0d03201e5ecc17eaee3114/src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php#L84-L107
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php
ConfigRepository.intersection
public function intersection(ConfigRepositoryInterface $repository) { $interception = function($main, $second) { $result = new ConfigRepository(); $keysMain = array_keys($main->getArray()); $keysSecond = array_keys($second->getArray()); $keys = array_intersect($keysMain, $keysSecond); foreach($keys as $key) { $result[$key] = $main[$key]; } return $result; }; return $interception($this, $repository); }
php
public function intersection(ConfigRepositoryInterface $repository) { $interception = function($main, $second) { $result = new ConfigRepository(); $keysMain = array_keys($main->getArray()); $keysSecond = array_keys($second->getArray()); $keys = array_intersect($keysMain, $keysSecond); foreach($keys as $key) { $result[$key] = $main[$key]; } return $result; }; return $interception($this, $repository); }
[ "public", "function", "intersection", "(", "ConfigRepositoryInterface", "$", "repository", ")", "{", "$", "interception", "=", "function", "(", "$", "main", ",", "$", "second", ")", "{", "$", "result", "=", "new", "ConfigRepository", "(", ")", ";", "$", "keysMain", "=", "array_keys", "(", "$", "main", "->", "getArray", "(", ")", ")", ";", "$", "keysSecond", "=", "array_keys", "(", "$", "second", "->", "getArray", "(", ")", ")", ";", "$", "keys", "=", "array_intersect", "(", "$", "keysMain", ",", "$", "keysSecond", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "main", "[", "$", "key", "]", ";", "}", "return", "$", "result", ";", "}", ";", "return", "$", "interception", "(", "$", "this", ",", "$", "repository", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosymfony/ConfigServiceProvider/blob/f6cb9a9fc707b6c92e0d03201e5ecc17eaee3114/src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php#L112-L130
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php
ConfigRepository.validateWith
public function validateWith(ConfigurationInterface $definition) { $processor = new Processor(); $processor->processConfiguration($definition, array($this->getArray())); }
php
public function validateWith(ConfigurationInterface $definition) { $processor = new Processor(); $processor->processConfiguration($definition, array($this->getArray())); }
[ "public", "function", "validateWith", "(", "ConfigurationInterface", "$", "definition", ")", "{", "$", "processor", "=", "new", "Processor", "(", ")", ";", "$", "processor", "->", "processConfiguration", "(", "$", "definition", ",", "array", "(", "$", "this", "->", "getArray", "(", ")", ")", ")", ";", "}" ]
{@inheritdoc }
[ "{" ]
train
https://github.com/yosymfony/ConfigServiceProvider/blob/f6cb9a9fc707b6c92e0d03201e5ecc17eaee3114/src/Yosymfony/Silex/ConfigServiceProvider/ConfigRepository.php#L135-L140
Eresus/EresusCMS
src/core/users.php
TUsers.checkMail
private function checkMail($mail) { $host = substr($mail, strpos($mail, '@')+1); $ip = gethostbyname($host); if ($ip == $host) { Eresus_Kernel::app()->getPage()->addErrorMessage(sprintf(errNonexistedDomain, $host)); return false; } return true; }
php
private function checkMail($mail) { $host = substr($mail, strpos($mail, '@')+1); $ip = gethostbyname($host); if ($ip == $host) { Eresus_Kernel::app()->getPage()->addErrorMessage(sprintf(errNonexistedDomain, $host)); return false; } return true; }
[ "private", "function", "checkMail", "(", "$", "mail", ")", "{", "$", "host", "=", "substr", "(", "$", "mail", ",", "strpos", "(", "$", "mail", ",", "'@'", ")", "+", "1", ")", ";", "$", "ip", "=", "gethostbyname", "(", "$", "host", ")", ";", "if", "(", "$", "ip", "==", "$", "host", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "sprintf", "(", "errNonexistedDomain", ",", "$", "host", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Проверяет правильность адреса e-mail @param string $mail адрес e-mail @return bool
[ "Проверяет", "правильность", "адреса", "e", "-", "mail" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L61-L71
Eresus/EresusCMS
src/core/users.php
TUsers.update
public function update($dummy) { $item = $this->accounts->get(arg('update', 'int')); foreach ($item as $key => $value) { if (isset(Eresus_CMS::getLegacyKernel()->request['arg'][$key])) { $item[$key] = arg($key, 'dbsafe'); } } $item['active'] = arg('active') || (Eresus_CMS::getLegacyKernel()->user['id'] == $item['id']); if ($this->checkMail($item['mail'])) { $this->accounts->update($item); }; HTTP::redirect(arg('submitURL')); }
php
public function update($dummy) { $item = $this->accounts->get(arg('update', 'int')); foreach ($item as $key => $value) { if (isset(Eresus_CMS::getLegacyKernel()->request['arg'][$key])) { $item[$key] = arg($key, 'dbsafe'); } } $item['active'] = arg('active') || (Eresus_CMS::getLegacyKernel()->user['id'] == $item['id']); if ($this->checkMail($item['mail'])) { $this->accounts->update($item); }; HTTP::redirect(arg('submitURL')); }
[ "public", "function", "update", "(", "$", "dummy", ")", "{", "$", "item", "=", "$", "this", "->", "accounts", "->", "get", "(", "arg", "(", "'update'", ",", "'int'", ")", ")", ";", "foreach", "(", "$", "item", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "isset", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", "[", "'arg'", "]", "[", "$", "key", "]", ")", ")", "{", "$", "item", "[", "$", "key", "]", "=", "arg", "(", "$", "key", ",", "'dbsafe'", ")", ";", "}", "}", "$", "item", "[", "'active'", "]", "=", "arg", "(", "'active'", ")", "||", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "user", "[", "'id'", "]", "==", "$", "item", "[", "'id'", "]", ")", ";", "if", "(", "$", "this", "->", "checkMail", "(", "$", "item", "[", "'mail'", "]", ")", ")", "{", "$", "this", "->", "accounts", "->", "update", "(", "$", "item", ")", ";", "}", ";", "HTTP", "::", "redirect", "(", "arg", "(", "'submitURL'", ")", ")", ";", "}" ]
@param mixed $dummy Используется для совместимости с родительским методом @return mixed void @see EresusAccounts::update()
[ "@param", "mixed", "$dummy", "Используется", "для", "совместимости", "с", "родительским", "методом" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L143-L159
Eresus/EresusCMS
src/core/users.php
TUsers.insert
function insert() { # Получение данных $item = array( 'name' => arg('name', 'dbsafe'), 'login' => arg('login', '/[^a-z0-9_]/'), 'access' => arg('access', 'int'), 'hash' => Eresus_CMS::getLegacyKernel()->password_hash(arg('pswd1')), 'mail' => arg('mail', 'dbsafe'), ); # Проверка входных данных $error = false; if (empty($item['name'])) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersNameInvalid); $error = true; } if (empty($item['login'])) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersLoginInvalid); $error = true; } if ($item['access'] <= ROOT) { Eresus_Kernel::app()->getPage()->addErrorMessage('Invalid access level!'); $error = true; } if ($item['hash'] != Eresus_CMS::getLegacyKernel()->password_hash(arg('pswd2'))) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersConfirmInvalid); $error = true; } # Проверка данных на уникальность $check = $this->accounts->get("`login` = '{$item['login']}'"); if ($check) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersLoginExists); $error = true; } if ($error) { saveRequest(); HTTP::redirect(Eresus_CMS::getLegacyKernel()->request['referer']); } if (!$this->accounts->add($item)) { Eresus_Kernel::app()->getPage()->addErrorMessage('Error creating user account'); } HTTP::redirect(arg('submitURL')); }
php
function insert() { # Получение данных $item = array( 'name' => arg('name', 'dbsafe'), 'login' => arg('login', '/[^a-z0-9_]/'), 'access' => arg('access', 'int'), 'hash' => Eresus_CMS::getLegacyKernel()->password_hash(arg('pswd1')), 'mail' => arg('mail', 'dbsafe'), ); # Проверка входных данных $error = false; if (empty($item['name'])) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersNameInvalid); $error = true; } if (empty($item['login'])) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersLoginInvalid); $error = true; } if ($item['access'] <= ROOT) { Eresus_Kernel::app()->getPage()->addErrorMessage('Invalid access level!'); $error = true; } if ($item['hash'] != Eresus_CMS::getLegacyKernel()->password_hash(arg('pswd2'))) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersConfirmInvalid); $error = true; } # Проверка данных на уникальность $check = $this->accounts->get("`login` = '{$item['login']}'"); if ($check) { Eresus_Kernel::app()->getPage()->addErrorMessage(admUsersLoginExists); $error = true; } if ($error) { saveRequest(); HTTP::redirect(Eresus_CMS::getLegacyKernel()->request['referer']); } if (!$this->accounts->add($item)) { Eresus_Kernel::app()->getPage()->addErrorMessage('Error creating user account'); } HTTP::redirect(arg('submitURL')); }
[ "function", "insert", "(", ")", "{", "# Получение данных", "$", "item", "=", "array", "(", "'name'", "=>", "arg", "(", "'name'", ",", "'dbsafe'", ")", ",", "'login'", "=>", "arg", "(", "'login'", ",", "'/[^a-z0-9_]/'", ")", ",", "'access'", "=>", "arg", "(", "'access'", ",", "'int'", ")", ",", "'hash'", "=>", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "password_hash", "(", "arg", "(", "'pswd1'", ")", ")", ",", "'mail'", "=>", "arg", "(", "'mail'", ",", "'dbsafe'", ")", ",", ")", ";", "# Проверка входных данных", "$", "error", "=", "false", ";", "if", "(", "empty", "(", "$", "item", "[", "'name'", "]", ")", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "admUsersNameInvalid", ")", ";", "$", "error", "=", "true", ";", "}", "if", "(", "empty", "(", "$", "item", "[", "'login'", "]", ")", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "admUsersLoginInvalid", ")", ";", "$", "error", "=", "true", ";", "}", "if", "(", "$", "item", "[", "'access'", "]", "<=", "ROOT", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "'Invalid access level!'", ")", ";", "$", "error", "=", "true", ";", "}", "if", "(", "$", "item", "[", "'hash'", "]", "!=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "password_hash", "(", "arg", "(", "'pswd2'", ")", ")", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "admUsersConfirmInvalid", ")", ";", "$", "error", "=", "true", ";", "}", "# Проверка данных на уникальность", "$", "check", "=", "$", "this", "->", "accounts", "->", "get", "(", "\"`login` = '{$item['login']}'\"", ")", ";", "if", "(", "$", "check", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "admUsersLoginExists", ")", ";", "$", "error", "=", "true", ";", "}", "if", "(", "$", "error", ")", "{", "saveRequest", "(", ")", ";", "HTTP", "::", "redirect", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", "[", "'referer'", "]", ")", ";", "}", "if", "(", "!", "$", "this", "->", "accounts", "->", "add", "(", "$", "item", ")", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "addErrorMessage", "(", "'Error creating user account'", ")", ";", "}", "HTTP", "::", "redirect", "(", "arg", "(", "'submitURL'", ")", ")", ";", "}" ]
Создание учётной записи
[ "Создание", "учётной", "записи" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L164-L213
Eresus/EresusCMS
src/core/users.php
TUsers.delete
public function delete($dummy) { $this->accounts->get(arg('delete', 'int')); $this->accounts->delete(arg('delete', 'int')); HTTP::redirect(Eresus_Kernel::app()->getPage()->url()); }
php
public function delete($dummy) { $this->accounts->get(arg('delete', 'int')); $this->accounts->delete(arg('delete', 'int')); HTTP::redirect(Eresus_Kernel::app()->getPage()->url()); }
[ "public", "function", "delete", "(", "$", "dummy", ")", "{", "$", "this", "->", "accounts", "->", "get", "(", "arg", "(", "'delete'", ",", "'int'", ")", ")", ";", "$", "this", "->", "accounts", "->", "delete", "(", "arg", "(", "'delete'", ",", "'int'", ")", ")", ";", "HTTP", "::", "redirect", "(", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "url", "(", ")", ")", ";", "}" ]
@param mixed $dummy Используется для совместимости с родительским методом @return mixed void @see EresusAccounts::delete()
[ "@param", "mixed", "$dummy", "Используется", "для", "совместимости", "с", "родительским", "методом" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L223-L228
Eresus/EresusCMS
src/core/users.php
TUsers.edit
private function edit() { $item = Eresus_CMS::getLegacyKernel()->db->selectItem('users', "`id`='".arg('id')."'"); $form = array( 'name' => 'UserForm', 'caption' => admUsersChangeUser.' №'.$item['id'], 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'update', 'value'=>$item['id']), array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%', 'value'=>$item['name'], 'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid), array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%', 'value'=>$item['login'], 'pattern'=>'/^[a-z\d_]+$/', 'errormsg'=>admUsersLoginInvalid, 'access'=>ADMIN), array('type'=>'select','name'=>'access','label'=>admAccessLevel, 'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2, ACCESSLEVEL3, ACCESSLEVEL4), 'value'=>$item['access'], 'disabled'=>$item['access'] == ROOT, 'access'=>ADMIN), array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState, 'value'=>$item['active'], 'access'=>ADMIN), array('type'=>'edit','name'=>'loginErrors','label'=>admUsersLoginErrors,'maxlength'=>2, 'width'=>'30px','value'=>$item['loginErrors'], 'access'=>ADMIN), array('type' => 'edit', 'name' => 'mail', 'label' => admUsersMail, 'maxlength' => 32, 'width' => '100%', 'value' => $item['mail'], 'access' => ADMIN), ), 'buttons' => array(UserRights($this->access)?'ok':'', 'apply', 'cancel'), ); $pswd = array( 'name' => 'PasswordForm', 'caption' => admUsersChangePassword, 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'password', 'value'=>$item['id']), array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32, 'width'=>'100%'), array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32, 'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid), ), 'buttons' => array(UserRights($this->access)?'ok':'apply', 'cancel'), ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form) . "<br />\n" . $page->renderForm($pswd); return $result; }
php
private function edit() { $item = Eresus_CMS::getLegacyKernel()->db->selectItem('users', "`id`='".arg('id')."'"); $form = array( 'name' => 'UserForm', 'caption' => admUsersChangeUser.' №'.$item['id'], 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'update', 'value'=>$item['id']), array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%', 'value'=>$item['name'], 'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid), array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%', 'value'=>$item['login'], 'pattern'=>'/^[a-z\d_]+$/', 'errormsg'=>admUsersLoginInvalid, 'access'=>ADMIN), array('type'=>'select','name'=>'access','label'=>admAccessLevel, 'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2, ACCESSLEVEL3, ACCESSLEVEL4), 'value'=>$item['access'], 'disabled'=>$item['access'] == ROOT, 'access'=>ADMIN), array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState, 'value'=>$item['active'], 'access'=>ADMIN), array('type'=>'edit','name'=>'loginErrors','label'=>admUsersLoginErrors,'maxlength'=>2, 'width'=>'30px','value'=>$item['loginErrors'], 'access'=>ADMIN), array('type' => 'edit', 'name' => 'mail', 'label' => admUsersMail, 'maxlength' => 32, 'width' => '100%', 'value' => $item['mail'], 'access' => ADMIN), ), 'buttons' => array(UserRights($this->access)?'ok':'', 'apply', 'cancel'), ); $pswd = array( 'name' => 'PasswordForm', 'caption' => admUsersChangePassword, 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'password', 'value'=>$item['id']), array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32, 'width'=>'100%'), array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32, 'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid), ), 'buttons' => array(UserRights($this->access)?'ok':'apply', 'cancel'), ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form) . "<br />\n" . $page->renderForm($pswd); return $result; }
[ "private", "function", "edit", "(", ")", "{", "$", "item", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "selectItem", "(", "'users'", ",", "\"`id`='\"", ".", "arg", "(", "'id'", ")", ".", "\"'\"", ")", ";", "$", "form", "=", "array", "(", "'name'", "=>", "'UserForm'", ",", "'caption'", "=>", "admUsersChangeUser", ".", "' №'.$", "i", "t", "em['", "i", "d'],", "", "", "'width'", "=>", "'400px'", ",", "'fields'", "=>", "array", "(", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "'update'", ",", "'value'", "=>", "$", "item", "[", "'id'", "]", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'name'", ",", "'label'", "=>", "admUsersName", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ",", "'value'", "=>", "$", "item", "[", "'name'", "]", ",", "'pattern'", "=>", "'/.+/'", ",", "'errormsg'", "=>", "admUsersNameInvalid", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'login'", ",", "'label'", "=>", "admUsersLogin", ",", "'maxlength'", "=>", "16", ",", "'width'", "=>", "'100%'", ",", "'value'", "=>", "$", "item", "[", "'login'", "]", ",", "'pattern'", "=>", "'/^[a-z\\d_]+$/'", ",", "'errormsg'", "=>", "admUsersLoginInvalid", ",", "'access'", "=>", "ADMIN", ")", ",", "array", "(", "'type'", "=>", "'select'", ",", "'name'", "=>", "'access'", ",", "'label'", "=>", "admAccessLevel", ",", "'values'", "=>", "array", "(", "'2'", ",", "'3'", ",", "'4'", ")", ",", "'items'", "=>", "array", "(", "ACCESSLEVEL2", ",", "ACCESSLEVEL3", ",", "ACCESSLEVEL4", ")", ",", "'value'", "=>", "$", "item", "[", "'access'", "]", ",", "'disabled'", "=>", "$", "item", "[", "'access'", "]", "==", "ROOT", ",", "'access'", "=>", "ADMIN", ")", ",", "array", "(", "'type'", "=>", "'checkbox'", ",", "'name'", "=>", "'active'", ",", "'label'", "=>", "admUsersAccountState", ",", "'value'", "=>", "$", "item", "[", "'active'", "]", ",", "'access'", "=>", "ADMIN", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'loginErrors'", ",", "'label'", "=>", "admUsersLoginErrors", ",", "'maxlength'", "=>", "2", ",", "'width'", "=>", "'30px'", ",", "'value'", "=>", "$", "item", "[", "'loginErrors'", "]", ",", "'access'", "=>", "ADMIN", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'mail'", ",", "'label'", "=>", "admUsersMail", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ",", "'value'", "=>", "$", "item", "[", "'mail'", "]", ",", "'access'", "=>", "ADMIN", ")", ",", ")", ",", "'buttons'", "=>", "array", "(", "UserRights", "(", "$", "this", "->", "access", ")", "?", "'ok'", ":", "''", ",", "'apply'", ",", "'cancel'", ")", ",", ")", ";", "$", "pswd", "=", "array", "(", "'name'", "=>", "'PasswordForm'", ",", "'caption'", "=>", "admUsersChangePassword", ",", "'width'", "=>", "'400px'", ",", "'fields'", "=>", "array", "(", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "'password'", ",", "'value'", "=>", "$", "item", "[", "'id'", "]", ")", ",", "array", "(", "'type'", "=>", "'password'", ",", "'name'", "=>", "'pswd1'", ",", "'label'", "=>", "admUsersPassword", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ")", ",", "array", "(", "'type'", "=>", "'password'", ",", "'name'", "=>", "'pswd2'", ",", "'label'", "=>", "admUsersConfirmation", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ",", "'equal'", "=>", "'pswd1'", ",", "'errormsg'", "=>", "admUsersConfirmInvalid", ")", ",", ")", ",", "'buttons'", "=>", "array", "(", "UserRights", "(", "$", "this", "->", "access", ")", "?", "'ok'", ":", "'apply'", ",", "'cancel'", ")", ",", ")", ";", "/** @var TAdminUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "result", "=", "$", "page", "->", "renderForm", "(", "$", "form", ")", ".", "\"<br />\\n\"", ".", "$", "page", "->", "renderForm", "(", "$", "pswd", ")", ";", "return", "$", "result", ";", "}" ]
??? @return string
[ "???" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L246-L292
Eresus/EresusCMS
src/core/users.php
TUsers.create
private function create() { restoreRequest(); $form = array( 'name'=>'UserForm', 'caption' => admUsersCreate, 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'action','value'=>'insert'), array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%', 'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid), array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%', 'pattern'=>'/^[a-z0-9_]+$/i', 'errormsg'=>admUsersLoginInvalid), array('type'=>'select','name'=>'access','label'=>admAccessLevel, 'width'=>'100%', 'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2,ACCESSLEVEL3,ACCESSLEVEL4), 'default' => USER), array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState, 'default' => true), array('type'=>'divider'), array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32, 'width'=>'100%'), array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32, 'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid), array('type'=>'divider'), array('type' => 'edit', 'name' => 'mail' , 'label' => admUsersMail, 'maxlength' => 32, 'width' => '100%'), ), 'buttons'=>array('ok', 'cancel') ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form, Eresus_CMS::getLegacyKernel()->request['arg']); return $result; }
php
private function create() { restoreRequest(); $form = array( 'name'=>'UserForm', 'caption' => admUsersCreate, 'width' => '400px', 'fields' => array ( array('type'=>'hidden','name'=>'action','value'=>'insert'), array('type'=>'edit','name'=>'name','label'=>admUsersName,'maxlength'=>32,'width'=>'100%', 'pattern'=>'/.+/', 'errormsg'=>admUsersNameInvalid), array('type'=>'edit','name'=>'login','label'=>admUsersLogin,'maxlength'=>16,'width'=>'100%', 'pattern'=>'/^[a-z0-9_]+$/i', 'errormsg'=>admUsersLoginInvalid), array('type'=>'select','name'=>'access','label'=>admAccessLevel, 'width'=>'100%', 'values'=>array('2','3','4'),'items'=>array(ACCESSLEVEL2,ACCESSLEVEL3,ACCESSLEVEL4), 'default' => USER), array('type'=>'checkbox','name'=>'active','label'=>admUsersAccountState, 'default' => true), array('type'=>'divider'), array('type'=>'password','name'=>'pswd1','label'=>admUsersPassword,'maxlength'=>32, 'width'=>'100%'), array('type'=>'password','name'=>'pswd2','label'=>admUsersConfirmation,'maxlength'=>32, 'width'=>'100%', 'equal'=>'pswd1', 'errormsg'=>admUsersConfirmInvalid), array('type'=>'divider'), array('type' => 'edit', 'name' => 'mail' , 'label' => admUsersMail, 'maxlength' => 32, 'width' => '100%'), ), 'buttons'=>array('ok', 'cancel') ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form, Eresus_CMS::getLegacyKernel()->request['arg']); return $result; }
[ "private", "function", "create", "(", ")", "{", "restoreRequest", "(", ")", ";", "$", "form", "=", "array", "(", "'name'", "=>", "'UserForm'", ",", "'caption'", "=>", "admUsersCreate", ",", "'width'", "=>", "'400px'", ",", "'fields'", "=>", "array", "(", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "'action'", ",", "'value'", "=>", "'insert'", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'name'", ",", "'label'", "=>", "admUsersName", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ",", "'pattern'", "=>", "'/.+/'", ",", "'errormsg'", "=>", "admUsersNameInvalid", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'login'", ",", "'label'", "=>", "admUsersLogin", ",", "'maxlength'", "=>", "16", ",", "'width'", "=>", "'100%'", ",", "'pattern'", "=>", "'/^[a-z0-9_]+$/i'", ",", "'errormsg'", "=>", "admUsersLoginInvalid", ")", ",", "array", "(", "'type'", "=>", "'select'", ",", "'name'", "=>", "'access'", ",", "'label'", "=>", "admAccessLevel", ",", "'width'", "=>", "'100%'", ",", "'values'", "=>", "array", "(", "'2'", ",", "'3'", ",", "'4'", ")", ",", "'items'", "=>", "array", "(", "ACCESSLEVEL2", ",", "ACCESSLEVEL3", ",", "ACCESSLEVEL4", ")", ",", "'default'", "=>", "USER", ")", ",", "array", "(", "'type'", "=>", "'checkbox'", ",", "'name'", "=>", "'active'", ",", "'label'", "=>", "admUsersAccountState", ",", "'default'", "=>", "true", ")", ",", "array", "(", "'type'", "=>", "'divider'", ")", ",", "array", "(", "'type'", "=>", "'password'", ",", "'name'", "=>", "'pswd1'", ",", "'label'", "=>", "admUsersPassword", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ")", ",", "array", "(", "'type'", "=>", "'password'", ",", "'name'", "=>", "'pswd2'", ",", "'label'", "=>", "admUsersConfirmation", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ",", "'equal'", "=>", "'pswd1'", ",", "'errormsg'", "=>", "admUsersConfirmInvalid", ")", ",", "array", "(", "'type'", "=>", "'divider'", ")", ",", "array", "(", "'type'", "=>", "'edit'", ",", "'name'", "=>", "'mail'", ",", "'label'", "=>", "admUsersMail", ",", "'maxlength'", "=>", "32", ",", "'width'", "=>", "'100%'", ")", ",", ")", ",", "'buttons'", "=>", "array", "(", "'ok'", ",", "'cancel'", ")", ")", ";", "/** @var TAdminUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "result", "=", "$", "page", "->", "renderForm", "(", "$", "form", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", "[", "'arg'", "]", ")", ";", "return", "$", "result", ";", "}" ]
??? @return mixed
[ "???" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/users.php#L299-L332
inhere/php-librarys
src/Files/FileFinder.php
FileFinder.filterResult
public function filterResult(callable $filter) { $result = []; foreach ($this->files as $file) { if ($filter($file)) { $result[] = $file; } } return $result; }
php
public function filterResult(callable $filter) { $result = []; foreach ($this->files as $file) { if ($filter($file)) { $result[] = $file; } } return $result; }
[ "public", "function", "filterResult", "(", "callable", "$", "filter", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "files", "as", "$", "file", ")", "{", "if", "(", "$", "filter", "(", "$", "file", ")", ")", "{", "$", "result", "[", "]", "=", "$", "file", ";", "}", "}", "return", "$", "result", ";", "}" ]
Further filtering the find result set @param callable $filter e.g: $filter = function($file) { if (false !== strpos($file, 'jqu') ) { return true; } return false; }; @return array
[ "Further", "filtering", "the", "find", "result", "set" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/FileFinder.php#L207-L218
inhere/php-librarys
src/Files/FileFinder.php
FileFinder.doFilterFile
protected function doFilterFile($name /*, $file*/) { // check include ... if (\in_array($name, $this->include['file'], true)) { return true; } // check exclude file ... if (\in_array($name, $this->exclude['file'], true)) { return false; } $ext = implode('|', $this->getInclude('ext')); // check include ext ... if ($ext && preg_match("/\.($ext)$/i", $name)) { // have been set custom file Filter if ($fileFilter = $this->fileFilter) { return $fileFilter($name); } return true; } $noExt = implode('|', $this->getExclude('ext')); // check exclude ext ... if ($noExt && preg_match("/\.($noExt)$/i", $name)) { return false; } // have been set custom file Filter if ($fileFilter = $this->fileFilter) { return $fileFilter($name); } return true; }
php
protected function doFilterFile($name /*, $file*/) { // check include ... if (\in_array($name, $this->include['file'], true)) { return true; } // check exclude file ... if (\in_array($name, $this->exclude['file'], true)) { return false; } $ext = implode('|', $this->getInclude('ext')); // check include ext ... if ($ext && preg_match("/\.($ext)$/i", $name)) { // have been set custom file Filter if ($fileFilter = $this->fileFilter) { return $fileFilter($name); } return true; } $noExt = implode('|', $this->getExclude('ext')); // check exclude ext ... if ($noExt && preg_match("/\.($noExt)$/i", $name)) { return false; } // have been set custom file Filter if ($fileFilter = $this->fileFilter) { return $fileFilter($name); } return true; }
[ "protected", "function", "doFilterFile", "(", "$", "name", "/*, $file*/", ")", "{", "// check include ...", "if", "(", "\\", "in_array", "(", "$", "name", ",", "$", "this", "->", "include", "[", "'file'", "]", ",", "true", ")", ")", "{", "return", "true", ";", "}", "// check exclude file ...", "if", "(", "\\", "in_array", "(", "$", "name", ",", "$", "this", "->", "exclude", "[", "'file'", "]", ",", "true", ")", ")", "{", "return", "false", ";", "}", "$", "ext", "=", "implode", "(", "'|'", ",", "$", "this", "->", "getInclude", "(", "'ext'", ")", ")", ";", "// check include ext ...", "if", "(", "$", "ext", "&&", "preg_match", "(", "\"/\\.($ext)$/i\"", ",", "$", "name", ")", ")", "{", "// have been set custom file Filter", "if", "(", "$", "fileFilter", "=", "$", "this", "->", "fileFilter", ")", "{", "return", "$", "fileFilter", "(", "$", "name", ")", ";", "}", "return", "true", ";", "}", "$", "noExt", "=", "implode", "(", "'|'", ",", "$", "this", "->", "getExclude", "(", "'ext'", ")", ")", ";", "// check exclude ext ...", "if", "(", "$", "noExt", "&&", "preg_match", "(", "\"/\\.($noExt)$/i\"", ",", "$", "name", ")", ")", "{", "return", "false", ";", "}", "// have been set custom file Filter", "if", "(", "$", "fileFilter", "=", "$", "this", "->", "fileFilter", ")", "{", "return", "$", "fileFilter", "(", "$", "name", ")", ";", "}", "return", "true", ";", "}" ]
文件过滤 -- 过滤掉不需要的文件. 也可自定义过滤回调,来实现个性化过滤 @param $name @return bool|mixed
[ "文件过滤", "--", "过滤掉不需要的文件", ".", "也可自定义过滤回调", "来实现个性化过滤" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/FileFinder.php#L257-L294
inhere/php-librarys
src/Files/FileFinder.php
FileFinder.doFilterDir
protected function doFilterDir($name /*, $dir*/) { if (\in_array($name, $this->include['dir'], true)) { // have bee set custom dir Filter if ($dirFilter = $this->dirFilter) { return $dirFilter($name); } return true; } if (\in_array($name, $this->exclude['dir'], true)) { return false; } // have bee set custom dir Filter if ($dirFilter = $this->dirFilter) { return $dirFilter($name); } // use default filter handle return true; }
php
protected function doFilterDir($name /*, $dir*/) { if (\in_array($name, $this->include['dir'], true)) { // have bee set custom dir Filter if ($dirFilter = $this->dirFilter) { return $dirFilter($name); } return true; } if (\in_array($name, $this->exclude['dir'], true)) { return false; } // have bee set custom dir Filter if ($dirFilter = $this->dirFilter) { return $dirFilter($name); } // use default filter handle return true; }
[ "protected", "function", "doFilterDir", "(", "$", "name", "/*, $dir*/", ")", "{", "if", "(", "\\", "in_array", "(", "$", "name", ",", "$", "this", "->", "include", "[", "'dir'", "]", ",", "true", ")", ")", "{", "// have bee set custom dir Filter", "if", "(", "$", "dirFilter", "=", "$", "this", "->", "dirFilter", ")", "{", "return", "$", "dirFilter", "(", "$", "name", ")", ";", "}", "return", "true", ";", "}", "if", "(", "\\", "in_array", "(", "$", "name", ",", "$", "this", "->", "exclude", "[", "'dir'", "]", ",", "true", ")", ")", "{", "return", "false", ";", "}", "// have bee set custom dir Filter", "if", "(", "$", "dirFilter", "=", "$", "this", "->", "dirFilter", ")", "{", "return", "$", "dirFilter", "(", "$", "name", ")", ";", "}", "// use default filter handle", "return", "true", ";", "}" ]
文件夹过滤 -- 过滤掉不需要的文件夹. 也可添加自定义过滤回调,来实现个性化过滤 @param $name @return bool
[ "文件夹过滤", "--", "过滤掉不需要的文件夹", ".", "也可添加自定义过滤回调", "来实现个性化过滤" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/FileFinder.php#L301-L323
mvccore/ext-router-module
src/MvcCore/Ext/Routers/Module/UrlByRoute.php
UrlByRoute.UrlByRoute
public function UrlByRoute (\MvcCore\IRoute & $route, array & $params = [], $urlParamRouteName = NULL) { $moduleParamName = static::URL_PARAM_MODULE; $moduleParamDefined = isset($params[$moduleParamName]); $currentDomainRouteMatched = $this->currentDomainRoute !== NULL; if ( $route->GetAbsolute() && $moduleParamDefined && $currentDomainRouteMatched && $params[$moduleParamName] !== $this->requestedDomainParams[$moduleParamName] ) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException( "[".$selfClass."] It's not possible to create URL address " ."to different module/domain for route defined as absolute." ); } list ($targetModule, $targetDomainRoute, $domainParamsDefault) = $this->urlGetDomainRouteAndDefaultDomainParams( $params, $moduleParamDefined, $currentDomainRouteMatched ); $domainUrlBaseSection = NULL; if ($targetModule !== NULL) $domainUrlBaseSection = $this->urlGetDomainUrlAndClasifyParamsAndDomainParams( $params, $domainParamsDefault, $targetDomainRoute ); // get domain with base path URL section, // path with query string URL section // and system params for URL prefixes list($urlBaseSection, $urlPathWithQuerySection, $systemParams) = $this->urlByRouteSections( $route, $params, $urlParamRouteName ); if ($targetModule !== NULL) $systemParams = array_diff_key($systemParams, $domainParamsDefault); $urlPathWithQueryIsHome = NULL; // create prefixed URL return $this->urlByRoutePrefixSystemParams( $domainUrlBaseSection ?: $urlBaseSection, $urlPathWithQuerySection, $systemParams, $urlPathWithQueryIsHome ); }
php
public function UrlByRoute (\MvcCore\IRoute & $route, array & $params = [], $urlParamRouteName = NULL) { $moduleParamName = static::URL_PARAM_MODULE; $moduleParamDefined = isset($params[$moduleParamName]); $currentDomainRouteMatched = $this->currentDomainRoute !== NULL; if ( $route->GetAbsolute() && $moduleParamDefined && $currentDomainRouteMatched && $params[$moduleParamName] !== $this->requestedDomainParams[$moduleParamName] ) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException( "[".$selfClass."] It's not possible to create URL address " ."to different module/domain for route defined as absolute." ); } list ($targetModule, $targetDomainRoute, $domainParamsDefault) = $this->urlGetDomainRouteAndDefaultDomainParams( $params, $moduleParamDefined, $currentDomainRouteMatched ); $domainUrlBaseSection = NULL; if ($targetModule !== NULL) $domainUrlBaseSection = $this->urlGetDomainUrlAndClasifyParamsAndDomainParams( $params, $domainParamsDefault, $targetDomainRoute ); // get domain with base path URL section, // path with query string URL section // and system params for URL prefixes list($urlBaseSection, $urlPathWithQuerySection, $systemParams) = $this->urlByRouteSections( $route, $params, $urlParamRouteName ); if ($targetModule !== NULL) $systemParams = array_diff_key($systemParams, $domainParamsDefault); $urlPathWithQueryIsHome = NULL; // create prefixed URL return $this->urlByRoutePrefixSystemParams( $domainUrlBaseSection ?: $urlBaseSection, $urlPathWithQuerySection, $systemParams, $urlPathWithQueryIsHome ); }
[ "public", "function", "UrlByRoute", "(", "\\", "MvcCore", "\\", "IRoute", "&", "$", "route", ",", "array", "&", "$", "params", "=", "[", "]", ",", "$", "urlParamRouteName", "=", "NULL", ")", "{", "$", "moduleParamName", "=", "static", "::", "URL_PARAM_MODULE", ";", "$", "moduleParamDefined", "=", "isset", "(", "$", "params", "[", "$", "moduleParamName", "]", ")", ";", "$", "currentDomainRouteMatched", "=", "$", "this", "->", "currentDomainRoute", "!==", "NULL", ";", "if", "(", "$", "route", "->", "GetAbsolute", "(", ")", "&&", "$", "moduleParamDefined", "&&", "$", "currentDomainRouteMatched", "&&", "$", "params", "[", "$", "moduleParamName", "]", "!==", "$", "this", "->", "requestedDomainParams", "[", "$", "moduleParamName", "]", ")", "{", "$", "selfClass", "=", "version_compare", "(", "PHP_VERSION", ",", "'5.5'", ",", "'>'", ")", "?", "self", "::", "class", ":", "__CLASS__", ";", "throw", "new", "\\", "InvalidArgumentException", "(", "\"[\"", ".", "$", "selfClass", ".", "\"] It's not possible to create URL address \"", ".", "\"to different module/domain for route defined as absolute.\"", ")", ";", "}", "list", "(", "$", "targetModule", ",", "$", "targetDomainRoute", ",", "$", "domainParamsDefault", ")", "=", "$", "this", "->", "urlGetDomainRouteAndDefaultDomainParams", "(", "$", "params", ",", "$", "moduleParamDefined", ",", "$", "currentDomainRouteMatched", ")", ";", "$", "domainUrlBaseSection", "=", "NULL", ";", "if", "(", "$", "targetModule", "!==", "NULL", ")", "$", "domainUrlBaseSection", "=", "$", "this", "->", "urlGetDomainUrlAndClasifyParamsAndDomainParams", "(", "$", "params", ",", "$", "domainParamsDefault", ",", "$", "targetDomainRoute", ")", ";", "// get domain with base path URL section, ", "// path with query string URL section ", "// and system params for URL prefixes", "list", "(", "$", "urlBaseSection", ",", "$", "urlPathWithQuerySection", ",", "$", "systemParams", ")", "=", "$", "this", "->", "urlByRouteSections", "(", "$", "route", ",", "$", "params", ",", "$", "urlParamRouteName", ")", ";", "if", "(", "$", "targetModule", "!==", "NULL", ")", "$", "systemParams", "=", "array_diff_key", "(", "$", "systemParams", ",", "$", "domainParamsDefault", ")", ";", "$", "urlPathWithQueryIsHome", "=", "NULL", ";", "// create prefixed URL", "return", "$", "this", "->", "urlByRoutePrefixSystemParams", "(", "$", "domainUrlBaseSection", "?", ":", "$", "urlBaseSection", ",", "$", "urlPathWithQuerySection", ",", "$", "systemParams", ",", "$", "urlPathWithQueryIsHome", ")", ";", "}" ]
Complete relative (or absolute) URL by route instance reverse info. If there is defined any target module in `$params`, absolute URL is returned. Example: Input (`\MvcCore\Route::$reverse`): `"/products-list/<name>/<color>"` Input ($params): `array( "name" => "cool-product-name", "color" => "red", "variant" => ["L", "XL"], "media_version" => "mobile", "localization" => "en-US", );` Output (relative): `/application/base-bath/products-list/cool-product-name/blue?variant[]=L&amp;variant[]=XL"` Output (absolute): `https://domain.com/application/base-bath/products-list/cool-product-name/blue?variant[]=L&amp;variant[]=XL"` @param \MvcCore\Route|\MvcCore\IRoute &$route @param array $params @param string $urlParamRouteName @return string
[ "Complete", "relative", "(", "or", "absolute", ")", "URL", "by", "route", "instance", "reverse", "info", ".", "If", "there", "is", "defined", "any", "target", "module", "in", "$params", "absolute", "URL", "is", "returned", ".", "Example", ":", "Input", "(", "\\", "MvcCore", "\\", "Route", "::", "$reverse", ")", ":", "/", "products", "-", "list", "/", "<name", ">", "/", "<color", ">", "Input", "(", "$params", ")", ":", "array", "(", "name", "=", ">", "cool", "-", "product", "-", "name", "color", "=", ">", "red", "variant", "=", ">", "[", "L", "XL", "]", "media_version", "=", ">", "mobile", "localization", "=", ">", "en", "-", "US", ")", ";", "Output", "(", "relative", ")", ":", "/", "application", "/", "base", "-", "bath", "/", "products", "-", "list", "/", "cool", "-", "product", "-", "name", "/", "blue?variant", "[]", "=", "L&amp", ";", "variant", "[]", "=", "XL", "Output", "(", "absolute", ")", ":", "https", ":", "//", "domain", ".", "com", "/", "application", "/", "base", "-", "bath", "/", "products", "-", "list", "/", "cool", "-", "product", "-", "name", "/", "blue?variant", "[]", "=", "L&amp", ";", "variant", "[]", "=", "XL" ]
train
https://github.com/mvccore/ext-router-module/blob/7695784a451db86cca6a43c98d076803cd0a50a7/src/MvcCore/Ext/Routers/Module/UrlByRoute.php#L41-L86
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/file.php
ezcMailFilePart.setHeaderContentType
private function setHeaderContentType() { $fileName = basename( $this->fileName ); if ( $this->contentDisposition !== null && $this->contentDisposition->fileName !== null ) { $fileName = $this->contentDisposition->fileName; } $this->setHeader( 'Content-Type', $this->contentType . '/' . $this->mimeType . '; ' . 'name="' . $fileName . '"' ); }
php
private function setHeaderContentType() { $fileName = basename( $this->fileName ); if ( $this->contentDisposition !== null && $this->contentDisposition->fileName !== null ) { $fileName = $this->contentDisposition->fileName; } $this->setHeader( 'Content-Type', $this->contentType . '/' . $this->mimeType . '; ' . 'name="' . $fileName . '"' ); }
[ "private", "function", "setHeaderContentType", "(", ")", "{", "$", "fileName", "=", "basename", "(", "$", "this", "->", "fileName", ")", ";", "if", "(", "$", "this", "->", "contentDisposition", "!==", "null", "&&", "$", "this", "->", "contentDisposition", "->", "fileName", "!==", "null", ")", "{", "$", "fileName", "=", "$", "this", "->", "contentDisposition", "->", "fileName", ";", "}", "$", "this", "->", "setHeader", "(", "'Content-Type'", ",", "$", "this", "->", "contentType", ".", "'/'", ".", "$", "this", "->", "mimeType", ".", "'; '", ".", "'name=\"'", ".", "$", "fileName", ".", "'\"'", ")", ";", "}" ]
Sets the Content-Type header. Based on the contentType, mimeType and fileName.
[ "Sets", "the", "Content", "-", "Type", "header", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/file.php#L184-L194
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/file.php
ezcMailFilePart.setHeaderContentDisposition
private function setHeaderContentDisposition() { if ( !isset( $this->dispositionType ) ) { $this->dispositionType = self::DISPLAY_ATTACHMENT; } if ( $this->contentDisposition == null ) { $this->contentDisposition = new ezcMailContentDispositionHeader(); // modified for issue #14025: set the file name and disposition // only if the contentDisposition was null (to not overwrite // the value set by the user) $this->contentDisposition->disposition = $this->dispositionType; $this->contentDisposition->fileName = basename( $this->fileName ); } }
php
private function setHeaderContentDisposition() { if ( !isset( $this->dispositionType ) ) { $this->dispositionType = self::DISPLAY_ATTACHMENT; } if ( $this->contentDisposition == null ) { $this->contentDisposition = new ezcMailContentDispositionHeader(); // modified for issue #14025: set the file name and disposition // only if the contentDisposition was null (to not overwrite // the value set by the user) $this->contentDisposition->disposition = $this->dispositionType; $this->contentDisposition->fileName = basename( $this->fileName ); } }
[ "private", "function", "setHeaderContentDisposition", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "dispositionType", ")", ")", "{", "$", "this", "->", "dispositionType", "=", "self", "::", "DISPLAY_ATTACHMENT", ";", "}", "if", "(", "$", "this", "->", "contentDisposition", "==", "null", ")", "{", "$", "this", "->", "contentDisposition", "=", "new", "ezcMailContentDispositionHeader", "(", ")", ";", "// modified for issue #14025: set the file name and disposition", "// only if the contentDisposition was null (to not overwrite", "// the value set by the user)", "$", "this", "->", "contentDisposition", "->", "disposition", "=", "$", "this", "->", "dispositionType", ";", "$", "this", "->", "contentDisposition", "->", "fileName", "=", "basename", "(", "$", "this", "->", "fileName", ")", ";", "}", "}" ]
Sets the Content-Disposition header based on the properties $dispositionType and $fileName. Does not set the fileNameCharSet and fileNameLanguage properties of the Content-Disposition header. For this purpose set directly $this->contentDisposition with an object of class ezcMailContentDispositionHeader.
[ "Sets", "the", "Content", "-", "Disposition", "header", "based", "on", "the", "properties", "$dispositionType", "and", "$fileName", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/file.php#L203-L219
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.convertCoordinatesFromUserSpace
public function convertCoordinatesFromUserSpace(&$x, &$y) { $x += $this->getLeftMargin(); $this->convertToPoints($x); $y += $this->getTopMargin(); $y = $this->getHeight() - $y; $this->convertToPoints($y); }
php
public function convertCoordinatesFromUserSpace(&$x, &$y) { $x += $this->getLeftMargin(); $this->convertToPoints($x); $y += $this->getTopMargin(); $y = $this->getHeight() - $y; $this->convertToPoints($y); }
[ "public", "function", "convertCoordinatesFromUserSpace", "(", "&", "$", "x", ",", "&", "$", "y", ")", "{", "$", "x", "+=", "$", "this", "->", "getLeftMargin", "(", ")", ";", "$", "this", "->", "convertToPoints", "(", "$", "x", ")", ";", "$", "y", "+=", "$", "this", "->", "getTopMargin", "(", ")", ";", "$", "y", "=", "$", "this", "->", "getHeight", "(", ")", "-", "$", "y", ";", "$", "this", "->", "convertToPoints", "(", "$", "y", ")", ";", "}" ]
Convert (x,y)-coordinates in the user space (top to bottom, in the given units, relative to the margins) to native geometry (points, bottom to top) @param float &$x x-coordinate (in the given units, from the left margin) to convert, BY REF @param float &$y y-coordinate (in the given units, from the top margin) to convert, BY REF
[ "Convert", "(", "x", "y", ")", "-", "coordinates", "in", "the", "user", "space", "(", "top", "to", "bottom", "in", "the", "given", "units", "relative", "to", "the", "margins", ")", "to", "native", "geometry", "(", "points", "bottom", "to", "top", ")" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L168-L176
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.convertCoordinatesToUserSpace
public function convertCoordinatesToUserSpace(&$x, &$y) { $this->convertFromPoints($x); $x -= $this->getLeftMargin(); $this->convertFromPoints($y); $y = $this->getHeight() - $y; $x -= $this->getLeftMargin(); }
php
public function convertCoordinatesToUserSpace(&$x, &$y) { $this->convertFromPoints($x); $x -= $this->getLeftMargin(); $this->convertFromPoints($y); $y = $this->getHeight() - $y; $x -= $this->getLeftMargin(); }
[ "public", "function", "convertCoordinatesToUserSpace", "(", "&", "$", "x", ",", "&", "$", "y", ")", "{", "$", "this", "->", "convertFromPoints", "(", "$", "x", ")", ";", "$", "x", "-=", "$", "this", "->", "getLeftMargin", "(", ")", ";", "$", "this", "->", "convertFromPoints", "(", "$", "y", ")", ";", "$", "y", "=", "$", "this", "->", "getHeight", "(", ")", "-", "$", "y", ";", "$", "x", "-=", "$", "this", "->", "getLeftMargin", "(", ")", ";", "}" ]
Convert (x,y)-coordinates in native geometry (points, bottom to top) to the user space (top to bottom, in the given units, relative to the margins) @param float &$x x-coordinate (in points, from the left) to convert, BY REF @param float &$y y-coordinate (in points, from the bottom) to convert, BY REF
[ "Convert", "(", "x", "y", ")", "-", "coordinates", "in", "native", "geometry", "(", "points", "bottom", "to", "top", ")", "to", "the", "user", "space", "(", "top", "to", "bottom", "in", "the", "given", "units", "relative", "to", "the", "margins", ")" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L185-L193
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.setMargins
public function setMargins($marginLeft, $marginRight, $marginTop, $marginBottom) { $this->setLeftMargin($marginLeft); $this->setRightMargin($marginRight); $this->setTopMargin($marginTop); $this->setBottomMargin($marginBottom); return $this; }
php
public function setMargins($marginLeft, $marginRight, $marginTop, $marginBottom) { $this->setLeftMargin($marginLeft); $this->setRightMargin($marginRight); $this->setTopMargin($marginTop); $this->setBottomMargin($marginBottom); return $this; }
[ "public", "function", "setMargins", "(", "$", "marginLeft", ",", "$", "marginRight", ",", "$", "marginTop", ",", "$", "marginBottom", ")", "{", "$", "this", "->", "setLeftMargin", "(", "$", "marginLeft", ")", ";", "$", "this", "->", "setRightMargin", "(", "$", "marginRight", ")", ";", "$", "this", "->", "setTopMargin", "(", "$", "marginTop", ")", ";", "$", "this", "->", "setBottomMargin", "(", "$", "marginBottom", ")", ";", "return", "$", "this", ";", "}" ]
Set new margin, in the given units @param float $marginLeft new left margin, in the given units @param float $marginRight new right margin, in the given units @param float $marginTop new top margin, in the given units @param float $marginBottom new bottom margin, in the given units @return \SimplePdf\Page this page
[ "Set", "new", "margin", "in", "the", "given", "units" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L326-L333
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.setFont
public function setFont(\ZendPdf\Resource\Font\AbstractFont $font, $fontSize = null) { if (is_null($fontSize)) { $fontSize = $this->getFontSize(); } return parent::setFont($font, $fontSize); }
php
public function setFont(\ZendPdf\Resource\Font\AbstractFont $font, $fontSize = null) { if (is_null($fontSize)) { $fontSize = $this->getFontSize(); } return parent::setFont($font, $fontSize); }
[ "public", "function", "setFont", "(", "\\", "ZendPdf", "\\", "Resource", "\\", "Font", "\\", "AbstractFont", "$", "font", ",", "$", "fontSize", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "fontSize", ")", ")", "{", "$", "fontSize", "=", "$", "this", "->", "getFontSize", "(", ")", ";", "}", "return", "parent", "::", "setFont", "(", "$", "font", ",", "$", "fontSize", ")", ";", "}" ]
Sets a new font family and, optionally, a new font size as well @param \ZendPdf\Resource\Font\AbstractFont $font font object to use @param float $fontSize new font size, leave it out to keep the current font size
[ "Sets", "a", "new", "font", "family", "and", "optionally", "a", "new", "font", "size", "as", "well" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L373-L380
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.drawTextBlock
public function drawTextBlock($text, $y = 0, $alignment = self::TEXT_ALIGN_LEFT, $x1 = 0, $x2 = null) { if (is_null($x2)) { $x2 = $this->getInnerWidth(); } $width = $x2 - $x1; $text = $this->wordWrapText($text, $width); $x = $x1 + $alignment * $width; $lineHeight = $this->getLineHeight(); $lines = explode(PHP_EOL, $text); foreach ($lines as $index => $line) { if (empty($line)) { continue; } $offset = ($alignment == 0) ? 0 : -$alignment * $this->getTextWidth($line); $this->drawText($line, $x + $offset, $y + $index * $lineHeight); } return $this; }
php
public function drawTextBlock($text, $y = 0, $alignment = self::TEXT_ALIGN_LEFT, $x1 = 0, $x2 = null) { if (is_null($x2)) { $x2 = $this->getInnerWidth(); } $width = $x2 - $x1; $text = $this->wordWrapText($text, $width); $x = $x1 + $alignment * $width; $lineHeight = $this->getLineHeight(); $lines = explode(PHP_EOL, $text); foreach ($lines as $index => $line) { if (empty($line)) { continue; } $offset = ($alignment == 0) ? 0 : -$alignment * $this->getTextWidth($line); $this->drawText($line, $x + $offset, $y + $index * $lineHeight); } return $this; }
[ "public", "function", "drawTextBlock", "(", "$", "text", ",", "$", "y", "=", "0", ",", "$", "alignment", "=", "self", "::", "TEXT_ALIGN_LEFT", ",", "$", "x1", "=", "0", ",", "$", "x2", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "x2", ")", ")", "{", "$", "x2", "=", "$", "this", "->", "getInnerWidth", "(", ")", ";", "}", "$", "width", "=", "$", "x2", "-", "$", "x1", ";", "$", "text", "=", "$", "this", "->", "wordWrapText", "(", "$", "text", ",", "$", "width", ")", ";", "$", "x", "=", "$", "x1", "+", "$", "alignment", "*", "$", "width", ";", "$", "lineHeight", "=", "$", "this", "->", "getLineHeight", "(", ")", ";", "$", "lines", "=", "explode", "(", "PHP_EOL", ",", "$", "text", ")", ";", "foreach", "(", "$", "lines", "as", "$", "index", "=>", "$", "line", ")", "{", "if", "(", "empty", "(", "$", "line", ")", ")", "{", "continue", ";", "}", "$", "offset", "=", "(", "$", "alignment", "==", "0", ")", "?", "0", ":", "-", "$", "alignment", "*", "$", "this", "->", "getTextWidth", "(", "$", "line", ")", ";", "$", "this", "->", "drawText", "(", "$", "line", ",", "$", "x", "+", "$", "offset", ",", "$", "y", "+", "$", "index", "*", "$", "lineHeight", ")", ";", "}", "return", "$", "this", ";", "}" ]
Draw (and wrap) algined text within a text block, by default within the page margins @param string $text text to draw; will be wrapped, but can also contain newlines already @param float $y vertical offset (from the top, in the given units) to start drawing text @param float $alignment where to align text within the block, defaults to left alignment @param float $x1 left boundary of the text block, defaults to left page margin @param float $x2 right boundary of the text block, defaults to right page margin @return \SimplePdf\Page this page
[ "Draw", "(", "and", "wrap", ")", "algined", "text", "within", "a", "text", "block", "by", "default", "within", "the", "page", "margins" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L402-L424
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.wordWrapText
public function wordWrapText($text, $wrapWidth) { $wrappedText = ''; foreach (explode(PHP_EOL, $text) as $line) { $words = explode(' ', $line); $currentLine = array_shift($words); while (count($words) > 0) { $word = array_shift($words); if ($this->getTextWidth($currentLine . ' ' . $word) > $wrapWidth) { $wrappedText .= PHP_EOL . $currentLine; $currentLine = $word; } else { $currentLine .= ' ' . $word; } } $wrappedText .= PHP_EOL . $currentLine; } return ltrim($wrappedText, PHP_EOL); }
php
public function wordWrapText($text, $wrapWidth) { $wrappedText = ''; foreach (explode(PHP_EOL, $text) as $line) { $words = explode(' ', $line); $currentLine = array_shift($words); while (count($words) > 0) { $word = array_shift($words); if ($this->getTextWidth($currentLine . ' ' . $word) > $wrapWidth) { $wrappedText .= PHP_EOL . $currentLine; $currentLine = $word; } else { $currentLine .= ' ' . $word; } } $wrappedText .= PHP_EOL . $currentLine; } return ltrim($wrappedText, PHP_EOL); }
[ "public", "function", "wordWrapText", "(", "$", "text", ",", "$", "wrapWidth", ")", "{", "$", "wrappedText", "=", "''", ";", "foreach", "(", "explode", "(", "PHP_EOL", ",", "$", "text", ")", "as", "$", "line", ")", "{", "$", "words", "=", "explode", "(", "' '", ",", "$", "line", ")", ";", "$", "currentLine", "=", "array_shift", "(", "$", "words", ")", ";", "while", "(", "count", "(", "$", "words", ")", ">", "0", ")", "{", "$", "word", "=", "array_shift", "(", "$", "words", ")", ";", "if", "(", "$", "this", "->", "getTextWidth", "(", "$", "currentLine", ".", "' '", ".", "$", "word", ")", ">", "$", "wrapWidth", ")", "{", "$", "wrappedText", ".=", "PHP_EOL", ".", "$", "currentLine", ";", "$", "currentLine", "=", "$", "word", ";", "}", "else", "{", "$", "currentLine", ".=", "' '", ".", "$", "word", ";", "}", "}", "$", "wrappedText", ".=", "PHP_EOL", ".", "$", "currentLine", ";", "}", "return", "ltrim", "(", "$", "wrappedText", ",", "PHP_EOL", ")", ";", "}" ]
Word-wrap a text to a certain width, using the current font properties @param string $text text to wrap (can already contain some newlines) @param string $wrapWidth width (in the given units) to wrap the text to @return string the same text but with newlines inserted at the specified $wrapWidth
[ "Word", "-", "wrap", "a", "text", "to", "a", "certain", "width", "using", "the", "current", "font", "properties" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L433-L451
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.getLineHeight
public function getLineHeight() { $lineHeight = $this->getFontSize() * 1.2 * $this->getLineSpacing(); $this->convertFromPoints($lineHeight); return $lineHeight; }
php
public function getLineHeight() { $lineHeight = $this->getFontSize() * 1.2 * $this->getLineSpacing(); $this->convertFromPoints($lineHeight); return $lineHeight; }
[ "public", "function", "getLineHeight", "(", ")", "{", "$", "lineHeight", "=", "$", "this", "->", "getFontSize", "(", ")", "*", "1.2", "*", "$", "this", "->", "getLineSpacing", "(", ")", ";", "$", "this", "->", "convertFromPoints", "(", "$", "lineHeight", ")", ";", "return", "$", "lineHeight", ";", "}" ]
Get the line height (the offset between consecutive lines) @return float distance between consecutive lines in the given units
[ "Get", "the", "line", "height", "(", "the", "offset", "between", "consecutive", "lines", ")" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L458-L463
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.getTextWidth
public function getTextWidth($text) { $font = $this->getFont(); $fontSize = $this->getFontSize(); $text = iconv('WINDOWS-1252', 'UTF-16BE', $text); $chars = array(); for ($i = 0; $i < strlen($text); $i++) { $chars[] = (ord($text[$i++]) << 8) | ord($text[$i]); } $glyphs = $font->glyphNumbersForCharacters($chars); $widths = $font->widthsForGlyphs($glyphs); $textWidth = $fontSize * array_sum($widths) / $font->getUnitsPerEm(); $this->convertFromPoints($textWidth); return $textWidth; }
php
public function getTextWidth($text) { $font = $this->getFont(); $fontSize = $this->getFontSize(); $text = iconv('WINDOWS-1252', 'UTF-16BE', $text); $chars = array(); for ($i = 0; $i < strlen($text); $i++) { $chars[] = (ord($text[$i++]) << 8) | ord($text[$i]); } $glyphs = $font->glyphNumbersForCharacters($chars); $widths = $font->widthsForGlyphs($glyphs); $textWidth = $fontSize * array_sum($widths) / $font->getUnitsPerEm(); $this->convertFromPoints($textWidth); return $textWidth; }
[ "public", "function", "getTextWidth", "(", "$", "text", ")", "{", "$", "font", "=", "$", "this", "->", "getFont", "(", ")", ";", "$", "fontSize", "=", "$", "this", "->", "getFontSize", "(", ")", ";", "$", "text", "=", "iconv", "(", "'WINDOWS-1252'", ",", "'UTF-16BE'", ",", "$", "text", ")", ";", "$", "chars", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "text", ")", ";", "$", "i", "++", ")", "{", "$", "chars", "[", "]", "=", "(", "ord", "(", "$", "text", "[", "$", "i", "++", "]", ")", "<<", "8", ")", "|", "ord", "(", "$", "text", "[", "$", "i", "]", ")", ";", "}", "$", "glyphs", "=", "$", "font", "->", "glyphNumbersForCharacters", "(", "$", "chars", ")", ";", "$", "widths", "=", "$", "font", "->", "widthsForGlyphs", "(", "$", "glyphs", ")", ";", "$", "textWidth", "=", "$", "fontSize", "*", "array_sum", "(", "$", "widths", ")", "/", "$", "font", "->", "getUnitsPerEm", "(", ")", ";", "$", "this", "->", "convertFromPoints", "(", "$", "textWidth", ")", ";", "return", "$", "textWidth", ";", "}" ]
Calculates how much (horizontal) space a text would use if written to the page, using the current font properties @param string $text text to calculate the width for (should not contain newlines) @return float width (in the given units) that the text would use if written to the page
[ "Calculates", "how", "much", "(", "horizontal", ")", "space", "a", "text", "would", "use", "if", "written", "to", "the", "page", "using", "the", "current", "font", "properties" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L472-L486
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.drawCircle
public function drawCircle($x, $y, $radius, $param4 = null, $param5 = null, $param6 = null) { // Don't convert units and call parent::drawCircle(), since it calls drawEllipse which will convert units twice! return $this->drawEllipse($x - $radius, $y - $radius, $x + $radius, $y + $radius, $param4, $param5, $param6); }
php
public function drawCircle($x, $y, $radius, $param4 = null, $param5 = null, $param6 = null) { // Don't convert units and call parent::drawCircle(), since it calls drawEllipse which will convert units twice! return $this->drawEllipse($x - $radius, $y - $radius, $x + $radius, $y + $radius, $param4, $param5, $param6); }
[ "public", "function", "drawCircle", "(", "$", "x", ",", "$", "y", ",", "$", "radius", ",", "$", "param4", "=", "null", ",", "$", "param5", "=", "null", ",", "$", "param6", "=", "null", ")", "{", "// Don't convert units and call parent::drawCircle(), since it calls drawEllipse which will convert units twice!", "return", "$", "this", "->", "drawEllipse", "(", "$", "x", "-", "$", "radius", ",", "$", "y", "-", "$", "radius", ",", "$", "x", "+", "$", "radius", ",", "$", "y", "+", "$", "radius", ",", "$", "param4", ",", "$", "param5", ",", "$", "param6", ")", ";", "}" ]
Wrapper taking custom units and margins into account @see \ZendPdf\Page::drawCircle() for documentation
[ "Wrapper", "taking", "custom", "units", "and", "margins", "into", "account" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L492-L496
robbertkl/simplepdf
classes/SimplePdf/Page.php
Page.drawEllipse
public function drawEllipse($x1, $y1, $x2, $y2, $param5 = null, $param6 = null, $param7 = null) { $this->convertCoordinatesFromUserSpace($x1, $y1); $this->convertCoordinatesFromUserSpace($x2, $y2); list($y1, $y2) = array($y2, $y1); return parent::drawEllipse($x1, $y1, $x2, $y2, $param5, $param6, $param7); }
php
public function drawEllipse($x1, $y1, $x2, $y2, $param5 = null, $param6 = null, $param7 = null) { $this->convertCoordinatesFromUserSpace($x1, $y1); $this->convertCoordinatesFromUserSpace($x2, $y2); list($y1, $y2) = array($y2, $y1); return parent::drawEllipse($x1, $y1, $x2, $y2, $param5, $param6, $param7); }
[ "public", "function", "drawEllipse", "(", "$", "x1", ",", "$", "y1", ",", "$", "x2", ",", "$", "y2", ",", "$", "param5", "=", "null", ",", "$", "param6", "=", "null", ",", "$", "param7", "=", "null", ")", "{", "$", "this", "->", "convertCoordinatesFromUserSpace", "(", "$", "x1", ",", "$", "y1", ")", ";", "$", "this", "->", "convertCoordinatesFromUserSpace", "(", "$", "x2", ",", "$", "y2", ")", ";", "list", "(", "$", "y1", ",", "$", "y2", ")", "=", "array", "(", "$", "y2", ",", "$", "y1", ")", ";", "return", "parent", "::", "drawEllipse", "(", "$", "x1", ",", "$", "y1", ",", "$", "x2", ",", "$", "y2", ",", "$", "param5", ",", "$", "param6", ",", "$", "param7", ")", ";", "}" ]
Wrapper taking custom units and margins into account @see \ZendPdf\Page::drawEllipse() for documentation
[ "Wrapper", "taking", "custom", "units", "and", "margins", "into", "account" ]
train
https://github.com/robbertkl/simplepdf/blob/f19cea8d4e52fe76d4fa447b411514dee688adbc/classes/SimplePdf/Page.php#L502-L508