repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
ikkez/f3-cortex
lib/db/cortex.php
Cortex.reset
public function reset($mapper = true) { if ($mapper) $this->mapper->reset(); $this->fieldsCache=[]; $this->saveCsd=[]; $this->countFields=[]; $this->preBinds=[]; $this->grp_stack=null; // set default values if (($this->dbsType == 'jig' || $this->dbsType == 'mongo') && !empty($this->fieldConf)) foreach($this->fieldConf as $field_key => $field_conf) if (array_key_exists('default',$field_conf)) { $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) ? date('Y-m-d H:i:s') : $field_conf['default']; $this->set($field_key, $val); } }
php
public function reset($mapper = true) { if ($mapper) $this->mapper->reset(); $this->fieldsCache=[]; $this->saveCsd=[]; $this->countFields=[]; $this->preBinds=[]; $this->grp_stack=null; // set default values if (($this->dbsType == 'jig' || $this->dbsType == 'mongo') && !empty($this->fieldConf)) foreach($this->fieldConf as $field_key => $field_conf) if (array_key_exists('default',$field_conf)) { $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) ? date('Y-m-d H:i:s') : $field_conf['default']; $this->set($field_key, $val); } }
[ "public", "function", "reset", "(", "$", "mapper", "=", "true", ")", "{", "if", "(", "$", "mapper", ")", "$", "this", "->", "mapper", "->", "reset", "(", ")", ";", "$", "this", "->", "fieldsCache", "=", "[", "]", ";", "$", "this", "->", "saveCsd"...
reset and re-initialize the mapper @param bool $mapper @return NULL|void
[ "reset", "and", "re", "-", "initialize", "the", "mapper" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2260-L2277
train
ikkez/f3-cortex
lib/db/cortex.php
Cortex.resetFields
public function resetFields(array $fields) { $defaults = $this->defaults(); foreach ($fields as $field) { unset($this->fieldsCache[$field]); unset($this->saveCsd[$field]); if (isset($defaults[$field])) $this->set($field,$defaults[$field]); else { $this->set($field,NULL); } } }
php
public function resetFields(array $fields) { $defaults = $this->defaults(); foreach ($fields as $field) { unset($this->fieldsCache[$field]); unset($this->saveCsd[$field]); if (isset($defaults[$field])) $this->set($field,$defaults[$field]); else { $this->set($field,NULL); } } }
[ "public", "function", "resetFields", "(", "array", "$", "fields", ")", "{", "$", "defaults", "=", "$", "this", "->", "defaults", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "unset", "(", "$", "this", "->", "fieldsCache...
reset only specific fields and return to their default values @param array $fields
[ "reset", "only", "specific", "fields", "and", "return", "to", "their", "default", "values" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2283-L2294
train
ikkez/f3-cortex
lib/db/cortex.php
Cortex.defaults
function defaults($set=false) { $out = []; $fields = $this->fieldConf; if ($this->dbsType == 'sql') $fields = array_replace_recursive($this->mapper->schema(),$fields); foreach($fields as $field_key => $field_conf) if (array_key_exists('default',$field_conf)) { $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) ? date('Y-m-d H:i:s') : $field_conf['default']; if ($val!==NULL) { $out[$field_key]=$val; if ($set) $this->set($field_key, $val); } } return $out; }
php
function defaults($set=false) { $out = []; $fields = $this->fieldConf; if ($this->dbsType == 'sql') $fields = array_replace_recursive($this->mapper->schema(),$fields); foreach($fields as $field_key => $field_conf) if (array_key_exists('default',$field_conf)) { $val = ($field_conf['default'] === \DB\SQL\Schema::DF_CURRENT_TIMESTAMP) ? date('Y-m-d H:i:s') : $field_conf['default']; if ($val!==NULL) { $out[$field_key]=$val; if ($set) $this->set($field_key, $val); } } return $out; }
[ "function", "defaults", "(", "$", "set", "=", "false", ")", "{", "$", "out", "=", "[", "]", ";", "$", "fields", "=", "$", "this", "->", "fieldConf", ";", "if", "(", "$", "this", "->", "dbsType", "==", "'sql'", ")", "$", "fields", "=", "array_repl...
return default values from schema configuration @param bool $set set default values to mapper @return array
[ "return", "default", "values", "from", "schema", "configuration" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2301-L2317
train
ikkez/f3-cortex
lib/db/cortex.php
Cortex.exists
function exists($key, $relField = false) { if (!$this->dry() && $key == '_id') return true; return $this->mapper->exists($key) || ($relField && isset($this->fieldConf[$key]['relType'])); }
php
function exists($key, $relField = false) { if (!$this->dry() && $key == '_id') return true; return $this->mapper->exists($key) || ($relField && isset($this->fieldConf[$key]['relType'])); }
[ "function", "exists", "(", "$", "key", ",", "$", "relField", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "dry", "(", ")", "&&", "$", "key", "==", "'_id'", ")", "return", "true", ";", "return", "$", "this", "->", "mapper", "->", "...
check if a certain field exists in the mapper or or is a virtual relation field @param string $key @param bool $relField @return bool
[ "check", "if", "a", "certain", "field", "exists", "in", "the", "mapper", "or", "or", "is", "a", "virtual", "relation", "field" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2326-L2330
train
ikkez/f3-cortex
lib/db/cortex.php
Cortex.clear
function clear($key) { unset($this->fieldsCache[$key]); if (isset($this->fieldConf[$key]['relType'])) $this->set($key,null); $this->mapper->clear($key); }
php
function clear($key) { unset($this->fieldsCache[$key]); if (isset($this->fieldConf[$key]['relType'])) $this->set($key,null); $this->mapper->clear($key); }
[ "function", "clear", "(", "$", "key", ")", "{", "unset", "(", "$", "this", "->", "fieldsCache", "[", "$", "key", "]", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "fieldConf", "[", "$", "key", "]", "[", "'relType'", "]", ")", ")", "$",...
clear any mapper field or relation @param string $key @return NULL|void
[ "clear", "any", "mapper", "field", "or", "relation" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2351-L2356
train
ikkez/f3-cortex
lib/db/cortex.php
CortexQueryParser.convertNamedParams
protected function convertNamedParams($parts, $args) { if (empty($args)) return array($parts, $args); $params = array(); $pos = 0; foreach ($parts as &$part) { if (preg_match('/:\w+/i', $part, $match)) { if (!array_key_exists($match[0],$args)) trigger_error(sprintf(self::E_MISSINGBINDKEY, $match[0]),E_USER_ERROR); $part = str_replace($match[0], '?', $part); $params[] = $args[$match[0]]; } elseif (is_int(strpos($part, '?'))) $params[] = $args[$pos++]; unset($part); } return array($parts, $params); }
php
protected function convertNamedParams($parts, $args) { if (empty($args)) return array($parts, $args); $params = array(); $pos = 0; foreach ($parts as &$part) { if (preg_match('/:\w+/i', $part, $match)) { if (!array_key_exists($match[0],$args)) trigger_error(sprintf(self::E_MISSINGBINDKEY, $match[0]),E_USER_ERROR); $part = str_replace($match[0], '?', $part); $params[] = $args[$match[0]]; } elseif (is_int(strpos($part, '?'))) $params[] = $args[$pos++]; unset($part); } return array($parts, $params); }
[ "protected", "function", "convertNamedParams", "(", "$", "parts", ",", "$", "args", ")", "{", "if", "(", "empty", "(", "$", "args", ")", ")", "return", "array", "(", "$", "parts", ",", "$", "args", ")", ";", "$", "params", "=", "array", "(", ")", ...
converts named parameter filter to positional @param $parts @param $args @return array
[ "converts", "named", "parameter", "filter", "to", "positional" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2521-L2537
train
ikkez/f3-cortex
lib/db/cortex.php
CortexQueryParser.sql_quoteCondition
public function sql_quoteCondition($cond, $db) { // https://www.debuggex.com/r/6AXwJ1Y3Aac8aocQ/3 // https://regex101.com/r/yM5vK4/1 // this took me lots of sleepless nights $out = preg_replace_callback('/'. '\w+\((?:(?>[^()]+)|\((?:(?>[^()]+)|^(?R))*\))*\)|'. // exclude SQL function names "foo(" '(?:(\b(?<!:)'. // exclude bind parameter ":foo" '[a-zA-Z_](?:[\w\-_.]+\.?))'. // match only identifier, exclude values '(?=[\s<>=!)]|$))/i', // only when part of condition or within brackets function($match) use($db) { if (!isset($match[1])) return $match[0]; if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[1])) return $match[1]; return $db->quotekey($match[1]); }, $cond); return $out ?: $cond; }
php
public function sql_quoteCondition($cond, $db) { // https://www.debuggex.com/r/6AXwJ1Y3Aac8aocQ/3 // https://regex101.com/r/yM5vK4/1 // this took me lots of sleepless nights $out = preg_replace_callback('/'. '\w+\((?:(?>[^()]+)|\((?:(?>[^()]+)|^(?R))*\))*\)|'. // exclude SQL function names "foo(" '(?:(\b(?<!:)'. // exclude bind parameter ":foo" '[a-zA-Z_](?:[\w\-_.]+\.?))'. // match only identifier, exclude values '(?=[\s<>=!)]|$))/i', // only when part of condition or within brackets function($match) use($db) { if (!isset($match[1])) return $match[0]; if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[1])) return $match[1]; return $db->quotekey($match[1]); }, $cond); return $out ?: $cond; }
[ "public", "function", "sql_quoteCondition", "(", "$", "cond", ",", "$", "db", ")", "{", "// https://www.debuggex.com/r/6AXwJ1Y3Aac8aocQ/3", "// https://regex101.com/r/yM5vK4/1", "// this took me lots of sleepless nights", "$", "out", "=", "preg_replace_callback", "(", "'/'", ...
quote identifiers in condition @param string $cond @param object $db @return string
[ "quote", "identifiers", "in", "condition" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2545-L2562
train
ikkez/f3-cortex
lib/db/cortex.php
CortexQueryParser.sql_prependTableToFields
public function sql_prependTableToFields($cond, $table) { $out = preg_replace_callback('/'. '(\w+\((?:[^)(]+|\((?:[^)(]+|(?R))*\))*\))|'. '(?:(\s)|^|(?<=[(]))'. '([a-zA-Z_](?:[\w\-_]+))'. '(?=[\s<>=!)]|$)/i', function($match) use($table) { if (!isset($match[3])) return $match[1]; if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[3])) return $match[0]; return $match[2].$table.'.'.$match[3]; }, $cond); return $out ?: $cond; }
php
public function sql_prependTableToFields($cond, $table) { $out = preg_replace_callback('/'. '(\w+\((?:[^)(]+|\((?:[^)(]+|(?R))*\))*\))|'. '(?:(\s)|^|(?<=[(]))'. '([a-zA-Z_](?:[\w\-_]+))'. '(?=[\s<>=!)]|$)/i', function($match) use($table) { if (!isset($match[3])) return $match[1]; if (preg_match('/\b(AND|OR|IN|LIKE|NOT)\b/i',$match[3])) return $match[0]; return $match[2].$table.'.'.$match[3]; }, $cond); return $out ?: $cond; }
[ "public", "function", "sql_prependTableToFields", "(", "$", "cond", ",", "$", "table", ")", "{", "$", "out", "=", "preg_replace_callback", "(", "'/'", ".", "'(\\w+\\((?:[^)(]+|\\((?:[^)(]+|(?R))*\\))*\\))|'", ".", "'(?:(\\s)|^|(?<=[(]))'", ".", "'([a-zA-Z_](?:[\\w\\-_]+))...
add table prefix to identifiers which do not have a table prefix yet @param string $cond @param string $table @return string
[ "add", "table", "prefix", "to", "identifiers", "which", "do", "not", "have", "a", "table", "prefix", "yet" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2570-L2584
train
ikkez/f3-cortex
lib/db/cortex.php
CortexQueryParser.prepareOptions
public function prepareOptions($options, $engine, $db) { if (empty($options) || !is_array($options)) return null; switch ($engine) { case 'jig': if (array_key_exists('order', $options)) $options['order'] = preg_replace( ['/(?<=\h)(ASC)(?=\W|$)/i','/(?<=\h)(DESC)(?=\W|$)/i'], ['SORT_ASC','SORT_DESC'],$options['order']); break; case 'mongo': if (array_key_exists('order', $options)) { $sorts = explode(',', $options['order']); $sorting = array(); foreach ($sorts as $sort) { $sp = explode(' ', trim($sort)); $sorting[$sp[0]] = (array_key_exists(1, $sp) && strtoupper($sp[1]) == 'DESC') ? -1 : 1; } $options['order'] = $sorting; } if (array_key_exists('group', $options) && is_string($options['group'])) { $keys = explode(',',$options['group']); $options['group']=array('keys'=>array(),'initial'=>array(), 'reduce'=>'function (obj, prev) {}','finalize'=>''); $keys = array_combine($keys,array_fill(0,count($keys),1)); $options['group']['keys']=$keys; $options['group']['initial']=$keys; } break; case 'sql': $char=substr($db->quotekey(''),0,1); if (array_key_exists('order', $options) && FALSE===strpos($options['order'],$char)) $options['order']=preg_replace_callback( '/(\w+\h?\(|'. // skip function names '\b(?!\w+)(?:\s+\w+)+|' . // skip field args '\)\s+\w+)|'. // skip function args '(\b\d?[a-zA-Z_](?:[\w\-.])*)/i', // match table/field keys function($match) use($db) { if (!isset($match[2])) return $match[1]; return $db->quotekey($match[2]); }, $options['order']); break; } return $options; }
php
public function prepareOptions($options, $engine, $db) { if (empty($options) || !is_array($options)) return null; switch ($engine) { case 'jig': if (array_key_exists('order', $options)) $options['order'] = preg_replace( ['/(?<=\h)(ASC)(?=\W|$)/i','/(?<=\h)(DESC)(?=\W|$)/i'], ['SORT_ASC','SORT_DESC'],$options['order']); break; case 'mongo': if (array_key_exists('order', $options)) { $sorts = explode(',', $options['order']); $sorting = array(); foreach ($sorts as $sort) { $sp = explode(' ', trim($sort)); $sorting[$sp[0]] = (array_key_exists(1, $sp) && strtoupper($sp[1]) == 'DESC') ? -1 : 1; } $options['order'] = $sorting; } if (array_key_exists('group', $options) && is_string($options['group'])) { $keys = explode(',',$options['group']); $options['group']=array('keys'=>array(),'initial'=>array(), 'reduce'=>'function (obj, prev) {}','finalize'=>''); $keys = array_combine($keys,array_fill(0,count($keys),1)); $options['group']['keys']=$keys; $options['group']['initial']=$keys; } break; case 'sql': $char=substr($db->quotekey(''),0,1); if (array_key_exists('order', $options) && FALSE===strpos($options['order'],$char)) $options['order']=preg_replace_callback( '/(\w+\h?\(|'. // skip function names '\b(?!\w+)(?:\s+\w+)+|' . // skip field args '\)\s+\w+)|'. // skip function args '(\b\d?[a-zA-Z_](?:[\w\-.])*)/i', // match table/field keys function($match) use($db) { if (!isset($match[2])) return $match[1]; return $db->quotekey($match[2]); }, $options['order']); break; } return $options; }
[ "public", "function", "prepareOptions", "(", "$", "options", ",", "$", "engine", ",", "$", "db", ")", "{", "if", "(", "empty", "(", "$", "options", ")", "||", "!", "is_array", "(", "$", "options", ")", ")", "return", "null", ";", "switch", "(", "$"...
convert options array syntax to given engine type example: array('order'=>'location') // default direction is ASC array('order'=>'num1 desc, num2 asc') @param array $options @param string $engine @param object $db @return array|null
[ "convert", "options", "array", "syntax", "to", "given", "engine", "type" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2793-L2840
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.setModels
function setModels($models, $init=true) { array_map(array($this,'add'),$models); if ($init) $this->changed = false; }
php
function setModels($models, $init=true) { array_map(array($this,'add'),$models); if ($init) $this->changed = false; }
[ "function", "setModels", "(", "$", "models", ",", "$", "init", "=", "true", ")", "{", "array_map", "(", "array", "(", "$", "this", ",", "'add'", ")", ",", "$", "models", ")", ";", "if", "(", "$", "init", ")", "$", "this", "->", "changed", "=", ...
set a collection of models @param $models
[ "set", "a", "collection", "of", "models" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2867-L2871
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.getRelSet
public function getRelSet($key) { return (isset($this->relSets[$key])) ? $this->relSets[$key] : null; }
php
public function getRelSet($key) { return (isset($this->relSets[$key])) ? $this->relSets[$key] : null; }
[ "public", "function", "getRelSet", "(", "$", "key", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "relSets", "[", "$", "key", "]", ")", ")", "?", "$", "this", "->", "relSets", "[", "$", "key", "]", ":", "null", ";", "}" ]
get a related collection @param $key @return null
[ "get", "a", "related", "collection" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2896-L2898
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.getSubset
public function getSubset($prop, $keys) { if (is_string($keys)) $keys = \Base::instance()->split($keys); if (!is_array($keys)) trigger_error(sprintf(self::E_SubsetKeysValue,gettype($keys)),E_USER_ERROR); if (!$this->hasRelSet($prop) || !($relSet = $this->getRelSet($prop))) return null; foreach ($keys as &$key) { if ($key instanceof \MongoId || $key instanceof \MongoDB\BSON\ObjectId) $key = (string) $key; unset($key); } return array_values(array_intersect_key($relSet, array_flip($keys))); }
php
public function getSubset($prop, $keys) { if (is_string($keys)) $keys = \Base::instance()->split($keys); if (!is_array($keys)) trigger_error(sprintf(self::E_SubsetKeysValue,gettype($keys)),E_USER_ERROR); if (!$this->hasRelSet($prop) || !($relSet = $this->getRelSet($prop))) return null; foreach ($keys as &$key) { if ($key instanceof \MongoId || $key instanceof \MongoDB\BSON\ObjectId) $key = (string) $key; unset($key); } return array_values(array_intersect_key($relSet, array_flip($keys))); }
[ "public", "function", "getSubset", "(", "$", "prop", ",", "$", "keys", ")", "{", "if", "(", "is_string", "(", "$", "keys", ")", ")", "$", "keys", "=", "\\", "Base", "::", "instance", "(", ")", "->", "split", "(", "$", "keys", ")", ";", "if", "(...
get an intersection from a cached relation-set, based on given keys @param string $prop @param array|string $keys @return array
[ "get", "an", "intersection", "from", "a", "cached", "relation", "-", "set", "based", "on", "given", "keys" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2928-L2941
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.getAll
public function getAll($prop, $raw = false) { $out = array(); foreach ($this->getArrayCopy() as $model) { if ($model instanceof Cortex && $model->exists($prop,true)) { $val = $model->get($prop, $raw); if (!empty($val)) $out[] = $val; } elseif($raw) $out[] = $model; } return $out; }
php
public function getAll($prop, $raw = false) { $out = array(); foreach ($this->getArrayCopy() as $model) { if ($model instanceof Cortex && $model->exists($prop,true)) { $val = $model->get($prop, $raw); if (!empty($val)) $out[] = $val; } elseif($raw) $out[] = $model; } return $out; }
[ "public", "function", "getAll", "(", "$", "prop", ",", "$", "raw", "=", "false", ")", "{", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getArrayCopy", "(", ")", "as", "$", "model", ")", "{", "if", "(", "$", "mode...
returns all values of a specified property from all models @param string $prop @param bool $raw @return array
[ "returns", "all", "values", "of", "a", "specified", "property", "from", "all", "models" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2949-L2960
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.castAll
public function castAll($rel_depths=1) { $out = array(); foreach ($this->getArrayCopy() as $model) $out[] = $model->cast(null,$rel_depths); return $out; }
php
public function castAll($rel_depths=1) { $out = array(); foreach ($this->getArrayCopy() as $model) $out[] = $model->cast(null,$rel_depths); return $out; }
[ "public", "function", "castAll", "(", "$", "rel_depths", "=", "1", ")", "{", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getArrayCopy", "(", ")", "as", "$", "model", ")", "$", "out", "[", "]", "=", "$", "model", ...
cast all contained mappers to a nested array @param int|array $rel_depths depths to resolve relations @return array
[ "cast", "all", "contained", "mappers", "to", "a", "nested", "array" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2967-L2972
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.getBy
public function getBy($index, $nested = false) { $out = array(); foreach ($this->getArrayCopy() as $model) if ($model->exists($index)) { $val = $model->get($index, true); if (!empty($val)) if($nested) $out[(string) $val][] = $model; else $out[(string) $val] = $model; } return $out; }
php
public function getBy($index, $nested = false) { $out = array(); foreach ($this->getArrayCopy() as $model) if ($model->exists($index)) { $val = $model->get($index, true); if (!empty($val)) if($nested) $out[(string) $val][] = $model; else $out[(string) $val] = $model; } return $out; }
[ "public", "function", "getBy", "(", "$", "index", ",", "$", "nested", "=", "false", ")", "{", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getArrayCopy", "(", ")", "as", "$", "model", ")", "if", "(", "$", "model", ...
return all models keyed by a specified index key @param string $index @param bool $nested @return array
[ "return", "all", "models", "keyed", "by", "a", "specified", "index", "key" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2980-L2990
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.orderBy
public function orderBy($cond) { $cols=\Base::instance()->split($cond); $this->uasort(function($val1,$val2) use($cols) { foreach ($cols as $col) { $parts=explode(' ',$col,2); $order=empty($parts[1])?'ASC':$parts[1]; $col=$parts[0]; list($v1,$v2)=array($val1[$col],$val2[$col]); if ($out=strnatcmp($v1,$v2)* ((strtoupper($order)=='ASC')*2-1)) return $out; } return 0; }); }
php
public function orderBy($cond) { $cols=\Base::instance()->split($cond); $this->uasort(function($val1,$val2) use($cols) { foreach ($cols as $col) { $parts=explode(' ',$col,2); $order=empty($parts[1])?'ASC':$parts[1]; $col=$parts[0]; list($v1,$v2)=array($val1[$col],$val2[$col]); if ($out=strnatcmp($v1,$v2)* ((strtoupper($order)=='ASC')*2-1)) return $out; } return 0; }); }
[ "public", "function", "orderBy", "(", "$", "cond", ")", "{", "$", "cols", "=", "\\", "Base", "::", "instance", "(", ")", "->", "split", "(", "$", "cond", ")", ";", "$", "this", "->", "uasort", "(", "function", "(", "$", "val1", ",", "$", "val2", ...
re-assort the current collection using a sql-like syntax @param $cond
[ "re", "-", "assort", "the", "current", "collection", "using", "a", "sql", "-", "like", "syntax" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L2996-L3010
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.slice
public function slice($offset, $limit=null) { $this->rewind(); $i=0; $del=array(); while ($this->valid()) { if ($i < $offset) $del[]=$this->key(); elseif ($i >= $offset && $limit && $i >= ($offset+$limit)) $del[]=$this->key(); $i++; $this->next(); } foreach ($del as $ii) unset($this[$ii]); }
php
public function slice($offset, $limit=null) { $this->rewind(); $i=0; $del=array(); while ($this->valid()) { if ($i < $offset) $del[]=$this->key(); elseif ($i >= $offset && $limit && $i >= ($offset+$limit)) $del[]=$this->key(); $i++; $this->next(); } foreach ($del as $ii) unset($this[$ii]); }
[ "public", "function", "slice", "(", "$", "offset", ",", "$", "limit", "=", "null", ")", "{", "$", "this", "->", "rewind", "(", ")", ";", "$", "i", "=", "0", ";", "$", "del", "=", "array", "(", ")", ";", "while", "(", "$", "this", "->", "valid...
slice the collection @param $offset @param null $limit
[ "slice", "the", "collection" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L3017-L3031
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.compare
public function compare($stack,$cpm_key='_id') { if ($stack instanceof CortexCollection) $stack = $stack->getAll($cpm_key,true); $keys = $this->getAll($cpm_key,true); $out = []; $new = array_diff($stack,$keys); $old = array_diff($keys,$stack); if ($new) $out['new'] = $new; if ($old) $out['old'] = $old; return $out; }
php
public function compare($stack,$cpm_key='_id') { if ($stack instanceof CortexCollection) $stack = $stack->getAll($cpm_key,true); $keys = $this->getAll($cpm_key,true); $out = []; $new = array_diff($stack,$keys); $old = array_diff($keys,$stack); if ($new) $out['new'] = $new; if ($old) $out['old'] = $old; return $out; }
[ "public", "function", "compare", "(", "$", "stack", ",", "$", "cpm_key", "=", "'_id'", ")", "{", "if", "(", "$", "stack", "instanceof", "CortexCollection", ")", "$", "stack", "=", "$", "stack", "->", "getAll", "(", "$", "cpm_key", ",", "true", ")", "...
compare collection with a given ID stack @param array|CortexCollection $stack @param string $cpm_key @return array
[ "compare", "collection", "with", "a", "given", "ID", "stack" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L3039-L3051
train
ikkez/f3-cortex
lib/db/cortex.php
CortexCollection.contains
public function contains($val,$key='_id') { $rel_ids = $this->getAll($key, true); if ($val instanceof Cursor) $val = $val->{$key}; return in_array($val,$rel_ids); }
php
public function contains($val,$key='_id') { $rel_ids = $this->getAll($key, true); if ($val instanceof Cursor) $val = $val->{$key}; return in_array($val,$rel_ids); }
[ "public", "function", "contains", "(", "$", "val", ",", "$", "key", "=", "'_id'", ")", "{", "$", "rel_ids", "=", "$", "this", "->", "getAll", "(", "$", "key", ",", "true", ")", ";", "if", "(", "$", "val", "instanceof", "Cursor", ")", "$", "val", ...
check if the collection contains a record with the given key-val set @param mixed $val @param string $key @return bool
[ "check", "if", "the", "collection", "contains", "a", "record", "with", "the", "given", "key", "-", "val", "set" ]
48c1b90e84ada2d539125708f520b6814f54a308
https://github.com/ikkez/f3-cortex/blob/48c1b90e84ada2d539125708f520b6814f54a308/lib/db/cortex.php#L3059-L3064
train
alexpechkarev/google-maps
src/GoogleMaps.php
GoogleMaps.load
public function load( $service ){ // is overwrite class specified $class = array_key_exists($service, $this->webServices) ? new $this->webServices[$service] : $this; $class->build( $service ); return $class; }
php
public function load( $service ){ // is overwrite class specified $class = array_key_exists($service, $this->webServices) ? new $this->webServices[$service] : $this; $class->build( $service ); return $class; }
[ "public", "function", "load", "(", "$", "service", ")", "{", "// is overwrite class specified ", "$", "class", "=", "array_key_exists", "(", "$", "service", ",", "$", "this", "->", "webServices", ")", "?", "new", "$", "this", "->", "webServices", "[", "$", ...
Bootstraping Web Service @param string $service @return \GoogleMaps\WebService
[ "Bootstraping", "Web", "Service" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/GoogleMaps.php#L26-L36
train
alexpechkarev/google-maps
src/Parameters.php
Parameters.joinParam
protected static function joinParam( $param = [], $join = '=', $glue = '&', $useKey = true){ $allParam = []; foreach ($param as $key => $val) { if( is_array( $val ) ){ if ($useKey && isset($val[0]) && is_array($val[0]) === false) { $newValue = []; foreach ($val as $element) { $newValue[] = $key . $join . self::replaceCharacters($element); } return implode($glue, $newValue); } else { $val = self::joinParam( $val, $join, $glue, $useKey); } } // ommit parameters with empty values if( !empty( $val )){ #self::$urlParam[] = $useKey $allParam[] = $useKey ? $key . $join .urlencode(URLify::downcode($val)) : $join .urlencode(URLify::downcode($val)); } } // no parameters given if( is_null( $allParam ) ) { return ''; } $allParam = self::replaceCharacters($allParam); return implode($glue, $allParam ); }
php
protected static function joinParam( $param = [], $join = '=', $glue = '&', $useKey = true){ $allParam = []; foreach ($param as $key => $val) { if( is_array( $val ) ){ if ($useKey && isset($val[0]) && is_array($val[0]) === false) { $newValue = []; foreach ($val as $element) { $newValue[] = $key . $join . self::replaceCharacters($element); } return implode($glue, $newValue); } else { $val = self::joinParam( $val, $join, $glue, $useKey); } } // ommit parameters with empty values if( !empty( $val )){ #self::$urlParam[] = $useKey $allParam[] = $useKey ? $key . $join .urlencode(URLify::downcode($val)) : $join .urlencode(URLify::downcode($val)); } } // no parameters given if( is_null( $allParam ) ) { return ''; } $allParam = self::replaceCharacters($allParam); return implode($glue, $allParam ); }
[ "protected", "static", "function", "joinParam", "(", "$", "param", "=", "[", "]", ",", "$", "join", "=", "'='", ",", "$", "glue", "=", "'&'", ",", "$", "useKey", "=", "true", ")", "{", "$", "allParam", "=", "[", "]", ";", "foreach", "(", "$", "...
Join array pairs into URL encoded string @param array $param - single dimension array @param string $join @param string $glue @param boolean $useKey @return string
[ "Join", "array", "pairs", "into", "URL", "encoded", "string" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/Parameters.php#L104-L142
train
alexpechkarev/google-maps
src/Parameters.php
Parameters.replaceCharacters
private static function replaceCharacters($allParam) { // replace special characters $allParam = str_replace(['%252C'], [','], $allParam); $allParam = str_replace(['%3A'], [':'], $allParam); return str_replace(['%7C'], ['|'], $allParam); }
php
private static function replaceCharacters($allParam) { // replace special characters $allParam = str_replace(['%252C'], [','], $allParam); $allParam = str_replace(['%3A'], [':'], $allParam); return str_replace(['%7C'], ['|'], $allParam); }
[ "private", "static", "function", "replaceCharacters", "(", "$", "allParam", ")", "{", "// replace special characters", "$", "allParam", "=", "str_replace", "(", "[", "'%252C'", "]", ",", "[", "','", "]", ",", "$", "allParam", ")", ";", "$", "allParam", "=", ...
Replace special characters @param array $allParam @return mixed
[ "Replace", "special", "characters" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/Parameters.php#L149-L155
train
alexpechkarev/google-maps
src/WebService.php
WebService.setParamByKey
public function setParamByKey($key, $value){ if( array_key_exists( $key, array_dot( $this->service['param'] ) ) ){ array_set($this->service['param'], $key, $value); } return $this; }
php
public function setParamByKey($key, $value){ if( array_key_exists( $key, array_dot( $this->service['param'] ) ) ){ array_set($this->service['param'], $key, $value); } return $this; }
[ "public", "function", "setParamByKey", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "array_dot", "(", "$", "this", "->", "service", "[", "'param'", "]", ")", ")", ")", "{", "array_set", "(", "$", ...
Set parameter by key @param string $key @param string $value @return $this
[ "Set", "parameter", "by", "key" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L108-L116
train
alexpechkarev/google-maps
src/WebService.php
WebService.getParamByKey
public function getParamByKey($key){ if( array_key_exists( $key, array_dot( $this->service['param'] ) ) ){ return array_get($this->service['param'], $key); } }
php
public function getParamByKey($key){ if( array_key_exists( $key, array_dot( $this->service['param'] ) ) ){ return array_get($this->service['param'], $key); } }
[ "public", "function", "getParamByKey", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "array_dot", "(", "$", "this", "->", "service", "[", "'param'", "]", ")", ")", ")", "{", "return", "array_get", "(", "$", "this", "...
Get parameter by the key @param string $key @return mixed
[ "Get", "parameter", "by", "the", "key" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L125-L131
train
alexpechkarev/google-maps
src/WebService.php
WebService.getResponseByKey
public function getResponseByKey( $needle = false, $offset = 0, $length = null ){ // set respons to json $this->setEndpoint('json'); // set default key parameter $needle = empty( $needle ) ? metaphone($this->service['responseDefaultKey']) : metaphone($needle); // get response $obj = json_decode( $this->get(), true); // flatten array into single level array using 'dot' notation $obj_dot = array_dot($obj); // create empty response $response = []; // iterate foreach( $obj_dot as $key => $val){ // Calculate the metaphone key and compare with needle if( strcmp( metaphone($key, strlen($needle)), $needle) === 0 ){ // set response value array_set($response, $key, $val); } } // finally extract slice of the array #return array_slice($response, $offset, $length); return count($response) < 1 ? $obj : $response; }
php
public function getResponseByKey( $needle = false, $offset = 0, $length = null ){ // set respons to json $this->setEndpoint('json'); // set default key parameter $needle = empty( $needle ) ? metaphone($this->service['responseDefaultKey']) : metaphone($needle); // get response $obj = json_decode( $this->get(), true); // flatten array into single level array using 'dot' notation $obj_dot = array_dot($obj); // create empty response $response = []; // iterate foreach( $obj_dot as $key => $val){ // Calculate the metaphone key and compare with needle if( strcmp( metaphone($key, strlen($needle)), $needle) === 0 ){ // set response value array_set($response, $key, $val); } } // finally extract slice of the array #return array_slice($response, $offset, $length); return count($response) < 1 ? $obj : $response; }
[ "public", "function", "getResponseByKey", "(", "$", "needle", "=", "false", ",", "$", "offset", "=", "0", ",", "$", "length", "=", "null", ")", "{", "// set respons to json", "$", "this", "->", "setEndpoint", "(", "'json'", ")", ";", "// set default key para...
Get response value by key @param string $needle - retrieves response parameter using "dot" notation @param int $offset @param int $length @return array
[ "Get", "response", "value", "by", "key" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L179-L214
train
alexpechkarev/google-maps
src/WebService.php
WebService.build
protected function build( $service ){ $this->validateConfig( $service ); // set default endpoint $this->setEndpoint(); // set web service parameters $this->service = config('googlemaps.service.'.$service); // is service key set, use it, otherwise use default key $this->key = empty( $this->service['key'] ) ? config('googlemaps.key') : $this->service['key']; // set service url $this->requestUrl = $this->service['url']; // is ssl_verify_peer key set, use it, otherwise use default key $this->verifySSL = empty(config('googlemaps.ssl_verify_peer')) ? FALSE :config('googlemaps.ssl_verify_peer'); $this->clearParameters(); }
php
protected function build( $service ){ $this->validateConfig( $service ); // set default endpoint $this->setEndpoint(); // set web service parameters $this->service = config('googlemaps.service.'.$service); // is service key set, use it, otherwise use default key $this->key = empty( $this->service['key'] ) ? config('googlemaps.key') : $this->service['key']; // set service url $this->requestUrl = $this->service['url']; // is ssl_verify_peer key set, use it, otherwise use default key $this->verifySSL = empty(config('googlemaps.ssl_verify_peer')) ? FALSE :config('googlemaps.ssl_verify_peer'); $this->clearParameters(); }
[ "protected", "function", "build", "(", "$", "service", ")", "{", "$", "this", "->", "validateConfig", "(", "$", "service", ")", ";", "// set default endpoint", "$", "this", "->", "setEndpoint", "(", ")", ";", "// set web service parameters", "$", "this", "->",...
Setup service parameters
[ "Setup", "service", "parameters" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L249-L273
train
alexpechkarev/google-maps
src/WebService.php
WebService.validateConfig
protected function validateConfig( $service ){ // Check for config file if( !\Config::has('googlemaps')){ throw new \ErrorException('Unable to find config file.'); } // Validate Key parameter if(!array_key_exists('key', config('googlemaps') ) ){ throw new \ErrorException('Unable to find Key parameter in configuration file.'); } // Validate Key parameter if(!array_key_exists('service', config('googlemaps') ) && !array_key_exists($service, config('googlemaps.service')) ){ throw new \ErrorException('Web service must be declared in the configuration file.'); } // Validate Endpoint $endpointCount = count(config('googlemaps.endpoint')); $endpointsKeyExists = array_key_exists('endpoint', config('googlemaps')); if($endpointsKeyExists === false || $endpointCount < 1){ throw new \ErrorException('End point must not be empty.'); } }
php
protected function validateConfig( $service ){ // Check for config file if( !\Config::has('googlemaps')){ throw new \ErrorException('Unable to find config file.'); } // Validate Key parameter if(!array_key_exists('key', config('googlemaps') ) ){ throw new \ErrorException('Unable to find Key parameter in configuration file.'); } // Validate Key parameter if(!array_key_exists('service', config('googlemaps') ) && !array_key_exists($service, config('googlemaps.service')) ){ throw new \ErrorException('Web service must be declared in the configuration file.'); } // Validate Endpoint $endpointCount = count(config('googlemaps.endpoint')); $endpointsKeyExists = array_key_exists('endpoint', config('googlemaps')); if($endpointsKeyExists === false || $endpointCount < 1){ throw new \ErrorException('End point must not be empty.'); } }
[ "protected", "function", "validateConfig", "(", "$", "service", ")", "{", "// Check for config file", "if", "(", "!", "\\", "Config", "::", "has", "(", "'googlemaps'", ")", ")", "{", "throw", "new", "\\", "ErrorException", "(", "'Unable to find config file.'", "...
Validate configuration file @throws \ErrorException
[ "Validate", "configuration", "file" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L281-L311
train
alexpechkarev/google-maps
src/WebService.php
WebService.make
protected function make( $isPost = false ){ $ch = curl_init( $this->requestUrl ); if( $isPost ){ curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS, $isPost ); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifySSL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $output = curl_exec($ch); if( $output === false ){ throw new \ErrorException( curl_error($ch) ); } curl_close($ch); return $output; }
php
protected function make( $isPost = false ){ $ch = curl_init( $this->requestUrl ); if( $isPost ){ curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS, $isPost ); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifySSL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $output = curl_exec($ch); if( $output === false ){ throw new \ErrorException( curl_error($ch) ); } curl_close($ch); return $output; }
[ "protected", "function", "make", "(", "$", "isPost", "=", "false", ")", "{", "$", "ch", "=", "curl_init", "(", "$", "this", "->", "requestUrl", ")", ";", "if", "(", "$", "isPost", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",...
Make cURL request to given URL @param boolean $isPost @return object
[ "Make", "cURL", "request", "to", "given", "URL" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/WebService.php#L361-L386
train
alexpechkarev/google-maps
src/Directions.php
Directions.decode
protected function decode( $rsp, $param = 'routes.overview_polyline.points' ){ $needle = metaphone($param); // get response $obj = json_decode( $rsp, true); // flatten array into single level array using 'dot' notation $obj_dot = array_dot($obj); // create empty response $response = []; // iterate foreach( $obj_dot as $key => $val){ // Calculate the metaphone key and compare with needle $val = strcmp( metaphone($key, strlen($needle)), $needle) === 0 ? PolyUtil::decode($val) // if matched decode polyline : $val; array_set($response, $key, $val); } return json_encode($response, JSON_PRETTY_PRINT) ; }
php
protected function decode( $rsp, $param = 'routes.overview_polyline.points' ){ $needle = metaphone($param); // get response $obj = json_decode( $rsp, true); // flatten array into single level array using 'dot' notation $obj_dot = array_dot($obj); // create empty response $response = []; // iterate foreach( $obj_dot as $key => $val){ // Calculate the metaphone key and compare with needle $val = strcmp( metaphone($key, strlen($needle)), $needle) === 0 ? PolyUtil::decode($val) // if matched decode polyline : $val; array_set($response, $key, $val); } return json_encode($response, JSON_PRETTY_PRINT) ; }
[ "protected", "function", "decode", "(", "$", "rsp", ",", "$", "param", "=", "'routes.overview_polyline.points'", ")", "{", "$", "needle", "=", "metaphone", "(", "$", "param", ")", ";", "// get response", "$", "obj", "=", "json_decode", "(", "$", "rsp", ","...
Get web wervice polyline parameter being decoded @param $rsp - string @param string $param - response key @return string - JSON
[ "Get", "web", "wervice", "polyline", "parameter", "being", "decoded" ]
4d88e626c566f14df93046ec9a047cf3a6fa13dd
https://github.com/alexpechkarev/google-maps/blob/4d88e626c566f14df93046ec9a047cf3a6fa13dd/src/Directions.php#L93-L120
train
appstract/laravel-opcache
src/Http/Middleware/Request.php
Request.isAllowed
protected function isAllowed($request) { try { $decrypted = Crypt::decrypt($request->get('key')); } catch (DecryptException $e) { $decrypted = ''; } return $decrypted == 'opcache' || in_array($this->getRequestIp($request), [$this->getServerIp(), '127.0.0.1', '::1']); }
php
protected function isAllowed($request) { try { $decrypted = Crypt::decrypt($request->get('key')); } catch (DecryptException $e) { $decrypted = ''; } return $decrypted == 'opcache' || in_array($this->getRequestIp($request), [$this->getServerIp(), '127.0.0.1', '::1']); }
[ "protected", "function", "isAllowed", "(", "$", "request", ")", "{", "try", "{", "$", "decrypted", "=", "Crypt", "::", "decrypt", "(", "$", "request", "->", "get", "(", "'key'", ")", ")", ";", "}", "catch", "(", "DecryptException", "$", "e", ")", "{"...
Check if the request is allowed. @param $request @return bool
[ "Check", "if", "the", "request", "is", "allowed", "." ]
ef41a0f5e6d717317d5434b39add6e17152b620b
https://github.com/appstract/laravel-opcache/blob/ef41a0f5e6d717317d5434b39add6e17152b620b/src/Http/Middleware/Request.php#L40-L49
train
appstract/laravel-opcache
src/Http/Middleware/Request.php
Request.getRequestIp
protected function getRequestIp($request) { if ($request->server('HTTP_CF_CONNECTING_IP')) { // cloudflare return $request->server('HTTP_CF_CONNECTING_IP'); } if ($request->server('X_FORWARDED_FOR')) { // forwarded proxy return $request->server('X_FORWARDED_FOR'); } if ($request->server('REMOTE_ADDR')) { // remote header return $request->server('REMOTE_ADDR'); } }
php
protected function getRequestIp($request) { if ($request->server('HTTP_CF_CONNECTING_IP')) { // cloudflare return $request->server('HTTP_CF_CONNECTING_IP'); } if ($request->server('X_FORWARDED_FOR')) { // forwarded proxy return $request->server('X_FORWARDED_FOR'); } if ($request->server('REMOTE_ADDR')) { // remote header return $request->server('REMOTE_ADDR'); } }
[ "protected", "function", "getRequestIp", "(", "$", "request", ")", "{", "if", "(", "$", "request", "->", "server", "(", "'HTTP_CF_CONNECTING_IP'", ")", ")", "{", "// cloudflare", "return", "$", "request", "->", "server", "(", "'HTTP_CF_CONNECTING_IP'", ")", ";...
Get ip from different request headers. @param $request @return mixed
[ "Get", "ip", "from", "different", "request", "headers", "." ]
ef41a0f5e6d717317d5434b39add6e17152b620b
https://github.com/appstract/laravel-opcache/blob/ef41a0f5e6d717317d5434b39add6e17152b620b/src/Http/Middleware/Request.php#L58-L74
train
appstract/laravel-opcache
src/OpcacheClass.php
OpcacheClass.optimize
public function optimize() { if (! function_exists('opcache_compile_file')) { return false; } // Get files in these paths $files = File::allFiles(config('opcache.directories')); $files = collect($files); // filter on php extension $files = $files->filter(function ($value) { return File::extension($value) == 'php'; }); // optimized files $optimized = 0; $files->each(function ($file) use (&$optimized) { if (! opcache_is_script_cached($file)) { if (@opcache_compile_file($file)) { $optimized++; } } }); return [ 'total_files_count' => $files->count(), 'compiled_count' => $optimized, ]; }
php
public function optimize() { if (! function_exists('opcache_compile_file')) { return false; } // Get files in these paths $files = File::allFiles(config('opcache.directories')); $files = collect($files); // filter on php extension $files = $files->filter(function ($value) { return File::extension($value) == 'php'; }); // optimized files $optimized = 0; $files->each(function ($file) use (&$optimized) { if (! opcache_is_script_cached($file)) { if (@opcache_compile_file($file)) { $optimized++; } } }); return [ 'total_files_count' => $files->count(), 'compiled_count' => $optimized, ]; }
[ "public", "function", "optimize", "(", ")", "{", "if", "(", "!", "function_exists", "(", "'opcache_compile_file'", ")", ")", "{", "return", "false", ";", "}", "// Get files in these paths", "$", "files", "=", "File", "::", "allFiles", "(", "config", "(", "'o...
Precompile app. @return bool | array
[ "Precompile", "app", "." ]
ef41a0f5e6d717317d5434b39add6e17152b620b
https://github.com/appstract/laravel-opcache/blob/ef41a0f5e6d717317d5434b39add6e17152b620b/src/OpcacheClass.php#L71-L102
train
appstract/laravel-opcache
src/Commands/Status.php
Status.displayTables
protected function displayTables($data) { $this->line('General:'); $general = (array) $data; unset($general['memory_usage'], $general['interned_strings_usage'], $general['opcache_statistics']); $this->table(['key', 'value'], $this->parseTable($general)); $this->line(PHP_EOL.'Memory usage:'); $this->table(['key', 'value'], $this->parseTable($data->memory_usage)); $this->line(PHP_EOL.'Interned strings usage:'); $this->table(['key', 'value'], $this->parseTable($data->interned_strings_usage)); $this->line(PHP_EOL.'Statistics:'); $this->table(['option', 'value'], $this->parseTable($data->opcache_statistics)); }
php
protected function displayTables($data) { $this->line('General:'); $general = (array) $data; unset($general['memory_usage'], $general['interned_strings_usage'], $general['opcache_statistics']); $this->table(['key', 'value'], $this->parseTable($general)); $this->line(PHP_EOL.'Memory usage:'); $this->table(['key', 'value'], $this->parseTable($data->memory_usage)); $this->line(PHP_EOL.'Interned strings usage:'); $this->table(['key', 'value'], $this->parseTable($data->interned_strings_usage)); $this->line(PHP_EOL.'Statistics:'); $this->table(['option', 'value'], $this->parseTable($data->opcache_statistics)); }
[ "protected", "function", "displayTables", "(", "$", "data", ")", "{", "$", "this", "->", "line", "(", "'General:'", ")", ";", "$", "general", "=", "(", "array", ")", "$", "data", ";", "unset", "(", "$", "general", "[", "'memory_usage'", "]", ",", "$"...
Display info tables. @param $data
[ "Display", "info", "tables", "." ]
ef41a0f5e6d717317d5434b39add6e17152b620b
https://github.com/appstract/laravel-opcache/blob/ef41a0f5e6d717317d5434b39add6e17152b620b/src/Commands/Status.php#L53-L68
train
appstract/laravel-opcache
src/Commands/Status.php
Status.parseTable
protected function parseTable($input) { $input = (array) $input; return array_map(function ($key, $value) { $bytes = ['used_memory', 'free_memory', 'wasted_memory', 'buffer_size']; $times = ['start_time', 'last_restart_time']; if (in_array($key, $bytes)) { $value = number_format($value / 1048576, 2).' MB'; } elseif (in_array($key, $times)) { $value = date('Y-m-d H:i:s', $value); } return [ 'key' => $key, 'value' => $value, ]; }, array_keys($input), $input); }
php
protected function parseTable($input) { $input = (array) $input; return array_map(function ($key, $value) { $bytes = ['used_memory', 'free_memory', 'wasted_memory', 'buffer_size']; $times = ['start_time', 'last_restart_time']; if (in_array($key, $bytes)) { $value = number_format($value / 1048576, 2).' MB'; } elseif (in_array($key, $times)) { $value = date('Y-m-d H:i:s', $value); } return [ 'key' => $key, 'value' => $value, ]; }, array_keys($input), $input); }
[ "protected", "function", "parseTable", "(", "$", "input", ")", "{", "$", "input", "=", "(", "array", ")", "$", "input", ";", "return", "array_map", "(", "function", "(", "$", "key", ",", "$", "value", ")", "{", "$", "bytes", "=", "[", "'used_memory'"...
Make up the table for console display. @param $input @return array
[ "Make", "up", "the", "table", "for", "console", "display", "." ]
ef41a0f5e6d717317d5434b39add6e17152b620b
https://github.com/appstract/laravel-opcache/blob/ef41a0f5e6d717317d5434b39add6e17152b620b/src/Commands/Status.php#L77-L96
train
Waavi/translation
src/UriLocalizer.php
UriLocalizer.localeFromRequest
public function localeFromRequest($segment = 0) { $url = $this->request->getUri(); return $this->getLocaleFromUrl($url, $segment); }
php
public function localeFromRequest($segment = 0) { $url = $this->request->getUri(); return $this->getLocaleFromUrl($url, $segment); }
[ "public", "function", "localeFromRequest", "(", "$", "segment", "=", "0", ")", "{", "$", "url", "=", "$", "this", "->", "request", "->", "getUri", "(", ")", ";", "return", "$", "this", "->", "getLocaleFromUrl", "(", "$", "url", ",", "$", "segment", "...
Returns the locale present in the current url, if any. @param integer $segment Index of the segment containing locale info @return string
[ "Returns", "the", "locale", "present", "in", "the", "current", "url", "if", "any", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/UriLocalizer.php#L24-L28
train
Waavi/translation
src/UriLocalizer.php
UriLocalizer.pathFromParsedUrl
protected function pathFromParsedUrl($parsedUrl) { $path = '/' . implode('/', $parsedUrl['segments']); if ($parsedUrl['query']) { $path .= "?{$parsedUrl['query']}"; } if ($parsedUrl['fragment']) { $path .= "#{$parsedUrl['fragment']}"; } return $path; }
php
protected function pathFromParsedUrl($parsedUrl) { $path = '/' . implode('/', $parsedUrl['segments']); if ($parsedUrl['query']) { $path .= "?{$parsedUrl['query']}"; } if ($parsedUrl['fragment']) { $path .= "#{$parsedUrl['fragment']}"; } return $path; }
[ "protected", "function", "pathFromParsedUrl", "(", "$", "parsedUrl", ")", "{", "$", "path", "=", "'/'", ".", "implode", "(", "'/'", ",", "$", "parsedUrl", "[", "'segments'", "]", ")", ";", "if", "(", "$", "parsedUrl", "[", "'query'", "]", ")", "{", "...
Returns the uri for the given parsed url based on its segments, query and fragment @return string
[ "Returns", "the", "uri", "for", "the", "given", "parsed", "url", "based", "on", "its", "segments", "query", "and", "fragment" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/UriLocalizer.php#L110-L120
train
Waavi/translation
src/Cache/TaggedRepository.php
TaggedRepository.flush
public function flush($locale, $group, $namespace) { $key = $this->getKey($locale, $group, $namespace); $this->store->tags([$key])->flush(); }
php
public function flush($locale, $group, $namespace) { $key = $this->getKey($locale, $group, $namespace); $this->store->tags([$key])->flush(); }
[ "public", "function", "flush", "(", "$", "locale", ",", "$", "group", ",", "$", "namespace", ")", "{", "$", "key", "=", "$", "this", "->", "getKey", "(", "$", "locale", ",", "$", "group", ",", "$", "namespace", ")", ";", "$", "this", "->", "store...
Flush the cache for the given entries @param string $locale @param string $group @param string $namespace @return void
[ "Flush", "the", "cache", "for", "the", "given", "entries" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Cache/TaggedRepository.php#L84-L88
train
Waavi/translation
src/TranslationServiceProvider.php
TranslationServiceProvider.registerCacheRepository
public function registerCacheRepository() { $this->app->singleton('translation.cache.repository', function ($app) { $cacheStore = $app['cache']->getStore(); return CacheRepositoryFactory::make($cacheStore, $app['config']->get('translator.cache.suffix')); }); }
php
public function registerCacheRepository() { $this->app->singleton('translation.cache.repository', function ($app) { $cacheStore = $app['cache']->getStore(); return CacheRepositoryFactory::make($cacheStore, $app['config']->get('translator.cache.suffix')); }); }
[ "public", "function", "registerCacheRepository", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'translation.cache.repository'", ",", "function", "(", "$", "app", ")", "{", "$", "cacheStore", "=", "$", "app", "[", "'cache'", "]", "->", "...
Register the translation cache repository @return void
[ "Register", "the", "translation", "cache", "repository" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/TranslationServiceProvider.php#L109-L115
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.update
public function update($id, $text) { $translation = $this->find($id); if (!$translation || $translation->isLocked()) { return false; } $translation->text = $text; $saved = $translation->save(); if ($saved && $translation->locale === $this->defaultLocale) { $this->flagAsUnstable($translation->namespace, $translation->group, $translation->item); } return $saved; }
php
public function update($id, $text) { $translation = $this->find($id); if (!$translation || $translation->isLocked()) { return false; } $translation->text = $text; $saved = $translation->save(); if ($saved && $translation->locale === $this->defaultLocale) { $this->flagAsUnstable($translation->namespace, $translation->group, $translation->item); } return $saved; }
[ "public", "function", "update", "(", "$", "id", ",", "$", "text", ")", "{", "$", "translation", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "translation", "||", "$", "translation", "->", "isLocked", "(", ")", ")...
Update a translation. If the translation is locked, no update will be made. @param array $attributes Model attributes @return boolean
[ "Update", "a", "translation", ".", "If", "the", "translation", "is", "locked", "no", "update", "will", "be", "made", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L69-L81
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.updateDefaultByCode
public function updateDefaultByCode($code, $text) { list($namespace, $group, $item) = $this->parseCode($code); $locale = $this->defaultLocale; $translation = $this->model->whereLocale($locale)->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->first(); if (!$translation) { return $this->create(compact('locale', 'namespace', 'group', 'item', 'text')); } return $this->update($translation->id, $text); }
php
public function updateDefaultByCode($code, $text) { list($namespace, $group, $item) = $this->parseCode($code); $locale = $this->defaultLocale; $translation = $this->model->whereLocale($locale)->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->first(); if (!$translation) { return $this->create(compact('locale', 'namespace', 'group', 'item', 'text')); } return $this->update($translation->id, $text); }
[ "public", "function", "updateDefaultByCode", "(", "$", "code", ",", "$", "text", ")", "{", "list", "(", "$", "namespace", ",", "$", "group", ",", "$", "item", ")", "=", "$", "this", "->", "parseCode", "(", "$", "code", ")", ";", "$", "locale", "=",...
Insert or Update entry by translation code for the default locale. @param string $code @param string $text @return boolean
[ "Insert", "or", "Update", "entry", "by", "translation", "code", "for", "the", "default", "locale", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L113-L122
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.delete
public function delete($id) { $translation = $this->find($id); if (!$translation) { return false; } if ($translation->locale === $this->defaultLocale) { return $this->model->whereNamespace($translation->namespace)->whereGroup($translation->group)->whereItem($translation->item)->delete(); } else { return $translation->delete(); } }
php
public function delete($id) { $translation = $this->find($id); if (!$translation) { return false; } if ($translation->locale === $this->defaultLocale) { return $this->model->whereNamespace($translation->namespace)->whereGroup($translation->group)->whereItem($translation->item)->delete(); } else { return $translation->delete(); } }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "translation", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "translation", ")", "{", "return", "false", ";", "}", "if", "(", "$", "translation", "->"...
Delete a translation. If the translation is of the default language, delete all translations with the same namespace, group and item @param integer $id @return boolean
[ "Delete", "a", "translation", ".", "If", "the", "translation", "is", "of", "the", "default", "language", "delete", "all", "translations", "with", "the", "same", "namespace", "group", "and", "item" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L130-L142
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.deleteByCode
public function deleteByCode($code) { list($namespace, $group, $item) = $this->parseCode($code); $this->model->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->delete(); }
php
public function deleteByCode($code) { list($namespace, $group, $item) = $this->parseCode($code); $this->model->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->delete(); }
[ "public", "function", "deleteByCode", "(", "$", "code", ")", "{", "list", "(", "$", "namespace", ",", "$", "group", ",", "$", "item", ")", "=", "$", "this", "->", "parseCode", "(", "$", "code", ")", ";", "$", "this", "->", "model", "->", "whereName...
Delete all entries by code @param string $code @return boolean
[ "Delete", "all", "entries", "by", "code" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L150-L154
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.loadArray
public function loadArray(array $lines, $locale, $group, $namespace = '*') { // Transform the lines into a flat dot array: $lines = array_dot($lines); foreach ($lines as $item => $text) { if (is_string($text)) { // Check if the entry exists in the database: $translation = Translation::whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->whereItem($item) ->first(); // If the translation already exists, we update the text: if ($translation && !$translation->isLocked()) { $translation->text = $text; $saved = $translation->save(); if ($saved && $translation->locale === $this->defaultLocale) { $this->flagAsUnstable($namespace, $group, $item); } } // If no entry was found, create it: else { $this->create(compact('locale', 'namespace', 'group', 'item', 'text')); } } } }
php
public function loadArray(array $lines, $locale, $group, $namespace = '*') { // Transform the lines into a flat dot array: $lines = array_dot($lines); foreach ($lines as $item => $text) { if (is_string($text)) { // Check if the entry exists in the database: $translation = Translation::whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->whereItem($item) ->first(); // If the translation already exists, we update the text: if ($translation && !$translation->isLocked()) { $translation->text = $text; $saved = $translation->save(); if ($saved && $translation->locale === $this->defaultLocale) { $this->flagAsUnstable($namespace, $group, $item); } } // If no entry was found, create it: else { $this->create(compact('locale', 'namespace', 'group', 'item', 'text')); } } } }
[ "public", "function", "loadArray", "(", "array", "$", "lines", ",", "$", "locale", ",", "$", "group", ",", "$", "namespace", "=", "'*'", ")", "{", "// Transform the lines into a flat dot array:", "$", "lines", "=", "array_dot", "(", "$", "lines", ")", ";", ...
Loads a localization array from a localization file into the databas. @param array $lines @param string $locale @param string $group @param string $namespace @return void
[ "Loads", "a", "localization", "array", "from", "a", "localization", "file", "into", "the", "databas", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L165-L192
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.allByLocale
public function allByLocale($locale, $perPage = 0) { $translations = $this->model->where('locale', $locale); return $perPage ? $translations->paginate($perPage) : $translations->get(); }
php
public function allByLocale($locale, $perPage = 0) { $translations = $this->model->where('locale', $locale); return $perPage ? $translations->paginate($perPage) : $translations->get(); }
[ "public", "function", "allByLocale", "(", "$", "locale", ",", "$", "perPage", "=", "0", ")", "{", "$", "translations", "=", "$", "this", "->", "model", "->", "where", "(", "'locale'", ",", "$", "locale", ")", ";", "return", "$", "perPage", "?", "$", ...
Return a list of translations for the given language. If perPage is > 0 a paginated list is returned with perPage items per page. @param string $locale @return Translation
[ "Return", "a", "list", "of", "translations", "for", "the", "given", "language", ".", "If", "perPage", "is", ">", "0", "a", "paginated", "list", "is", "returned", "with", "perPage", "items", "per", "page", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L200-L204
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.getItems
public function getItems($locale, $namespace, $group) { return $this->model ->whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->get() ->toArray(); }
php
public function getItems($locale, $namespace, $group) { return $this->model ->whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->get() ->toArray(); }
[ "public", "function", "getItems", "(", "$", "locale", ",", "$", "namespace", ",", "$", "group", ")", "{", "return", "$", "this", "->", "model", "->", "whereLocale", "(", "$", "locale", ")", "->", "whereNamespace", "(", "$", "namespace", ")", "->", "whe...
Return all items for a given locale, namespace and group @param string $locale @param string $namespace @param string $group @return array
[ "Return", "all", "items", "for", "a", "given", "locale", "namespace", "and", "group" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L214-L222
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.loadSource
public function loadSource($locale, $namespace, $group) { return $this->model ->whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->get() ->keyBy('item') ->map(function ($translation) { return $translation['text']; }) ->toArray(); }
php
public function loadSource($locale, $namespace, $group) { return $this->model ->whereLocale($locale) ->whereNamespace($namespace) ->whereGroup($group) ->get() ->keyBy('item') ->map(function ($translation) { return $translation['text']; }) ->toArray(); }
[ "public", "function", "loadSource", "(", "$", "locale", ",", "$", "namespace", ",", "$", "group", ")", "{", "return", "$", "this", "->", "model", "->", "whereLocale", "(", "$", "locale", ")", "->", "whereNamespace", "(", "$", "namespace", ")", "->", "w...
Return all items formatted as if coming from a PHP language file. @param string $locale @param string $namespace @param string $group @return array
[ "Return", "all", "items", "formatted", "as", "if", "coming", "from", "a", "PHP", "language", "file", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L232-L244
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.pendingReview
public function pendingReview($locale, $perPage = 0) { $underReview = $this->model->whereLocale($locale)->whereUnstable(1); return $perPage ? $underReview->paginate($perPage) : $underReview->get(); }
php
public function pendingReview($locale, $perPage = 0) { $underReview = $this->model->whereLocale($locale)->whereUnstable(1); return $perPage ? $underReview->paginate($perPage) : $underReview->get(); }
[ "public", "function", "pendingReview", "(", "$", "locale", ",", "$", "perPage", "=", "0", ")", "{", "$", "underReview", "=", "$", "this", "->", "model", "->", "whereLocale", "(", "$", "locale", ")", "->", "whereUnstable", "(", "1", ")", ";", "return", ...
Retrieve translations pending review for the given locale. @param string $locale @param int $perPage Number of elements per page. 0 if all are wanted. @return Translation
[ "Retrieve", "translations", "pending", "review", "for", "the", "given", "locale", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L253-L257
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.search
public function search($locale, $partialCode, $perPage = 0) { // Get the namespace, if any: $colonIndex = stripos($partialCode, '::'); $query = $this->model->whereLocale($locale); if ($colonIndex === 0) { $query = $query->where('namespace', '!=', '*'); } elseif ($colonIndex > 0) { $namespace = substr($partialCode, 0, $colonIndex); $query = $query->where('namespace', 'like', "%{$namespace}%"); $partialCode = substr($partialCode, $colonIndex + 2); } // Divide the code in segments by . $elements = explode('.', $partialCode); foreach ($elements as $element) { if ($element) { $query = $query->where(function ($query) use ($element) { $query->where('group', 'like', "%{$element}%")->orWhere('item', 'like', "%{$element}%")->orWhere('text', 'like', "%{$element}%"); }); } } return $perPage ? $query->paginate($perPage) : $query->get(); }
php
public function search($locale, $partialCode, $perPage = 0) { // Get the namespace, if any: $colonIndex = stripos($partialCode, '::'); $query = $this->model->whereLocale($locale); if ($colonIndex === 0) { $query = $query->where('namespace', '!=', '*'); } elseif ($colonIndex > 0) { $namespace = substr($partialCode, 0, $colonIndex); $query = $query->where('namespace', 'like', "%{$namespace}%"); $partialCode = substr($partialCode, $colonIndex + 2); } // Divide the code in segments by . $elements = explode('.', $partialCode); foreach ($elements as $element) { if ($element) { $query = $query->where(function ($query) use ($element) { $query->where('group', 'like', "%{$element}%")->orWhere('item', 'like', "%{$element}%")->orWhere('text', 'like', "%{$element}%"); }); } } return $perPage ? $query->paginate($perPage) : $query->get(); }
[ "public", "function", "search", "(", "$", "locale", ",", "$", "partialCode", ",", "$", "perPage", "=", "0", ")", "{", "// Get the namespace, if any:", "$", "colonIndex", "=", "stripos", "(", "$", "partialCode", ",", "'::'", ")", ";", "$", "query", "=", "...
Search for entries given a partial code and a locale @param string $locale @param string $partialCode @param integer $perPage 0 if all, > 0 if paginated list with that number of elements per page. @return Translation
[ "Search", "for", "entries", "given", "a", "partial", "code", "and", "a", "locale" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L267-L291
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.untranslated
public function untranslated($locale, $perPage = 0, $text = null) { $ids = $this->untranslatedQuery($locale)->pluck('id'); $untranslated = $text ? $this->model->whereIn('id', $ids)->where('text', 'like', "%$text%") : $this->model->whereIn('id', $ids); return $perPage ? $untranslated->paginate($perPage) : $untranslated->get(); }
php
public function untranslated($locale, $perPage = 0, $text = null) { $ids = $this->untranslatedQuery($locale)->pluck('id'); $untranslated = $text ? $this->model->whereIn('id', $ids)->where('text', 'like', "%$text%") : $this->model->whereIn('id', $ids); return $perPage ? $untranslated->paginate($perPage) : $untranslated->get(); }
[ "public", "function", "untranslated", "(", "$", "locale", ",", "$", "perPage", "=", "0", ",", "$", "text", "=", "null", ")", "{", "$", "ids", "=", "$", "this", "->", "untranslatedQuery", "(", "$", "locale", ")", "->", "pluck", "(", "'id'", ")", ";"...
List all entries in the default locale that do not exist for the target locale. @param string $locale Language to translate to. @param integer $perPage If greater than zero, return a paginated list with $perPage items per page. @param string $text [optional] Show only entries with the given text in them in the reference language. @return Collection
[ "List", "all", "entries", "in", "the", "default", "locale", "that", "do", "not", "exist", "for", "the", "target", "locale", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L301-L308
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.translateText
public function translateText($text, $textLocale, $targetLocale) { $table = $this->model->getTable(); return $this->model ->newQuery() ->select($table . '.text') ->from($table) ->leftJoin("{$table} as e", function ($join) use ($table, $text, $textLocale) { $join->on('e.namespace', '=', "{$table}.namespace") ->on('e.group', '=', "{$table}.group") ->on('e.item', '=', "{$table}.item"); }) ->where("{$table}.locale", $targetLocale) ->where('e.locale', $textLocale) ->where('e.text', $text) ->get() ->pluck('text') ->unique() ->toArray(); }
php
public function translateText($text, $textLocale, $targetLocale) { $table = $this->model->getTable(); return $this->model ->newQuery() ->select($table . '.text') ->from($table) ->leftJoin("{$table} as e", function ($join) use ($table, $text, $textLocale) { $join->on('e.namespace', '=', "{$table}.namespace") ->on('e.group', '=', "{$table}.group") ->on('e.item', '=', "{$table}.item"); }) ->where("{$table}.locale", $targetLocale) ->where('e.locale', $textLocale) ->where('e.text', $text) ->get() ->pluck('text') ->unique() ->toArray(); }
[ "public", "function", "translateText", "(", "$", "text", ",", "$", "textLocale", ",", "$", "targetLocale", ")", "{", "$", "table", "=", "$", "this", "->", "model", "->", "getTable", "(", ")", ";", "return", "$", "this", "->", "model", "->", "newQuery",...
Check if there are existing translations for the given text in the given locale for the target locale. @param string $text @param string $textLocale @param string $targetLocale @return array
[ "Check", "if", "there", "are", "existing", "translations", "for", "the", "given", "text", "in", "the", "given", "locale", "for", "the", "target", "locale", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L358-L378
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.flagAsUnstable
public function flagAsUnstable($namespace, $group, $item) { $this->model->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->where('locale', '!=', $this->defaultLocale)->update(['unstable' => '1']); }
php
public function flagAsUnstable($namespace, $group, $item) { $this->model->whereNamespace($namespace)->whereGroup($group)->whereItem($item)->where('locale', '!=', $this->defaultLocale)->update(['unstable' => '1']); }
[ "public", "function", "flagAsUnstable", "(", "$", "namespace", ",", "$", "group", ",", "$", "item", ")", "{", "$", "this", "->", "model", "->", "whereNamespace", "(", "$", "namespace", ")", "->", "whereGroup", "(", "$", "group", ")", "->", "whereItem", ...
Flag all entries with the given namespace, group and item and locale other than default as pending review. This is used when an entry for the default locale is updated. @param Translation $entry @return boolean
[ "Flag", "all", "entries", "with", "the", "given", "namespace", "group", "and", "item", "and", "locale", "other", "than", "default", "as", "pending", "review", ".", "This", "is", "used", "when", "an", "entry", "for", "the", "default", "locale", "is", "updat...
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L387-L390
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.parseCode
public function parseCode($code) { $segments = (new NamespacedItemResolver)->parseKey($code); if (is_null($segments[0])) { $segments[0] = '*'; } return $segments; }
php
public function parseCode($code) { $segments = (new NamespacedItemResolver)->parseKey($code); if (is_null($segments[0])) { $segments[0] = '*'; } return $segments; }
[ "public", "function", "parseCode", "(", "$", "code", ")", "{", "$", "segments", "=", "(", "new", "NamespacedItemResolver", ")", "->", "parseKey", "(", "$", "code", ")", ";", "if", "(", "is_null", "(", "$", "segments", "[", "0", "]", ")", ")", "{", ...
Parse a translation code into its components @param string $code @return boolean
[ "Parse", "a", "translation", "code", "into", "its", "components" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L446-L455
train
Waavi/translation
src/Repositories/TranslationRepository.php
TranslationRepository.untranslatedQuery
protected function untranslatedQuery($locale) { $table = $this->model->getTable(); return $this->database->table("$table as $table") ->select("$table.id") ->leftJoin("$table as e", function (JoinClause $query) use ($table, $locale) { $query->on('e.namespace', '=', "$table.namespace") ->on('e.group', '=', "$table.group") ->on('e.item', '=', "$table.item") ->where('e.locale', '=', $locale); }) ->where("$table.locale", $this->defaultLocale) ->whereNull("e.id"); }
php
protected function untranslatedQuery($locale) { $table = $this->model->getTable(); return $this->database->table("$table as $table") ->select("$table.id") ->leftJoin("$table as e", function (JoinClause $query) use ($table, $locale) { $query->on('e.namespace', '=', "$table.namespace") ->on('e.group', '=', "$table.group") ->on('e.item', '=', "$table.item") ->where('e.locale', '=', $locale); }) ->where("$table.locale", $this->defaultLocale) ->whereNull("e.id"); }
[ "protected", "function", "untranslatedQuery", "(", "$", "locale", ")", "{", "$", "table", "=", "$", "this", "->", "model", "->", "getTable", "(", ")", ";", "return", "$", "this", "->", "database", "->", "table", "(", "\"$table as $table\"", ")", "->", "s...
Create and return a new query to identify untranslated records. @param string $locale @return \Illuminate\Database\Query\Builder
[ "Create", "and", "return", "a", "new", "query", "to", "identify", "untranslated", "records", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/TranslationRepository.php#L463-L477
train
Waavi/translation
src/Repositories/Repository.php
Repository.all
public function all($related = [], $perPage = 0) { $results = $this->model->with($related)->orderBy('created_at', 'DESC'); return $perPage ? $results->paginate($perPage) : $results->get(); }
php
public function all($related = [], $perPage = 0) { $results = $this->model->with($related)->orderBy('created_at', 'DESC'); return $perPage ? $results->paginate($perPage) : $results->get(); }
[ "public", "function", "all", "(", "$", "related", "=", "[", "]", ",", "$", "perPage", "=", "0", ")", "{", "$", "results", "=", "$", "this", "->", "model", "->", "with", "(", "$", "related", ")", "->", "orderBy", "(", "'created_at'", ",", "'DESC'", ...
Retrieve all records. @param array $related Related object to include. @param integer $perPage Number of records to retrieve per page. If zero the whole result set is returned. @return \Illuminate\Database\Eloquent\Model
[ "Retrieve", "all", "records", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/Repository.php#L32-L36
train
Waavi/translation
src/Repositories/Repository.php
Repository.trashed
public function trashed($related = [], $perPage = 0) { $trashed = $this->model->onlyTrashed()->with($related); return $perPage ? $trashed->paginate($perPage) : $trashed->get(); }
php
public function trashed($related = [], $perPage = 0) { $trashed = $this->model->onlyTrashed()->with($related); return $perPage ? $trashed->paginate($perPage) : $trashed->get(); }
[ "public", "function", "trashed", "(", "$", "related", "=", "[", "]", ",", "$", "perPage", "=", "0", ")", "{", "$", "trashed", "=", "$", "this", "->", "model", "->", "onlyTrashed", "(", ")", "->", "with", "(", "$", "related", ")", ";", "return", "...
Retrieve all trashed. @param array $related Related object to include. @param integer $perPage Number of records to retrieve per page. If zero the whole result set is returned. @return \Illuminate\Database\Eloquent\Model
[ "Retrieve", "all", "trashed", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/Repository.php#L45-L49
train
Waavi/translation
src/Repositories/Repository.php
Repository.findTrashed
public function findTrashed($id, $related = []) { return $this->model->onlyTrashed()->with($related)->find($id); }
php
public function findTrashed($id, $related = []) { return $this->model->onlyTrashed()->with($related)->find($id); }
[ "public", "function", "findTrashed", "(", "$", "id", ",", "$", "related", "=", "[", "]", ")", "{", "return", "$", "this", "->", "model", "->", "onlyTrashed", "(", ")", "->", "with", "(", "$", "related", ")", "->", "find", "(", "$", "id", ")", ";"...
Retrieve a single record by id. @param integer $id @return \Illuminate\Database\Eloquent\Model
[ "Retrieve", "a", "single", "record", "by", "id", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/Repository.php#L68-L71
train
Waavi/translation
src/Repositories/Repository.php
Repository.delete
public function delete($id) { $model = $this->model->where('id', $id)->first(); if (!$model) { return false; } return $model->delete(); }
php
public function delete($id) { $model = $this->model->where('id', $id)->first(); if (!$model) { return false; } return $model->delete(); }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "model", "=", "$", "this", "->", "model", "->", "where", "(", "'id'", ",", "$", "id", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "model", ")", "{", "return", "false", ...
Remove a record. @param \Illuminate\Database\Eloquent\Model $model @return boolean
[ "Remove", "a", "record", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/Repository.php#L79-L86
train
Waavi/translation
src/Repositories/Repository.php
Repository.restore
public function restore($id) { $model = $this->findTrashed($id); if ($model) { $model->restore(); } return $model; }
php
public function restore($id) { $model = $this->findTrashed($id); if ($model) { $model->restore(); } return $model; }
[ "public", "function", "restore", "(", "$", "id", ")", "{", "$", "model", "=", "$", "this", "->", "findTrashed", "(", "$", "id", ")", ";", "if", "(", "$", "model", ")", "{", "$", "model", "->", "restore", "(", ")", ";", "}", "return", "$", "mode...
Restore a record. @param int $id @return boolean
[ "Restore", "a", "record", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/Repository.php#L94-L101
train
Waavi/translation
src/Commands/FileLoaderCommand.php
FileLoaderCommand.loadVendor
public function loadVendor($path) { $directories = $this->files->directories($path); foreach ($directories as $directory) { $namespace = basename($directory); $this->loadLocaleDirectories($directory, $namespace); } }
php
public function loadVendor($path) { $directories = $this->files->directories($path); foreach ($directories as $directory) { $namespace = basename($directory); $this->loadLocaleDirectories($directory, $namespace); } }
[ "public", "function", "loadVendor", "(", "$", "path", ")", "{", "$", "directories", "=", "$", "this", "->", "files", "->", "directories", "(", "$", "path", ")", ";", "foreach", "(", "$", "directories", "as", "$", "directory", ")", "{", "$", "namespace"...
Load all vendor overriden localization packages. Calls loadLocaleDirectories with the appropriate namespace. @param string $path Path to vendor locale root, usually /path/to/laravel/resources/lang/vendor. @see http://laravel.com/docs/5.1/localization#overriding-vendor-language-files @return void
[ "Load", "all", "vendor", "overriden", "localization", "packages", ".", "Calls", "loadLocaleDirectories", "with", "the", "appropriate", "namespace", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Commands/FileLoaderCommand.php#L86-L93
train
Waavi/translation
src/Commands/FileLoaderCommand.php
FileLoaderCommand.loadDirectory
public function loadDirectory($path, $locale, $namespace = '*', $group = '') { // Load all files inside subdirectories: $directories = $this->files->directories($path); foreach ($directories as $directory) { $directoryName = str_replace($path . '/', '', $directory); $dirGroup = $group . basename($directory) . '/'; $this->loadDirectory($directory, $locale, $namespace, $dirGroup); } // Load all files in root: $files = $this->files->files($path); foreach ($files as $file) { $this->loadFile($file, $locale, $namespace, $group); } }
php
public function loadDirectory($path, $locale, $namespace = '*', $group = '') { // Load all files inside subdirectories: $directories = $this->files->directories($path); foreach ($directories as $directory) { $directoryName = str_replace($path . '/', '', $directory); $dirGroup = $group . basename($directory) . '/'; $this->loadDirectory($directory, $locale, $namespace, $dirGroup); } // Load all files in root: $files = $this->files->files($path); foreach ($files as $file) { $this->loadFile($file, $locale, $namespace, $group); } }
[ "public", "function", "loadDirectory", "(", "$", "path", ",", "$", "locale", ",", "$", "namespace", "=", "'*'", ",", "$", "group", "=", "''", ")", "{", "// Load all files inside subdirectories:", "$", "directories", "=", "$", "this", "->", "files", "->", "...
Load all files inside a locale directory and its subdirectories. @param string $path Path to locale root. Ex: /path/to/laravel/resources/lang/en @param string $locale Locale to apply when loading the localization files. @param string $namespace Namespace to apply when loading the localization files ('*' by default, or the vendor package name if not) @param string $group When loading from a subdirectory, the subdirectory's name must be prepended. For example: trans('subdir/file.entry'). @return void
[ "Load", "all", "files", "inside", "a", "locale", "directory", "and", "its", "subdirectories", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Commands/FileLoaderCommand.php#L104-L119
train
Waavi/translation
src/Commands/FileLoaderCommand.php
FileLoaderCommand.loadFile
public function loadFile($file, $locale, $namespace = '*', $group = '') { $group = $group . basename($file, '.php'); $translations = $this->files->getRequire($file); $this->translationRepository->loadArray($translations, $locale, $group, $namespace, $locale == $this->defaultLocale); }
php
public function loadFile($file, $locale, $namespace = '*', $group = '') { $group = $group . basename($file, '.php'); $translations = $this->files->getRequire($file); $this->translationRepository->loadArray($translations, $locale, $group, $namespace, $locale == $this->defaultLocale); }
[ "public", "function", "loadFile", "(", "$", "file", ",", "$", "locale", ",", "$", "namespace", "=", "'*'", ",", "$", "group", "=", "''", ")", "{", "$", "group", "=", "$", "group", ".", "basename", "(", "$", "file", ",", "'.php'", ")", ";", "$", ...
Loads the given file into the database @param string $path Full path to the localization file. For example: /path/to/laravel/resources/lang/en/auth.php @param string $locale @param string $namespace @param string $group Relative from the locale directory's root. For example subdirectory/subdir2/ @return void
[ "Loads", "the", "given", "file", "into", "the", "database" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Commands/FileLoaderCommand.php#L130-L135
train
Waavi/translation
src/Cache/SimpleRepository.php
SimpleRepository.put
public function put($locale, $group, $namespace, $content, $minutes) { $key = $this->getKey($locale, $group, $namespace); $this->store->put($key, $content, $minutes); }
php
public function put($locale, $group, $namespace, $content, $minutes) { $key = $this->getKey($locale, $group, $namespace); $this->store->put($key, $content, $minutes); }
[ "public", "function", "put", "(", "$", "locale", ",", "$", "group", ",", "$", "namespace", ",", "$", "content", ",", "$", "minutes", ")", "{", "$", "key", "=", "$", "this", "->", "getKey", "(", "$", "locale", ",", "$", "group", ",", "$", "namespa...
Put an item into the cache store @param string $locale @param string $group @param string $namespace @param mixed $content @param integer $minutes @return void
[ "Put", "an", "item", "into", "the", "cache", "store" ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Cache/SimpleRepository.php#L63-L67
train
Waavi/translation
src/Repositories/LanguageRepository.php
LanguageRepository.availableLocales
public function availableLocales() { if ($this->config->has('translator.locales')) { return $this->config->get('translator.locales'); } if ($this->config->get('translator.source') !== 'files') { if ($this->tableExists()) { $locales = $this->model->distinct()->get()->pluck('locale')->toArray(); $this->config->set('translator.locales', $locales); return $locales; } } return $this->defaultAvailableLocales; }
php
public function availableLocales() { if ($this->config->has('translator.locales')) { return $this->config->get('translator.locales'); } if ($this->config->get('translator.source') !== 'files') { if ($this->tableExists()) { $locales = $this->model->distinct()->get()->pluck('locale')->toArray(); $this->config->set('translator.locales', $locales); return $locales; } } return $this->defaultAvailableLocales; }
[ "public", "function", "availableLocales", "(", ")", "{", "if", "(", "$", "this", "->", "config", "->", "has", "(", "'translator.locales'", ")", ")", "{", "return", "$", "this", "->", "config", "->", "get", "(", "'translator.locales'", ")", ";", "}", "if"...
Returns a list of all available locales. @return array
[ "Returns", "a", "list", "of", "all", "available", "locales", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/LanguageRepository.php#L127-L142
train
Waavi/translation
src/Repositories/LanguageRepository.php
LanguageRepository.percentTranslated
public function percentTranslated($locale) { $lang = $this->findByLocale($locale); $referenceLang = $this->findByLocale($this->defaultLocale); $langEntries = $lang->translations()->count(); $referenceEntries = $referenceLang->translations()->count(); return $referenceEntries > 0 ? (int) round($langEntries * 100 / $referenceEntries) : 0; }
php
public function percentTranslated($locale) { $lang = $this->findByLocale($locale); $referenceLang = $this->findByLocale($this->defaultLocale); $langEntries = $lang->translations()->count(); $referenceEntries = $referenceLang->translations()->count(); return $referenceEntries > 0 ? (int) round($langEntries * 100 / $referenceEntries) : 0; }
[ "public", "function", "percentTranslated", "(", "$", "locale", ")", "{", "$", "lang", "=", "$", "this", "->", "findByLocale", "(", "$", "locale", ")", ";", "$", "referenceLang", "=", "$", "this", "->", "findByLocale", "(", "$", "this", "->", "defaultLoca...
Compute percentage translate of the given language. @param string $locale @param string $referenceLocale @return int
[ "Compute", "percentage", "translate", "of", "the", "given", "language", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Repositories/LanguageRepository.php#L161-L170
train
Waavi/translation
src/Traits/TranslatableObserver.php
TranslatableObserver.saved
public function saved($model) { $translationRepository = \App::make(TranslationRepository::class); $cacheRepository = \App::make('translation.cache.repository'); foreach ($model->translatableAttributes() as $attribute) { // If the value of the translatable attribute has changed: if ($model->isDirty($attribute)) { $translationRepository->updateDefaultByCode($model->translationCodeFor($attribute), $model->getRawAttribute($attribute)); } } $cacheRepository->flush(config('app.locale'), 'translatable', '*'); }
php
public function saved($model) { $translationRepository = \App::make(TranslationRepository::class); $cacheRepository = \App::make('translation.cache.repository'); foreach ($model->translatableAttributes() as $attribute) { // If the value of the translatable attribute has changed: if ($model->isDirty($attribute)) { $translationRepository->updateDefaultByCode($model->translationCodeFor($attribute), $model->getRawAttribute($attribute)); } } $cacheRepository->flush(config('app.locale'), 'translatable', '*'); }
[ "public", "function", "saved", "(", "$", "model", ")", "{", "$", "translationRepository", "=", "\\", "App", "::", "make", "(", "TranslationRepository", "::", "class", ")", ";", "$", "cacheRepository", "=", "\\", "App", "::", "make", "(", "'translation.cache....
Save translations when model is saved. @param Model $model @return void
[ "Save", "translations", "when", "model", "is", "saved", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/TranslatableObserver.php#L14-L25
train
Waavi/translation
src/Traits/TranslatableObserver.php
TranslatableObserver.deleted
public function deleted($model) { $translationRepository = \App::make(TranslationRepository::class); foreach ($model->translatableAttributes() as $attribute) { $translationRepository->deleteByCode($model->translationCodeFor($attribute)); } }
php
public function deleted($model) { $translationRepository = \App::make(TranslationRepository::class); foreach ($model->translatableAttributes() as $attribute) { $translationRepository->deleteByCode($model->translationCodeFor($attribute)); } }
[ "public", "function", "deleted", "(", "$", "model", ")", "{", "$", "translationRepository", "=", "\\", "App", "::", "make", "(", "TranslationRepository", "::", "class", ")", ";", "foreach", "(", "$", "model", "->", "translatableAttributes", "(", ")", "as", ...
Delete translations when model is deleted. @param Model $model @return void
[ "Delete", "translations", "when", "model", "is", "deleted", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/TranslatableObserver.php#L33-L39
train
Waavi/translation
src/Traits/Translatable.php
Translatable.getAttribute
public function getAttribute($attribute) { // Return the raw value of a translatable attribute if requested if ($this->rawValueRequested($attribute)) { $rawAttribute = snake_case(str_replace('raw', '', $attribute)); return $this->attributes[$rawAttribute]; } // Return the translation for the given attribute if available if ($this->isTranslated($attribute)) { return $this->translate($attribute); } // Return parent return parent::getAttribute($attribute); }
php
public function getAttribute($attribute) { // Return the raw value of a translatable attribute if requested if ($this->rawValueRequested($attribute)) { $rawAttribute = snake_case(str_replace('raw', '', $attribute)); return $this->attributes[$rawAttribute]; } // Return the translation for the given attribute if available if ($this->isTranslated($attribute)) { return $this->translate($attribute); } // Return parent return parent::getAttribute($attribute); }
[ "public", "function", "getAttribute", "(", "$", "attribute", ")", "{", "// Return the raw value of a translatable attribute if requested", "if", "(", "$", "this", "->", "rawValueRequested", "(", "$", "attribute", ")", ")", "{", "$", "rawAttribute", "=", "snake_case", ...
Hijack parent's getAttribute to get the translation of the given field instead of its value. @param string $key Attribute name @return mixed
[ "Hijack", "parent", "s", "getAttribute", "to", "get", "the", "translation", "of", "the", "given", "field", "instead", "of", "its", "value", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/Translatable.php#L24-L37
train
Waavi/translation
src/Traits/Translatable.php
Translatable.setAttribute
public function setAttribute($attribute, $value) { if ($this->isTranslatable($attribute) && !empty($value)) { // If a translation code has not yet been set, generate one: if (!$this->translationCodeFor($attribute)) { $reflected = new \ReflectionClass($this); $group = 'translatable'; $item = strtolower($reflected->getShortName()) . '.' . strtolower($attribute) . '.' . Str::random(); $this->attributes["{$attribute}_translation"] = "$group.$item"; } } return parent::setAttribute($attribute, $value); }
php
public function setAttribute($attribute, $value) { if ($this->isTranslatable($attribute) && !empty($value)) { // If a translation code has not yet been set, generate one: if (!$this->translationCodeFor($attribute)) { $reflected = new \ReflectionClass($this); $group = 'translatable'; $item = strtolower($reflected->getShortName()) . '.' . strtolower($attribute) . '.' . Str::random(); $this->attributes["{$attribute}_translation"] = "$group.$item"; } } return parent::setAttribute($attribute, $value); }
[ "public", "function", "setAttribute", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "isTranslatable", "(", "$", "attribute", ")", "&&", "!", "empty", "(", "$", "value", ")", ")", "{", "// If a translation code has not ye...
Hijack Eloquent's setAttribute to create a Language Entry, or update the existing one, when setting the value of this attribute. @param string $attribute Attribute name @param string $value Text value in default locale. @return void
[ "Hijack", "Eloquent", "s", "setAttribute", "to", "create", "a", "Language", "Entry", "or", "update", "the", "existing", "one", "when", "setting", "the", "value", "of", "this", "attribute", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/Translatable.php#L46-L58
train
Waavi/translation
src/Traits/Translatable.php
Translatable.attributesToArray
public function attributesToArray() { $attributes = parent::attributesToArray(); foreach ($this->translatableAttributes as $translatableAttribute) { if (isset($attributes[$translatableAttribute])) { $attributes[$translatableAttribute] = $this->translate($translatableAttribute); } unset($attributes["{$translatableAttribute}_translation"]); } return $attributes; }
php
public function attributesToArray() { $attributes = parent::attributesToArray(); foreach ($this->translatableAttributes as $translatableAttribute) { if (isset($attributes[$translatableAttribute])) { $attributes[$translatableAttribute] = $this->translate($translatableAttribute); } unset($attributes["{$translatableAttribute}_translation"]); } return $attributes; }
[ "public", "function", "attributesToArray", "(", ")", "{", "$", "attributes", "=", "parent", "::", "attributesToArray", "(", ")", ";", "foreach", "(", "$", "this", "->", "translatableAttributes", "as", "$", "translatableAttribute", ")", "{", "if", "(", "isset",...
Extend parent's attributesToArray so that _translation attributes do not appear in array, and translatable attributes are translated. @return array
[ "Extend", "parent", "s", "attributesToArray", "so", "that", "_translation", "attributes", "do", "not", "appear", "in", "array", "and", "translatable", "attributes", "are", "translated", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/Translatable.php#L65-L77
train
Waavi/translation
src/Traits/Translatable.php
Translatable.rawValueRequested
public function rawValueRequested($attribute) { if (strrpos($attribute, 'raw') === 0) { $rawAttribute = snake_case(str_replace('raw', '', $attribute)); return $this->isTranslatable($rawAttribute); } return false; }
php
public function rawValueRequested($attribute) { if (strrpos($attribute, 'raw') === 0) { $rawAttribute = snake_case(str_replace('raw', '', $attribute)); return $this->isTranslatable($rawAttribute); } return false; }
[ "public", "function", "rawValueRequested", "(", "$", "attribute", ")", "{", "if", "(", "strrpos", "(", "$", "attribute", ",", "'raw'", ")", "===", "0", ")", "{", "$", "rawAttribute", "=", "snake_case", "(", "str_replace", "(", "'raw'", ",", "''", ",", ...
Check if the attribute being queried is the raw value of a translatable attribute. @param string $attribute @return boolean
[ "Check", "if", "the", "attribute", "being", "queried", "is", "the", "raw", "value", "of", "a", "translatable", "attribute", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/Translatable.php#L96-L103
train
Waavi/translation
src/Traits/Translatable.php
Translatable.translate
public function translate($attribute) { $translationCode = $this->translationCodeFor($attribute); $translation = $translationCode ? trans($translationCode) : false; return $translation ?: parent::getAttribute($attribute); }
php
public function translate($attribute) { $translationCode = $this->translationCodeFor($attribute); $translation = $translationCode ? trans($translationCode) : false; return $translation ?: parent::getAttribute($attribute); }
[ "public", "function", "translate", "(", "$", "attribute", ")", "{", "$", "translationCode", "=", "$", "this", "->", "translationCodeFor", "(", "$", "attribute", ")", ";", "$", "translation", "=", "$", "translationCode", "?", "trans", "(", "$", "translationCo...
Return the translation related to a translatable attribute. @param string $attribute @return Translation
[ "Return", "the", "translation", "related", "to", "a", "translatable", "attribute", "." ]
cd0d00180cafe01ec6db70a8c2f96af8af041cec
https://github.com/Waavi/translation/blob/cd0d00180cafe01ec6db70a8c2f96af8af041cec/src/Traits/Translatable.php#L119-L124
train
yadakhov/insert-on-duplicate-key
src/InsertOnDuplicateKey.php
InsertOnDuplicateKey.insertIgnore
public static function insertIgnore(array $data) { if (empty($data)) { return false; } // Case where $data is not an array of arrays. if (!isset($data[0])) { $data = [$data]; } $sql = static::buildInsertIgnoreSql($data); $data = static::inLineArray($data); return self::getModelConnectionName()->affectingStatement($sql, $data); }
php
public static function insertIgnore(array $data) { if (empty($data)) { return false; } // Case where $data is not an array of arrays. if (!isset($data[0])) { $data = [$data]; } $sql = static::buildInsertIgnoreSql($data); $data = static::inLineArray($data); return self::getModelConnectionName()->affectingStatement($sql, $data); }
[ "public", "static", "function", "insertIgnore", "(", "array", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "// Case where $data is not an array of arrays.", "if", "(", "!", "isset", "(", "$", "dat...
Insert using mysql INSERT IGNORE INTO. @param array $data @return int 0 if row is ignored, 1 if row is inserted
[ "Insert", "using", "mysql", "INSERT", "IGNORE", "INTO", "." ]
dbca15aaa6dc39df77553837d4e8988d4c6245a7
https://github.com/yadakhov/insert-on-duplicate-key/blob/dbca15aaa6dc39df77553837d4e8988d4c6245a7/src/InsertOnDuplicateKey.php#L46-L62
train
yadakhov/insert-on-duplicate-key
src/InsertOnDuplicateKey.php
InsertOnDuplicateKey.replace
public static function replace(array $data) { if (empty($data)) { return false; } // Case where $data is not an array of arrays. if (!isset($data[0])) { $data = [$data]; } $sql = static::buildReplaceSql($data); $data = static::inLineArray($data); return self::getModelConnectionName()->affectingStatement($sql, $data); }
php
public static function replace(array $data) { if (empty($data)) { return false; } // Case where $data is not an array of arrays. if (!isset($data[0])) { $data = [$data]; } $sql = static::buildReplaceSql($data); $data = static::inLineArray($data); return self::getModelConnectionName()->affectingStatement($sql, $data); }
[ "public", "static", "function", "replace", "(", "array", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "// Case where $data is not an array of arrays.", "if", "(", "!", "isset", "(", "$", "data", ...
Insert using mysql REPLACE INTO. @param array $data @return int 1 if row is inserted without replacements, greater than 1 if rows were replaced
[ "Insert", "using", "mysql", "REPLACE", "INTO", "." ]
dbca15aaa6dc39df77553837d4e8988d4c6245a7
https://github.com/yadakhov/insert-on-duplicate-key/blob/dbca15aaa6dc39df77553837d4e8988d4c6245a7/src/InsertOnDuplicateKey.php#L71-L87
train
yadakhov/insert-on-duplicate-key
src/InsertOnDuplicateKey.php
InsertOnDuplicateKey.buildValuesList
protected static function buildValuesList(array $updatedColumns) { $out = []; foreach ($updatedColumns as $key => $value) { if (is_numeric($key)) { $out[] = sprintf('`%s` = VALUES(`%s`)', $value, $value); } else { $out[] = sprintf('%s = %s', $key, $value); } } return implode(', ', $out); }
php
protected static function buildValuesList(array $updatedColumns) { $out = []; foreach ($updatedColumns as $key => $value) { if (is_numeric($key)) { $out[] = sprintf('`%s` = VALUES(`%s`)', $value, $value); } else { $out[] = sprintf('%s = %s', $key, $value); } } return implode(', ', $out); }
[ "protected", "static", "function", "buildValuesList", "(", "array", "$", "updatedColumns", ")", "{", "$", "out", "=", "[", "]", ";", "foreach", "(", "$", "updatedColumns", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$...
Build a value list. @param array $updatedColumns @return string
[ "Build", "a", "value", "list", "." ]
dbca15aaa6dc39df77553837d4e8988d4c6245a7
https://github.com/yadakhov/insert-on-duplicate-key/blob/dbca15aaa6dc39df77553837d4e8988d4c6245a7/src/InsertOnDuplicateKey.php#L199-L212
train
yadakhov/insert-on-duplicate-key
src/InsertOnDuplicateKey.php
InsertOnDuplicateKey.buildInsertOnDuplicateSql
protected static function buildInsertOnDuplicateSql(array $data, array $updateColumns = null) { $first = static::getFirstRow($data); $sql = 'INSERT INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; $sql .= static::buildQuestionMarks($data) . PHP_EOL; $sql .= 'ON DUPLICATE KEY UPDATE '; if (empty($updateColumns)) { $sql .= static::buildValuesList(array_keys($first)); } else { $sql .= static::buildValuesList($updateColumns); } return $sql; }
php
protected static function buildInsertOnDuplicateSql(array $data, array $updateColumns = null) { $first = static::getFirstRow($data); $sql = 'INSERT INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; $sql .= static::buildQuestionMarks($data) . PHP_EOL; $sql .= 'ON DUPLICATE KEY UPDATE '; if (empty($updateColumns)) { $sql .= static::buildValuesList(array_keys($first)); } else { $sql .= static::buildValuesList($updateColumns); } return $sql; }
[ "protected", "static", "function", "buildInsertOnDuplicateSql", "(", "array", "$", "data", ",", "array", "$", "updateColumns", "=", "null", ")", "{", "$", "first", "=", "static", "::", "getFirstRow", "(", "$", "data", ")", ";", "$", "sql", "=", "'INSERT IN...
Build the INSERT ON DUPLICATE KEY sql statement. @param array $data @param array $updateColumns @return string
[ "Build", "the", "INSERT", "ON", "DUPLICATE", "KEY", "sql", "statement", "." ]
dbca15aaa6dc39df77553837d4e8988d4c6245a7
https://github.com/yadakhov/insert-on-duplicate-key/blob/dbca15aaa6dc39df77553837d4e8988d4c6245a7/src/InsertOnDuplicateKey.php#L234-L249
train
yadakhov/insert-on-duplicate-key
src/InsertOnDuplicateKey.php
InsertOnDuplicateKey.buildReplaceSql
protected static function buildReplaceSql(array $data) { $first = static::getFirstRow($data); $sql = 'REPLACE INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; $sql .= static::buildQuestionMarks($data); return $sql; }
php
protected static function buildReplaceSql(array $data) { $first = static::getFirstRow($data); $sql = 'REPLACE INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; $sql .= static::buildQuestionMarks($data); return $sql; }
[ "protected", "static", "function", "buildReplaceSql", "(", "array", "$", "data", ")", "{", "$", "first", "=", "static", "::", "getFirstRow", "(", "$", "data", ")", ";", "$", "sql", "=", "'REPLACE INTO `'", ".", "static", "::", "getTablePrefix", "(", ")", ...
Build REPLACE sql statement. @param array $data @return string
[ "Build", "REPLACE", "sql", "statement", "." ]
dbca15aaa6dc39df77553837d4e8988d4c6245a7
https://github.com/yadakhov/insert-on-duplicate-key/blob/dbca15aaa6dc39df77553837d4e8988d4c6245a7/src/InsertOnDuplicateKey.php#L275-L283
train
lochmueller/staticfilecache
Classes/Service/HttpPush/AbstractHttpPush.php
AbstractHttpPush.streamlineFilePaths
protected function streamlineFilePaths(array $paths): array { $paths = \array_map(function ($url) { if (!GeneralUtility::isValidUrl($url) && ':' !== $url[0]) { $url = GeneralUtility::locationHeaderUrl($url); } return $url; }, $paths); $paths = \array_filter($paths, function ($path) { return GeneralUtility::isOnCurrentHost($path) && ':' !== $path[0]; }); $paths = \array_map(function ($url) { return '/' . \ltrim(\str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $url), '/'); }, $paths); return $paths; }
php
protected function streamlineFilePaths(array $paths): array { $paths = \array_map(function ($url) { if (!GeneralUtility::isValidUrl($url) && ':' !== $url[0]) { $url = GeneralUtility::locationHeaderUrl($url); } return $url; }, $paths); $paths = \array_filter($paths, function ($path) { return GeneralUtility::isOnCurrentHost($path) && ':' !== $path[0]; }); $paths = \array_map(function ($url) { return '/' . \ltrim(\str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $url), '/'); }, $paths); return $paths; }
[ "protected", "function", "streamlineFilePaths", "(", "array", "$", "paths", ")", ":", "array", "{", "$", "paths", "=", "\\", "array_map", "(", "function", "(", "$", "url", ")", "{", "if", "(", "!", "GeneralUtility", "::", "isValidUrl", "(", "$", "url", ...
Streamline file paths. @param array $paths @return array
[ "Streamline", "file", "paths", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/HttpPush/AbstractHttpPush.php#L47-L66
train
lochmueller/staticfilecache
Classes/Service/HttpPush/AbstractHttpPush.php
AbstractHttpPush.mapPathsWithType
protected function mapPathsWithType(array $paths, string $type): array { return \array_map(function ($item) use ($type) { return [ 'path' => $item, 'type' => $type, ]; }, \array_unique($paths)); }
php
protected function mapPathsWithType(array $paths, string $type): array { return \array_map(function ($item) use ($type) { return [ 'path' => $item, 'type' => $type, ]; }, \array_unique($paths)); }
[ "protected", "function", "mapPathsWithType", "(", "array", "$", "paths", ",", "string", "$", "type", ")", ":", "array", "{", "return", "\\", "array_map", "(", "function", "(", "$", "item", ")", "use", "(", "$", "type", ")", "{", "return", "[", "'path'"...
Map the path with the right types. Take care that paths are not used twice. @param array $paths @param string $type @return array
[ "Map", "the", "path", "with", "the", "right", "types", ".", "Take", "care", "that", "paths", "are", "not", "used", "twice", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/HttpPush/AbstractHttpPush.php#L77-L85
train
lochmueller/staticfilecache
Classes/Service/CookieService.php
CookieService.setCookie
public function setCookie(int $lifetime) { $cookieDomain = $this->getCookieDomain(); if ($cookieDomain) { \setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime, '/', $cookieDomain); return; } \setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime, '/'); }
php
public function setCookie(int $lifetime) { $cookieDomain = $this->getCookieDomain(); if ($cookieDomain) { \setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime, '/', $cookieDomain); return; } \setcookie(self::FE_COOKIE_NAME, 'typo_user_logged_in', $lifetime, '/'); }
[ "public", "function", "setCookie", "(", "int", "$", "lifetime", ")", "{", "$", "cookieDomain", "=", "$", "this", "->", "getCookieDomain", "(", ")", ";", "if", "(", "$", "cookieDomain", ")", "{", "\\", "setcookie", "(", "self", "::", "FE_COOKIE_NAME", ","...
Set the Cookie. @param $lifetime
[ "Set", "the", "Cookie", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/CookieService.php#L29-L38
train
lochmueller/staticfilecache
Classes/Cache/Rule/StaticCacheable.php
StaticCacheable.checkRule
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { if (!$frontendController->isStaticCacheble()) { $explanation[__CLASS__] = 'The page is not static cacheable via TypoScriptFrontend. Check the first Question on: https://github.com/lochmueller/staticfilecache/blob/master/Documentation/Faq/Index.rst'; } }
php
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { if (!$frontendController->isStaticCacheble()) { $explanation[__CLASS__] = 'The page is not static cacheable via TypoScriptFrontend. Check the first Question on: https://github.com/lochmueller/staticfilecache/blob/master/Documentation/Faq/Index.rst'; } }
[ "public", "function", "checkRule", "(", "TypoScriptFrontendController", "$", "frontendController", ",", "string", "$", "uri", ",", "array", "&", "$", "explanation", ",", "bool", "&", "$", "skipProcessing", ")", "{", "if", "(", "!", "$", "frontendController", "...
Check if the page is static cacheable. Please keep this topic in mind: https://forge.typo3.org/issues/83212 EXT:form honeypot uses anonymous FE user, so the caching is disabled @param TypoScriptFrontendController $frontendController @param string $uri @param array $explanation @param bool $skipProcessing
[ "Check", "if", "the", "page", "is", "static", "cacheable", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/StaticCacheable.php#L29-L34
train
lochmueller/staticfilecache
Classes/Controller/BackendController.php
BackendController.listAction
public function listAction(string $filter = '') { $filter = $this->setFilter($filter); $this->view->assignMultiple([ 'rows' => $this->getCachePagesEntries($filter), 'filter' => $filter, 'pageId' => $this->getCurrentUid(), 'backendDisplayMode' => $this->getDisplayMode(), ]); }
php
public function listAction(string $filter = '') { $filter = $this->setFilter($filter); $this->view->assignMultiple([ 'rows' => $this->getCachePagesEntries($filter), 'filter' => $filter, 'pageId' => $this->getCurrentUid(), 'backendDisplayMode' => $this->getDisplayMode(), ]); }
[ "public", "function", "listAction", "(", "string", "$", "filter", "=", "''", ")", "{", "$", "filter", "=", "$", "this", "->", "setFilter", "(", "$", "filter", ")", ";", "$", "this", "->", "view", "->", "assignMultiple", "(", "[", "'rows'", "=>", "$",...
MAIN function for static publishing information. @param string $filter
[ "MAIN", "function", "for", "static", "publishing", "information", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Controller/BackendController.php#L32-L41
train
lochmueller/staticfilecache
Classes/Controller/BackendController.php
BackendController.boostAction
public function boostAction($run = false) { $configurationService = $this->objectManager->get(ConfigurationService::class); $queueRepository = $this->objectManager->get(QueueRepository::class); if ($run) { $items = $queueRepository->findOpen(10); $queueService = GeneralUtility::makeInstance(QueueService::class); try { foreach ($items as $item) { $queueService->runSingleRequest($item); } } catch (\Exception $ex) { } $this->addFlashMessage('Run ' . \count($items) . ' entries', 'Runner', FlashMessage::OK, true); } $this->view->assignMultiple([ 'enable' => (bool)$configurationService->get('boostMode'), 'open' => \count($queueRepository->findOpen(99999999)), 'old' => \count($queueRepository->findOld()), ]); }
php
public function boostAction($run = false) { $configurationService = $this->objectManager->get(ConfigurationService::class); $queueRepository = $this->objectManager->get(QueueRepository::class); if ($run) { $items = $queueRepository->findOpen(10); $queueService = GeneralUtility::makeInstance(QueueService::class); try { foreach ($items as $item) { $queueService->runSingleRequest($item); } } catch (\Exception $ex) { } $this->addFlashMessage('Run ' . \count($items) . ' entries', 'Runner', FlashMessage::OK, true); } $this->view->assignMultiple([ 'enable' => (bool)$configurationService->get('boostMode'), 'open' => \count($queueRepository->findOpen(99999999)), 'old' => \count($queueRepository->findOld()), ]); }
[ "public", "function", "boostAction", "(", "$", "run", "=", "false", ")", "{", "$", "configurationService", "=", "$", "this", "->", "objectManager", "->", "get", "(", "ConfigurationService", "::", "class", ")", ";", "$", "queueRepository", "=", "$", "this", ...
Boost action. @param bool $run
[ "Boost", "action", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Controller/BackendController.php#L48-L69
train
lochmueller/staticfilecache
Classes/Controller/BackendController.php
BackendController.getCachePagesEntries
protected function getCachePagesEntries(string $filter): array { $rows = []; try { $cache = GeneralUtility::makeInstance(CacheService::class)->get(); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems by fetching the cache: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); return $rows; } $dbRows = GeneralUtility::makeInstance(PageRepository::class)->findForBackend($this->getCurrentUid(), $this->getDisplayMode()); foreach ($dbRows as $row) { $cacheEntries = $cache->getByTag('sfc_pageId_' . $row['uid']); foreach ($cacheEntries as $identifier => $info) { $cached = 0 === \count($info['explanation']); if ('all' !== $filter && (('cached' === $filter && !$cached) || ('notCached' === $filter && $cached))) { continue; } $rows[] = [ 'uid' => $row['uid'], 'title' => BackendUtility::getRecordTitle( 'pages', $row, true ), 'identifier' => $identifier, 'info' => $info, ]; } } return $rows; }
php
protected function getCachePagesEntries(string $filter): array { $rows = []; try { $cache = GeneralUtility::makeInstance(CacheService::class)->get(); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems by fetching the cache: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); return $rows; } $dbRows = GeneralUtility::makeInstance(PageRepository::class)->findForBackend($this->getCurrentUid(), $this->getDisplayMode()); foreach ($dbRows as $row) { $cacheEntries = $cache->getByTag('sfc_pageId_' . $row['uid']); foreach ($cacheEntries as $identifier => $info) { $cached = 0 === \count($info['explanation']); if ('all' !== $filter && (('cached' === $filter && !$cached) || ('notCached' === $filter && $cached))) { continue; } $rows[] = [ 'uid' => $row['uid'], 'title' => BackendUtility::getRecordTitle( 'pages', $row, true ), 'identifier' => $identifier, 'info' => $info, ]; } } return $rows; }
[ "protected", "function", "getCachePagesEntries", "(", "string", "$", "filter", ")", ":", "array", "{", "$", "rows", "=", "[", "]", ";", "try", "{", "$", "cache", "=", "GeneralUtility", "::", "makeInstance", "(", "CacheService", "::", "class", ")", "->", ...
Get cache pages entries. @return array
[ "Get", "cache", "pages", "entries", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Controller/BackendController.php#L112-L148
train
lochmueller/staticfilecache
Classes/ViewHelpers/Be/Widget/Controller/PaginateController.php
PaginateController.prepareObjectsSlice
protected function prepareObjectsSlice($itemsPerPage, $offset) { if ($this->objects instanceof QueryResultInterface) { $currentRange = $offset + $itemsPerPage; $endOfRange = \min($currentRange, \count($this->objects)); $query = $this->objects->getQuery(); $query->setLimit($itemsPerPage); if ($offset > 0) { $query->setOffset($offset); if ($currentRange > $endOfRange) { $newLimit = $endOfRange - $offset; $query->setLimit($newLimit); } } $modifiedObjects = $query->execute(); return $modifiedObjects; } if ($this->objects instanceof ObjectStorage) { $modifiedObjects = []; $objectArray = $this->objects->toArray(); $endOfRange = \min($offset + $itemsPerPage, \count($objectArray)); for ($i = $offset; $i < $endOfRange; ++$i) { $modifiedObjects[] = $objectArray[$i]; } return $modifiedObjects; } if (\is_array($this->objects)) { $modifiedObjects = \array_slice($this->objects, $offset, $itemsPerPage); return $modifiedObjects; } throw new \InvalidArgumentException( 'The view helper "' . static::class . '" accepts as argument "QueryResultInterface", "\SplObjectStorage", "ObjectStorage" or an array. ' . 'given: ' . \get_class($this->objects), 1385547291 ); }
php
protected function prepareObjectsSlice($itemsPerPage, $offset) { if ($this->objects instanceof QueryResultInterface) { $currentRange = $offset + $itemsPerPage; $endOfRange = \min($currentRange, \count($this->objects)); $query = $this->objects->getQuery(); $query->setLimit($itemsPerPage); if ($offset > 0) { $query->setOffset($offset); if ($currentRange > $endOfRange) { $newLimit = $endOfRange - $offset; $query->setLimit($newLimit); } } $modifiedObjects = $query->execute(); return $modifiedObjects; } if ($this->objects instanceof ObjectStorage) { $modifiedObjects = []; $objectArray = $this->objects->toArray(); $endOfRange = \min($offset + $itemsPerPage, \count($objectArray)); for ($i = $offset; $i < $endOfRange; ++$i) { $modifiedObjects[] = $objectArray[$i]; } return $modifiedObjects; } if (\is_array($this->objects)) { $modifiedObjects = \array_slice($this->objects, $offset, $itemsPerPage); return $modifiedObjects; } throw new \InvalidArgumentException( 'The view helper "' . static::class . '" accepts as argument "QueryResultInterface", "\SplObjectStorage", "ObjectStorage" or an array. ' . 'given: ' . \get_class($this->objects), 1385547291 ); }
[ "protected", "function", "prepareObjectsSlice", "(", "$", "itemsPerPage", ",", "$", "offset", ")", "{", "if", "(", "$", "this", "->", "objects", "instanceof", "QueryResultInterface", ")", "{", "$", "currentRange", "=", "$", "offset", "+", "$", "itemsPerPage", ...
Copy the prepareObjectsSlice from the frontend paginate viewhelper. @param int $itemsPerPage @param int $offset @throws \InvalidArgumentException @return array|QueryResultInterface
[ "Copy", "the", "prepareObjectsSlice", "from", "the", "frontend", "paginate", "viewhelper", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/ViewHelpers/Be/Widget/Controller/PaginateController.php#L58-L97
train
lochmueller/staticfilecache
Classes/Domain/Repository/PageRepository.php
PageRepository.findForBackend
public function findForBackend($pageId, $displayMode): array { $queryBuilder = $this->createQuery(); $where = []; switch ($displayMode) { case 'current': $where[] = $queryBuilder->expr()->eq('uid', $pageId); break; case 'childs': $where[] = $queryBuilder->expr()->eq('pid', $pageId); break; case 'both': $where[] = $queryBuilder->expr()->eq('uid', $pageId); $where[] = $queryBuilder->expr()->eq('pid', $pageId); break; } return (array)$queryBuilder->select('*') ->from('pages') ->orWhere(...$where) ->execute() ->fetchAll(); }
php
public function findForBackend($pageId, $displayMode): array { $queryBuilder = $this->createQuery(); $where = []; switch ($displayMode) { case 'current': $where[] = $queryBuilder->expr()->eq('uid', $pageId); break; case 'childs': $where[] = $queryBuilder->expr()->eq('pid', $pageId); break; case 'both': $where[] = $queryBuilder->expr()->eq('uid', $pageId); $where[] = $queryBuilder->expr()->eq('pid', $pageId); break; } return (array)$queryBuilder->select('*') ->from('pages') ->orWhere(...$where) ->execute() ->fetchAll(); }
[ "public", "function", "findForBackend", "(", "$", "pageId", ",", "$", "displayMode", ")", ":", "array", "{", "$", "queryBuilder", "=", "$", "this", "->", "createQuery", "(", ")", ";", "$", "where", "=", "[", "]", ";", "switch", "(", "$", "displayMode",...
Get for backend output. @param int $pageId @param string $displayMode @return array
[ "Get", "for", "backend", "output", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Domain/Repository/PageRepository.php#L24-L47
train
lochmueller/staticfilecache
Classes/Cache/Rule/NoUserOrGroupSet.php
NoUserOrGroupSet.checkRule
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { if ($this->isUserOrGroupSet($frontendController)) { $explanation[__CLASS__] = 'User or group are set'; } }
php
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { if ($this->isUserOrGroupSet($frontendController)) { $explanation[__CLASS__] = 'User or group are set'; } }
[ "public", "function", "checkRule", "(", "TypoScriptFrontendController", "$", "frontendController", ",", "string", "$", "uri", ",", "array", "&", "$", "explanation", ",", "bool", "&", "$", "skipProcessing", ")", "{", "if", "(", "$", "this", "->", "isUserOrGroup...
Check if no user or group is set. @param TypoScriptFrontendController $frontendController @param string $uri @param array $explanation @param bool $skipProcessing
[ "Check", "if", "no", "user", "or", "group", "is", "set", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/NoUserOrGroupSet.php#L30-L35
train
lochmueller/staticfilecache
Classes/Hook/LogNoCache.php
LogNoCache.log
public function log(&$parameters, $parentObject) { if ($parameters['pObj']) { if ($parameters['pObj']->no_cache) { $timeOutTime = 0; StaticFileCache::getInstance() ->insertPageInCache($parameters['pObj'], $timeOutTime); } } }
php
public function log(&$parameters, $parentObject) { if ($parameters['pObj']) { if ($parameters['pObj']->no_cache) { $timeOutTime = 0; StaticFileCache::getInstance() ->insertPageInCache($parameters['pObj'], $timeOutTime); } } }
[ "public", "function", "log", "(", "&", "$", "parameters", ",", "$", "parentObject", ")", "{", "if", "(", "$", "parameters", "[", "'pObj'", "]", ")", "{", "if", "(", "$", "parameters", "[", "'pObj'", "]", "->", "no_cache", ")", "{", "$", "timeOutTime"...
Log cache miss if no_cache is true. @param array $parameters @param object $parentObject
[ "Log", "cache", "miss", "if", "no_cache", "is", "true", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Hook/LogNoCache.php#L24-L33
train
lochmueller/staticfilecache
Classes/Hook/Crawler.php
Crawler.clearCache
protected function clearCache(TypoScriptFrontendController $parentObject) { $pageId = $parentObject->id; if (!\is_numeric($pageId)) { $parentObject->applicationData['tx_crawler']['log'][] = 'EXT:staticfilecache skipped'; return; } GeneralUtility::makeInstance(CacheService::class)->clearByPageId($pageId); $parentObject->applicationData['tx_crawler']['log'][] = 'EXT:staticfilecache cleared static file'; }
php
protected function clearCache(TypoScriptFrontendController $parentObject) { $pageId = $parentObject->id; if (!\is_numeric($pageId)) { $parentObject->applicationData['tx_crawler']['log'][] = 'EXT:staticfilecache skipped'; return; } GeneralUtility::makeInstance(CacheService::class)->clearByPageId($pageId); $parentObject->applicationData['tx_crawler']['log'][] = 'EXT:staticfilecache cleared static file'; }
[ "protected", "function", "clearCache", "(", "TypoScriptFrontendController", "$", "parentObject", ")", "{", "$", "pageId", "=", "$", "parentObject", "->", "id", ";", "if", "(", "!", "\\", "is_numeric", "(", "$", "pageId", ")", ")", "{", "$", "parentObject", ...
Execute the clear cache. @param TypoScriptFrontendController $parentObject @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
[ "Execute", "the", "clear", "cache", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Hook/Crawler.php#L50-L61
train
lochmueller/staticfilecache
Classes/Cache/Rule/ForceStaticCache.php
ForceStaticCache.isForceCacheUri
protected function isForceCacheUri(TypoScriptFrontendController $frontendController, string $uri): bool { $signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class); $forceStatic = (bool)$frontendController->page['tx_staticfilecache_cache_force']; $params = [ 'forceStatic' => $forceStatic, 'frontendController' => $frontendController, 'uri' => $uri, ]; try { $params = $signalSlotDispatcher->dispatch(__CLASS__, 'isForceCacheUri', $params); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems by calling signal: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); } return (bool)$params['forceStatic']; }
php
protected function isForceCacheUri(TypoScriptFrontendController $frontendController, string $uri): bool { $signalSlotDispatcher = GeneralUtility::makeInstance(Dispatcher::class); $forceStatic = (bool)$frontendController->page['tx_staticfilecache_cache_force']; $params = [ 'forceStatic' => $forceStatic, 'frontendController' => $frontendController, 'uri' => $uri, ]; try { $params = $signalSlotDispatcher->dispatch(__CLASS__, 'isForceCacheUri', $params); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems by calling signal: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); } return (bool)$params['forceStatic']; }
[ "protected", "function", "isForceCacheUri", "(", "TypoScriptFrontendController", "$", "frontendController", ",", "string", "$", "uri", ")", ":", "bool", "{", "$", "signalSlotDispatcher", "=", "GeneralUtility", "::", "makeInstance", "(", "Dispatcher", "::", "class", ...
Is force cache URI? @param TypoScriptFrontendController $frontendController @param string $uri @return bool
[ "Is", "force", "cache", "URI?" ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/ForceStaticCache.php#L74-L91
train
lochmueller/staticfilecache
Classes/Hook/LogoffFrontendUser.php
LogoffFrontendUser.logoff
public function logoff($parameters, AbstractUserAuthentication $parentObject) { $service = GeneralUtility::makeInstance(CookieService::class); if (('FE' === $parentObject->loginType || 'BE' === $parentObject->loginType) && true === $parentObject->newSessionID) { $service->setCookie(\time() + 3600); } else { $service->setCookie(\time() - 3600); } }
php
public function logoff($parameters, AbstractUserAuthentication $parentObject) { $service = GeneralUtility::makeInstance(CookieService::class); if (('FE' === $parentObject->loginType || 'BE' === $parentObject->loginType) && true === $parentObject->newSessionID) { $service->setCookie(\time() + 3600); } else { $service->setCookie(\time() - 3600); } }
[ "public", "function", "logoff", "(", "$", "parameters", ",", "AbstractUserAuthentication", "$", "parentObject", ")", "{", "$", "service", "=", "GeneralUtility", "::", "makeInstance", "(", "CookieService", "::", "class", ")", ";", "if", "(", "(", "'FE'", "===",...
Logoff process. @param array $parameters @param AbstractUserAuthentication $parentObject
[ "Logoff", "process", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Hook/LogoffFrontendUser.php#L26-L34
train
lochmueller/staticfilecache
Classes/Service/CacheService.php
CacheService.clearByPageId
public function clearByPageId(int $pageId) { $cache = $this->get(); $cacheEntries = \array_keys($cache->getByTag('pageId_' . $pageId)); foreach ($cacheEntries as $cacheEntry) { $cache->remove($cacheEntry); } }
php
public function clearByPageId(int $pageId) { $cache = $this->get(); $cacheEntries = \array_keys($cache->getByTag('pageId_' . $pageId)); foreach ($cacheEntries as $cacheEntry) { $cache->remove($cacheEntry); } }
[ "public", "function", "clearByPageId", "(", "int", "$", "pageId", ")", "{", "$", "cache", "=", "$", "this", "->", "get", "(", ")", ";", "$", "cacheEntries", "=", "\\", "array_keys", "(", "$", "cache", "->", "getByTag", "(", "'pageId_'", ".", "$", "pa...
Clear cache by page ID. @param int $pageId @throws NoSuchCacheException
[ "Clear", "cache", "by", "page", "ID", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/CacheService.php#L52-L59
train
lochmueller/staticfilecache
Classes/Cache/Rule/NoFakeFrontend.php
NoFakeFrontend.checkRule
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { $ignorePaths = [ // Solr extension '/solr/Classes/Eid/Suggest.php', '/solr/Classes/Util.php', ]; foreach ($ignorePaths as $ignorePath) { foreach ($this->getCallPaths() as $path) { if (StringUtility::endsWith($path, $ignorePath)) { $skipProcessing = true; return; } } } }
php
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { $ignorePaths = [ // Solr extension '/solr/Classes/Eid/Suggest.php', '/solr/Classes/Util.php', ]; foreach ($ignorePaths as $ignorePath) { foreach ($this->getCallPaths() as $path) { if (StringUtility::endsWith($path, $ignorePath)) { $skipProcessing = true; return; } } } }
[ "public", "function", "checkRule", "(", "TypoScriptFrontendController", "$", "frontendController", ",", "string", "$", "uri", ",", "array", "&", "$", "explanation", ",", "bool", "&", "$", "skipProcessing", ")", "{", "$", "ignorePaths", "=", "[", "// Solr extensi...
No fake frontend. @param TypoScriptFrontendController $frontendController @param string $uri @param array $explanation @param bool $skipProcessing
[ "No", "fake", "frontend", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/NoFakeFrontend.php#L27-L43
train
lochmueller/staticfilecache
Classes/Cache/Rule/NoFakeFrontend.php
NoFakeFrontend.getCallPaths
protected function getCallPaths(): array { $paths = []; $backTrace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($backTrace as $value) { if (isset($value['file'])) { $paths[] = $value['file']; } } return $paths; }
php
protected function getCallPaths(): array { $paths = []; $backTrace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($backTrace as $value) { if (isset($value['file'])) { $paths[] = $value['file']; } } return $paths; }
[ "protected", "function", "getCallPaths", "(", ")", ":", "array", "{", "$", "paths", "=", "[", "]", ";", "$", "backTrace", "=", "\\", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "foreach", "(", "$", "backTrace", "as", "$", "value", ")",...
Get all call paths. @return array
[ "Get", "all", "call", "paths", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/NoFakeFrontend.php#L50-L61
train
lochmueller/staticfilecache
Classes/Service/ClientService.php
ClientService.runSingleRequest
public function runSingleRequest(string $url): int { try { $host = \parse_url($url, PHP_URL_HOST); if (false === $host) { throw new \Exception('No host in cache_url', 1263782); } $client = $this->getCallableClient($host); $response = $client->get($url); return (int)$response->getStatusCode(); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems in single request running: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); } return 900; }
php
public function runSingleRequest(string $url): int { try { $host = \parse_url($url, PHP_URL_HOST); if (false === $host) { throw new \Exception('No host in cache_url', 1263782); } $client = $this->getCallableClient($host); $response = $client->get($url); return (int)$response->getStatusCode(); } catch (\Exception $exception) { $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__); $logger->error('Problems in single request running: ' . $exception->getMessage() . ' / ' . $exception->getFile() . ':' . $exception->getLine()); } return 900; }
[ "public", "function", "runSingleRequest", "(", "string", "$", "url", ")", ":", "int", "{", "try", "{", "$", "host", "=", "\\", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ";", "if", "(", "false", "===", "$", "host", ")", "{", "throw", "...
Run a single request with guzzle and return status code. @param string $url @return int
[ "Run", "a", "single", "request", "with", "guzzle", "and", "return", "status", "code", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/ClientService.php#L29-L46
train
lochmueller/staticfilecache
Classes/Service/ClientService.php
ClientService.getCallableClient
protected function getCallableClient(string $domain): Client { if (!\class_exists(Client::class) || !\class_exists(CookieJar::class)) { throw new \Exception('You need guzzle to handle the Queue Management', 1236728342); } $jar = GeneralUtility::makeInstance(CookieJar::class); $cookie = GeneralUtility::makeInstance(SetCookie::class); $cookie->setName('staticfilecache'); $cookie->setValue('1'); $cookie->setPath('/'); $cookie->setExpires((new DateTimeService())->getCurrentTime() + 3600); $cookie->setDomain($domain); $jar->setCookie($cookie); $options = [ 'cookies' => $jar, 'allow_redirects' => [ 'max' => false, ], 'headers' => [ 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0', ], ]; return GeneralUtility::makeInstance(Client::class, $options); }
php
protected function getCallableClient(string $domain): Client { if (!\class_exists(Client::class) || !\class_exists(CookieJar::class)) { throw new \Exception('You need guzzle to handle the Queue Management', 1236728342); } $jar = GeneralUtility::makeInstance(CookieJar::class); $cookie = GeneralUtility::makeInstance(SetCookie::class); $cookie->setName('staticfilecache'); $cookie->setValue('1'); $cookie->setPath('/'); $cookie->setExpires((new DateTimeService())->getCurrentTime() + 3600); $cookie->setDomain($domain); $jar->setCookie($cookie); $options = [ 'cookies' => $jar, 'allow_redirects' => [ 'max' => false, ], 'headers' => [ 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0', ], ]; return GeneralUtility::makeInstance(Client::class, $options); }
[ "protected", "function", "getCallableClient", "(", "string", "$", "domain", ")", ":", "Client", "{", "if", "(", "!", "\\", "class_exists", "(", "Client", "::", "class", ")", "||", "!", "\\", "class_exists", "(", "CookieJar", "::", "class", ")", ")", "{",...
Get a cllable client. @param string $domain @throws \Exception @return Client
[ "Get", "a", "cllable", "client", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/ClientService.php#L57-L81
train
lochmueller/staticfilecache
Classes/Hook/Cache/InsertPageIncacheHook.php
InsertPageIncacheHook.insertPageInCache
public function insertPageInCache(TypoScriptFrontendController $tsfe, $timeOutTime) { $this->getStaticFileCache()->insertPageInCache($tsfe, (int)$timeOutTime); }
php
public function insertPageInCache(TypoScriptFrontendController $tsfe, $timeOutTime) { $this->getStaticFileCache()->insertPageInCache($tsfe, (int)$timeOutTime); }
[ "public", "function", "insertPageInCache", "(", "TypoScriptFrontendController", "$", "tsfe", ",", "$", "timeOutTime", ")", "{", "$", "this", "->", "getStaticFileCache", "(", ")", "->", "insertPageInCache", "(", "$", "tsfe", ",", "(", "int", ")", "$", "timeOutT...
Insert cache entry. @param TypoScriptFrontendController $tsfe The parent object @param int $timeOutTime The timestamp when the page times out
[ "Insert", "cache", "entry", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Hook/Cache/InsertPageIncacheHook.php#L24-L27
train
lochmueller/staticfilecache
Classes/ViewHelpers/Be/Widget/PaginateViewHelper.php
PaginateViewHelper.initiateSubRequest
protected function initiateSubRequest() { $objectManager = new ObjectManager(); $this->controller = $objectManager->get(PaginateController::class); return parent::initiateSubRequest(); }
php
protected function initiateSubRequest() { $objectManager = new ObjectManager(); $this->controller = $objectManager->get(PaginateController::class); return parent::initiateSubRequest(); }
[ "protected", "function", "initiateSubRequest", "(", ")", "{", "$", "objectManager", "=", "new", "ObjectManager", "(", ")", ";", "$", "this", "->", "controller", "=", "$", "objectManager", "->", "get", "(", "PaginateController", "::", "class", ")", ";", "retu...
Init subrequest. @return \TYPO3\CMS\Extbase\Mvc\ResponseInterface
[ "Init", "subrequest", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/ViewHelpers/Be/Widget/PaginateViewHelper.php#L56-L62
train
lochmueller/staticfilecache
Classes/Cache/Rule/DomainCacheable.php
DomainCacheable.checkRule
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { $domainString = \parse_url($uri, PHP_URL_HOST); $domainRepository = GeneralUtility::makeInstance(DomainRepository::class); $domain = $domainRepository->findOneByDomainName($domainString); if (\is_array($domain) && \array_key_exists('tx_staticfilecache_cache', $domain)) { $cachableDomain = (bool)$domain['tx_staticfilecache_cache']; if (!$cachableDomain) { $explanation[__CLASS__] = 'static cache disabled on domain: ' . $domainString; } } }
php
public function checkRule(TypoScriptFrontendController $frontendController, string $uri, array &$explanation, bool &$skipProcessing) { $domainString = \parse_url($uri, PHP_URL_HOST); $domainRepository = GeneralUtility::makeInstance(DomainRepository::class); $domain = $domainRepository->findOneByDomainName($domainString); if (\is_array($domain) && \array_key_exists('tx_staticfilecache_cache', $domain)) { $cachableDomain = (bool)$domain['tx_staticfilecache_cache']; if (!$cachableDomain) { $explanation[__CLASS__] = 'static cache disabled on domain: ' . $domainString; } } }
[ "public", "function", "checkRule", "(", "TypoScriptFrontendController", "$", "frontendController", ",", "string", "$", "uri", ",", "array", "&", "$", "explanation", ",", "bool", "&", "$", "skipProcessing", ")", "{", "$", "domainString", "=", "\\", "parse_url", ...
Check if the current domain is static cacheable in Domain property context. @param TypoScriptFrontendController $frontendController @param string $uri @param array $explanation @param bool $skipProcessing
[ "Check", "if", "the", "current", "domain", "is", "static", "cacheable", "in", "Domain", "property", "context", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Cache/Rule/DomainCacheable.php#L28-L39
train
lochmueller/staticfilecache
Classes/Service/TagService.php
TagService.send
public function send() { if (!$this->isEnable()) { return; } $tags = $this->getTags(); if (!empty($tags)) { \header($this->getHeaderName() . ': ' . \implode(',', $tags)); } }
php
public function send() { if (!$this->isEnable()) { return; } $tags = $this->getTags(); if (!empty($tags)) { \header($this->getHeaderName() . ': ' . \implode(',', $tags)); } }
[ "public", "function", "send", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isEnable", "(", ")", ")", "{", "return", ";", "}", "$", "tags", "=", "$", "this", "->", "getTags", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "tags", ")",...
Send the cache headers.
[ "Send", "the", "cache", "headers", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Service/TagService.php#L44-L54
train
lochmueller/staticfilecache
Classes/Hook/UninstallProcess.php
UninstallProcess.afterExtensionUninstall
public function afterExtensionUninstall(string $extensionKey, InstallUtility $installUtility) { if (!\defined('SFC_QUEUE_WORKER')) { \define('SFC_QUEUE_WORKER', true); } $cacheService = GeneralUtility::makeInstance(CacheService::class); $cacheService->get()->flush(); return [$extensionKey, $installUtility]; }
php
public function afterExtensionUninstall(string $extensionKey, InstallUtility $installUtility) { if (!\defined('SFC_QUEUE_WORKER')) { \define('SFC_QUEUE_WORKER', true); } $cacheService = GeneralUtility::makeInstance(CacheService::class); $cacheService->get()->flush(); return [$extensionKey, $installUtility]; }
[ "public", "function", "afterExtensionUninstall", "(", "string", "$", "extensionKey", ",", "InstallUtility", "$", "installUtility", ")", "{", "if", "(", "!", "\\", "defined", "(", "'SFC_QUEUE_WORKER'", ")", ")", "{", "\\", "define", "(", "'SFC_QUEUE_WORKER'", ","...
Check if staticfile cache is deactived and drop the current cache. @param string $extensionKey @param InstallUtility $installUtility @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException @return array
[ "Check", "if", "staticfile", "cache", "is", "deactived", "and", "drop", "the", "current", "cache", "." ]
1435f20afb95f88ae6a9bd935b2fae1e7d034f60
https://github.com/lochmueller/staticfilecache/blob/1435f20afb95f88ae6a9bd935b2fae1e7d034f60/Classes/Hook/UninstallProcess.php#L30-L39
train