id
int32
0
241k
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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
12,900
jakew/path
src/Path.php
Path.valid
public function valid() { if (!isset($this->keys[$this->index])) { return false; } $hasContent = $this->hasContentForKey($this->keys[$this->index], $this->content); if (!$hasContent && $this->throwOnNotReachable) { $message = sprintf('No current content contains new content at a key of "%s".', $this->keys[$this->index]); throw new PathNotReachableException($this->keys[$this->index], $message); } return $hasContent; }
php
public function valid() { if (!isset($this->keys[$this->index])) { return false; } $hasContent = $this->hasContentForKey($this->keys[$this->index], $this->content); if (!$hasContent && $this->throwOnNotReachable) { $message = sprintf('No current content contains new content at a key of "%s".', $this->keys[$this->index]); throw new PathNotReachableException($this->keys[$this->index], $message); } return $hasContent; }
[ "public", "function", "valid", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "keys", "[", "$", "this", "->", "index", "]", ")", ")", "{", "return", "false", ";", "}", "$", "hasContent", "=", "$", "this", "->", "hasContentForKey", "(", "$", "this", "->", "keys", "[", "$", "this", "->", "index", "]", ",", "$", "this", "->", "content", ")", ";", "if", "(", "!", "$", "hasContent", "&&", "$", "this", "->", "throwOnNotReachable", ")", "{", "$", "message", "=", "sprintf", "(", "'No current content contains new content at a key of \"%s\".'", ",", "$", "this", "->", "keys", "[", "$", "this", "->", "index", "]", ")", ";", "throw", "new", "PathNotReachableException", "(", "$", "this", "->", "keys", "[", "$", "this", "->", "index", "]", ",", "$", "message", ")", ";", "}", "return", "$", "hasContent", ";", "}" ]
Returns true if content exists for the current key. @return bool True if content exists for the current key.
[ "Returns", "true", "if", "content", "exists", "for", "the", "current", "key", "." ]
9cc35dad3e74f11b127954a682363f2fa92201fd
https://github.com/jakew/path/blob/9cc35dad3e74f11b127954a682363f2fa92201fd/src/Path.php#L131-L145
12,901
emaphp/eMapper
lib/eMapper/Procedure/StoredProcedure.php
StoredProcedure.call
public function call() { $args = func_get_args(); $this->build($args); return $this->mapper->merge($this->config)->execute($this->expression, $args); }
php
public function call() { $args = func_get_args(); $this->build($args); return $this->mapper->merge($this->config)->execute($this->expression, $args); }
[ "public", "function", "call", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "this", "->", "build", "(", "$", "args", ")", ";", "return", "$", "this", "->", "mapper", "->", "merge", "(", "$", "this", "->", "config", ")", "->", "execute", "(", "$", "this", "->", "expression", ",", "$", "args", ")", ";", "}" ]
Invokes a stored procedure with the given list of arguments @return mixed
[ "Invokes", "a", "stored", "procedure", "with", "the", "given", "list", "of", "arguments" ]
df7100e601d2a1363d07028a786b6ceb22271829
https://github.com/emaphp/eMapper/blob/df7100e601d2a1363d07028a786b6ceb22271829/lib/eMapper/Procedure/StoredProcedure.php#L76-L80
12,902
emaphp/eMapper
lib/eMapper/Procedure/StoredProcedure.php
StoredProcedure.callWith
public function callWith($args) { $this->build($args); return $this->mapper->merge($this->config)->execute($this->expression, $args); }
php
public function callWith($args) { $this->build($args); return $this->mapper->merge($this->config)->execute($this->expression, $args); }
[ "public", "function", "callWith", "(", "$", "args", ")", "{", "$", "this", "->", "build", "(", "$", "args", ")", ";", "return", "$", "this", "->", "mapper", "->", "merge", "(", "$", "this", "->", "config", ")", "->", "execute", "(", "$", "this", "->", "expression", ",", "$", "args", ")", ";", "}" ]
Invokes a stored procedure with the given array of arguments @param array $args @return mixed
[ "Invokes", "a", "stored", "procedure", "with", "the", "given", "array", "of", "arguments" ]
df7100e601d2a1363d07028a786b6ceb22271829
https://github.com/emaphp/eMapper/blob/df7100e601d2a1363d07028a786b6ceb22271829/lib/eMapper/Procedure/StoredProcedure.php#L87-L90
12,903
emaphp/eMapper
lib/eMapper/Procedure/StoredProcedure.php
StoredProcedure.argTypes
public function argTypes($types) { is_array($types) ? $this->argumentTypes = $types : $this->argumentTypes = func_get_args(); return $this; }
php
public function argTypes($types) { is_array($types) ? $this->argumentTypes = $types : $this->argumentTypes = func_get_args(); return $this; }
[ "public", "function", "argTypes", "(", "$", "types", ")", "{", "is_array", "(", "$", "types", ")", "?", "$", "this", "->", "argumentTypes", "=", "$", "types", ":", "$", "this", "->", "argumentTypes", "=", "func_get_args", "(", ")", ";", "return", "$", "this", ";", "}" ]
Configures argument types @param array $types @return \eMapper\Procedure\StoredProcedure
[ "Configures", "argument", "types" ]
df7100e601d2a1363d07028a786b6ceb22271829
https://github.com/emaphp/eMapper/blob/df7100e601d2a1363d07028a786b6ceb22271829/lib/eMapper/Procedure/StoredProcedure.php#L111-L114
12,904
pacificnm/pacificnm-history
src/Mapper/MysqlMapper.php
MysqlMapper.filter
protected function filter(array $filter) { // email if(array_key_exists('authEmail', $filter) && strlen($filter['authEmail']) > 0) { $this->select->where->like('auth.auth_email', $filter['authEmail'] . '%'); } //auth id if(array_key_exists('authId', $filter) && $filter['authId'] > 0) { $this->select->where(array( 'history.auth_id = ?' => $filter['authId'] )); } return $this; }
php
protected function filter(array $filter) { // email if(array_key_exists('authEmail', $filter) && strlen($filter['authEmail']) > 0) { $this->select->where->like('auth.auth_email', $filter['authEmail'] . '%'); } //auth id if(array_key_exists('authId', $filter) && $filter['authId'] > 0) { $this->select->where(array( 'history.auth_id = ?' => $filter['authId'] )); } return $this; }
[ "protected", "function", "filter", "(", "array", "$", "filter", ")", "{", "// email", "if", "(", "array_key_exists", "(", "'authEmail'", ",", "$", "filter", ")", "&&", "strlen", "(", "$", "filter", "[", "'authEmail'", "]", ")", ">", "0", ")", "{", "$", "this", "->", "select", "->", "where", "->", "like", "(", "'auth.auth_email'", ",", "$", "filter", "[", "'authEmail'", "]", ".", "'%'", ")", ";", "}", "//auth id", "if", "(", "array_key_exists", "(", "'authId'", ",", "$", "filter", ")", "&&", "$", "filter", "[", "'authId'", "]", ">", "0", ")", "{", "$", "this", "->", "select", "->", "where", "(", "array", "(", "'history.auth_id = ?'", "=>", "$", "filter", "[", "'authId'", "]", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Filters and search @param array $filter @return \History\Mapper\MysqlMapper
[ "Filters", "and", "search" ]
d81be7c7fed6f0a1f41bdf5b321bd7b8f0c9e1db
https://github.com/pacificnm/pacificnm-history/blob/d81be7c7fed6f0a1f41bdf5b321bd7b8f0c9e1db/src/Mapper/MysqlMapper.php#L132-L147
12,905
easy-system/es-error
src/TemplateRenderer/ErrorRenderer.php
ErrorRenderer.render
public function render($__template, array $__variables = []) { extract($__variables); try { ob_start(); include $this->getResolver()->resolve($__template); $__return = ob_get_clean(); } catch (Error $__error) { ob_end_clean(); throw $__error; } catch (Exception $__exception) { ob_end_clean(); throw $__exception; } return $__return; }
php
public function render($__template, array $__variables = []) { extract($__variables); try { ob_start(); include $this->getResolver()->resolve($__template); $__return = ob_get_clean(); } catch (Error $__error) { ob_end_clean(); throw $__error; } catch (Exception $__exception) { ob_end_clean(); throw $__exception; } return $__return; }
[ "public", "function", "render", "(", "$", "__template", ",", "array", "$", "__variables", "=", "[", "]", ")", "{", "extract", "(", "$", "__variables", ")", ";", "try", "{", "ob_start", "(", ")", ";", "include", "$", "this", "->", "getResolver", "(", ")", "->", "resolve", "(", "$", "__template", ")", ";", "$", "__return", "=", "ob_get_clean", "(", ")", ";", "}", "catch", "(", "Error", "$", "__error", ")", "{", "ob_end_clean", "(", ")", ";", "throw", "$", "__error", ";", "}", "catch", "(", "Exception", "$", "__exception", ")", "{", "ob_end_clean", "(", ")", ";", "throw", "$", "__exception", ";", "}", "return", "$", "__return", ";", "}" ]
Renders template. @param string $__template The name of error template @param array $__variables Optional; the variables to rendering @throws \Exception Translates any exception thrown during the rendering @throws \Error Translates any error thrown during the rendering @return string The string representation of error
[ "Renders", "template", "." ]
5248c52f2992acc9ddf3542092ad7bbbb440e621
https://github.com/easy-system/es-error/blob/5248c52f2992acc9ddf3542092ad7bbbb440e621/src/TemplateRenderer/ErrorRenderer.php#L52-L69
12,906
phapi/endpoint
src/Phapi/Endpoint.php
Endpoint.outputMultipleValues
protected function outputMultipleValues(array $output, $key, $value, $longKey) { // remove the key from the value and remove whitespace $newValue = str_replace($longKey.' ', '', trim($value)); // check if there was a key to remove if (trim($value) !== $newValue) { // the key was removed and that means we wasn't to add the line as a new row in the array $output[$key][] = $newValue; } else { // the key wasn't removed so we want to merge this line with the previous one // count rows in array to get the last key $last = count($output[$key]) -1; // merge this line with the previous one $output[$key][$last] = $output[$key][$last]. ' '. $newValue; } return $output; }
php
protected function outputMultipleValues(array $output, $key, $value, $longKey) { // remove the key from the value and remove whitespace $newValue = str_replace($longKey.' ', '', trim($value)); // check if there was a key to remove if (trim($value) !== $newValue) { // the key was removed and that means we wasn't to add the line as a new row in the array $output[$key][] = $newValue; } else { // the key wasn't removed so we want to merge this line with the previous one // count rows in array to get the last key $last = count($output[$key]) -1; // merge this line with the previous one $output[$key][$last] = $output[$key][$last]. ' '. $newValue; } return $output; }
[ "protected", "function", "outputMultipleValues", "(", "array", "$", "output", ",", "$", "key", ",", "$", "value", ",", "$", "longKey", ")", "{", "// remove the key from the value and remove whitespace", "$", "newValue", "=", "str_replace", "(", "$", "longKey", ".", "' '", ",", "''", ",", "trim", "(", "$", "value", ")", ")", ";", "// check if there was a key to remove", "if", "(", "trim", "(", "$", "value", ")", "!==", "$", "newValue", ")", "{", "// the key was removed and that means we wasn't to add the line as a new row in the array", "$", "output", "[", "$", "key", "]", "[", "]", "=", "$", "newValue", ";", "}", "else", "{", "// the key wasn't removed so we want to merge this line with the previous one", "// count rows in array to get the last key", "$", "last", "=", "count", "(", "$", "output", "[", "$", "key", "]", ")", "-", "1", ";", "// merge this line with the previous one", "$", "output", "[", "$", "key", "]", "[", "$", "last", "]", "=", "$", "output", "[", "$", "key", "]", "[", "$", "last", "]", ".", "' '", ".", "$", "newValue", ";", "}", "return", "$", "output", ";", "}" ]
Handle output with multiple values @param array $output @param $key @param $value @param $longKey @return array
[ "Handle", "output", "with", "multiple", "values" ]
dcf57d915eea2c47e3075ad98ccbd82bc294e0f5
https://github.com/phapi/endpoint/blob/dcf57d915eea2c47e3075ad98ccbd82bc294e0f5/src/Phapi/Endpoint.php#L250-L268
12,907
phapi/endpoint
src/Phapi/Endpoint.php
Endpoint.outputSingleValue
protected function outputSingleValue(array $output, $key, $value, $longKey) { // save the current value $oldValue = $output[$key]; // remove the key from the value and remove whitespace $newValue = trim(str_replace($longKey.' ', '', trim($value))); // check if there was a key to remove if (trim($value) !== $newValue) { // the key was removed so we want to create an array with the previous and new value $output[$key] = [$oldValue, $newValue]; } else { // the wasn't a key to remove so we want to merge this line with the previous one $output[$key] .= ' '. $newValue; } return $output; }
php
protected function outputSingleValue(array $output, $key, $value, $longKey) { // save the current value $oldValue = $output[$key]; // remove the key from the value and remove whitespace $newValue = trim(str_replace($longKey.' ', '', trim($value))); // check if there was a key to remove if (trim($value) !== $newValue) { // the key was removed so we want to create an array with the previous and new value $output[$key] = [$oldValue, $newValue]; } else { // the wasn't a key to remove so we want to merge this line with the previous one $output[$key] .= ' '. $newValue; } return $output; }
[ "protected", "function", "outputSingleValue", "(", "array", "$", "output", ",", "$", "key", ",", "$", "value", ",", "$", "longKey", ")", "{", "// save the current value", "$", "oldValue", "=", "$", "output", "[", "$", "key", "]", ";", "// remove the key from the value and remove whitespace", "$", "newValue", "=", "trim", "(", "str_replace", "(", "$", "longKey", ".", "' '", ",", "''", ",", "trim", "(", "$", "value", ")", ")", ")", ";", "// check if there was a key to remove", "if", "(", "trim", "(", "$", "value", ")", "!==", "$", "newValue", ")", "{", "// the key was removed so we want to create an array with the previous and new value", "$", "output", "[", "$", "key", "]", "=", "[", "$", "oldValue", ",", "$", "newValue", "]", ";", "}", "else", "{", "// the wasn't a key to remove so we want to merge this line with the previous one", "$", "output", "[", "$", "key", "]", ".=", "' '", ".", "$", "newValue", ";", "}", "return", "$", "output", ";", "}" ]
Handle output with single value @param array $output @param $key @param $value @param $longKey @return array
[ "Handle", "output", "with", "single", "value" ]
dcf57d915eea2c47e3075ad98ccbd82bc294e0f5
https://github.com/phapi/endpoint/blob/dcf57d915eea2c47e3075ad98ccbd82bc294e0f5/src/Phapi/Endpoint.php#L279-L297
12,908
gap-db/orm
GapOrm/Mapper/BaseModel.php
BaseModel.convertFromDB
private function convertFromDB($obj) { foreach ($this->fields as $field) { switch ($field->type()) { case self::FIELD_TYPE_BOOL : $obj->{$field->identifier()} = (bool) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_INT : $obj->{$field->identifier()} = (int) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_FLOAT : $obj->{$field->identifier()} = (float) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_STR : break; case self::FIELD_TYPE_DATETIME : if ($obj->{$field->identifier()} === '0') { $obj->{$field->identifier()} = false; } else { $d = new \DateTime(); if (!is_object($obj->{$field->identifier()})) { $d->setTimestamp($obj->{$field->identifier()}); $obj->{$field->identifier()} = $d; } $obj->{$field->identifier()} = $d; } break; case self::FIELD_TYPE_STR_ARRAY : $delimiter = '(^!)'; if (empty($obj->{$field->identifier()})) $obj->{$field->identifier()} = []; else $obj->{$field->identifier()} = array_map(function($v) use ($delimiter) { return stripslashes($v); }, explode($delimiter, $obj->{$field->identifier()})); break; case self::FIELD_TYPE_INT_ARRAY : $arr = empty($obj->{$field->identifier()}) ? [] : explode(',', $obj->{$field->identifier()}); $obj->{$field->identifier()} = array_map(function($v) { return (int) str_replace('\'', '', $v); }, $arr); break; case self::FIELD_TYPE_OBJ : $obj->{$field->identifier()} = empty($obj->{$field->identifier()}) ? new \StdClass() : json_decode($obj->{$field->identifier()}); break; default : throw new TypeNotExistException(); } } return $obj; }
php
private function convertFromDB($obj) { foreach ($this->fields as $field) { switch ($field->type()) { case self::FIELD_TYPE_BOOL : $obj->{$field->identifier()} = (bool) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_INT : $obj->{$field->identifier()} = (int) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_FLOAT : $obj->{$field->identifier()} = (float) $obj->{$field->identifier()}; break; case self::FIELD_TYPE_STR : break; case self::FIELD_TYPE_DATETIME : if ($obj->{$field->identifier()} === '0') { $obj->{$field->identifier()} = false; } else { $d = new \DateTime(); if (!is_object($obj->{$field->identifier()})) { $d->setTimestamp($obj->{$field->identifier()}); $obj->{$field->identifier()} = $d; } $obj->{$field->identifier()} = $d; } break; case self::FIELD_TYPE_STR_ARRAY : $delimiter = '(^!)'; if (empty($obj->{$field->identifier()})) $obj->{$field->identifier()} = []; else $obj->{$field->identifier()} = array_map(function($v) use ($delimiter) { return stripslashes($v); }, explode($delimiter, $obj->{$field->identifier()})); break; case self::FIELD_TYPE_INT_ARRAY : $arr = empty($obj->{$field->identifier()}) ? [] : explode(',', $obj->{$field->identifier()}); $obj->{$field->identifier()} = array_map(function($v) { return (int) str_replace('\'', '', $v); }, $arr); break; case self::FIELD_TYPE_OBJ : $obj->{$field->identifier()} = empty($obj->{$field->identifier()}) ? new \StdClass() : json_decode($obj->{$field->identifier()}); break; default : throw new TypeNotExistException(); } } return $obj; }
[ "private", "function", "convertFromDB", "(", "$", "obj", ")", "{", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "switch", "(", "$", "field", "->", "type", "(", ")", ")", "{", "case", "self", "::", "FIELD_TYPE_BOOL", ":", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "(", "bool", ")", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_INT", ":", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "(", "int", ")", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_FLOAT", ":", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "(", "float", ")", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_STR", ":", "break", ";", "case", "self", "::", "FIELD_TYPE_DATETIME", ":", "if", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "===", "'0'", ")", "{", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "false", ";", "}", "else", "{", "$", "d", "=", "new", "\\", "DateTime", "(", ")", ";", "if", "(", "!", "is_object", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ")", "{", "$", "d", "->", "setTimestamp", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ";", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "$", "d", ";", "}", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "$", "d", ";", "}", "break", ";", "case", "self", "::", "FIELD_TYPE_STR_ARRAY", ":", "$", "delimiter", "=", "'(^!)'", ";", "if", "(", "empty", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ")", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "[", "]", ";", "else", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "array_map", "(", "function", "(", "$", "v", ")", "use", "(", "$", "delimiter", ")", "{", "return", "stripslashes", "(", "$", "v", ")", ";", "}", ",", "explode", "(", "$", "delimiter", ",", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ")", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_INT_ARRAY", ":", "$", "arr", "=", "empty", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", "?", "[", "]", ":", "explode", "(", "','", ",", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ";", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "array_map", "(", "function", "(", "$", "v", ")", "{", "return", "(", "int", ")", "str_replace", "(", "'\\''", ",", "''", ",", "$", "v", ")", ";", "}", ",", "$", "arr", ")", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_OBJ", ":", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "empty", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", "?", "new", "\\", "StdClass", "(", ")", ":", "json_decode", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ";", "break", ";", "default", ":", "throw", "new", "TypeNotExistException", "(", ")", ";", "}", "}", "return", "$", "obj", ";", "}" ]
Check & convert Fields for Select @param $obj @return mixed @throws \GapOrm\Exceptions\TypeNotExistException
[ "Check", "&", "convert", "Fields", "for", "Select" ]
bcd8e3d27b19b14814d3207489071c4a250a6ac5
https://github.com/gap-db/orm/blob/bcd8e3d27b19b14814d3207489071c4a250a6ac5/GapOrm/Mapper/BaseModel.php#L100-L152
12,909
gap-db/orm
GapOrm/Mapper/BaseModel.php
BaseModel.convertToDB
private function convertToDB($obj) { $o = $this->getEmptyObject(); foreach ($this->fields as $field) { if (!property_exists($obj, $field->identifier())) continue; if (is_null($obj->{$field->identifier()})) { $o->{$field->identifier()} = 'NULL'; continue; } $val = $obj->{$field->identifier()}; switch ($field->type()) { case self::FIELD_TYPE_BOOL : $o->{$field->identifier()} = $val ? 1 : 0; break; case self::FIELD_TYPE_INT : $o->{$field->identifier()} = (int) $val; break; case self::FIELD_TYPE_FLOAT : $o->{$field->identifier()} = (float) $val; break; case self::FIELD_TYPE_STR : $o->{$field->identifier()} = $this->escape($val); break; case self::FIELD_TYPE_DATETIME : if ($val && !is_null($val)) { $o->{$field->identifier()} = $val->getTimestamp(); } else { $o->{$field->identifier()} = 0; } break; case self::FIELD_TYPE_STR_ARRAY : $delimiter = '(^!)'; $o->{$field->identifier()} = '"' . implode($delimiter, array_map(function($v) use ($delimiter) { str_replace($delimiter, '', $v); }, $val)) . '"'; break; case self::FIELD_TYPE_INT_ARRAY : $val = array_map(function($v){ return "'" . (int)$v . "'"; }, $val); $o->{$field->identifier()} = '"' . implode(',', $val) . '"'; break; case self::FIELD_TYPE_OBJ : $o->{$field->identifier()} = '"' . addslashes(json_encode($val)) . '"'; break; default : throw new TypeNotExistException(); } } return $o; }
php
private function convertToDB($obj) { $o = $this->getEmptyObject(); foreach ($this->fields as $field) { if (!property_exists($obj, $field->identifier())) continue; if (is_null($obj->{$field->identifier()})) { $o->{$field->identifier()} = 'NULL'; continue; } $val = $obj->{$field->identifier()}; switch ($field->type()) { case self::FIELD_TYPE_BOOL : $o->{$field->identifier()} = $val ? 1 : 0; break; case self::FIELD_TYPE_INT : $o->{$field->identifier()} = (int) $val; break; case self::FIELD_TYPE_FLOAT : $o->{$field->identifier()} = (float) $val; break; case self::FIELD_TYPE_STR : $o->{$field->identifier()} = $this->escape($val); break; case self::FIELD_TYPE_DATETIME : if ($val && !is_null($val)) { $o->{$field->identifier()} = $val->getTimestamp(); } else { $o->{$field->identifier()} = 0; } break; case self::FIELD_TYPE_STR_ARRAY : $delimiter = '(^!)'; $o->{$field->identifier()} = '"' . implode($delimiter, array_map(function($v) use ($delimiter) { str_replace($delimiter, '', $v); }, $val)) . '"'; break; case self::FIELD_TYPE_INT_ARRAY : $val = array_map(function($v){ return "'" . (int)$v . "'"; }, $val); $o->{$field->identifier()} = '"' . implode(',', $val) . '"'; break; case self::FIELD_TYPE_OBJ : $o->{$field->identifier()} = '"' . addslashes(json_encode($val)) . '"'; break; default : throw new TypeNotExistException(); } } return $o; }
[ "private", "function", "convertToDB", "(", "$", "obj", ")", "{", "$", "o", "=", "$", "this", "->", "getEmptyObject", "(", ")", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "if", "(", "!", "property_exists", "(", "$", "obj", ",", "$", "field", "->", "identifier", "(", ")", ")", ")", "continue", ";", "if", "(", "is_null", "(", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ")", ")", "{", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "'NULL'", ";", "continue", ";", "}", "$", "val", "=", "$", "obj", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", ";", "switch", "(", "$", "field", "->", "type", "(", ")", ")", "{", "case", "self", "::", "FIELD_TYPE_BOOL", ":", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "$", "val", "?", "1", ":", "0", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_INT", ":", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "(", "int", ")", "$", "val", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_FLOAT", ":", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "(", "float", ")", "$", "val", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_STR", ":", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "$", "this", "->", "escape", "(", "$", "val", ")", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_DATETIME", ":", "if", "(", "$", "val", "&&", "!", "is_null", "(", "$", "val", ")", ")", "{", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "$", "val", "->", "getTimestamp", "(", ")", ";", "}", "else", "{", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "0", ";", "}", "break", ";", "case", "self", "::", "FIELD_TYPE_STR_ARRAY", ":", "$", "delimiter", "=", "'(^!)'", ";", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "'\"'", ".", "implode", "(", "$", "delimiter", ",", "array_map", "(", "function", "(", "$", "v", ")", "use", "(", "$", "delimiter", ")", "{", "str_replace", "(", "$", "delimiter", ",", "''", ",", "$", "v", ")", ";", "}", ",", "$", "val", ")", ")", ".", "'\"'", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_INT_ARRAY", ":", "$", "val", "=", "array_map", "(", "function", "(", "$", "v", ")", "{", "return", "\"'\"", ".", "(", "int", ")", "$", "v", ".", "\"'\"", ";", "}", ",", "$", "val", ")", ";", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "'\"'", ".", "implode", "(", "','", ",", "$", "val", ")", ".", "'\"'", ";", "break", ";", "case", "self", "::", "FIELD_TYPE_OBJ", ":", "$", "o", "->", "{", "$", "field", "->", "identifier", "(", ")", "}", "=", "'\"'", ".", "addslashes", "(", "json_encode", "(", "$", "val", ")", ")", ".", "'\"'", ";", "break", ";", "default", ":", "throw", "new", "TypeNotExistException", "(", ")", ";", "}", "}", "return", "$", "o", ";", "}" ]
Check & convert Fields for Insert, Update @param $obj @return object @throws \GapOrm\Exceptions\TypeNotExistException
[ "Check", "&", "convert", "Fields", "for", "Insert", "Update" ]
bcd8e3d27b19b14814d3207489071c4a250a6ac5
https://github.com/gap-db/orm/blob/bcd8e3d27b19b14814d3207489071c4a250a6ac5/GapOrm/Mapper/BaseModel.php#L161-L216
12,910
gap-db/orm
GapOrm/Mapper/BaseModel.php
BaseModel.getPK
public function getPK($require = true) { foreach ($this->fields as $field) { if ($field->pk()) { return $field; } } if ($require) { throw new NoPKException(); } }
php
public function getPK($require = true) { foreach ($this->fields as $field) { if ($field->pk()) { return $field; } } if ($require) { throw new NoPKException(); } }
[ "public", "function", "getPK", "(", "$", "require", "=", "true", ")", "{", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "if", "(", "$", "field", "->", "pk", "(", ")", ")", "{", "return", "$", "field", ";", "}", "}", "if", "(", "$", "require", ")", "{", "throw", "new", "NoPKException", "(", ")", ";", "}", "}" ]
Get primary key @param bool $require @return mixed @throws NoPkException
[ "Get", "primary", "key" ]
bcd8e3d27b19b14814d3207489071c4a250a6ac5
https://github.com/gap-db/orm/blob/bcd8e3d27b19b14814d3207489071c4a250a6ac5/GapOrm/Mapper/BaseModel.php#L235-L246
12,911
potfur/statemachine
src/StateMachine/Collection/Collection.php
Collection.get
public function get($offset) { if (!$this->has($offset)) { throw OutOfRangeException::offsetNotFound($offset); } return $this->collection[$offset]; }
php
public function get($offset) { if (!$this->has($offset)) { throw OutOfRangeException::offsetNotFound($offset); } return $this->collection[$offset]; }
[ "public", "function", "get", "(", "$", "offset", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "offset", ")", ")", "{", "throw", "OutOfRangeException", "::", "offsetNotFound", "(", "$", "offset", ")", ";", "}", "return", "$", "this", "->", "collection", "[", "$", "offset", "]", ";", "}" ]
Return value for given offset @param string $offset @return mixed @throws OutOfRangeException
[ "Return", "value", "for", "given", "offset" ]
6b68535e6c94b10bf618a7809a48f6a8f6d30deb
https://github.com/potfur/statemachine/blob/6b68535e6c94b10bf618a7809a48f6a8f6d30deb/src/StateMachine/Collection/Collection.php#L39-L46
12,912
Kylob/Validator
src/Component.php
Component.certified
public function certified() { if (!is_null($this->submitted)) { return $this->certified; // so we don't overwrite error messages } $errors = array(); $this->values = array(); $this->submitted = false; foreach ($this->data as $field => $data) { if (!is_null($data['value'])) { $this->submitted = true; } if (!empty($data['value'])) { $this->values[$field] = $data['value']; } elseif (strpos($field, '[]') !== false) { $this->values[$field] = array(); } else { $this->values[$field] = (isset($data['rules']['default'])) ? $data['rules']['default'] : ''; } if (!is_null($data['error'])) { $errors[$field] = $data['error']; } } if ($this->submitted) { $submitted = array(); foreach ($this->data as $field => $data) { $value = &$submitted; foreach ($data['field'] as $index) { $value = &$value[$index]; } $value = $this->values[$field]; if (isset($data['rules']['required']) && empty($value)) { $errors[$field] = $this->errorMessage('required'); } elseif (!isset($errors[$field])) { if (isset($data['rules']['equalTo']) && $value != $this->value($data['rules']['equalTo'])) { $errors[$field] = $this->errorMessage('equalTo'); } elseif (isset($data['rules']['notEqualTo']) && $value == $this->value($data['rules']['notEqualTo'])) { $errors[$field] = $this->errorMessage('notEqualTo'); } } } $this->certified = (!empty($errors)) ? false : $submitted; } $this->errors = $errors; return $this->certified; }
php
public function certified() { if (!is_null($this->submitted)) { return $this->certified; // so we don't overwrite error messages } $errors = array(); $this->values = array(); $this->submitted = false; foreach ($this->data as $field => $data) { if (!is_null($data['value'])) { $this->submitted = true; } if (!empty($data['value'])) { $this->values[$field] = $data['value']; } elseif (strpos($field, '[]') !== false) { $this->values[$field] = array(); } else { $this->values[$field] = (isset($data['rules']['default'])) ? $data['rules']['default'] : ''; } if (!is_null($data['error'])) { $errors[$field] = $data['error']; } } if ($this->submitted) { $submitted = array(); foreach ($this->data as $field => $data) { $value = &$submitted; foreach ($data['field'] as $index) { $value = &$value[$index]; } $value = $this->values[$field]; if (isset($data['rules']['required']) && empty($value)) { $errors[$field] = $this->errorMessage('required'); } elseif (!isset($errors[$field])) { if (isset($data['rules']['equalTo']) && $value != $this->value($data['rules']['equalTo'])) { $errors[$field] = $this->errorMessage('equalTo'); } elseif (isset($data['rules']['notEqualTo']) && $value == $this->value($data['rules']['notEqualTo'])) { $errors[$field] = $this->errorMessage('notEqualTo'); } } } $this->certified = (!empty($errors)) ? false : $submitted; } $this->errors = $errors; return $this->certified; }
[ "public", "function", "certified", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "submitted", ")", ")", "{", "return", "$", "this", "->", "certified", ";", "// so we don't overwrite error messages", "}", "$", "errors", "=", "array", "(", ")", ";", "$", "this", "->", "values", "=", "array", "(", ")", ";", "$", "this", "->", "submitted", "=", "false", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "field", "=>", "$", "data", ")", "{", "if", "(", "!", "is_null", "(", "$", "data", "[", "'value'", "]", ")", ")", "{", "$", "this", "->", "submitted", "=", "true", ";", "}", "if", "(", "!", "empty", "(", "$", "data", "[", "'value'", "]", ")", ")", "{", "$", "this", "->", "values", "[", "$", "field", "]", "=", "$", "data", "[", "'value'", "]", ";", "}", "elseif", "(", "strpos", "(", "$", "field", ",", "'[]'", ")", "!==", "false", ")", "{", "$", "this", "->", "values", "[", "$", "field", "]", "=", "array", "(", ")", ";", "}", "else", "{", "$", "this", "->", "values", "[", "$", "field", "]", "=", "(", "isset", "(", "$", "data", "[", "'rules'", "]", "[", "'default'", "]", ")", ")", "?", "$", "data", "[", "'rules'", "]", "[", "'default'", "]", ":", "''", ";", "}", "if", "(", "!", "is_null", "(", "$", "data", "[", "'error'", "]", ")", ")", "{", "$", "errors", "[", "$", "field", "]", "=", "$", "data", "[", "'error'", "]", ";", "}", "}", "if", "(", "$", "this", "->", "submitted", ")", "{", "$", "submitted", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "field", "=>", "$", "data", ")", "{", "$", "value", "=", "&", "$", "submitted", ";", "foreach", "(", "$", "data", "[", "'field'", "]", "as", "$", "index", ")", "{", "$", "value", "=", "&", "$", "value", "[", "$", "index", "]", ";", "}", "$", "value", "=", "$", "this", "->", "values", "[", "$", "field", "]", ";", "if", "(", "isset", "(", "$", "data", "[", "'rules'", "]", "[", "'required'", "]", ")", "&&", "empty", "(", "$", "value", ")", ")", "{", "$", "errors", "[", "$", "field", "]", "=", "$", "this", "->", "errorMessage", "(", "'required'", ")", ";", "}", "elseif", "(", "!", "isset", "(", "$", "errors", "[", "$", "field", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'rules'", "]", "[", "'equalTo'", "]", ")", "&&", "$", "value", "!=", "$", "this", "->", "value", "(", "$", "data", "[", "'rules'", "]", "[", "'equalTo'", "]", ")", ")", "{", "$", "errors", "[", "$", "field", "]", "=", "$", "this", "->", "errorMessage", "(", "'equalTo'", ")", ";", "}", "elseif", "(", "isset", "(", "$", "data", "[", "'rules'", "]", "[", "'notEqualTo'", "]", ")", "&&", "$", "value", "==", "$", "this", "->", "value", "(", "$", "data", "[", "'rules'", "]", "[", "'notEqualTo'", "]", ")", ")", "{", "$", "errors", "[", "$", "field", "]", "=", "$", "this", "->", "errorMessage", "(", "'notEqualTo'", ")", ";", "}", "}", "}", "$", "this", "->", "certified", "=", "(", "!", "empty", "(", "$", "errors", ")", ")", "?", "false", ":", "$", "submitted", ";", "}", "$", "this", "->", "errors", "=", "$", "errors", ";", "return", "$", "this", "->", "certified", ";", "}" ]
This method goes through all of the fields you set above, determines if the form has been sent, and picks out any errors. @return false|array Returns an array of validated and filtered form values for every ``$validator->set('field')`` IF the form was submitted (ie. at least one field has it's $_GET or $_POST counterpart), AND there were no errors. ```php if ($vars = $validator->certified()) { // process $vars } ```
[ "This", "method", "goes", "through", "all", "of", "the", "fields", "you", "set", "above", "determines", "if", "the", "form", "has", "been", "sent", "and", "picks", "out", "any", "errors", "." ]
1687ada6d86dac87dd80796c0665d10b91fb1a6f
https://github.com/Kylob/Validator/blob/1687ada6d86dac87dd80796c0665d10b91fb1a6f/src/Component.php#L368-L414
12,913
Kylob/Validator
src/Component.php
Component.errorMessage
private function errorMessage($rule, $param = null) { if ($rule == 'remote' && isset($this->errors[$param])) { return $this->errorMessage($param); } if (is_null($param)) { $param = ''; } $params = array_pad((array) $param, 2, ''); return (isset($this->errors[$rule])) ? str_replace(array('{0}', '{1}'), $params, $this->errors[$rule]) : null; }
php
private function errorMessage($rule, $param = null) { if ($rule == 'remote' && isset($this->errors[$param])) { return $this->errorMessage($param); } if (is_null($param)) { $param = ''; } $params = array_pad((array) $param, 2, ''); return (isset($this->errors[$rule])) ? str_replace(array('{0}', '{1}'), $params, $this->errors[$rule]) : null; }
[ "private", "function", "errorMessage", "(", "$", "rule", ",", "$", "param", "=", "null", ")", "{", "if", "(", "$", "rule", "==", "'remote'", "&&", "isset", "(", "$", "this", "->", "errors", "[", "$", "param", "]", ")", ")", "{", "return", "$", "this", "->", "errorMessage", "(", "$", "param", ")", ";", "}", "if", "(", "is_null", "(", "$", "param", ")", ")", "{", "$", "param", "=", "''", ";", "}", "$", "params", "=", "array_pad", "(", "(", "array", ")", "$", "param", ",", "2", ",", "''", ")", ";", "return", "(", "isset", "(", "$", "this", "->", "errors", "[", "$", "rule", "]", ")", ")", "?", "str_replace", "(", "array", "(", "'{0}'", ",", "'{1}'", ")", ",", "$", "params", ",", "$", "this", "->", "errors", "[", "$", "rule", "]", ")", ":", "null", ";", "}" ]
A helper method to retrieve the associated error message when something goes wrong. @param string $rule @param mixed $param @return null|string
[ "A", "helper", "method", "to", "retrieve", "the", "associated", "error", "message", "when", "something", "goes", "wrong", "." ]
1687ada6d86dac87dd80796c0665d10b91fb1a6f
https://github.com/Kylob/Validator/blob/1687ada6d86dac87dd80796c0665d10b91fb1a6f/src/Component.php#L982-L993
12,914
studyportals/Utils
src/Net.php
Net.subnetMatch
public static function subnetMatch($subnet, $ip, &$prefix = -1){ $ip = ip2long($ip); if(strpos($subnet, '/') !== false){ list($net, $prefix) = explode('/', $subnet, 2); // Ensure the provided CIDR-prefix (e.g. subnet mask) is valid if(!ctype_digit($prefix) || $prefix > 32){ $prefix = -1; return false; } $net = ip2long($net); $prefix = (int) $prefix; } else{ $net = ip2long($subnet); $prefix = 32; } // Empty/invalid IP-address or invalid subnet provided if(empty($ip) || $net === false){ return false; } // Empty prefix; all IP-addresses will match (short-circuit) if($prefix === 0){ if(!empty($net)){ ExceptionHandler::notice("Invalid CIDR-notation '$subnet', assuming '0.0.0.0/0'"); } return true; } if($prefix < 32){ $mask = 0xffffffff << (32 - $prefix); $net_mask = $net & $mask; $ip_mask = $ip & $mask; /* * When properly specified in CIDR-notation, both the input subnet * and the "masked" input subnet (as calculated above) should be * equal. Non-fatal, but a strong indication someone wasn't paying * attention while configuring the subnet... */ if($net_mask !== $net){ ExceptionHandler::notice("Invalid CIDR-notation '$subnet', assuming " . long2ip($net_mask) . "/$prefix"); } return (($net_mask ^ $ip_mask) === 0); } else{ return ($net === $ip); } }
php
public static function subnetMatch($subnet, $ip, &$prefix = -1){ $ip = ip2long($ip); if(strpos($subnet, '/') !== false){ list($net, $prefix) = explode('/', $subnet, 2); // Ensure the provided CIDR-prefix (e.g. subnet mask) is valid if(!ctype_digit($prefix) || $prefix > 32){ $prefix = -1; return false; } $net = ip2long($net); $prefix = (int) $prefix; } else{ $net = ip2long($subnet); $prefix = 32; } // Empty/invalid IP-address or invalid subnet provided if(empty($ip) || $net === false){ return false; } // Empty prefix; all IP-addresses will match (short-circuit) if($prefix === 0){ if(!empty($net)){ ExceptionHandler::notice("Invalid CIDR-notation '$subnet', assuming '0.0.0.0/0'"); } return true; } if($prefix < 32){ $mask = 0xffffffff << (32 - $prefix); $net_mask = $net & $mask; $ip_mask = $ip & $mask; /* * When properly specified in CIDR-notation, both the input subnet * and the "masked" input subnet (as calculated above) should be * equal. Non-fatal, but a strong indication someone wasn't paying * attention while configuring the subnet... */ if($net_mask !== $net){ ExceptionHandler::notice("Invalid CIDR-notation '$subnet', assuming " . long2ip($net_mask) . "/$prefix"); } return (($net_mask ^ $ip_mask) === 0); } else{ return ($net === $ip); } }
[ "public", "static", "function", "subnetMatch", "(", "$", "subnet", ",", "$", "ip", ",", "&", "$", "prefix", "=", "-", "1", ")", "{", "$", "ip", "=", "ip2long", "(", "$", "ip", ")", ";", "if", "(", "strpos", "(", "$", "subnet", ",", "'/'", ")", "!==", "false", ")", "{", "list", "(", "$", "net", ",", "$", "prefix", ")", "=", "explode", "(", "'/'", ",", "$", "subnet", ",", "2", ")", ";", "// Ensure the provided CIDR-prefix (e.g. subnet mask) is valid", "if", "(", "!", "ctype_digit", "(", "$", "prefix", ")", "||", "$", "prefix", ">", "32", ")", "{", "$", "prefix", "=", "-", "1", ";", "return", "false", ";", "}", "$", "net", "=", "ip2long", "(", "$", "net", ")", ";", "$", "prefix", "=", "(", "int", ")", "$", "prefix", ";", "}", "else", "{", "$", "net", "=", "ip2long", "(", "$", "subnet", ")", ";", "$", "prefix", "=", "32", ";", "}", "// Empty/invalid IP-address or invalid subnet provided", "if", "(", "empty", "(", "$", "ip", ")", "||", "$", "net", "===", "false", ")", "{", "return", "false", ";", "}", "// Empty prefix; all IP-addresses will match (short-circuit)", "if", "(", "$", "prefix", "===", "0", ")", "{", "if", "(", "!", "empty", "(", "$", "net", ")", ")", "{", "ExceptionHandler", "::", "notice", "(", "\"Invalid CIDR-notation '$subnet',\n\t\t\t\t\tassuming '0.0.0.0/0'\"", ")", ";", "}", "return", "true", ";", "}", "if", "(", "$", "prefix", "<", "32", ")", "{", "$", "mask", "=", "0xffffffff", "<<", "(", "32", "-", "$", "prefix", ")", ";", "$", "net_mask", "=", "$", "net", "&", "$", "mask", ";", "$", "ip_mask", "=", "$", "ip", "&", "$", "mask", ";", "/*\n\t\t\t * When properly specified in CIDR-notation, both the input subnet\n\t\t\t * and the \"masked\" input subnet (as calculated above) should be\n\t\t\t * equal. Non-fatal, but a strong indication someone wasn't paying\n\t\t\t * attention while configuring the subnet...\n\t\t\t */", "if", "(", "$", "net_mask", "!==", "$", "net", ")", "{", "ExceptionHandler", "::", "notice", "(", "\"Invalid CIDR-notation '$subnet',\n\t\t\t\t\tassuming \"", ".", "long2ip", "(", "$", "net_mask", ")", ".", "\"/$prefix\"", ")", ";", "}", "return", "(", "(", "$", "net_mask", "^", "$", "ip_mask", ")", "===", "0", ")", ";", "}", "else", "{", "return", "(", "$", "net", "===", "$", "ip", ")", ";", "}", "}" ]
Check if an IP-address falls within a given subnet. <p>The provided {@link $subnet} should be in CIDR-notation (e.g. "192.168.1.0/24"). This function only supports IPv4-addresses.</p> <p>The optional, pass-by-reference, parameter {@link $prefix} is used to pass back the length of the CIDR-prefix in the provided {@link $subnet}. This method validates the prefix, so it's best to use this parameter instead of relying on your own logic. A valid prefix-length is between <em>0</em> and <em>31</em>; for invalid prefixes <em>-1</em> is returned.<br> This information is useful for determining the "specificity" of the match. The higher the prefix the smaller the provided {@link $subnet} and as such the "closer" the match with the provided {@link $ip}.</p> @param string $subnet @param string $ip @param integer &$prefix @return bool @see http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
[ "Check", "if", "an", "IP", "-", "address", "falls", "within", "a", "given", "subnet", "." ]
eab69ca10ce3261480164cf8108ae7020459c847
https://github.com/studyportals/Utils/blob/eab69ca10ce3261480164cf8108ae7020459c847/src/Net.php#L48-L120
12,915
helionogueir/changedirective
core/cgi/Debug.class.php
Debug.set
public function set(string $mode): bool { $auth = false; file_exists($mode); switch ($mode) { case Debug::HOMOLOGATION: case Debug::DEVELOPER: ini_set('display_errors', true); error_reporting(E_ALL); $auth = true; break; case Debug::PRODUCTION: $auth = true; default: ini_set('display_errors', false); error_reporting(E_ERROR); $auth = $auth ?? false; break; } return $auth; }
php
public function set(string $mode): bool { $auth = false; file_exists($mode); switch ($mode) { case Debug::HOMOLOGATION: case Debug::DEVELOPER: ini_set('display_errors', true); error_reporting(E_ALL); $auth = true; break; case Debug::PRODUCTION: $auth = true; default: ini_set('display_errors', false); error_reporting(E_ERROR); $auth = $auth ?? false; break; } return $auth; }
[ "public", "function", "set", "(", "string", "$", "mode", ")", ":", "bool", "{", "$", "auth", "=", "false", ";", "file_exists", "(", "$", "mode", ")", ";", "switch", "(", "$", "mode", ")", "{", "case", "Debug", "::", "HOMOLOGATION", ":", "case", "Debug", "::", "DEVELOPER", ":", "ini_set", "(", "'display_errors'", ",", "true", ")", ";", "error_reporting", "(", "E_ALL", ")", ";", "$", "auth", "=", "true", ";", "break", ";", "case", "Debug", "::", "PRODUCTION", ":", "$", "auth", "=", "true", ";", "default", ":", "ini_set", "(", "'display_errors'", ",", "false", ")", ";", "error_reporting", "(", "E_ERROR", ")", ";", "$", "auth", "=", "$", "auth", "??", "false", ";", "break", ";", "}", "return", "$", "auth", ";", "}" ]
- Set debug mode @param string $mode Mode name (Ex: Debug::DEVELOPER, Debug::HOMOLOGATION, Debug::PRODUCTION) @return bool Return true case $mode exits, or return false and set debug PRODUCTION mode
[ "-", "Set", "debug", "mode" ]
4c02ed10afceefc48909fdacadfe4e19cd52e88c
https://github.com/helionogueir/changedirective/blob/4c02ed10afceefc48909fdacadfe4e19cd52e88c/core/cgi/Debug.class.php#L32-L51
12,916
magicphp/framework
src/magicphp/events.class.php
Events.Call
public static function Call($sName, $aParams = null){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix if(array_key_exists($sName, $oThis->aEvents)){ switch($oThis->aEvents[$sName]["type"]){ case "perroute": $sCurrentRoute = strtolower(str_replace(array("/", "\\", "--"), "-", Storage::Get("route")));//Bugfix $sRoute = strtolower($oThis->aEvents[$sName]["method"]."_".$oThis->aEvents[$sName]["route"]); if($sRoute == $sCurrentRoute) return call_user_func($oThis->aEvents[$sName]["func"], $aParams); break; case "default": return call_user_func($oThis->aEvents[$sName]["func"], $aParams); break; } } else{ return false; } }
php
public static function Call($sName, $aParams = null){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix if(array_key_exists($sName, $oThis->aEvents)){ switch($oThis->aEvents[$sName]["type"]){ case "perroute": $sCurrentRoute = strtolower(str_replace(array("/", "\\", "--"), "-", Storage::Get("route")));//Bugfix $sRoute = strtolower($oThis->aEvents[$sName]["method"]."_".$oThis->aEvents[$sName]["route"]); if($sRoute == $sCurrentRoute) return call_user_func($oThis->aEvents[$sName]["func"], $aParams); break; case "default": return call_user_func($oThis->aEvents[$sName]["func"], $aParams); break; } } else{ return false; } }
[ "public", "static", "function", "Call", "(", "$", "sName", ",", "$", "aParams", "=", "null", ")", "{", "$", "oThis", "=", "self", "::", "CreateInstanceIfNotExists", "(", ")", ";", "$", "sName", "=", "strtolower", "(", "str_replace", "(", "array", "(", "\"/\"", ",", "\"\\\\\"", ",", "\"--\"", ")", ",", "\"-\"", ",", "$", "sName", ")", ")", ";", "//Bugfix", "if", "(", "array_key_exists", "(", "$", "sName", ",", "$", "oThis", "->", "aEvents", ")", ")", "{", "switch", "(", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "[", "\"type\"", "]", ")", "{", "case", "\"perroute\"", ":", "$", "sCurrentRoute", "=", "strtolower", "(", "str_replace", "(", "array", "(", "\"/\"", ",", "\"\\\\\"", ",", "\"--\"", ")", ",", "\"-\"", ",", "Storage", "::", "Get", "(", "\"route\"", ")", ")", ")", ";", "//Bugfix", "$", "sRoute", "=", "strtolower", "(", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "[", "\"method\"", "]", ".", "\"_\"", ".", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "[", "\"route\"", "]", ")", ";", "if", "(", "$", "sRoute", "==", "$", "sCurrentRoute", ")", "return", "call_user_func", "(", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "[", "\"func\"", "]", ",", "$", "aParams", ")", ";", "break", ";", "case", "\"default\"", ":", "return", "call_user_func", "(", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "[", "\"func\"", "]", ",", "$", "aParams", ")", ";", "break", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Function to call the event @static @access public @param string $sName @param array $aParams @return mixed
[ "Function", "to", "call", "the", "event" ]
199934b61c46ec596c27d4fb0355b216dde51d58
https://github.com/magicphp/framework/blob/199934b61c46ec596c27d4fb0355b216dde51d58/src/magicphp/events.class.php#L45-L64
12,917
magicphp/framework
src/magicphp/events.class.php
Events.Set
public static function Set($sName, $fCallback){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix $oThis->aEvents[$sName] = array("type" => "default", "func" => $fCallback); }
php
public static function Set($sName, $fCallback){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix $oThis->aEvents[$sName] = array("type" => "default", "func" => $fCallback); }
[ "public", "static", "function", "Set", "(", "$", "sName", ",", "$", "fCallback", ")", "{", "$", "oThis", "=", "self", "::", "CreateInstanceIfNotExists", "(", ")", ";", "$", "sName", "=", "strtolower", "(", "str_replace", "(", "array", "(", "\"/\"", ",", "\"\\\\\"", ",", "\"--\"", ")", ",", "\"-\"", ",", "$", "sName", ")", ")", ";", "//Bugfix", "$", "oThis", "->", "aEvents", "[", "$", "sName", "]", "=", "array", "(", "\"type\"", "=>", "\"default\"", ",", "\"func\"", "=>", "$", "fCallback", ")", ";", "}" ]
Function to set the event @static @access public @param string $sName @param function $fCallback @return void
[ "Function", "to", "set", "the", "event" ]
199934b61c46ec596c27d4fb0355b216dde51d58
https://github.com/magicphp/framework/blob/199934b61c46ec596c27d4fb0355b216dde51d58/src/magicphp/events.class.php#L75-L79
12,918
magicphp/framework
src/magicphp/events.class.php
Events.SetPerRoute
public static function SetPerRoute($sName, $sRoute, $sMethod, $fCallback){ $oThis = self::CreateInstanceIfNotExists(); $sRoute = strtolower(str_replace(array("/", "\\", "--"), "-", $sRoute));//Bugfix $oThis->aEvents[strtolower($sMethod."_".$sRoute."_".$sName)] = array("type" => "perroute", "func" => $fCallback, "route" => $sRoute, "method" => $sMethod); }
php
public static function SetPerRoute($sName, $sRoute, $sMethod, $fCallback){ $oThis = self::CreateInstanceIfNotExists(); $sRoute = strtolower(str_replace(array("/", "\\", "--"), "-", $sRoute));//Bugfix $oThis->aEvents[strtolower($sMethod."_".$sRoute."_".$sName)] = array("type" => "perroute", "func" => $fCallback, "route" => $sRoute, "method" => $sMethod); }
[ "public", "static", "function", "SetPerRoute", "(", "$", "sName", ",", "$", "sRoute", ",", "$", "sMethod", ",", "$", "fCallback", ")", "{", "$", "oThis", "=", "self", "::", "CreateInstanceIfNotExists", "(", ")", ";", "$", "sRoute", "=", "strtolower", "(", "str_replace", "(", "array", "(", "\"/\"", ",", "\"\\\\\"", ",", "\"--\"", ")", ",", "\"-\"", ",", "$", "sRoute", ")", ")", ";", "//Bugfix", "$", "oThis", "->", "aEvents", "[", "strtolower", "(", "$", "sMethod", ".", "\"_\"", ".", "$", "sRoute", ".", "\"_\"", ".", "$", "sName", ")", "]", "=", "array", "(", "\"type\"", "=>", "\"perroute\"", ",", "\"func\"", "=>", "$", "fCallback", ",", "\"route\"", "=>", "$", "sRoute", ",", "\"method\"", "=>", "$", "sMethod", ")", ";", "}" ]
Function to ser the evenet per route @static @access public @param string $sName @param string $sRoute @param string $sMethod @param function $fCallback @return void
[ "Function", "to", "ser", "the", "evenet", "per", "route" ]
199934b61c46ec596c27d4fb0355b216dde51d58
https://github.com/magicphp/framework/blob/199934b61c46ec596c27d4fb0355b216dde51d58/src/magicphp/events.class.php#L92-L96
12,919
magicphp/framework
src/magicphp/events.class.php
Events.Has
public static function Has($sName){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix return array_key_exists($sName, $oThis->aEvents); }
php
public static function Has($sName){ $oThis = self::CreateInstanceIfNotExists(); $sName = strtolower(str_replace(array("/", "\\", "--"), "-", $sName));//Bugfix return array_key_exists($sName, $oThis->aEvents); }
[ "public", "static", "function", "Has", "(", "$", "sName", ")", "{", "$", "oThis", "=", "self", "::", "CreateInstanceIfNotExists", "(", ")", ";", "$", "sName", "=", "strtolower", "(", "str_replace", "(", "array", "(", "\"/\"", ",", "\"\\\\\"", ",", "\"--\"", ")", ",", "\"-\"", ",", "$", "sName", ")", ")", ";", "//Bugfix ", "return", "array_key_exists", "(", "$", "sName", ",", "$", "oThis", "->", "aEvents", ")", ";", "}" ]
Function to check existence of event @static @access public @param string $sName @return boolean
[ "Function", "to", "check", "existence", "of", "event" ]
199934b61c46ec596c27d4fb0355b216dde51d58
https://github.com/magicphp/framework/blob/199934b61c46ec596c27d4fb0355b216dde51d58/src/magicphp/events.class.php#L106-L110
12,920
sheychen290/colis
src/StreamFactory.php
StreamFactory.copyTo
public function copyTo(StreamInterface $source, StreamInterface $dest) { $source->rewind(); $dest->write($source->getContents()); return $dest; }
php
public function copyTo(StreamInterface $source, StreamInterface $dest) { $source->rewind(); $dest->write($source->getContents()); return $dest; }
[ "public", "function", "copyTo", "(", "StreamInterface", "$", "source", ",", "StreamInterface", "$", "dest", ")", "{", "$", "source", "->", "rewind", "(", ")", ";", "$", "dest", "->", "write", "(", "$", "source", "->", "getContents", "(", ")", ")", ";", "return", "$", "dest", ";", "}" ]
Non-Psr
[ "Non", "-", "Psr" ]
b0552ece885d6b258e73ddbccf0b52c5c28e6054
https://github.com/sheychen290/colis/blob/b0552ece885d6b258e73ddbccf0b52c5c28e6054/src/StreamFactory.php#L51-L56
12,921
sirgrimorum/crudgenerator
src/ExtendedValidator.php
ExtendedValidator.getIgnore
private function getIgnore(&$parameters) { $lastParam = end($parameters); $lastParam = array_map('trim', explode('=', $lastParam)); // An ignore_id is only specified if the last param starts with a // number greater than 1 (a valid id in the database) if (!preg_match('/^[1-9][0-9]*$/', $lastParam[0])) { return array(null, null); } $ignoreId = $lastParam[0]; $ignoreColumn = (sizeof($lastParam) > 1) ? end($lastParam) : null; // Shave of the ignore_id from the array for later processing array_pop($parameters); return array($ignoreId, $ignoreColumn); }
php
private function getIgnore(&$parameters) { $lastParam = end($parameters); $lastParam = array_map('trim', explode('=', $lastParam)); // An ignore_id is only specified if the last param starts with a // number greater than 1 (a valid id in the database) if (!preg_match('/^[1-9][0-9]*$/', $lastParam[0])) { return array(null, null); } $ignoreId = $lastParam[0]; $ignoreColumn = (sizeof($lastParam) > 1) ? end($lastParam) : null; // Shave of the ignore_id from the array for later processing array_pop($parameters); return array($ignoreId, $ignoreColumn); }
[ "private", "function", "getIgnore", "(", "&", "$", "parameters", ")", "{", "$", "lastParam", "=", "end", "(", "$", "parameters", ")", ";", "$", "lastParam", "=", "array_map", "(", "'trim'", ",", "explode", "(", "'='", ",", "$", "lastParam", ")", ")", ";", "// An ignore_id is only specified if the last param starts with a", "// number greater than 1 (a valid id in the database)", "if", "(", "!", "preg_match", "(", "'/^[1-9][0-9]*$/'", ",", "$", "lastParam", "[", "0", "]", ")", ")", "{", "return", "array", "(", "null", ",", "null", ")", ";", "}", "$", "ignoreId", "=", "$", "lastParam", "[", "0", "]", ";", "$", "ignoreColumn", "=", "(", "sizeof", "(", "$", "lastParam", ")", ">", "1", ")", "?", "end", "(", "$", "lastParam", ")", ":", "null", ";", "// Shave of the ignore_id from the array for later processing", "array_pop", "(", "$", "parameters", ")", ";", "return", "array", "(", "$", "ignoreId", ",", "$", "ignoreColumn", ")", ";", "}" ]
Returns an array with value and column name for an optional ignore. Shaves of the ignore_id from the end of the array, if there is one. @param array $parameters @return array [$ignoreId, $ignoreColumn]
[ "Returns", "an", "array", "with", "value", "and", "column", "name", "for", "an", "optional", "ignore", ".", "Shaves", "of", "the", "ignore_id", "from", "the", "end", "of", "the", "array", "if", "there", "is", "one", "." ]
4431e9991a705689be50c4367776dc611bffb863
https://github.com/sirgrimorum/crudgenerator/blob/4431e9991a705689be50c4367776dc611bffb863/src/ExtendedValidator.php#L327-L344
12,922
rafflesargentina/l5-resource-composer
src/ResourceComposer.php
ResourceComposer.composeIndex
public function composeIndex(View $view) { $this->composeWithTitle($view); $this->composeWithLayout($view); $this->composeWithAllRouteNames($view); $this->composeWithRequiredFields($view); $this->composeWithValidationRules($view); $this->composeWithPartialsLocation($view); $this->composeWithResourceLocation($view); }
php
public function composeIndex(View $view) { $this->composeWithTitle($view); $this->composeWithLayout($view); $this->composeWithAllRouteNames($view); $this->composeWithRequiredFields($view); $this->composeWithValidationRules($view); $this->composeWithPartialsLocation($view); $this->composeWithResourceLocation($view); }
[ "public", "function", "composeIndex", "(", "View", "$", "view", ")", "{", "$", "this", "->", "composeWithTitle", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithLayout", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithAllRouteNames", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithRequiredFields", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithValidationRules", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithPartialsLocation", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithResourceLocation", "(", "$", "view", ")", ";", "}" ]
Compose Index view. @param \Illuminate\Contracts\View\View $view The view object. @return void
[ "Compose", "Index", "view", "." ]
65332c5ccfdc7dc3bfec85cd20c560c3eaa3d743
https://github.com/rafflesargentina/l5-resource-composer/blob/65332c5ccfdc7dc3bfec85cd20c560c3eaa3d743/src/ResourceComposer.php#L16-L25
12,923
rafflesargentina/l5-resource-composer
src/ResourceComposer.php
ResourceComposer.composeShow
public function composeShow(View $view) { $this->composeWithTitle($view); $this->composeWithLayout($view); $this->composeWithAllRouteNames($view); $this->composeWithPartialsLocation($view); $this->composeWithResourceLocation($view); }
php
public function composeShow(View $view) { $this->composeWithTitle($view); $this->composeWithLayout($view); $this->composeWithAllRouteNames($view); $this->composeWithPartialsLocation($view); $this->composeWithResourceLocation($view); }
[ "public", "function", "composeShow", "(", "View", "$", "view", ")", "{", "$", "this", "->", "composeWithTitle", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithLayout", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithAllRouteNames", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithPartialsLocation", "(", "$", "view", ")", ";", "$", "this", "->", "composeWithResourceLocation", "(", "$", "view", ")", ";", "}" ]
Compose Show view. @param \Illuminate\Contracts\View\View $view The view object. @return void
[ "Compose", "Show", "view", "." ]
65332c5ccfdc7dc3bfec85cd20c560c3eaa3d743
https://github.com/rafflesargentina/l5-resource-composer/blob/65332c5ccfdc7dc3bfec85cd20c560c3eaa3d743/src/ResourceComposer.php#L46-L53
12,924
mandango/MandangoBundle
DataCollector/MandangoDataCollector.php
MandangoDataCollector.getFormattedQueries
public function getFormattedQueries() { $formattedQueries = array(); foreach ($this->getQueries() as $query) { if (!isset($query['type'])) { print_r($query); exit(); } $formattedQuery = array( 'connection' => $query['connection'], 'database' => $query['database'], 'type' => $query['type'], 'time' => $query['time'], ); foreach (array( 'connection', 'database', 'type', 'time', ) as $key) { unset($query[$key]); } $formattedQuery['query'] = Yaml::dump($query, 'batchInsert' == $formattedQuery['type'] ? 6 : 2); $formattedQueries[] = $formattedQuery; } return $formattedQueries; }
php
public function getFormattedQueries() { $formattedQueries = array(); foreach ($this->getQueries() as $query) { if (!isset($query['type'])) { print_r($query); exit(); } $formattedQuery = array( 'connection' => $query['connection'], 'database' => $query['database'], 'type' => $query['type'], 'time' => $query['time'], ); foreach (array( 'connection', 'database', 'type', 'time', ) as $key) { unset($query[$key]); } $formattedQuery['query'] = Yaml::dump($query, 'batchInsert' == $formattedQuery['type'] ? 6 : 2); $formattedQueries[] = $formattedQuery; } return $formattedQueries; }
[ "public", "function", "getFormattedQueries", "(", ")", "{", "$", "formattedQueries", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getQueries", "(", ")", "as", "$", "query", ")", "{", "if", "(", "!", "isset", "(", "$", "query", "[", "'type'", "]", ")", ")", "{", "print_r", "(", "$", "query", ")", ";", "exit", "(", ")", ";", "}", "$", "formattedQuery", "=", "array", "(", "'connection'", "=>", "$", "query", "[", "'connection'", "]", ",", "'database'", "=>", "$", "query", "[", "'database'", "]", ",", "'type'", "=>", "$", "query", "[", "'type'", "]", ",", "'time'", "=>", "$", "query", "[", "'time'", "]", ",", ")", ";", "foreach", "(", "array", "(", "'connection'", ",", "'database'", ",", "'type'", ",", "'time'", ",", ")", "as", "$", "key", ")", "{", "unset", "(", "$", "query", "[", "$", "key", "]", ")", ";", "}", "$", "formattedQuery", "[", "'query'", "]", "=", "Yaml", "::", "dump", "(", "$", "query", ",", "'batchInsert'", "==", "$", "formattedQuery", "[", "'type'", "]", "?", "6", ":", "2", ")", ";", "$", "formattedQueries", "[", "]", "=", "$", "formattedQuery", ";", "}", "return", "$", "formattedQueries", ";", "}" ]
Returns the queries formatted. @return array The queries formatted.
[ "Returns", "the", "queries", "formatted", "." ]
36e2ff4cc43989abbb3bd2f84cd7909c0f39d5b9
https://github.com/mandango/MandangoBundle/blob/36e2ff4cc43989abbb3bd2f84cd7909c0f39d5b9/DataCollector/MandangoDataCollector.php#L89-L119
12,925
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.setKept
protected function setKept($key, $value) { if ($key == 'deleted_at') { $this->kept_at = $value; $this->kept_data[$key] = $value; } // $this->kept_data[$key] = $value; }
php
protected function setKept($key, $value) { if ($key == 'deleted_at') { $this->kept_at = $value; $this->kept_data[$key] = $value; } // $this->kept_data[$key] = $value; }
[ "protected", "function", "setKept", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "$", "key", "==", "'deleted_at'", ")", "{", "$", "this", "->", "kept_at", "=", "$", "value", ";", "$", "this", "->", "kept_data", "[", "$", "key", "]", "=", "$", "value", ";", "}", "//", "$", "this", "->", "kept_data", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Set kept data.
[ "Set", "kept", "data", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L129-L137
12,926
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.forceDelete
public function forceDelete() { $key = $this->getPKvalue(); $sql = 'delete from '.$this->DBtable.' where '.$this->keyName." = '".$key."' "; // return Database::exec($sql); }
php
public function forceDelete() { $key = $this->getPKvalue(); $sql = 'delete from '.$this->DBtable.' where '.$this->keyName." = '".$key."' "; // return Database::exec($sql); }
[ "public", "function", "forceDelete", "(", ")", "{", "$", "key", "=", "$", "this", "->", "getPKvalue", "(", ")", ";", "$", "sql", "=", "'delete from '", ".", "$", "this", "->", "DBtable", ".", "' where '", ".", "$", "this", "->", "keyName", ".", "\" = '\"", ".", "$", "key", ".", "\"' \"", ";", "//", "return", "Database", "::", "exec", "(", "$", "sql", ")", ";", "}" ]
force delete if the resource is kept delete.
[ "force", "delete", "if", "the", "resource", "is", "kept", "delete", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L357-L363
12,927
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.lightDelete
protected function lightDelete() { $now = Time::current(); $key = $this->getPKvalue(); // $sql = 'update '.$this->DBtable." set deleted_at='".$now."' where ".$this->keyName." = '".$key."' "; if (Database::exec($sql)) { $this->clean(); $this->deleted_at = $now; } }
php
protected function lightDelete() { $now = Time::current(); $key = $this->getPKvalue(); // $sql = 'update '.$this->DBtable." set deleted_at='".$now."' where ".$this->keyName." = '".$key."' "; if (Database::exec($sql)) { $this->clean(); $this->deleted_at = $now; } }
[ "protected", "function", "lightDelete", "(", ")", "{", "$", "now", "=", "Time", "::", "current", "(", ")", ";", "$", "key", "=", "$", "this", "->", "getPKvalue", "(", ")", ";", "//", "$", "sql", "=", "'update '", ".", "$", "this", "->", "DBtable", ".", "\" set deleted_at='\"", ".", "$", "now", ".", "\"' where \"", ".", "$", "this", "->", "keyName", ".", "\" = '\"", ".", "$", "key", ".", "\"' \"", ";", "if", "(", "Database", "::", "exec", "(", "$", "sql", ")", ")", "{", "$", "this", "->", "clean", "(", ")", ";", "$", "this", "->", "deleted_at", "=", "$", "now", ";", "}", "}" ]
light delete if the resource is kept delete.
[ "light", "delete", "if", "the", "resource", "is", "kept", "delete", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L368-L378
12,928
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.restore
public function restore() { if ($this->isKept) { $key = $this->getPKvalue(); $sql = 'update '.$this->DBtable.' set deleted_at=null where '.$this->keyName." = '".$key."' "; // if (Database::exec($sql)) { // Code to execute the init the model } } }
php
public function restore() { if ($this->isKept) { $key = $this->getPKvalue(); $sql = 'update '.$this->DBtable.' set deleted_at=null where '.$this->keyName." = '".$key."' "; // if (Database::exec($sql)) { // Code to execute the init the model } } }
[ "public", "function", "restore", "(", ")", "{", "if", "(", "$", "this", "->", "isKept", ")", "{", "$", "key", "=", "$", "this", "->", "getPKvalue", "(", ")", ";", "$", "sql", "=", "'update '", ".", "$", "this", "->", "DBtable", ".", "' set deleted_at=null where '", ".", "$", "this", "->", "keyName", ".", "\" = '\"", ".", "$", "key", ".", "\"' \"", ";", "//", "if", "(", "Database", "::", "exec", "(", "$", "sql", ")", ")", "{", "// Code to execute the init the model", "}", "}", "}" ]
restore if kept deleted.
[ "restore", "if", "kept", "deleted", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L383-L393
12,929
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.getCallable
public function getCallable($name) { if (method_exists($this, $name)) { return call_user_func([$this, $name]); } else { throw new InvalidArgumentException('Undefined property: '.get_class($this)."::$name"); } }
php
public function getCallable($name) { if (method_exists($this, $name)) { return call_user_func([$this, $name]); } else { throw new InvalidArgumentException('Undefined property: '.get_class($this)."::$name"); } }
[ "public", "function", "getCallable", "(", "$", "name", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "return", "call_user_func", "(", "[", "$", "this", ",", "$", "name", "]", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Undefined property: '", ".", "get_class", "(", "$", "this", ")", ".", "\"::$name\"", ")", ";", "}", "}" ]
Dynamic Property. @param $name : name of the function
[ "Dynamic", "Property", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L400-L407
12,930
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.all
public static function all() { $self = self::instance(); // // Pagination // $sql = 'select * from '.$self->DBtable; return Database::read($sql, 1); }
php
public static function all() { $self = self::instance(); // // Pagination // $sql = 'select * from '.$self->DBtable; return Database::read($sql, 1); }
[ "public", "static", "function", "all", "(", ")", "{", "$", "self", "=", "self", "::", "instance", "(", ")", ";", "//", "// Pagination", "//", "$", "sql", "=", "'select * from '", ".", "$", "self", "->", "DBtable", ";", "return", "Database", "::", "read", "(", "$", "sql", ",", "1", ")", ";", "}" ]
Get all rows of Data Table.
[ "Get", "all", "rows", "of", "Data", "Table", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L412-L421
12,931
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.count
public static function count($where) { $self = self::instance(); $rows = new ModelArray(); // $sql = 'select count(*) as cnt from '.$self->DBtable." where $where "; $data = Database::read($sql, 1); // return $data[0]['cnt']; }
php
public static function count($where) { $self = self::instance(); $rows = new ModelArray(); // $sql = 'select count(*) as cnt from '.$self->DBtable." where $where "; $data = Database::read($sql, 1); // return $data[0]['cnt']; }
[ "public", "static", "function", "count", "(", "$", "where", ")", "{", "$", "self", "=", "self", "::", "instance", "(", ")", ";", "$", "rows", "=", "new", "ModelArray", "(", ")", ";", "//", "$", "sql", "=", "'select count(*) as cnt from '", ".", "$", "self", "->", "DBtable", ".", "\" where $where \"", ";", "$", "data", "=", "Database", "::", "read", "(", "$", "sql", ",", "1", ")", ";", "//", "return", "$", "data", "[", "0", "]", "[", "'cnt'", "]", ";", "}" ]
To count rows by where clause. @param $where (string) : the where clause
[ "To", "count", "rows", "by", "where", "clause", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L502-L511
12,932
vinala/kernel
src/MVC/Model/ORM_.php
ORM_.hasOne
public function hasOne($model, $local = null, $remote = null) { return (new OneToOne())->ini($model, $this, $local, $remote); }
php
public function hasOne($model, $local = null, $remote = null) { return (new OneToOne())->ini($model, $this, $local, $remote); }
[ "public", "function", "hasOne", "(", "$", "model", ",", "$", "local", "=", "null", ",", "$", "remote", "=", "null", ")", "{", "return", "(", "new", "OneToOne", "(", ")", ")", "->", "ini", "(", "$", "model", ",", "$", "this", ",", "$", "local", ",", "$", "remote", ")", ";", "}" ]
The has one relation for one to one. @param $model : the model wanted to be related to the current model @param $local : if not null would be the local column of the relation @param $remote : if not null would be the $remote column of the relation
[ "The", "has", "one", "relation", "for", "one", "to", "one", "." ]
346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a
https://github.com/vinala/kernel/blob/346c8a4dca48fd1ab88fdc9f7004ecb7bce6a67a/src/MVC/Model/ORM_.php#L539-L542
12,933
horse-php/horse
src/Horse/Parsers/MetadataParser.php
MetadataParser.parseMany
public function parseMany($line) { $results = []; $buffer = ''; foreach (\str_split($line) as $character) { if ('{' == $character) { $buffer = $character; } elseif ('}' == $character) { $results[] = $this->parse($buffer.$character); } else { $buffer .= $character; } } return $results; }
php
public function parseMany($line) { $results = []; $buffer = ''; foreach (\str_split($line) as $character) { if ('{' == $character) { $buffer = $character; } elseif ('}' == $character) { $results[] = $this->parse($buffer.$character); } else { $buffer .= $character; } } return $results; }
[ "public", "function", "parseMany", "(", "$", "line", ")", "{", "$", "results", "=", "[", "]", ";", "$", "buffer", "=", "''", ";", "foreach", "(", "\\", "str_split", "(", "$", "line", ")", "as", "$", "character", ")", "{", "if", "(", "'{'", "==", "$", "character", ")", "{", "$", "buffer", "=", "$", "character", ";", "}", "elseif", "(", "'}'", "==", "$", "character", ")", "{", "$", "results", "[", "]", "=", "$", "this", "->", "parse", "(", "$", "buffer", ".", "$", "character", ")", ";", "}", "else", "{", "$", "buffer", ".=", "$", "character", ";", "}", "}", "return", "$", "results", ";", "}" ]
Parse multiple elements. @param string $line @return array
[ "Parse", "multiple", "elements", "." ]
e2b72508dde353de6cacfbed852aa3de3fc06eff
https://github.com/horse-php/horse/blob/e2b72508dde353de6cacfbed852aa3de3fc06eff/src/Horse/Parsers/MetadataParser.php#L11-L33
12,934
horse-php/horse
src/Horse/Parsers/MetadataParser.php
MetadataParser.parse
public function parse($line) { $elements = []; // 1. remove braces $line = \str_replace(['{', '}'], '', $line); // 2. extract elements $elements = $this->extractElements($line); // 3. remove quotes $iterator = function($element) { return \str_replace(['\'', '"'], '', $element); }; return \array_map($iterator, $elements); }
php
public function parse($line) { $elements = []; // 1. remove braces $line = \str_replace(['{', '}'], '', $line); // 2. extract elements $elements = $this->extractElements($line); // 3. remove quotes $iterator = function($element) { return \str_replace(['\'', '"'], '', $element); }; return \array_map($iterator, $elements); }
[ "public", "function", "parse", "(", "$", "line", ")", "{", "$", "elements", "=", "[", "]", ";", "// 1. remove braces", "$", "line", "=", "\\", "str_replace", "(", "[", "'{'", ",", "'}'", "]", ",", "''", ",", "$", "line", ")", ";", "// 2. extract elements", "$", "elements", "=", "$", "this", "->", "extractElements", "(", "$", "line", ")", ";", "// 3. remove quotes", "$", "iterator", "=", "function", "(", "$", "element", ")", "{", "return", "\\", "str_replace", "(", "[", "'\\''", ",", "'\"'", "]", ",", "''", ",", "$", "element", ")", ";", "}", ";", "return", "\\", "array_map", "(", "$", "iterator", ",", "$", "elements", ")", ";", "}" ]
Parse a single element. @param string $line @return array
[ "Parse", "a", "single", "element", "." ]
e2b72508dde353de6cacfbed852aa3de3fc06eff
https://github.com/horse-php/horse/blob/e2b72508dde353de6cacfbed852aa3de3fc06eff/src/Horse/Parsers/MetadataParser.php#L41-L58
12,935
horse-php/horse
src/Horse/Parsers/MetadataParser.php
MetadataParser.extractElements
protected function extractElements($line) { $elements = []; $buffer = ''; $quote = false; foreach (\str_split($line) as $character) { if (\in_array($character, ['\'', '"'])) { $quote = ! $quote; continue; } if ((':' == $character) and ! $quote) { $elements[] = $buffer; $buffer = ''; continue; } $buffer .= $character; } if ($buffer) { $elements[] = $buffer; } return $elements; }
php
protected function extractElements($line) { $elements = []; $buffer = ''; $quote = false; foreach (\str_split($line) as $character) { if (\in_array($character, ['\'', '"'])) { $quote = ! $quote; continue; } if ((':' == $character) and ! $quote) { $elements[] = $buffer; $buffer = ''; continue; } $buffer .= $character; } if ($buffer) { $elements[] = $buffer; } return $elements; }
[ "protected", "function", "extractElements", "(", "$", "line", ")", "{", "$", "elements", "=", "[", "]", ";", "$", "buffer", "=", "''", ";", "$", "quote", "=", "false", ";", "foreach", "(", "\\", "str_split", "(", "$", "line", ")", "as", "$", "character", ")", "{", "if", "(", "\\", "in_array", "(", "$", "character", ",", "[", "'\\''", ",", "'\"'", "]", ")", ")", "{", "$", "quote", "=", "!", "$", "quote", ";", "continue", ";", "}", "if", "(", "(", "':'", "==", "$", "character", ")", "and", "!", "$", "quote", ")", "{", "$", "elements", "[", "]", "=", "$", "buffer", ";", "$", "buffer", "=", "''", ";", "continue", ";", "}", "$", "buffer", ".=", "$", "character", ";", "}", "if", "(", "$", "buffer", ")", "{", "$", "elements", "[", "]", "=", "$", "buffer", ";", "}", "return", "$", "elements", ";", "}" ]
Extract an array of elements from the string. @param string $line @return array
[ "Extract", "an", "array", "of", "elements", "from", "the", "string", "." ]
e2b72508dde353de6cacfbed852aa3de3fc06eff
https://github.com/horse-php/horse/blob/e2b72508dde353de6cacfbed852aa3de3fc06eff/src/Horse/Parsers/MetadataParser.php#L66-L99
12,936
clagiordano/weblibs-dbabstraction
src/Response.php
Response.getResponse
public function getResponse($printResponse = true) { $this->setStatusInfo(); if ($printResponse) { header('Content-Type: application/json'); echo $this->ResponseData; } else { return $this->ResponseData; } return null; }
php
public function getResponse($printResponse = true) { $this->setStatusInfo(); if ($printResponse) { header('Content-Type: application/json'); echo $this->ResponseData; } else { return $this->ResponseData; } return null; }
[ "public", "function", "getResponse", "(", "$", "printResponse", "=", "true", ")", "{", "$", "this", "->", "setStatusInfo", "(", ")", ";", "if", "(", "$", "printResponse", ")", "{", "header", "(", "'Content-Type: application/json'", ")", ";", "echo", "$", "this", "->", "ResponseData", ";", "}", "else", "{", "return", "$", "this", "->", "ResponseData", ";", "}", "return", "null", ";", "}" ]
Print or return ResponseData @param boolean $printResponse @return array|null
[ "Print", "or", "return", "ResponseData" ]
167988f73f1d6d0a013179c4a211bdc673a4667e
https://github.com/clagiordano/weblibs-dbabstraction/blob/167988f73f1d6d0a013179c4a211bdc673a4667e/src/Response.php#L49-L59
12,937
clagiordano/weblibs-dbabstraction
src/Response.php
Response.setStatusInfo
private function setStatusInfo() { $statusInfo['status'] = [ 'data' => date('Y-m-d H:i:s') ]; $origData = json_decode($this->ResponseData, true); if (!is_null($origData)) { $this->ResponseData = json_encode(array_merge($origData, $statusInfo)); } else { $this->ResponseData = json_encode($statusInfo); } return $this; }
php
private function setStatusInfo() { $statusInfo['status'] = [ 'data' => date('Y-m-d H:i:s') ]; $origData = json_decode($this->ResponseData, true); if (!is_null($origData)) { $this->ResponseData = json_encode(array_merge($origData, $statusInfo)); } else { $this->ResponseData = json_encode($statusInfo); } return $this; }
[ "private", "function", "setStatusInfo", "(", ")", "{", "$", "statusInfo", "[", "'status'", "]", "=", "[", "'data'", "=>", "date", "(", "'Y-m-d H:i:s'", ")", "]", ";", "$", "origData", "=", "json_decode", "(", "$", "this", "->", "ResponseData", ",", "true", ")", ";", "if", "(", "!", "is_null", "(", "$", "origData", ")", ")", "{", "$", "this", "->", "ResponseData", "=", "json_encode", "(", "array_merge", "(", "$", "origData", ",", "$", "statusInfo", ")", ")", ";", "}", "else", "{", "$", "this", "->", "ResponseData", "=", "json_encode", "(", "$", "statusInfo", ")", ";", "}", "return", "$", "this", ";", "}" ]
Append status info to a response data @return clagiordano\weblibs\dbabstraction\Response
[ "Append", "status", "info", "to", "a", "response", "data" ]
167988f73f1d6d0a013179c4a211bdc673a4667e
https://github.com/clagiordano/weblibs-dbabstraction/blob/167988f73f1d6d0a013179c4a211bdc673a4667e/src/Response.php#L65-L77
12,938
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.run
public function run() { $this->logger->notice('Starting to run an election'); $this->logger->notice(sprintf('There are %d candidates, %d ballots and to be %d winners', $this->election->getCandidateCount(), $this->validBallots, $this->election->getWinnersCount())); // Reject invalid ballots, then calculate the quota based on remaining valid ballots // p. 46(3) and p 47 $this->rejectInvalidBallots(); $this->setQuota(); // First step of standard allocation of ballots // p. 46(1) and 46(2) $this->firstStep(); $candidates = $this->election->getActiveCandidates(); // All the re-allocation rounds until we have filled all seats or // have the same number of seats left to fill and candidates remaining // (then elect them). $this->processReallocationRounds($candidates); // p. 53 $this->reallocateRemainingVotes($candidates); $this->logger->notice('Election complete'); return $this->election->getElectedCandidates(); }
php
public function run() { $this->logger->notice('Starting to run an election'); $this->logger->notice(sprintf('There are %d candidates, %d ballots and to be %d winners', $this->election->getCandidateCount(), $this->validBallots, $this->election->getWinnersCount())); // Reject invalid ballots, then calculate the quota based on remaining valid ballots // p. 46(3) and p 47 $this->rejectInvalidBallots(); $this->setQuota(); // First step of standard allocation of ballots // p. 46(1) and 46(2) $this->firstStep(); $candidates = $this->election->getActiveCandidates(); // All the re-allocation rounds until we have filled all seats or // have the same number of seats left to fill and candidates remaining // (then elect them). $this->processReallocationRounds($candidates); // p. 53 $this->reallocateRemainingVotes($candidates); $this->logger->notice('Election complete'); return $this->election->getElectedCandidates(); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "logger", "->", "notice", "(", "'Starting to run an election'", ")", ";", "$", "this", "->", "logger", "->", "notice", "(", "sprintf", "(", "'There are %d candidates, %d ballots and to be %d winners'", ",", "$", "this", "->", "election", "->", "getCandidateCount", "(", ")", ",", "$", "this", "->", "validBallots", ",", "$", "this", "->", "election", "->", "getWinnersCount", "(", ")", ")", ")", ";", "// Reject invalid ballots, then calculate the quota based on remaining valid ballots", "// p. 46(3) and p 47", "$", "this", "->", "rejectInvalidBallots", "(", ")", ";", "$", "this", "->", "setQuota", "(", ")", ";", "// First step of standard allocation of ballots", "// p. 46(1) and 46(2)", "$", "this", "->", "firstStep", "(", ")", ";", "$", "candidates", "=", "$", "this", "->", "election", "->", "getActiveCandidates", "(", ")", ";", "// All the re-allocation rounds until we have filled all seats or", "// have the same number of seats left to fill and candidates remaining", "// (then elect them).", "$", "this", "->", "processReallocationRounds", "(", "$", "candidates", ")", ";", "// p. 53", "$", "this", "->", "reallocateRemainingVotes", "(", "$", "candidates", ")", ";", "$", "this", "->", "logger", "->", "notice", "(", "'Election complete'", ")", ";", "return", "$", "this", "->", "election", "->", "getElectedCandidates", "(", ")", ";", "}" ]
Run the election. @return Candidate[] Winning candidates
[ "Run", "the", "election", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L103-L129
12,939
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.firstStep
protected function firstStep() { $this->logger->info('Beginning the first step'); // Allocate all the ballots foreach ($this->ballots as $i => $ballot) { $this->allocateVotes($ballot); } $this->logger->notice('Step 1 complete', ['candidatesStatus' => $this->election->getCandidatesStatus()] ); $this->steps[1] = $this->election->getCandidatesStatus(); return; }
php
protected function firstStep() { $this->logger->info('Beginning the first step'); // Allocate all the ballots foreach ($this->ballots as $i => $ballot) { $this->allocateVotes($ballot); } $this->logger->notice('Step 1 complete', ['candidatesStatus' => $this->election->getCandidatesStatus()] ); $this->steps[1] = $this->election->getCandidatesStatus(); return; }
[ "protected", "function", "firstStep", "(", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Beginning the first step'", ")", ";", "// Allocate all the ballots", "foreach", "(", "$", "this", "->", "ballots", "as", "$", "i", "=>", "$", "ballot", ")", "{", "$", "this", "->", "allocateVotes", "(", "$", "ballot", ")", ";", "}", "$", "this", "->", "logger", "->", "notice", "(", "'Step 1 complete'", ",", "[", "'candidatesStatus'", "=>", "$", "this", "->", "election", "->", "getCandidatesStatus", "(", ")", "]", ")", ";", "$", "this", "->", "steps", "[", "1", "]", "=", "$", "this", "->", "election", "->", "getCandidatesStatus", "(", ")", ";", "return", ";", "}" ]
Perform the initial vote allocation. p. 46. @return
[ "Perform", "the", "initial", "vote", "allocation", ".", "p", ".", "46", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L137-L153
12,940
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.checkCandidates
protected function checkCandidates(array $candidates): bool { $elected = false; $candidatesToElect = []; $this->logger->info('Checking if candidates have passed quota'); if (empty($candidates)) { throw new LogicException('There are no more candidates left'); } foreach ($candidates as $i => $candidate) { if ($candidate->getState() !== Candidate::RUNNING) { throw new LogicException('Candidate is not marked as not running but has not been excluded'); } $votes = $candidate->getVotes(); $this->logger->debug("Checking candidate ($candidate) with $votes", ['candidate' => $candidate]); // p. 48(1) // Immediately elect a candidate if they hit the quota // We check all the candidates, see who has hit the quota, // add them to a queue, then elect those who have hit the quota to prevent // surplus allocations pushing a candidate over the quota early. if ($votes >= $this->quota) { $candidatesToElect[] = $candidate; $elected = true; } } // TODO: Put this in a try, and catch the RuntimeError. // Then sort by the surplus, and fill available seats. // If have same surplus then select randomly (Contary to Scottish STV) // p. 50 $this->electCandidates($candidatesToElect); $this->logger->info(('Candidate checking complete. Elected: '.count($candidatesToElect))); return $elected; }
php
protected function checkCandidates(array $candidates): bool { $elected = false; $candidatesToElect = []; $this->logger->info('Checking if candidates have passed quota'); if (empty($candidates)) { throw new LogicException('There are no more candidates left'); } foreach ($candidates as $i => $candidate) { if ($candidate->getState() !== Candidate::RUNNING) { throw new LogicException('Candidate is not marked as not running but has not been excluded'); } $votes = $candidate->getVotes(); $this->logger->debug("Checking candidate ($candidate) with $votes", ['candidate' => $candidate]); // p. 48(1) // Immediately elect a candidate if they hit the quota // We check all the candidates, see who has hit the quota, // add them to a queue, then elect those who have hit the quota to prevent // surplus allocations pushing a candidate over the quota early. if ($votes >= $this->quota) { $candidatesToElect[] = $candidate; $elected = true; } } // TODO: Put this in a try, and catch the RuntimeError. // Then sort by the surplus, and fill available seats. // If have same surplus then select randomly (Contary to Scottish STV) // p. 50 $this->electCandidates($candidatesToElect); $this->logger->info(('Candidate checking complete. Elected: '.count($candidatesToElect))); return $elected; }
[ "protected", "function", "checkCandidates", "(", "array", "$", "candidates", ")", ":", "bool", "{", "$", "elected", "=", "false", ";", "$", "candidatesToElect", "=", "[", "]", ";", "$", "this", "->", "logger", "->", "info", "(", "'Checking if candidates have passed quota'", ")", ";", "if", "(", "empty", "(", "$", "candidates", ")", ")", "{", "throw", "new", "LogicException", "(", "'There are no more candidates left'", ")", ";", "}", "foreach", "(", "$", "candidates", "as", "$", "i", "=>", "$", "candidate", ")", "{", "if", "(", "$", "candidate", "->", "getState", "(", ")", "!==", "Candidate", "::", "RUNNING", ")", "{", "throw", "new", "LogicException", "(", "'Candidate is not marked as not running but has not been excluded'", ")", ";", "}", "$", "votes", "=", "$", "candidate", "->", "getVotes", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "\"Checking candidate ($candidate) with $votes\"", ",", "[", "'candidate'", "=>", "$", "candidate", "]", ")", ";", "// p. 48(1)", "// Immediately elect a candidate if they hit the quota", "// We check all the candidates, see who has hit the quota,", "// add them to a queue, then elect those who have hit the quota to prevent", "// surplus allocations pushing a candidate over the quota early.", "if", "(", "$", "votes", ">=", "$", "this", "->", "quota", ")", "{", "$", "candidatesToElect", "[", "]", "=", "$", "candidate", ";", "$", "elected", "=", "true", ";", "}", "}", "// TODO: Put this in a try, and catch the RuntimeError.", "// Then sort by the surplus, and fill available seats.", "// If have same surplus then select randomly (Contary to Scottish STV)", "// p. 50", "$", "this", "->", "electCandidates", "(", "$", "candidatesToElect", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "(", "'Candidate checking complete. Elected: '", ".", "count", "(", "$", "candidatesToElect", ")", ")", ")", ";", "return", "$", "elected", ";", "}" ]
Check if any candidates have reached the quota and can be elected. @param Candidate[] $candidates Array of active candidates to check @return bool Whether any candidates were changed to elected
[ "Check", "if", "any", "candidates", "have", "reached", "the", "quota", "and", "can", "be", "elected", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L192-L232
12,941
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.electCandidates
protected function electCandidates(array $candidates) { if ($this->candidatesToElect < count($candidates)) { throw new RuntimeException('Cannot elect candidate as not enough seats to fill'); } foreach ($candidates as $i => $candidate) { $this->electCandidate($candidate); } return; }
php
protected function electCandidates(array $candidates) { if ($this->candidatesToElect < count($candidates)) { throw new RuntimeException('Cannot elect candidate as not enough seats to fill'); } foreach ($candidates as $i => $candidate) { $this->electCandidate($candidate); } return; }
[ "protected", "function", "electCandidates", "(", "array", "$", "candidates", ")", "{", "if", "(", "$", "this", "->", "candidatesToElect", "<", "count", "(", "$", "candidates", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Cannot elect candidate as not enough seats to fill'", ")", ";", "}", "foreach", "(", "$", "candidates", "as", "$", "i", "=>", "$", "candidate", ")", "{", "$", "this", "->", "electCandidate", "(", "$", "candidate", ")", ";", "}", "return", ";", "}" ]
Elect an array of candidates. @param Candidate[] $candidates Array of candidates to elect @return
[ "Elect", "an", "array", "of", "candidates", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L241-L252
12,942
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.allocateVotes
protected function allocateVotes(Ballot $ballot, float $multiplier = 1.0, float $divisor = 1.0): Ballot { $currentWeight = $ballot->getWeight(); // p. 49(3) // "A divided by B" Where A = the value which is calculated // by multiplying the surplus of the transferring candidate // by the value of the ballot paper when received by that candidate; and // B = the total number of votes credited to that candidate $weight = $ballot->setWeight(($currentWeight * $multiplier) / $divisor); // Get the next candidate on their ballot paper which has not been assigned // a vote this could be the first candidate in round 1 $candidate = $ballot->getNextChoice(); $this->logger->debug("Allocating vote of weight $weight to $candidate. Previous weight: $currentWeight", array( 'ballot' => $ballot, )); // Check there was a next candidate, if only x candidates where listed where // x < the number of candidates standing this will occur. if ($candidate !== null) { // Allocate those surplus votes. p. 49(1) and p. 49(2) $this->election->getCandidate($candidate)->addVotes($weight); $ballot->incrementLevelUsed(); $this->logger->debug('Vote added to candidate'); // If the candidate is no longer running due to being defeated or // elected then we re-allocate their vote again. if (!in_array($candidate, $this->election->getActiveCandidateIds())) { $this->allocateVotes($ballot); } } return $ballot; }
php
protected function allocateVotes(Ballot $ballot, float $multiplier = 1.0, float $divisor = 1.0): Ballot { $currentWeight = $ballot->getWeight(); // p. 49(3) // "A divided by B" Where A = the value which is calculated // by multiplying the surplus of the transferring candidate // by the value of the ballot paper when received by that candidate; and // B = the total number of votes credited to that candidate $weight = $ballot->setWeight(($currentWeight * $multiplier) / $divisor); // Get the next candidate on their ballot paper which has not been assigned // a vote this could be the first candidate in round 1 $candidate = $ballot->getNextChoice(); $this->logger->debug("Allocating vote of weight $weight to $candidate. Previous weight: $currentWeight", array( 'ballot' => $ballot, )); // Check there was a next candidate, if only x candidates where listed where // x < the number of candidates standing this will occur. if ($candidate !== null) { // Allocate those surplus votes. p. 49(1) and p. 49(2) $this->election->getCandidate($candidate)->addVotes($weight); $ballot->incrementLevelUsed(); $this->logger->debug('Vote added to candidate'); // If the candidate is no longer running due to being defeated or // elected then we re-allocate their vote again. if (!in_array($candidate, $this->election->getActiveCandidateIds())) { $this->allocateVotes($ballot); } } return $ballot; }
[ "protected", "function", "allocateVotes", "(", "Ballot", "$", "ballot", ",", "float", "$", "multiplier", "=", "1.0", ",", "float", "$", "divisor", "=", "1.0", ")", ":", "Ballot", "{", "$", "currentWeight", "=", "$", "ballot", "->", "getWeight", "(", ")", ";", "// p. 49(3)", "// \"A divided by B\" Where A = the value which is calculated", "// by multiplying the surplus of the transferring candidate", "// by the value of the ballot paper when received by that candidate; and", "// B = the total number of votes credited to that candidate", "$", "weight", "=", "$", "ballot", "->", "setWeight", "(", "(", "$", "currentWeight", "*", "$", "multiplier", ")", "/", "$", "divisor", ")", ";", "// Get the next candidate on their ballot paper which has not been assigned", "// a vote this could be the first candidate in round 1", "$", "candidate", "=", "$", "ballot", "->", "getNextChoice", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "\"Allocating vote of weight $weight to $candidate. Previous weight: $currentWeight\"", ",", "array", "(", "'ballot'", "=>", "$", "ballot", ",", ")", ")", ";", "// Check there was a next candidate, if only x candidates where listed where", "// x < the number of candidates standing this will occur.", "if", "(", "$", "candidate", "!==", "null", ")", "{", "// Allocate those surplus votes. p. 49(1) and p. 49(2)", "$", "this", "->", "election", "->", "getCandidate", "(", "$", "candidate", ")", "->", "addVotes", "(", "$", "weight", ")", ";", "$", "ballot", "->", "incrementLevelUsed", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "'Vote added to candidate'", ")", ";", "// If the candidate is no longer running due to being defeated or", "// elected then we re-allocate their vote again.", "if", "(", "!", "in_array", "(", "$", "candidate", ",", "$", "this", "->", "election", "->", "getActiveCandidateIds", "(", ")", ")", ")", "{", "$", "this", "->", "allocateVotes", "(", "$", "ballot", ")", ";", "}", "}", "return", "$", "ballot", ";", "}" ]
Allocate the next votes from a Ballot. p. 49. @param Ballot $ballot The ballot to allocate the votes from @param float $multiplier Number to multiply the weight by (surplus) @param float $divisor The divisor of the weight (Total number of candidate votes) @return Ballot The same ballot passed in modified
[ "Allocate", "the", "next", "votes", "from", "a", "Ballot", ".", "p", ".", "49", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L265-L299
12,943
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.transferSurplusVotes
protected function transferSurplusVotes(float $surplus, Candidate $candidate) { $totalVotes = $candidate->getVotes(); $candidateId = $candidate->getId(); $this->logger->info('Transfering surplus votes'); foreach ($this->ballots as $i => $ballot) { if ($ballot->getLastChoice() == $candidateId) { $this->allocateVotes($ballot, $surplus, $totalVotes); } } return; }
php
protected function transferSurplusVotes(float $surplus, Candidate $candidate) { $totalVotes = $candidate->getVotes(); $candidateId = $candidate->getId(); $this->logger->info('Transfering surplus votes'); foreach ($this->ballots as $i => $ballot) { if ($ballot->getLastChoice() == $candidateId) { $this->allocateVotes($ballot, $surplus, $totalVotes); } } return; }
[ "protected", "function", "transferSurplusVotes", "(", "float", "$", "surplus", ",", "Candidate", "$", "candidate", ")", "{", "$", "totalVotes", "=", "$", "candidate", "->", "getVotes", "(", ")", ";", "$", "candidateId", "=", "$", "candidate", "->", "getId", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'Transfering surplus votes'", ")", ";", "foreach", "(", "$", "this", "->", "ballots", "as", "$", "i", "=>", "$", "ballot", ")", "{", "if", "(", "$", "ballot", "->", "getLastChoice", "(", ")", "==", "$", "candidateId", ")", "{", "$", "this", "->", "allocateVotes", "(", "$", "ballot", ",", "$", "surplus", ",", "$", "totalVotes", ")", ";", "}", "}", "return", ";", "}" ]
Transfer the votes from one candidate to other candidates. @param float $surplus The number of surplus votes to transfer @param Candidate $candidate The candidate being elected to transfer the votes from @return
[ "Transfer", "the", "votes", "from", "one", "candidate", "to", "other", "candidates", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L310-L324
12,944
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.electCandidate
protected function electCandidate(Candidate $candidate) { $this->logger->notice("Electing a candidate: $candidate"); $candidate->setState(Candidate::ELECTED); ++$this->electedCandidates; --$this->candidatesToElect; if ($this->electedCandidates < $this->election->getWinnersCount()) { $surplus = $candidate->getVotes() - $this->quota; if ($surplus > 0) { $this->transferSurplusVotes($surplus, $candidate); } else { $this->logger->notice("No surplus votes from $candidate to reallocate"); } } return; }
php
protected function electCandidate(Candidate $candidate) { $this->logger->notice("Electing a candidate: $candidate"); $candidate->setState(Candidate::ELECTED); ++$this->electedCandidates; --$this->candidatesToElect; if ($this->electedCandidates < $this->election->getWinnersCount()) { $surplus = $candidate->getVotes() - $this->quota; if ($surplus > 0) { $this->transferSurplusVotes($surplus, $candidate); } else { $this->logger->notice("No surplus votes from $candidate to reallocate"); } } return; }
[ "protected", "function", "electCandidate", "(", "Candidate", "$", "candidate", ")", "{", "$", "this", "->", "logger", "->", "notice", "(", "\"Electing a candidate: $candidate\"", ")", ";", "$", "candidate", "->", "setState", "(", "Candidate", "::", "ELECTED", ")", ";", "++", "$", "this", "->", "electedCandidates", ";", "--", "$", "this", "->", "candidatesToElect", ";", "if", "(", "$", "this", "->", "electedCandidates", "<", "$", "this", "->", "election", "->", "getWinnersCount", "(", ")", ")", "{", "$", "surplus", "=", "$", "candidate", "->", "getVotes", "(", ")", "-", "$", "this", "->", "quota", ";", "if", "(", "$", "surplus", ">", "0", ")", "{", "$", "this", "->", "transferSurplusVotes", "(", "$", "surplus", ",", "$", "candidate", ")", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "notice", "(", "\"No surplus votes from $candidate to reallocate\"", ")", ";", "}", "}", "return", ";", "}" ]
Elect a candidate after they've passed the threshold. @param Candidate $candidate
[ "Elect", "a", "candidate", "after", "they", "ve", "passed", "the", "threshold", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L360-L378
12,945
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.eliminateCandidates
protected function eliminateCandidates(array $candidates): int { $minimumCandidates = $this->getLowestCandidates($candidates); $count = count($minimumCandidates); // p. 52(2)(b) - the returning officer shall decide, by lot, which of those // candidates is to be excluded. // We do not look back on previous rounds at all as per p. 52(2)(a) $minimumCandidate = $minimumCandidates[(array_rand($minimumCandidates))]; $this->logger->notice(sprintf('There were %d joint lowest candidates, %d was randomly selected to be eliminated', $count, $minimumCandidate->getId())); $this->transferEliminatedVotes($minimumCandidate); $minimumCandidate->setState(Candidate::DEFEATED); return count($minimumCandidates); }
php
protected function eliminateCandidates(array $candidates): int { $minimumCandidates = $this->getLowestCandidates($candidates); $count = count($minimumCandidates); // p. 52(2)(b) - the returning officer shall decide, by lot, which of those // candidates is to be excluded. // We do not look back on previous rounds at all as per p. 52(2)(a) $minimumCandidate = $minimumCandidates[(array_rand($minimumCandidates))]; $this->logger->notice(sprintf('There were %d joint lowest candidates, %d was randomly selected to be eliminated', $count, $minimumCandidate->getId())); $this->transferEliminatedVotes($minimumCandidate); $minimumCandidate->setState(Candidate::DEFEATED); return count($minimumCandidates); }
[ "protected", "function", "eliminateCandidates", "(", "array", "$", "candidates", ")", ":", "int", "{", "$", "minimumCandidates", "=", "$", "this", "->", "getLowestCandidates", "(", "$", "candidates", ")", ";", "$", "count", "=", "count", "(", "$", "minimumCandidates", ")", ";", "// p. 52(2)(b) - the returning officer shall decide, by lot, which of those", "// candidates is to be excluded.", "// We do not look back on previous rounds at all as per p. 52(2)(a)", "$", "minimumCandidate", "=", "$", "minimumCandidates", "[", "(", "array_rand", "(", "$", "minimumCandidates", ")", ")", "]", ";", "$", "this", "->", "logger", "->", "notice", "(", "sprintf", "(", "'There were %d joint lowest candidates,\n %d was randomly selected to be eliminated'", ",", "$", "count", ",", "$", "minimumCandidate", "->", "getId", "(", ")", ")", ")", ";", "$", "this", "->", "transferEliminatedVotes", "(", "$", "minimumCandidate", ")", ";", "$", "minimumCandidate", "->", "setState", "(", "Candidate", "::", "DEFEATED", ")", ";", "return", "count", "(", "$", "minimumCandidates", ")", ";", "}" ]
Eliminate the candidate with the lowest number of votes and reallocated their votes. p. 51. @param Candidate[] $candidates Array of active candidates @return int Number of candidates eliminated
[ "Eliminate", "the", "candidate", "with", "the", "lowest", "number", "of", "votes", "and", "reallocated", "their", "votes", ".", "p", ".", "51", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L389-L406
12,946
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.checkBallotValidity
public function checkBallotValidity(Ballot $ballot): bool { $ranking = $ballot->getRanking(); if (!$this->checkCandidateCountValidity($ranking) || !$this->checkBallotVoteDuplicationValidity($ranking) || !$this->checkAllBallotCandidatesValid($ranking)) { return false; } $this->logger->debug('Ballot is valid'); return true; }
php
public function checkBallotValidity(Ballot $ballot): bool { $ranking = $ballot->getRanking(); if (!$this->checkCandidateCountValidity($ranking) || !$this->checkBallotVoteDuplicationValidity($ranking) || !$this->checkAllBallotCandidatesValid($ranking)) { return false; } $this->logger->debug('Ballot is valid'); return true; }
[ "public", "function", "checkBallotValidity", "(", "Ballot", "$", "ballot", ")", ":", "bool", "{", "$", "ranking", "=", "$", "ballot", "->", "getRanking", "(", ")", ";", "if", "(", "!", "$", "this", "->", "checkCandidateCountValidity", "(", "$", "ranking", ")", "||", "!", "$", "this", "->", "checkBallotVoteDuplicationValidity", "(", "$", "ranking", ")", "||", "!", "$", "this", "->", "checkAllBallotCandidatesValid", "(", "$", "ranking", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "'Ballot is valid'", ")", ";", "return", "true", ";", "}" ]
Check if ballot is valid. @param Ballot $ballot Ballot to test @return bool True if valid, false if invalid
[ "Check", "if", "ballot", "is", "valid", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L468-L480
12,947
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.reallocateRemainingVotes
protected function reallocateRemainingVotes(array &$candidates) { if (!empty($candidates)) { $this->logger->info('All votes re-allocated. Electing all remaining candidates'); if ($this->candidatesToElect < count($candidates)) { throw new LogicException('Cannot elect candidate as no more seats to fill'); } $this->electCandidates($candidates); } return; }
php
protected function reallocateRemainingVotes(array &$candidates) { if (!empty($candidates)) { $this->logger->info('All votes re-allocated. Electing all remaining candidates'); if ($this->candidatesToElect < count($candidates)) { throw new LogicException('Cannot elect candidate as no more seats to fill'); } $this->electCandidates($candidates); } return; }
[ "protected", "function", "reallocateRemainingVotes", "(", "array", "&", "$", "candidates", ")", "{", "if", "(", "!", "empty", "(", "$", "candidates", ")", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'All votes re-allocated. Electing all remaining candidates'", ")", ";", "if", "(", "$", "this", "->", "candidatesToElect", "<", "count", "(", "$", "candidates", ")", ")", "{", "throw", "new", "LogicException", "(", "'Cannot elect candidate as no more seats to fill'", ")", ";", "}", "$", "this", "->", "electCandidates", "(", "$", "candidates", ")", ";", "}", "return", ";", "}" ]
Reallocate any remaining votes p. 53. @param Candidate[] $candidates All remaining candidates to elect @return
[ "Reallocate", "any", "remaining", "votes", "p", ".", "53", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L490-L503
12,948
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.setQuota
public function setQuota(): int { $this->quota = (int) floor( ($this->validBallots / ($this->election->getWinnersCount() + 1) ) // p. 47 (1) + 1); // p. 47 (2) $this->logger->info(sprintf('Quota set at %d based on %d winners and %d valid ballots', $this->quota, $this->election->getWinnersCount(), $this->validBallots)); return $this->quota; }
php
public function setQuota(): int { $this->quota = (int) floor( ($this->validBallots / ($this->election->getWinnersCount() + 1) ) // p. 47 (1) + 1); // p. 47 (2) $this->logger->info(sprintf('Quota set at %d based on %d winners and %d valid ballots', $this->quota, $this->election->getWinnersCount(), $this->validBallots)); return $this->quota; }
[ "public", "function", "setQuota", "(", ")", ":", "int", "{", "$", "this", "->", "quota", "=", "(", "int", ")", "floor", "(", "(", "$", "this", "->", "validBallots", "/", "(", "$", "this", "->", "election", "->", "getWinnersCount", "(", ")", "+", "1", ")", ")", "// p. 47 (1)", "+", "1", ")", ";", "// p. 47 (2)", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'Quota set at %d based on %d winners and %d valid ballots'", ",", "$", "this", "->", "quota", ",", "$", "this", "->", "election", "->", "getWinnersCount", "(", ")", ",", "$", "this", "->", "validBallots", ")", ")", ";", "return", "$", "this", "->", "quota", ";", "}" ]
Get the quota to win. p. 47. TODO: Move this out of this method and use params/args @return int
[ "Get", "the", "quota", "to", "win", ".", "p", ".", "47", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L513-L524
12,949
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.checkCandidateCountValidity
protected function checkCandidateCountValidity(array $ranking): bool { if (count($ranking) > $this->election->getCandidateCount()) { $this->logger->debug('Invalid ballot - number of candidates'); return false; } return true; }
php
protected function checkCandidateCountValidity(array $ranking): bool { if (count($ranking) > $this->election->getCandidateCount()) { $this->logger->debug('Invalid ballot - number of candidates'); return false; } return true; }
[ "protected", "function", "checkCandidateCountValidity", "(", "array", "$", "ranking", ")", ":", "bool", "{", "if", "(", "count", "(", "$", "ranking", ")", ">", "$", "this", "->", "election", "->", "getCandidateCount", "(", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Invalid ballot - number of candidates'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check that a ballot's ranking doesn't have more elements than we have candidates @param array $ranking Ballot ranking @return bool False if invalid, True if valid
[ "Check", "that", "a", "ballot", "s", "ranking", "doesn", "t", "have", "more", "elements", "than", "we", "have", "candidates" ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L555-L564
12,950
michaelcullum/voting-lib
src/STV/ElectionRunner.php
ElectionRunner.checkAllBallotCandidatesValid
protected function checkAllBallotCandidatesValid(array $ranking): bool { $candidateIds = $this->election->getCandidateIds(); foreach ($ranking as $candidate) { if (!in_array($candidate, $candidateIds)) { $this->logger->debug('Invalid ballot - invalid candidate'); return false; } } return true; }
php
protected function checkAllBallotCandidatesValid(array $ranking): bool { $candidateIds = $this->election->getCandidateIds(); foreach ($ranking as $candidate) { if (!in_array($candidate, $candidateIds)) { $this->logger->debug('Invalid ballot - invalid candidate'); return false; } } return true; }
[ "protected", "function", "checkAllBallotCandidatesValid", "(", "array", "$", "ranking", ")", ":", "bool", "{", "$", "candidateIds", "=", "$", "this", "->", "election", "->", "getCandidateIds", "(", ")", ";", "foreach", "(", "$", "ranking", "as", "$", "candidate", ")", "{", "if", "(", "!", "in_array", "(", "$", "candidate", ",", "$", "candidateIds", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Invalid ballot - invalid candidate'", ")", ";", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check that a ballot only contains candidate id numbers that are integers and correspond to valid candidates. @param array $ranking Ballot ranking @return bool False if invalid, True if valid
[ "Check", "that", "a", "ballot", "only", "contains", "candidate", "id", "numbers", "that", "are", "integers", "and", "correspond", "to", "valid", "candidates", "." ]
83f0543493448021386e3a3b8c95d3268f1ee212
https://github.com/michaelcullum/voting-lib/blob/83f0543493448021386e3a3b8c95d3268f1ee212/src/STV/ElectionRunner.php#L591-L604
12,951
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.time
public static function time() { if (!is_null(self::$_now)) { if (is_int(self::$_now)) { return self::$_now; } return strtotime(self::$_now); } return time(); }
php
public static function time() { if (!is_null(self::$_now)) { if (is_int(self::$_now)) { return self::$_now; } return strtotime(self::$_now); } return time(); }
[ "public", "static", "function", "time", "(", ")", "{", "if", "(", "!", "is_null", "(", "self", "::", "$", "_now", ")", ")", "{", "if", "(", "is_int", "(", "self", "::", "$", "_now", ")", ")", "{", "return", "self", "::", "$", "_now", ";", "}", "return", "strtotime", "(", "self", "::", "$", "_now", ")", ";", "}", "return", "time", "(", ")", ";", "}" ]
Get the current time. @return int Unix timestamp
[ "Get", "the", "current", "time", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L42-L53
12,952
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.strtotime
public static function strtotime($str, $time = null) { if (is_null($time)) { $time = self::time(); } return strtotime($str, $time); }
php
public static function strtotime($str, $time = null) { if (is_null($time)) { $time = self::time(); } return strtotime($str, $time); }
[ "public", "static", "function", "strtotime", "(", "$", "str", ",", "$", "time", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "time", ")", ")", "{", "$", "time", "=", "self", "::", "time", "(", ")", ";", "}", "return", "strtotime", "(", "$", "str", ",", "$", "time", ")", ";", "}" ]
Strtotime with fallback on overriden application time. @see php:strtotime @param string $str strtotime string @param int $time Unix timestamp (optional) @return string formatted date @see php:strtotime
[ "Strtotime", "with", "fallback", "on", "overriden", "application", "time", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L90-L97
12,953
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.inPast
public static function inPast($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time > $date; }
php
public static function inPast($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time > $date; }
[ "public", "static", "function", "inPast", "(", "$", "date", ",", "$", "time", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "time", ")", ")", "{", "$", "time", "=", "self", "::", "time", "(", ")", ";", "}", "if", "(", "!", "is_int", "(", "$", "date", ")", ")", "{", "$", "date", "=", "self", "::", "strtotime", "(", "$", "date", ")", ";", "}", "return", "$", "time", ">", "$", "date", ";", "}" ]
Is the date in the past? @param varies $date @param int $time (optional) @return bool Is the time in the past or not
[ "Is", "the", "date", "in", "the", "past?" ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L133-L143
12,954
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.inFuture
public static function inFuture($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time < $date; }
php
public static function inFuture($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time < $date; }
[ "public", "static", "function", "inFuture", "(", "$", "date", ",", "$", "time", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "time", ")", ")", "{", "$", "time", "=", "self", "::", "time", "(", ")", ";", "}", "if", "(", "!", "is_int", "(", "$", "date", ")", ")", "{", "$", "date", "=", "self", "::", "strtotime", "(", "$", "date", ")", ";", "}", "return", "$", "time", "<", "$", "date", ";", "}" ]
Is the date in the future? @param varies $date @param int $time (optional) @return bool Is the time in the past or not
[ "Is", "the", "date", "in", "the", "future?" ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L153-L163
12,955
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.isPresent
public static function isPresent($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time === $date; }
php
public static function isPresent($date, $time = null) { if (is_null($time)) { $time = self::time(); } if (!is_int($date)) { $date = self::strtotime($date); } return $time === $date; }
[ "public", "static", "function", "isPresent", "(", "$", "date", ",", "$", "time", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "time", ")", ")", "{", "$", "time", "=", "self", "::", "time", "(", ")", ";", "}", "if", "(", "!", "is_int", "(", "$", "date", ")", ")", "{", "$", "date", "=", "self", "::", "strtotime", "(", "$", "date", ")", ";", "}", "return", "$", "time", "===", "$", "date", ";", "}" ]
Is it now. @param varies $date @param int $time (optional) @return bool Is the time in the past or not
[ "Is", "it", "now", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L173-L183
12,956
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.niceTimeDiff
public static function niceTimeDiff($d1, $d2, $limitPeriods = 2) { if (!is_int($d1)) { $d1 = self::strtotime($d1); } if (!is_int($d2)) { $d2 = self::strtotime($d2); } if (empty($d1) or empty($d2)) { return false; } $max = max($d1, $d2); $min = min($d1, $d2); $diff = $max - $min; return self::niceDuration($diff, $limitPeriods); }
php
public static function niceTimeDiff($d1, $d2, $limitPeriods = 2) { if (!is_int($d1)) { $d1 = self::strtotime($d1); } if (!is_int($d2)) { $d2 = self::strtotime($d2); } if (empty($d1) or empty($d2)) { return false; } $max = max($d1, $d2); $min = min($d1, $d2); $diff = $max - $min; return self::niceDuration($diff, $limitPeriods); }
[ "public", "static", "function", "niceTimeDiff", "(", "$", "d1", ",", "$", "d2", ",", "$", "limitPeriods", "=", "2", ")", "{", "if", "(", "!", "is_int", "(", "$", "d1", ")", ")", "{", "$", "d1", "=", "self", "::", "strtotime", "(", "$", "d1", ")", ";", "}", "if", "(", "!", "is_int", "(", "$", "d2", ")", ")", "{", "$", "d2", "=", "self", "::", "strtotime", "(", "$", "d2", ")", ";", "}", "if", "(", "empty", "(", "$", "d1", ")", "or", "empty", "(", "$", "d2", ")", ")", "{", "return", "false", ";", "}", "$", "max", "=", "max", "(", "$", "d1", ",", "$", "d2", ")", ";", "$", "min", "=", "min", "(", "$", "d1", ",", "$", "d2", ")", ";", "$", "diff", "=", "$", "max", "-", "$", "min", ";", "return", "self", "::", "niceDuration", "(", "$", "diff", ",", "$", "limitPeriods", ")", ";", "}" ]
Nice time difference. @param string $d1 Date string @param string $d2 Date string @param int $limitPeriods Number of periods to show (optional) @return string Nice duration
[ "Nice", "time", "difference", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L276-L292
12,957
canis-io/yii2-canis-lib
lib/helpers/Date.php
Date.niceDuration
public static function niceDuration($seconds, $limitPeriods = 7, $zeros = false) { // Define time periods $periods = [ 'years' => 31556926, 'months' => 2629743, //'weeks' => 604800, 'days' => 86400, 'hours' => 3600, 'minutes' => 60, 'seconds' => 1, ]; // Break into periods $seconds = (float) $seconds; $segments = []; foreach ($periods as $period => $value) { if ($limitPeriods >= 1) { $count = floor($seconds / $value); $seconds = $seconds % $value; } else { $count = round($seconds / $value); $seconds = 0; } if (($count == 0 && !$zeros) or $limitPeriods < 1) { continue; } $segments[strtolower($period)] = $count; $limitPeriods--; } // Build the string $string = []; foreach ($segments as $key => $value) { $segment_name = substr($key, 0, -1); $segment = $value . ' ' . $segment_name; if ($value != 1) { $segment .= 's'; } $string[] = $segment; } return implode(', ', $string); }
php
public static function niceDuration($seconds, $limitPeriods = 7, $zeros = false) { // Define time periods $periods = [ 'years' => 31556926, 'months' => 2629743, //'weeks' => 604800, 'days' => 86400, 'hours' => 3600, 'minutes' => 60, 'seconds' => 1, ]; // Break into periods $seconds = (float) $seconds; $segments = []; foreach ($periods as $period => $value) { if ($limitPeriods >= 1) { $count = floor($seconds / $value); $seconds = $seconds % $value; } else { $count = round($seconds / $value); $seconds = 0; } if (($count == 0 && !$zeros) or $limitPeriods < 1) { continue; } $segments[strtolower($period)] = $count; $limitPeriods--; } // Build the string $string = []; foreach ($segments as $key => $value) { $segment_name = substr($key, 0, -1); $segment = $value . ' ' . $segment_name; if ($value != 1) { $segment .= 's'; } $string[] = $segment; } return implode(', ', $string); }
[ "public", "static", "function", "niceDuration", "(", "$", "seconds", ",", "$", "limitPeriods", "=", "7", ",", "$", "zeros", "=", "false", ")", "{", "// Define time periods", "$", "periods", "=", "[", "'years'", "=>", "31556926", ",", "'months'", "=>", "2629743", ",", "//'weeks' => 604800,", "'days'", "=>", "86400", ",", "'hours'", "=>", "3600", ",", "'minutes'", "=>", "60", ",", "'seconds'", "=>", "1", ",", "]", ";", "// Break into periods", "$", "seconds", "=", "(", "float", ")", "$", "seconds", ";", "$", "segments", "=", "[", "]", ";", "foreach", "(", "$", "periods", "as", "$", "period", "=>", "$", "value", ")", "{", "if", "(", "$", "limitPeriods", ">=", "1", ")", "{", "$", "count", "=", "floor", "(", "$", "seconds", "/", "$", "value", ")", ";", "$", "seconds", "=", "$", "seconds", "%", "$", "value", ";", "}", "else", "{", "$", "count", "=", "round", "(", "$", "seconds", "/", "$", "value", ")", ";", "$", "seconds", "=", "0", ";", "}", "if", "(", "(", "$", "count", "==", "0", "&&", "!", "$", "zeros", ")", "or", "$", "limitPeriods", "<", "1", ")", "{", "continue", ";", "}", "$", "segments", "[", "strtolower", "(", "$", "period", ")", "]", "=", "$", "count", ";", "$", "limitPeriods", "--", ";", "}", "// Build the string", "$", "string", "=", "[", "]", ";", "foreach", "(", "$", "segments", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "segment_name", "=", "substr", "(", "$", "key", ",", "0", ",", "-", "1", ")", ";", "$", "segment", "=", "$", "value", ".", "' '", ".", "$", "segment_name", ";", "if", "(", "$", "value", "!=", "1", ")", "{", "$", "segment", ".=", "'s'", ";", "}", "$", "string", "[", "]", "=", "$", "segment", ";", "}", "return", "implode", "(", "', '", ",", "$", "string", ")", ";", "}" ]
Get the human string of a duration. @param int $seconds Number of seconds @param int $limitPeriods (optional) @param bool $zeros Show zeros (optional; default false) @return string Nice human duration
[ "Get", "the", "human", "string", "of", "a", "duration", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/helpers/Date.php#L322-L366
12,958
AdrianSkierniewski/laravel-oauth
src/Gzero/OAuth/OAuth.php
OAuth.loadConfig
protected function loadConfig($serviceName) { if (!empty($this->config[$serviceName])) { return $this->config[$serviceName]; } else { throw new OAuthServiceException('No configuration for ' . $serviceName . ' service'); } }
php
protected function loadConfig($serviceName) { if (!empty($this->config[$serviceName])) { return $this->config[$serviceName]; } else { throw new OAuthServiceException('No configuration for ' . $serviceName . ' service'); } }
[ "protected", "function", "loadConfig", "(", "$", "serviceName", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "config", "[", "$", "serviceName", "]", ")", ")", "{", "return", "$", "this", "->", "config", "[", "$", "serviceName", "]", ";", "}", "else", "{", "throw", "new", "OAuthServiceException", "(", "'No configuration for '", ".", "$", "serviceName", ".", "' service'", ")", ";", "}", "}" ]
Returns config for specific service @param $serviceName @return @throws OAuthServiceException
[ "Returns", "config", "for", "specific", "service" ]
28a7ec445377c44ca78ebd8cc0eb4c8e2979796e
https://github.com/AdrianSkierniewski/laravel-oauth/blob/28a7ec445377c44ca78ebd8cc0eb4c8e2979796e/src/Gzero/OAuth/OAuth.php#L71-L78
12,959
MINISTRYGmbH/morrow-core
src/Event.php
Event.trigger
public function trigger($event, $data = null) { $event = strtolower(trim($event)); if (!isset($this->_events[$event])) return $data; foreach ($this->_events[$event] as $callback) { // we don't want to affect the data if someone forgets to return the original data in his callback. $result = call_user_func($callback, $event, $data); if ($result !== null) $data = $result; } return $data; }
php
public function trigger($event, $data = null) { $event = strtolower(trim($event)); if (!isset($this->_events[$event])) return $data; foreach ($this->_events[$event] as $callback) { // we don't want to affect the data if someone forgets to return the original data in his callback. $result = call_user_func($callback, $event, $data); if ($result !== null) $data = $result; } return $data; }
[ "public", "function", "trigger", "(", "$", "event", ",", "$", "data", "=", "null", ")", "{", "$", "event", "=", "strtolower", "(", "trim", "(", "$", "event", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "_events", "[", "$", "event", "]", ")", ")", "return", "$", "data", ";", "foreach", "(", "$", "this", "->", "_events", "[", "$", "event", "]", "as", "$", "callback", ")", "{", "// we don't want to affect the data if someone forgets to return the original data in his callback. ", "$", "result", "=", "call_user_func", "(", "$", "callback", ",", "$", "event", ",", "$", "data", ")", ";", "if", "(", "$", "result", "!==", "null", ")", "$", "data", "=", "$", "result", ";", "}", "return", "$", "data", ";", "}" ]
Triggers an event. @param string $event The case insensitive event name that should be triggered. @param mixed $data The data that should be passed to one or many callbacks. @return mixed $data The data that was changed by one or many callbacks.
[ "Triggers", "an", "event", "." ]
bdc916eedb14b65b06dbc88efbd2b7779f4a9a9e
https://github.com/MINISTRYGmbH/morrow-core/blob/bdc916eedb14b65b06dbc88efbd2b7779f4a9a9e/src/Event.php#L114-L125
12,960
arvici/framework
src/Arvici/Heart/Bootstrapper.php
Bootstrapper.startWeb
public function startWeb() { // Start the base. $this->startBase(); // Start debug profilers etc. if (Configuration::get('app.env') === 'development' && Configuration::get('app.profiler', false)) { DebugBarHelper::getInstance(); } // Start router and start parsing request. $this->router->run(); }
php
public function startWeb() { // Start the base. $this->startBase(); // Start debug profilers etc. if (Configuration::get('app.env') === 'development' && Configuration::get('app.profiler', false)) { DebugBarHelper::getInstance(); } // Start router and start parsing request. $this->router->run(); }
[ "public", "function", "startWeb", "(", ")", "{", "// Start the base.", "$", "this", "->", "startBase", "(", ")", ";", "// Start debug profilers etc.", "if", "(", "Configuration", "::", "get", "(", "'app.env'", ")", "===", "'development'", "&&", "Configuration", "::", "get", "(", "'app.profiler'", ",", "false", ")", ")", "{", "DebugBarHelper", "::", "getInstance", "(", ")", ";", "}", "// Start router and start parsing request.", "$", "this", "->", "router", "->", "run", "(", ")", ";", "}" ]
Start from web, will make sure we start the logger, some kernel parts, and the router.
[ "Start", "from", "web", "will", "make", "sure", "we", "start", "the", "logger", "some", "kernel", "parts", "and", "the", "router", "." ]
4d0933912fef8f9edc756ef1ace009e96d9fc4b1
https://github.com/arvici/framework/blob/4d0933912fef8f9edc756ef1ace009e96d9fc4b1/src/Arvici/Heart/Bootstrapper.php#L56-L68
12,961
mxc-commons/mxc-servicemanager
src/AbstractPluginManager.php
AbstractPluginManager.setService
public function setService($name, $service) { $this->validate($service); parent::setService($name, $service); }
php
public function setService($name, $service) { $this->validate($service); parent::setService($name, $service); }
[ "public", "function", "setService", "(", "$", "name", ",", "$", "service", ")", "{", "$", "this", "->", "validate", "(", "$", "service", ")", ";", "parent", "::", "setService", "(", "$", "name", ",", "$", "service", ")", ";", "}" ]
Override setService for additional plugin validation. {@inheritDoc}
[ "Override", "setService", "for", "additional", "plugin", "validation", "." ]
547a9ed579b96d32cb54db5723510d75fcad71be
https://github.com/mxc-commons/mxc-servicemanager/blob/547a9ed579b96d32cb54db5723510d75fcad71be/src/AbstractPluginManager.php#L129-L133
12,962
mxc-commons/mxc-servicemanager
src/AbstractPluginManager.php
AbstractPluginManager.setServiceLocator
public function setServiceLocator(ContainerInterface $container) { trigger_error(sprintf( 'Usage of %s is deprecated since v3.0.0; please pass the container to the constructor instead', __METHOD__ ), E_USER_DEPRECATED); $this->creationContext = $container; }
php
public function setServiceLocator(ContainerInterface $container) { trigger_error(sprintf( 'Usage of %s is deprecated since v3.0.0; please pass the container to the constructor instead', __METHOD__ ), E_USER_DEPRECATED); $this->creationContext = $container; }
[ "public", "function", "setServiceLocator", "(", "ContainerInterface", "$", "container", ")", "{", "trigger_error", "(", "sprintf", "(", "'Usage of %s is deprecated since v3.0.0; please pass the container to the constructor instead'", ",", "__METHOD__", ")", ",", "E_USER_DEPRECATED", ")", ";", "$", "this", "->", "creationContext", "=", "$", "container", ";", "}" ]
Implemented for backwards compatibility only. Returns the creation context. @deprecated since 3.0.0. The creation context should be passed during instantiation instead. @param ContainerInterface $container @return void
[ "Implemented", "for", "backwards", "compatibility", "only", "." ]
547a9ed579b96d32cb54db5723510d75fcad71be
https://github.com/mxc-commons/mxc-servicemanager/blob/547a9ed579b96d32cb54db5723510d75fcad71be/src/AbstractPluginManager.php#L202-L209
12,963
joomlatools/joomlatools-platform-categories
administrator/components/com_categories/helpers/association.php
CategoryHelperAssociation.getCategoryAssociations
public static function getCategoryAssociations($id = 0, $extension = 'com_content') { $return = array(); if ($id) { // Load route helper jimport('helper.route', JPATH_COMPONENT_SITE); $helperClassname = ucfirst(substr($extension, 4)) . 'HelperRoute'; $associations = CategoriesHelper::getAssociations($id, $extension); foreach ($associations as $tag => $item) { if (class_exists($helperClassname) && is_callable(array($helperClassname, 'getCategoryRoute'))) { $return[$tag] = $helperClassname::getCategoryRoute($item, $tag); } else { $return[$tag] = 'index.php?option=' . $extension . '&view=category&id=' . $item; } } } return $return; }
php
public static function getCategoryAssociations($id = 0, $extension = 'com_content') { $return = array(); if ($id) { // Load route helper jimport('helper.route', JPATH_COMPONENT_SITE); $helperClassname = ucfirst(substr($extension, 4)) . 'HelperRoute'; $associations = CategoriesHelper::getAssociations($id, $extension); foreach ($associations as $tag => $item) { if (class_exists($helperClassname) && is_callable(array($helperClassname, 'getCategoryRoute'))) { $return[$tag] = $helperClassname::getCategoryRoute($item, $tag); } else { $return[$tag] = 'index.php?option=' . $extension . '&view=category&id=' . $item; } } } return $return; }
[ "public", "static", "function", "getCategoryAssociations", "(", "$", "id", "=", "0", ",", "$", "extension", "=", "'com_content'", ")", "{", "$", "return", "=", "array", "(", ")", ";", "if", "(", "$", "id", ")", "{", "// Load route helper", "jimport", "(", "'helper.route'", ",", "JPATH_COMPONENT_SITE", ")", ";", "$", "helperClassname", "=", "ucfirst", "(", "substr", "(", "$", "extension", ",", "4", ")", ")", ".", "'HelperRoute'", ";", "$", "associations", "=", "CategoriesHelper", "::", "getAssociations", "(", "$", "id", ",", "$", "extension", ")", ";", "foreach", "(", "$", "associations", "as", "$", "tag", "=>", "$", "item", ")", "{", "if", "(", "class_exists", "(", "$", "helperClassname", ")", "&&", "is_callable", "(", "array", "(", "$", "helperClassname", ",", "'getCategoryRoute'", ")", ")", ")", "{", "$", "return", "[", "$", "tag", "]", "=", "$", "helperClassname", "::", "getCategoryRoute", "(", "$", "item", ",", "$", "tag", ")", ";", "}", "else", "{", "$", "return", "[", "$", "tag", "]", "=", "'index.php?option='", ".", "$", "extension", ".", "'&view=category&id='", ".", "$", "item", ";", "}", "}", "}", "return", "$", "return", ";", "}" ]
Method to get the associations for a given category @param integer $id Id of the item @param string $extension Name of the component @return array Array of associations for the component categories @since 3.0
[ "Method", "to", "get", "the", "associations", "for", "a", "given", "category" ]
9fe50b6c4ebe6ebfcf98e50067922fcf4a76d350
https://github.com/joomlatools/joomlatools-platform-categories/blob/9fe50b6c4ebe6ebfcf98e50067922fcf4a76d350/administrator/components/com_categories/helpers/association.php#L33-L59
12,964
railsphp/framework
src/Rails/ActiveRecord/Adapter/Driver/Pdo/Connection.php
Connection.connect
public function connect() { parent::connect(); $this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); return $this; }
php
public function connect() { parent::connect(); $this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); return $this; }
[ "public", "function", "connect", "(", ")", "{", "parent", "::", "connect", "(", ")", ";", "$", "this", "->", "resource", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "\\", "PDO", "::", "ERRMODE_SILENT", ")", ";", "return", "$", "this", ";", "}" ]
Extended to set error mode to silent.
[ "Extended", "to", "set", "error", "mode", "to", "silent", "." ]
2ac9d3e493035dcc68f3c3812423327127327cd5
https://github.com/railsphp/framework/blob/2ac9d3e493035dcc68f3c3812423327127327cd5/src/Rails/ActiveRecord/Adapter/Driver/Pdo/Connection.php#L36-L41
12,965
loopsframework/base
src/Loops/Misc/EventTrait.php
EventTrait.bindEventObject
public function bindEventObject($object, $filter = FALSE) { $this->bound_event_objects[] = [ $filter === FALSE ? FALSE : (array)$filter, $object ]; $this->event_cache_state = []; }
php
public function bindEventObject($object, $filter = FALSE) { $this->bound_event_objects[] = [ $filter === FALSE ? FALSE : (array)$filter, $object ]; $this->event_cache_state = []; }
[ "public", "function", "bindEventObject", "(", "$", "object", ",", "$", "filter", "=", "FALSE", ")", "{", "$", "this", "->", "bound_event_objects", "[", "]", "=", "[", "$", "filter", "===", "FALSE", "?", "FALSE", ":", "(", "array", ")", "$", "filter", ",", "$", "object", "]", ";", "$", "this", "->", "event_cache_state", "=", "[", "]", ";", "}" ]
Registers all event listener of an object to this object. After an object is bound, all listeners of that object will also be called if an event is fired (on this object). @param object $object The target object from which the listeners will be registered. @param bool|string[] Only register the listeners that are passed via an array. Set to FALSE to register all listeners.
[ "Registers", "all", "event", "listener", "of", "an", "object", "to", "this", "object", "." ]
5a15172ed4e543d7d5ecd8bd65e31f26bab3d192
https://github.com/loopsframework/base/blob/5a15172ed4e543d7d5ecd8bd65e31f26bab3d192/src/Loops/Misc/EventTrait.php#L108-L111
12,966
loopsframework/base
src/Loops/Misc/EventTrait.php
EventTrait.addListener
public function addListener($name, callable $callback) { if(!array_key_exists($name, $this->registered_events)) { $this->registered_events[$name] = []; } $this->registered_events[$name][] = $callback; }
php
public function addListener($name, callable $callback) { if(!array_key_exists($name, $this->registered_events)) { $this->registered_events[$name] = []; } $this->registered_events[$name][] = $callback; }
[ "public", "function", "addListener", "(", "$", "name", ",", "callable", "$", "callback", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "registered_events", ")", ")", "{", "$", "this", "->", "registered_events", "[", "$", "name", "]", "=", "[", "]", ";", "}", "$", "this", "->", "registered_events", "[", "$", "name", "]", "[", "]", "=", "$", "callback", ";", "}" ]
Manually adds a listener @param string $name The name of the event. @param callable $callback The callable that will be called if the event is fired.
[ "Manually", "adds", "a", "listener" ]
5a15172ed4e543d7d5ecd8bd65e31f26bab3d192
https://github.com/loopsframework/base/blob/5a15172ed4e543d7d5ecd8bd65e31f26bab3d192/src/Loops/Misc/EventTrait.php#L119-L125
12,967
unimapper/unimapper
src/Entity/Reflection/Annotation.php
Annotation.registerOption
public static function registerOption($key, $class) { if (empty($key)) { throw new Exception\AnnotationException( "Option key can not be empty!" ); } if (!class_exists($class)) { throw new Exception\AnnotationException( "Class " . $class . " not found!" ); } if (!in_array("UniMapper\Entity\Reflection\Property\IOption", class_implements($class))) { throw new Exception\AnnotationException( "Class " . $class . " should implement UniMapper\Entity\Reflection\Property\IOption!" ); } self::$options[$key] = $class; }
php
public static function registerOption($key, $class) { if (empty($key)) { throw new Exception\AnnotationException( "Option key can not be empty!" ); } if (!class_exists($class)) { throw new Exception\AnnotationException( "Class " . $class . " not found!" ); } if (!in_array("UniMapper\Entity\Reflection\Property\IOption", class_implements($class))) { throw new Exception\AnnotationException( "Class " . $class . " should implement UniMapper\Entity\Reflection\Property\IOption!" ); } self::$options[$key] = $class; }
[ "public", "static", "function", "registerOption", "(", "$", "key", ",", "$", "class", ")", "{", "if", "(", "empty", "(", "$", "key", ")", ")", "{", "throw", "new", "Exception", "\\", "AnnotationException", "(", "\"Option key can not be empty!\"", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "throw", "new", "Exception", "\\", "AnnotationException", "(", "\"Class \"", ".", "$", "class", ".", "\" not found!\"", ")", ";", "}", "if", "(", "!", "in_array", "(", "\"UniMapper\\Entity\\Reflection\\Property\\IOption\"", ",", "class_implements", "(", "$", "class", ")", ")", ")", "{", "throw", "new", "Exception", "\\", "AnnotationException", "(", "\"Class \"", ".", "$", "class", ".", "\" should implement UniMapper\\Entity\\Reflection\\Property\\IOption!\"", ")", ";", "}", "self", "::", "$", "options", "[", "$", "key", "]", "=", "$", "class", ";", "}" ]
Register new property option @param string $key @param string $class @throws Exception\AnnotationException
[ "Register", "new", "property", "option" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Entity/Reflection/Annotation.php#L32-L51
12,968
unimapper/unimapper
src/Entity/Reflection/Annotation.php
Annotation.parseOptions
public static function parseOptions($definition) { preg_match_all('/m:([a-z-]+)(?:\(([^)]*)\))?/i', $definition, $matched, PREG_SET_ORDER); $result = []; foreach ($matched as $match) { if (array_key_exists($match[1], $result)) { throw new Exception\AnnotationException( "Duplicate option '" . $match[1] . "'!" ); } $result[$match[1]] = isset($match[2]) ? trim($match[2]) : null; } return $result; }
php
public static function parseOptions($definition) { preg_match_all('/m:([a-z-]+)(?:\(([^)]*)\))?/i', $definition, $matched, PREG_SET_ORDER); $result = []; foreach ($matched as $match) { if (array_key_exists($match[1], $result)) { throw new Exception\AnnotationException( "Duplicate option '" . $match[1] . "'!" ); } $result[$match[1]] = isset($match[2]) ? trim($match[2]) : null; } return $result; }
[ "public", "static", "function", "parseOptions", "(", "$", "definition", ")", "{", "preg_match_all", "(", "'/m:([a-z-]+)(?:\\(([^)]*)\\))?/i'", ",", "$", "definition", ",", "$", "matched", ",", "PREG_SET_ORDER", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "matched", "as", "$", "match", ")", "{", "if", "(", "array_key_exists", "(", "$", "match", "[", "1", "]", ",", "$", "result", ")", ")", "{", "throw", "new", "Exception", "\\", "AnnotationException", "(", "\"Duplicate option '\"", ".", "$", "match", "[", "1", "]", ".", "\"'!\"", ")", ";", "}", "$", "result", "[", "$", "match", "[", "1", "]", "]", "=", "isset", "(", "$", "match", "[", "2", "]", ")", "?", "trim", "(", "$", "match", "[", "2", "]", ")", ":", "null", ";", "}", "return", "$", "result", ";", "}" ]
Find all property options @param string $definition @return array @throws Exception\AnnotationException
[ "Find", "all", "property", "options" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Entity/Reflection/Annotation.php#L112-L128
12,969
vi-kon/laravel-parser
src/ViKon/Parser/renderer/AbstractRenderer.php
AbstractRenderer.registerTokenRenderer
protected function registerTokenRenderer($tokenName, $callbackName, Renderer $renderer) { $renderer->registerTokenRenderer($tokenName, [$this, $callbackName], $this->set->getName()); }
php
protected function registerTokenRenderer($tokenName, $callbackName, Renderer $renderer) { $renderer->registerTokenRenderer($tokenName, [$this, $callbackName], $this->set->getName()); }
[ "protected", "function", "registerTokenRenderer", "(", "$", "tokenName", ",", "$", "callbackName", ",", "Renderer", "$", "renderer", ")", "{", "$", "renderer", "->", "registerTokenRenderer", "(", "$", "tokenName", ",", "[", "$", "this", ",", "$", "callbackName", "]", ",", "$", "this", "->", "set", "->", "getName", "(", ")", ")", ";", "}" ]
Register token renderer @param string $tokenName token name @param string $callbackName callback function in class @param \ViKon\Parser\Renderer\Renderer $renderer
[ "Register", "token", "renderer" ]
070f0bb9120cb9ca6ff836d4f418e78ee33ee182
https://github.com/vi-kon/laravel-parser/blob/070f0bb9120cb9ca6ff836d4f418e78ee33ee182/src/ViKon/Parser/renderer/AbstractRenderer.php#L50-L52
12,970
sifophp/sifo-common-instance
controllers/manager/findi18n.php
ManagerFindi18nController.getFileSystemFiles
public function getFileSystemFiles( $relative_path, $only_dirs = false ) { $files = array(); // Extract directories: $iterator = new \DirectoryIterator( ROOT_PATH . "/$relative_path" ); foreach ( $iterator as $file_info ) { $file = $file_info->getFilename(); // Exclude .svn, .cache and any other file starting with . if ( 0 !== strpos( $file, '.' ) ) { if ( !$only_dirs || $file_info->isDir() ) { $files[] = $file; } } } return $files; }
php
public function getFileSystemFiles( $relative_path, $only_dirs = false ) { $files = array(); // Extract directories: $iterator = new \DirectoryIterator( ROOT_PATH . "/$relative_path" ); foreach ( $iterator as $file_info ) { $file = $file_info->getFilename(); // Exclude .svn, .cache and any other file starting with . if ( 0 !== strpos( $file, '.' ) ) { if ( !$only_dirs || $file_info->isDir() ) { $files[] = $file; } } } return $files; }
[ "public", "function", "getFileSystemFiles", "(", "$", "relative_path", ",", "$", "only_dirs", "=", "false", ")", "{", "$", "files", "=", "array", "(", ")", ";", "// Extract directories:", "$", "iterator", "=", "new", "\\", "DirectoryIterator", "(", "ROOT_PATH", ".", "\"/$relative_path\"", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "file_info", ")", "{", "$", "file", "=", "$", "file_info", "->", "getFilename", "(", ")", ";", "// Exclude .svn, .cache and any other file starting with .", "if", "(", "0", "!==", "strpos", "(", "$", "file", ",", "'.'", ")", ")", "{", "if", "(", "!", "$", "only_dirs", "||", "$", "file_info", "->", "isDir", "(", ")", ")", "{", "$", "files", "[", "]", "=", "$", "file", ";", "}", "}", "}", "return", "$", "files", ";", "}" ]
Extracts from the filesystem all the files under a path. If the flag only_dirs is set to true returns only the directories names. @param string $relative_path @param bool $only_dirs @return array
[ "Extracts", "from", "the", "filesystem", "all", "the", "files", "under", "a", "path", ".", "If", "the", "flag", "only_dirs", "is", "set", "to", "true", "returns", "only", "the", "directories", "names", "." ]
52d54ea3e565bd2bccd77e0b0a6a99b5cae3aff5
https://github.com/sifophp/sifo-common-instance/blob/52d54ea3e565bd2bccd77e0b0a6a99b5cae3aff5/controllers/manager/findi18n.php#L50-L72
12,971
sifophp/sifo-common-instance
controllers/manager/findi18n.php
ManagerFindi18nController.getLiterals
public function getLiterals( $instance ) { $path = \Sifo\Bootstrap::$application . "/$instance"; // Parse all templates $literals_groups['tpl'] = $this->extractStringsForTranslation( "$path/templates", $instance, true ); // Parse all models: $literals_groups['models'] = $this->extractStringsForTranslation( "$path/models", $instance, false ); // Parse all controllers: $literals_groups['controllers'] = $this->extractStringsForTranslation( "$path/controllers", $instance, false ); // Parse all form configs: $literals_groups['forms'] = $this->extractStringsForTranslation( "$path/config", $instance, false ); // Smarty plugins: $sifo_plugins_path = ROOT_PATH . '/vendor/sifophp/sifo/src/Smarty-sifo-plugins'; $literals_groups['smarty'] = $this->extractStringsForTranslation( $sifo_plugins_path, 'libs', false ); // Your instance plugins: $instance_plugins = $path . '/templates/_smarty/plugins'; if ( is_dir( $instance_plugins ) ) { $literals_groups['smarty'] = array_merge( $literals_groups['smarty'], $this->extractStringsForTranslation( $instance_plugins, $instance, false ) ); } $final_literals = array(); foreach ( $literals_groups as $group ) { foreach ( $group as $literal => $relative_path ) { if ( array_key_exists( $literal, $final_literals ) ) { $final_literals[$literal] = ( $final_literals[$literal] . ", " . $relative_path ); } else { $final_literals[$literal] = $relative_path; } } } return $final_literals; }
php
public function getLiterals( $instance ) { $path = \Sifo\Bootstrap::$application . "/$instance"; // Parse all templates $literals_groups['tpl'] = $this->extractStringsForTranslation( "$path/templates", $instance, true ); // Parse all models: $literals_groups['models'] = $this->extractStringsForTranslation( "$path/models", $instance, false ); // Parse all controllers: $literals_groups['controllers'] = $this->extractStringsForTranslation( "$path/controllers", $instance, false ); // Parse all form configs: $literals_groups['forms'] = $this->extractStringsForTranslation( "$path/config", $instance, false ); // Smarty plugins: $sifo_plugins_path = ROOT_PATH . '/vendor/sifophp/sifo/src/Smarty-sifo-plugins'; $literals_groups['smarty'] = $this->extractStringsForTranslation( $sifo_plugins_path, 'libs', false ); // Your instance plugins: $instance_plugins = $path . '/templates/_smarty/plugins'; if ( is_dir( $instance_plugins ) ) { $literals_groups['smarty'] = array_merge( $literals_groups['smarty'], $this->extractStringsForTranslation( $instance_plugins, $instance, false ) ); } $final_literals = array(); foreach ( $literals_groups as $group ) { foreach ( $group as $literal => $relative_path ) { if ( array_key_exists( $literal, $final_literals ) ) { $final_literals[$literal] = ( $final_literals[$literal] . ", " . $relative_path ); } else { $final_literals[$literal] = $relative_path; } } } return $final_literals; }
[ "public", "function", "getLiterals", "(", "$", "instance", ")", "{", "$", "path", "=", "\\", "Sifo", "\\", "Bootstrap", "::", "$", "application", ".", "\"/$instance\"", ";", "// Parse all templates", "$", "literals_groups", "[", "'tpl'", "]", "=", "$", "this", "->", "extractStringsForTranslation", "(", "\"$path/templates\"", ",", "$", "instance", ",", "true", ")", ";", "// Parse all models:", "$", "literals_groups", "[", "'models'", "]", "=", "$", "this", "->", "extractStringsForTranslation", "(", "\"$path/models\"", ",", "$", "instance", ",", "false", ")", ";", "// Parse all controllers:", "$", "literals_groups", "[", "'controllers'", "]", "=", "$", "this", "->", "extractStringsForTranslation", "(", "\"$path/controllers\"", ",", "$", "instance", ",", "false", ")", ";", "// Parse all form configs:", "$", "literals_groups", "[", "'forms'", "]", "=", "$", "this", "->", "extractStringsForTranslation", "(", "\"$path/config\"", ",", "$", "instance", ",", "false", ")", ";", "// Smarty plugins:", "$", "sifo_plugins_path", "=", "ROOT_PATH", ".", "'/vendor/sifophp/sifo/src/Smarty-sifo-plugins'", ";", "$", "literals_groups", "[", "'smarty'", "]", "=", "$", "this", "->", "extractStringsForTranslation", "(", "$", "sifo_plugins_path", ",", "'libs'", ",", "false", ")", ";", "// Your instance plugins:", "$", "instance_plugins", "=", "$", "path", ".", "'/templates/_smarty/plugins'", ";", "if", "(", "is_dir", "(", "$", "instance_plugins", ")", ")", "{", "$", "literals_groups", "[", "'smarty'", "]", "=", "array_merge", "(", "$", "literals_groups", "[", "'smarty'", "]", ",", "$", "this", "->", "extractStringsForTranslation", "(", "$", "instance_plugins", ",", "$", "instance", ",", "false", ")", ")", ";", "}", "$", "final_literals", "=", "array", "(", ")", ";", "foreach", "(", "$", "literals_groups", "as", "$", "group", ")", "{", "foreach", "(", "$", "group", "as", "$", "literal", "=>", "$", "relative_path", ")", "{", "if", "(", "array_key_exists", "(", "$", "literal", ",", "$", "final_literals", ")", ")", "{", "$", "final_literals", "[", "$", "literal", "]", "=", "(", "$", "final_literals", "[", "$", "literal", "]", ".", "\", \"", ".", "$", "relative_path", ")", ";", "}", "else", "{", "$", "final_literals", "[", "$", "literal", "]", "=", "$", "relative_path", ";", "}", "}", "}", "return", "$", "final_literals", ";", "}" ]
Parses all templates, models, controllers, configs and Smarty plugins searching for strings used inside translation methods and returns them structured in an array. @param string $instance Sifo instance to search in @return array structured array where: array key: The string to be translated (message). array value: The different files which uses this message separated by commas.
[ "Parses", "all", "templates", "models", "controllers", "configs", "and", "Smarty", "plugins", "searching", "for", "strings", "used", "inside", "translation", "methods", "and", "returns", "them", "structured", "in", "an", "array", "." ]
52d54ea3e565bd2bccd77e0b0a6a99b5cae3aff5
https://github.com/sifophp/sifo-common-instance/blob/52d54ea3e565bd2bccd77e0b0a6a99b5cae3aff5/controllers/manager/findi18n.php#L118-L163
12,972
eleven-lab/php-ogc
src/DataTypes/Polygon.php
Polygon.fromString
public static function fromString($linestrings, $linestrings_separator = ";", $points_separator = ",", $coords_separator = " ") { $separators = [$linestrings_separator, $points_separator, $coords_separator]; if(sizeof($separators) != sizeof(array_unique($separators))) throw new GeoSpatialException("Error: separators must be different"); $parsed_linestrings = array_map(function($linestring) use ($points_separator, $coords_separator){ return LineString::fromString($linestring, $points_separator, $coords_separator); }, explode($linestrings_separator, trim($linestrings))); return new static($parsed_linestrings); }
php
public static function fromString($linestrings, $linestrings_separator = ";", $points_separator = ",", $coords_separator = " ") { $separators = [$linestrings_separator, $points_separator, $coords_separator]; if(sizeof($separators) != sizeof(array_unique($separators))) throw new GeoSpatialException("Error: separators must be different"); $parsed_linestrings = array_map(function($linestring) use ($points_separator, $coords_separator){ return LineString::fromString($linestring, $points_separator, $coords_separator); }, explode($linestrings_separator, trim($linestrings))); return new static($parsed_linestrings); }
[ "public", "static", "function", "fromString", "(", "$", "linestrings", ",", "$", "linestrings_separator", "=", "\";\"", ",", "$", "points_separator", "=", "\",\"", ",", "$", "coords_separator", "=", "\" \"", ")", "{", "$", "separators", "=", "[", "$", "linestrings_separator", ",", "$", "points_separator", ",", "$", "coords_separator", "]", ";", "if", "(", "sizeof", "(", "$", "separators", ")", "!=", "sizeof", "(", "array_unique", "(", "$", "separators", ")", ")", ")", "throw", "new", "GeoSpatialException", "(", "\"Error: separators must be different\"", ")", ";", "$", "parsed_linestrings", "=", "array_map", "(", "function", "(", "$", "linestring", ")", "use", "(", "$", "points_separator", ",", "$", "coords_separator", ")", "{", "return", "LineString", "::", "fromString", "(", "$", "linestring", ",", "$", "points_separator", ",", "$", "coords_separator", ")", ";", "}", ",", "explode", "(", "$", "linestrings_separator", ",", "trim", "(", "$", "linestrings", ")", ")", ")", ";", "return", "new", "static", "(", "$", "parsed_linestrings", ")", ";", "}" ]
A Polygon could be instantiated using a string containing linestrings. es. "lat lon, lat lon; lat lon, lat lon; lat lon, lat lon" @param $linestrings @param $linestrings_separator @param $points_separator @param $coords_separator @return Polygon @throws GeoSpatialException
[ "A", "Polygon", "could", "be", "instantiated", "using", "a", "string", "containing", "linestrings", ".", "es", ".", "lat", "lon", "lat", "lon", ";", "lat", "lon", "lat", "lon", ";", "lat", "lon", "lat", "lon" ]
ba15cea3ba71a65f14f3cadcb08bfce34f4489ce
https://github.com/eleven-lab/php-ogc/blob/ba15cea3ba71a65f14f3cadcb08bfce34f4489ce/src/DataTypes/Polygon.php#L56-L67
12,973
venta/framework
src/Adr/src/AbstractResponder.php
AbstractResponder.html
protected function html(string $html, int $status = 200, array $headers = []): ResponseInterface { return $this->responseFactory->createHtmlResponse($html, $status, $headers); }
php
protected function html(string $html, int $status = 200, array $headers = []): ResponseInterface { return $this->responseFactory->createHtmlResponse($html, $status, $headers); }
[ "protected", "function", "html", "(", "string", "$", "html", ",", "int", "$", "status", "=", "200", ",", "array", "$", "headers", "=", "[", "]", ")", ":", "ResponseInterface", "{", "return", "$", "this", "->", "responseFactory", "->", "createHtmlResponse", "(", "$", "html", ",", "$", "status", ",", "$", "headers", ")", ";", "}" ]
Creates html response. @param string $html @param int $status @param array $headers @return ResponseInterface
[ "Creates", "html", "response", "." ]
514a7854cc69f84f47e62a58cc55efd68b7c9f83
https://github.com/venta/framework/blob/514a7854cc69f84f47e62a58cc55efd68b7c9f83/src/Adr/src/AbstractResponder.php#L45-L48
12,974
venta/framework
src/Adr/src/AbstractResponder.php
AbstractResponder.response
protected function response($bodyStream = 'php://memory', int $status = 200, array $headers = []): ResponseInterface { return $this->responseFactory->createResponse($bodyStream, $status, $headers); }
php
protected function response($bodyStream = 'php://memory', int $status = 200, array $headers = []): ResponseInterface { return $this->responseFactory->createResponse($bodyStream, $status, $headers); }
[ "protected", "function", "response", "(", "$", "bodyStream", "=", "'php://memory'", ",", "int", "$", "status", "=", "200", ",", "array", "$", "headers", "=", "[", "]", ")", ":", "ResponseInterface", "{", "return", "$", "this", "->", "responseFactory", "->", "createResponse", "(", "$", "bodyStream", ",", "$", "status", ",", "$", "headers", ")", ";", "}" ]
Creates HTTP response. @param string $bodyStream Stream to use as response body. @param int $status @param array $headers @return ResponseInterface
[ "Creates", "HTTP", "response", "." ]
514a7854cc69f84f47e62a58cc55efd68b7c9f83
https://github.com/venta/framework/blob/514a7854cc69f84f47e62a58cc55efd68b7c9f83/src/Adr/src/AbstractResponder.php#L89-L92
12,975
DevGroup-ru/yii2-data-structure-tools
src/migrations/m150923_140300_properties.php
m150923_140300_properties.down
public function down() { $this->db->createCommand("SET foreign_key_checks = 0")->execute(); $this->dropTable('{{%property_property_group}}'); $this->dropTable('{{%property_translation}}'); $this->dropTable('{{%property}}'); $this->dropTable('{{%property_group_translation}}'); $this->dropTable('{{%property_group}}'); $this->dropTable('{{%property_storage}}'); $this->dropTable('{{%static_value_translation}}'); $this->dropTable('{{%static_value}}'); $this->dropTable(ApplicablePropertyModels::tableName()); $this->dropTable('{{%property_handlers}}'); $this->db->createCommand("SET foreign_key_checks = 1")->execute(); }
php
public function down() { $this->db->createCommand("SET foreign_key_checks = 0")->execute(); $this->dropTable('{{%property_property_group}}'); $this->dropTable('{{%property_translation}}'); $this->dropTable('{{%property}}'); $this->dropTable('{{%property_group_translation}}'); $this->dropTable('{{%property_group}}'); $this->dropTable('{{%property_storage}}'); $this->dropTable('{{%static_value_translation}}'); $this->dropTable('{{%static_value}}'); $this->dropTable(ApplicablePropertyModels::tableName()); $this->dropTable('{{%property_handlers}}'); $this->db->createCommand("SET foreign_key_checks = 1")->execute(); }
[ "public", "function", "down", "(", ")", "{", "$", "this", "->", "db", "->", "createCommand", "(", "\"SET foreign_key_checks = 0\"", ")", "->", "execute", "(", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_property_group}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_translation}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_group_translation}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_group}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_storage}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%static_value_translation}}'", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%static_value}}'", ")", ";", "$", "this", "->", "dropTable", "(", "ApplicablePropertyModels", "::", "tableName", "(", ")", ")", ";", "$", "this", "->", "dropTable", "(", "'{{%property_handlers}}'", ")", ";", "$", "this", "->", "db", "->", "createCommand", "(", "\"SET foreign_key_checks = 1\"", ")", "->", "execute", "(", ")", ";", "}" ]
Removes all properties related tables
[ "Removes", "all", "properties", "related", "tables" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/migrations/m150923_140300_properties.php#L177-L195
12,976
serverdensity/sd-php-wrapper
lib/serverdensity/Api/Alerts.php
Alerts.create
public function create($alert, $recipients, $wait, $repeat){ $alert['recipients'] = json_encode($recipients); $alert['wait'] = json_encode($wait); $alert['repeat'] = json_encode($repeat); return $this->post('alerts/configs/', $alert); }
php
public function create($alert, $recipients, $wait, $repeat){ $alert['recipients'] = json_encode($recipients); $alert['wait'] = json_encode($wait); $alert['repeat'] = json_encode($repeat); return $this->post('alerts/configs/', $alert); }
[ "public", "function", "create", "(", "$", "alert", ",", "$", "recipients", ",", "$", "wait", ",", "$", "repeat", ")", "{", "$", "alert", "[", "'recipients'", "]", "=", "json_encode", "(", "$", "recipients", ")", ";", "$", "alert", "[", "'wait'", "]", "=", "json_encode", "(", "$", "wait", ")", ";", "$", "alert", "[", "'repeat'", "]", "=", "json_encode", "(", "$", "repeat", ")", ";", "return", "$", "this", "->", "post", "(", "'alerts/configs/'", ",", "$", "alert", ")", ";", "}" ]
Create an alert @link https://developer.serverdensity.com/docs/creating-an-alert @param array $alert with the basic attributes @param array $recipients with all its recipients @param array $wait with seconds, enabled and displayunit @param array $repeat with seconds, enabled and displayunit @return an array that is the alert
[ "Create", "an", "alert" ]
9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e
https://github.com/serverdensity/sd-php-wrapper/blob/9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e/lib/serverdensity/Api/Alerts.php#L16-L22
12,977
serverdensity/sd-php-wrapper
lib/serverdensity/Api/Alerts.php
Alerts.bySubject
public function bySubject($subjectId, $subjectType){ $type = array('subjectType' => $subjectType); return $this->get('alerts/configs/'.rawurlencode($subjectId), $type); }
php
public function bySubject($subjectId, $subjectType){ $type = array('subjectType' => $subjectType); return $this->get('alerts/configs/'.rawurlencode($subjectId), $type); }
[ "public", "function", "bySubject", "(", "$", "subjectId", ",", "$", "subjectType", ")", "{", "$", "type", "=", "array", "(", "'subjectType'", "=>", "$", "subjectType", ")", ";", "return", "$", "this", "->", "get", "(", "'alerts/configs/'", ".", "rawurlencode", "(", "$", "subjectId", ")", ",", "$", "type", ")", ";", "}" ]
Get all alerts by subjectId @link https://developer.serverdensity.com/docs/listing-alerts-by-subject @param string $subjectId Id of the subject tied to alert @param string $subjectType either device or service @return an array of arrays with devices.
[ "Get", "all", "alerts", "by", "subjectId" ]
9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e
https://github.com/serverdensity/sd-php-wrapper/blob/9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e/lib/serverdensity/Api/Alerts.php#L74-L78
12,978
serverdensity/sd-php-wrapper
lib/serverdensity/Api/Alerts.php
Alerts.triggered
public function triggered($closed='', $subjectType='', $subjectId=''){ $fields = array(); if(!empty($closed)){ $fields['closed'] = $closed; } if (!empty($subjectType)) { $fields['subjectType'] = $subjectType; } return $this->get('alerts/triggered/'.rawurlencode($subjectId), $fields); }
php
public function triggered($closed='', $subjectType='', $subjectId=''){ $fields = array(); if(!empty($closed)){ $fields['closed'] = $closed; } if (!empty($subjectType)) { $fields['subjectType'] = $subjectType; } return $this->get('alerts/triggered/'.rawurlencode($subjectId), $fields); }
[ "public", "function", "triggered", "(", "$", "closed", "=", "''", ",", "$", "subjectType", "=", "''", ",", "$", "subjectId", "=", "''", ")", "{", "$", "fields", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "closed", ")", ")", "{", "$", "fields", "[", "'closed'", "]", "=", "$", "closed", ";", "}", "if", "(", "!", "empty", "(", "$", "subjectType", ")", ")", "{", "$", "fields", "[", "'subjectType'", "]", "=", "$", "subjectType", ";", "}", "return", "$", "this", "->", "get", "(", "'alerts/triggered/'", ".", "rawurlencode", "(", "$", "subjectId", ")", ",", "$", "fields", ")", ";", "}" ]
Get triggered alerts @link https://developer.serverdensity.com/docs/triggered-alerts @param bool $closed whether alert is closed or open @param string $subjectType the subjecttype to filter on @param string $subjectId optional subjectID to filter on. @return an array of arrays with devices.
[ "Get", "triggered", "alerts" ]
9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e
https://github.com/serverdensity/sd-php-wrapper/blob/9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e/lib/serverdensity/Api/Alerts.php#L99-L109
12,979
fuelphp/filesystem
src/File.php
File.append
public function append($data) { $bites = file_put_contents($this->path, $data, FILE_APPEND | LOCK_EX); return $bites !== false; }
php
public function append($data) { $bites = file_put_contents($this->path, $data, FILE_APPEND | LOCK_EX); return $bites !== false; }
[ "public", "function", "append", "(", "$", "data", ")", "{", "$", "bites", "=", "file_put_contents", "(", "$", "this", "->", "path", ",", "$", "data", ",", "FILE_APPEND", "|", "LOCK_EX", ")", ";", "return", "$", "bites", "!==", "false", ";", "}" ]
Appends data to a file @param string $data @return boolean
[ "Appends", "data", "to", "a", "file" ]
770a8cb04caca920af8029d7aad7208bc0592743
https://github.com/fuelphp/filesystem/blob/770a8cb04caca920af8029d7aad7208bc0592743/src/File.php#L32-L37
12,980
fuelphp/filesystem
src/File.php
File.getMimeType
public function getMimeType() { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $this->path); finfo_close($finfo); return $mime; }
php
public function getMimeType() { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $this->path); finfo_close($finfo); return $mime; }
[ "public", "function", "getMimeType", "(", ")", "{", "$", "finfo", "=", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "mime", "=", "finfo_file", "(", "$", "finfo", ",", "$", "this", "->", "path", ")", ";", "finfo_close", "(", "$", "finfo", ")", ";", "return", "$", "mime", ";", "}" ]
Returns the mime-type @return string
[ "Returns", "the", "mime", "-", "type" ]
770a8cb04caca920af8029d7aad7208bc0592743
https://github.com/fuelphp/filesystem/blob/770a8cb04caca920af8029d7aad7208bc0592743/src/File.php#L82-L89
12,981
crysalead/net
src/Http/Cookie/Jar.php
Jar.toJar
public static function toJar($cookies) { $result = []; foreach ($cookies as $name => $cookie) { if (!$cookie->expired()) { $result[] = static::_line($name, $cookie); } } return $result ? join("\n", $result) . "\n" : ''; }
php
public static function toJar($cookies) { $result = []; foreach ($cookies as $name => $cookie) { if (!$cookie->expired()) { $result[] = static::_line($name, $cookie); } } return $result ? join("\n", $result) . "\n" : ''; }
[ "public", "static", "function", "toJar", "(", "$", "cookies", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "cookies", "as", "$", "name", "=>", "$", "cookie", ")", "{", "if", "(", "!", "$", "cookie", "->", "expired", "(", ")", ")", "{", "$", "result", "[", "]", "=", "static", "::", "_line", "(", "$", "name", ",", "$", "cookie", ")", ";", "}", "}", "return", "$", "result", "?", "join", "(", "\"\\n\"", ",", "$", "result", ")", ".", "\"\\n\"", ":", "''", ";", "}" ]
Exports the cookies into a JAR string. @param object $cookies A `SetCookies` collection. @return string
[ "Exports", "the", "cookies", "into", "a", "JAR", "string", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cookie/Jar.php#L17-L26
12,982
crysalead/net
src/Http/Cookie/Jar.php
Jar._line
protected static function _line($name, $cookie) { if (!$cookie->isValid()) { throw new RuntimeException("Invalid cookie `'{$name}'`."); } $domain = $cookie->domain(); $parts = [ $cookie->httponly() ? '#HttpOnly_' . $domain : $domain, $domain === '.' ? 'TRUE' : 'FALSE', $cookie->path() ?: '/', $cookie->secure() ? 'TRUE' : 'FALSE', (string) $cookie->expires(), $cookie->name(), $cookie->value() ]; return join("\t", $parts); }
php
protected static function _line($name, $cookie) { if (!$cookie->isValid()) { throw new RuntimeException("Invalid cookie `'{$name}'`."); } $domain = $cookie->domain(); $parts = [ $cookie->httponly() ? '#HttpOnly_' . $domain : $domain, $domain === '.' ? 'TRUE' : 'FALSE', $cookie->path() ?: '/', $cookie->secure() ? 'TRUE' : 'FALSE', (string) $cookie->expires(), $cookie->name(), $cookie->value() ]; return join("\t", $parts); }
[ "protected", "static", "function", "_line", "(", "$", "name", ",", "$", "cookie", ")", "{", "if", "(", "!", "$", "cookie", "->", "isValid", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Invalid cookie `'{$name}'`.\"", ")", ";", "}", "$", "domain", "=", "$", "cookie", "->", "domain", "(", ")", ";", "$", "parts", "=", "[", "$", "cookie", "->", "httponly", "(", ")", "?", "'#HttpOnly_'", ".", "$", "domain", ":", "$", "domain", ",", "$", "domain", "===", "'.'", "?", "'TRUE'", ":", "'FALSE'", ",", "$", "cookie", "->", "path", "(", ")", "?", ":", "'/'", ",", "$", "cookie", "->", "secure", "(", ")", "?", "'TRUE'", ":", "'FALSE'", ",", "(", "string", ")", "$", "cookie", "->", "expires", "(", ")", ",", "$", "cookie", "->", "name", "(", ")", ",", "$", "cookie", "->", "value", "(", ")", "]", ";", "return", "join", "(", "\"\\t\"", ",", "$", "parts", ")", ";", "}" ]
Creates a cookie JAR line from a name and a SetCookie value. @param string The cookie name. @param string The cookie instance value. @return string
[ "Creates", "a", "cookie", "JAR", "line", "from", "a", "name", "and", "a", "SetCookie", "value", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cookie/Jar.php#L35-L52
12,983
crysalead/net
src/Http/Cookie/Jar.php
Jar.parse
public static function parse($line) { $parts = explode("\t", trim($line)); if (count($parts) !== 7) { throw new RuntimeException("Invalid cookie JAR format."); } $config = []; $config['httponly'] = '#HttpOnly_' === substr($parts[0], 0, 10); $config['domain'] = $config['httponly'] ? substr($parts[0], 10) : $parts[0]; $config['path'] = $parts[2]; $config['secure'] = ($parts[3] === 'TRUE') ? true : false; $config['expires'] = (integer) $parts[4]; $config['name'] = $parts[5]; $config['value'] = $parts[6]; return $config; }
php
public static function parse($line) { $parts = explode("\t", trim($line)); if (count($parts) !== 7) { throw new RuntimeException("Invalid cookie JAR format."); } $config = []; $config['httponly'] = '#HttpOnly_' === substr($parts[0], 0, 10); $config['domain'] = $config['httponly'] ? substr($parts[0], 10) : $parts[0]; $config['path'] = $parts[2]; $config['secure'] = ($parts[3] === 'TRUE') ? true : false; $config['expires'] = (integer) $parts[4]; $config['name'] = $parts[5]; $config['value'] = $parts[6]; return $config; }
[ "public", "static", "function", "parse", "(", "$", "line", ")", "{", "$", "parts", "=", "explode", "(", "\"\\t\"", ",", "trim", "(", "$", "line", ")", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "!==", "7", ")", "{", "throw", "new", "RuntimeException", "(", "\"Invalid cookie JAR format.\"", ")", ";", "}", "$", "config", "=", "[", "]", ";", "$", "config", "[", "'httponly'", "]", "=", "'#HttpOnly_'", "===", "substr", "(", "$", "parts", "[", "0", "]", ",", "0", ",", "10", ")", ";", "$", "config", "[", "'domain'", "]", "=", "$", "config", "[", "'httponly'", "]", "?", "substr", "(", "$", "parts", "[", "0", "]", ",", "10", ")", ":", "$", "parts", "[", "0", "]", ";", "$", "config", "[", "'path'", "]", "=", "$", "parts", "[", "2", "]", ";", "$", "config", "[", "'secure'", "]", "=", "(", "$", "parts", "[", "3", "]", "===", "'TRUE'", ")", "?", "true", ":", "false", ";", "$", "config", "[", "'expires'", "]", "=", "(", "integer", ")", "$", "parts", "[", "4", "]", ";", "$", "config", "[", "'name'", "]", "=", "$", "parts", "[", "5", "]", ";", "$", "config", "[", "'value'", "]", "=", "$", "parts", "[", "6", "]", ";", "return", "$", "config", ";", "}" ]
Parses a cookie JAR line. @param string $line The cookie JAR line. @return array The data array. @throws Exception It throws an exception the cookie JAR line is invalid.
[ "Parses", "a", "cookie", "JAR", "line", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cookie/Jar.php#L61-L79
12,984
iP1SMS/ip1-php-sdk
src/SMS/OutGoingSMS.php
OutGoingSMS.removeNumber
public function removeNumber(int $index): void { unset($this->numbers[$index]); $this->numbers = array_values($this->numbers); }
php
public function removeNumber(int $index): void { unset($this->numbers[$index]); $this->numbers = array_values($this->numbers); }
[ "public", "function", "removeNumber", "(", "int", "$", "index", ")", ":", "void", "{", "unset", "(", "$", "this", "->", "numbers", "[", "$", "index", "]", ")", ";", "$", "this", "->", "numbers", "=", "array_values", "(", "$", "this", "->", "numbers", ")", ";", "}" ]
Removes the given index from the number recipient list. @param integer $index The index being requested for deletion. @return void
[ "Removes", "the", "given", "index", "from", "the", "number", "recipient", "list", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/OutGoingSMS.php#L68-L72
12,985
iP1SMS/ip1-php-sdk
src/SMS/OutGoingSMS.php
OutGoingSMS.getNumber
public function getNumber(int $index): string { if ($index >= count($this->numbers)) { throw new \UndefinedOffsetException(); } return $this->numbers[$index]; }
php
public function getNumber(int $index): string { if ($index >= count($this->numbers)) { throw new \UndefinedOffsetException(); } return $this->numbers[$index]; }
[ "public", "function", "getNumber", "(", "int", "$", "index", ")", ":", "string", "{", "if", "(", "$", "index", ">=", "count", "(", "$", "this", "->", "numbers", ")", ")", "{", "throw", "new", "\\", "UndefinedOffsetException", "(", ")", ";", "}", "return", "$", "this", "->", "numbers", "[", "$", "index", "]", ";", "}" ]
Returns the number in the given index. @param integer $index The index being requested. @return string Phone number. @throws \UndefinedOffsetException Thrown when the index requested does not exist.
[ "Returns", "the", "number", "in", "the", "given", "index", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/OutGoingSMS.php#L79-L85
12,986
iP1SMS/ip1-php-sdk
src/SMS/OutGoingSMS.php
OutGoingSMS.removeContact
public function removeContact(int $index): void { unset($this->contacts[$index]); $this->contacts = array_values($this->contacts); }
php
public function removeContact(int $index): void { unset($this->contacts[$index]); $this->contacts = array_values($this->contacts); }
[ "public", "function", "removeContact", "(", "int", "$", "index", ")", ":", "void", "{", "unset", "(", "$", "this", "->", "contacts", "[", "$", "index", "]", ")", ";", "$", "this", "->", "contacts", "=", "array_values", "(", "$", "this", "->", "contacts", ")", ";", "}" ]
Removes the Contact in the given index and reindexes the array. @param integer $index The index being requested for deletion. @return void
[ "Removes", "the", "Contact", "in", "the", "given", "index", "and", "reindexes", "the", "array", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/OutGoingSMS.php#L108-L112
12,987
iP1SMS/ip1-php-sdk
src/SMS/OutGoingSMS.php
OutGoingSMS.removeGroup
public function removeGroup(int $index): void { unset($this->groups[$index]); $this->groups = array_values($this->groups); }
php
public function removeGroup(int $index): void { unset($this->groups[$index]); $this->groups = array_values($this->groups); }
[ "public", "function", "removeGroup", "(", "int", "$", "index", ")", ":", "void", "{", "unset", "(", "$", "this", "->", "groups", "[", "$", "index", "]", ")", ";", "$", "this", "->", "groups", "=", "array_values", "(", "$", "this", "->", "groups", ")", ";", "}" ]
Removes the Group in the given index and reindexes the array. @param integer $index The index being requested for deletion. @return void
[ "Removes", "the", "Group", "in", "the", "given", "index", "and", "reindexes", "the", "array", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/OutGoingSMS.php#L145-L149
12,988
iP1SMS/ip1-php-sdk
src/SMS/OutGoingSMS.php
OutGoingSMS.getGroup
public function getGroup(int $index): Group { if ($index >= count($this->groups)) { throw new \UndefinedOffsetException(); } return $this->groups[$index]; }
php
public function getGroup(int $index): Group { if ($index >= count($this->groups)) { throw new \UndefinedOffsetException(); } return $this->groups[$index]; }
[ "public", "function", "getGroup", "(", "int", "$", "index", ")", ":", "Group", "{", "if", "(", "$", "index", ">=", "count", "(", "$", "this", "->", "groups", ")", ")", "{", "throw", "new", "\\", "UndefinedOffsetException", "(", ")", ";", "}", "return", "$", "this", "->", "groups", "[", "$", "index", "]", ";", "}" ]
Returns the group in the given index. @param integer $index The index being requested. @return Group @throws \UndefinedOffsetException Thrown when the index requested does not exist.
[ "Returns", "the", "group", "in", "the", "given", "index", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/OutGoingSMS.php#L156-L162
12,989
yiidoc/yii2-selectize
Selectize.php
Selectize.registerEvents
public function registerEvents() { if (!empty($this->clientEvents)) { $js = []; foreach ($this->clientEvents as $event => $handle) { $js[] = "jQuery('#{$this->options['id']}').on('{$event}',{$handle});"; } $this->getView()->registerJs(implode(PHP_EOL, $js)); } }
php
public function registerEvents() { if (!empty($this->clientEvents)) { $js = []; foreach ($this->clientEvents as $event => $handle) { $js[] = "jQuery('#{$this->options['id']}').on('{$event}',{$handle});"; } $this->getView()->registerJs(implode(PHP_EOL, $js)); } }
[ "public", "function", "registerEvents", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "clientEvents", ")", ")", "{", "$", "js", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "clientEvents", "as", "$", "event", "=>", "$", "handle", ")", "{", "$", "js", "[", "]", "=", "\"jQuery('#{$this->options['id']}').on('{$event}',{$handle});\"", ";", "}", "$", "this", "->", "getView", "(", ")", "->", "registerJs", "(", "implode", "(", "PHP_EOL", ",", "$", "js", ")", ")", ";", "}", "}" ]
Register client script handles
[ "Register", "client", "script", "handles" ]
4bb53e73c7b9324e687c0a5f7ef391ec7b29da44
https://github.com/yiidoc/yii2-selectize/blob/4bb53e73c7b9324e687c0a5f7ef391ec7b29da44/Selectize.php#L91-L100
12,990
crysalead/net
src/Header.php
Header.value
public function value() { if (strtolower($this->name()) === 'set-cookie') { return join("\r\n" . $this->name() . ': ', $this->data()); } else { return join(', ', $this->_data); } }
php
public function value() { if (strtolower($this->name()) === 'set-cookie') { return join("\r\n" . $this->name() . ': ', $this->data()); } else { return join(', ', $this->_data); } }
[ "public", "function", "value", "(", ")", "{", "if", "(", "strtolower", "(", "$", "this", "->", "name", "(", ")", ")", "===", "'set-cookie'", ")", "{", "return", "join", "(", "\"\\r\\n\"", ".", "$", "this", "->", "name", "(", ")", ".", "': '", ",", "$", "this", "->", "data", "(", ")", ")", ";", "}", "else", "{", "return", "join", "(", "', '", ",", "$", "this", "->", "_data", ")", ";", "}", "}" ]
Gets the header's value. @return array Returns the headers.
[ "Gets", "the", "header", "s", "value", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Header.php#L106-L113
12,991
crysalead/net
src/Header.php
Header.parse
public static function parse($value) { $values = explode(':', $value, 2); if (count($values) !== 2) { return; } return new static($values[0], trim($values[1])); }
php
public static function parse($value) { $values = explode(':', $value, 2); if (count($values) !== 2) { return; } return new static($values[0], trim($values[1])); }
[ "public", "static", "function", "parse", "(", "$", "value", ")", "{", "$", "values", "=", "explode", "(", "':'", ",", "$", "value", ",", "2", ")", ";", "if", "(", "count", "(", "$", "values", ")", "!==", "2", ")", "{", "return", ";", "}", "return", "new", "static", "(", "$", "values", "[", "0", "]", ",", "trim", "(", "$", "values", "[", "1", "]", ")", ")", ";", "}" ]
Parses a header string value. @param string $header A header string value. @return object A header collection.
[ "Parses", "a", "header", "string", "value", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Header.php#L141-L149
12,992
crysalead/net
src/Header.php
Header.wrap
public static function wrap($header, $width = 0) { if ($width <= 0) { return $header; } $result = []; $lineLength = 0; $parts = preg_split('~\s+~', $header); while ($current = current($parts)) { $next = next($parts); $lineLength += strlen($current); if ($next && ($lineLength + strlen($next)) > ($width - 1)) { $result[] = $current . Headers::EOL; $lineLength = 0; } else { $result[] = $current; } } return join(' ', $result); }
php
public static function wrap($header, $width = 0) { if ($width <= 0) { return $header; } $result = []; $lineLength = 0; $parts = preg_split('~\s+~', $header); while ($current = current($parts)) { $next = next($parts); $lineLength += strlen($current); if ($next && ($lineLength + strlen($next)) > ($width - 1)) { $result[] = $current . Headers::EOL; $lineLength = 0; } else { $result[] = $current; } } return join(' ', $result); }
[ "public", "static", "function", "wrap", "(", "$", "header", ",", "$", "width", "=", "0", ")", "{", "if", "(", "$", "width", "<=", "0", ")", "{", "return", "$", "header", ";", "}", "$", "result", "=", "[", "]", ";", "$", "lineLength", "=", "0", ";", "$", "parts", "=", "preg_split", "(", "'~\\s+~'", ",", "$", "header", ")", ";", "while", "(", "$", "current", "=", "current", "(", "$", "parts", ")", ")", "{", "$", "next", "=", "next", "(", "$", "parts", ")", ";", "$", "lineLength", "+=", "strlen", "(", "$", "current", ")", ";", "if", "(", "$", "next", "&&", "(", "$", "lineLength", "+", "strlen", "(", "$", "next", ")", ")", ">", "(", "$", "width", "-", "1", ")", ")", "{", "$", "result", "[", "]", "=", "$", "current", ".", "Headers", "::", "EOL", ";", "$", "lineLength", "=", "0", ";", "}", "else", "{", "$", "result", "[", "]", "=", "$", "current", ";", "}", "}", "return", "join", "(", "' '", ",", "$", "result", ")", ";", "}" ]
Fold a header entry @param string $header The header to fold.
[ "Fold", "a", "header", "entry" ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Header.php#L182-L203
12,993
iP1SMS/ip1-php-sdk
src/SMS/ProcessedOutGoingSMS.php
ProcessedOutGoingSMS.getUpdated
public function getUpdated(\DateTimeZone $timezone = null): ?\DateTime { if (!is_null($timezone)) { $returnDate = clone $this->updated; $returnDate->setTimeZone($timezone); return $returnDate; } return $this->updated ?? null; }
php
public function getUpdated(\DateTimeZone $timezone = null): ?\DateTime { if (!is_null($timezone)) { $returnDate = clone $this->updated; $returnDate->setTimeZone($timezone); return $returnDate; } return $this->updated ?? null; }
[ "public", "function", "getUpdated", "(", "\\", "DateTimeZone", "$", "timezone", "=", "null", ")", ":", "?", "\\", "DateTime", "{", "if", "(", "!", "is_null", "(", "$", "timezone", ")", ")", "{", "$", "returnDate", "=", "clone", "$", "this", "->", "updated", ";", "$", "returnDate", "->", "setTimeZone", "(", "$", "timezone", ")", ";", "return", "$", "returnDate", ";", "}", "return", "$", "this", "->", "updated", "??", "null", ";", "}" ]
Returns when the component was updated last. @param \DateTimeZone $timezone The timezone that the user wants to get the DateTime in. Default is UTC. @return \DateTime When the contact was updated/modified last.
[ "Returns", "when", "the", "component", "was", "updated", "last", "." ]
348e6572a279363ba689c9e0f5689b83a25930f5
https://github.com/iP1SMS/ip1-php-sdk/blob/348e6572a279363ba689c9e0f5689b83a25930f5/src/SMS/ProcessedOutGoingSMS.php#L128-L136
12,994
venta/framework
src/Http/src/CookieJar.php
CookieJar.expirationToDateTime
private function expirationToDateTime($expires): DateTimeInterface { if ($expires instanceof DateTimeImmutable) { return $expires; } if ($expires instanceof DateInterval) { $expires = (new DateTime)->add($expires); } elseif (is_string($expires) || is_int($expires)) { $expires = new DateTime(is_numeric($expires) ? '@' . $expires : $expires); } if (!$expires instanceof DateTimeInterface) { throw new InvalidArgumentException( 'Invalid cookie expiration time. Cannot be converted to DateTimeInterface.' ); } return new DateTimeImmutable($expires->format(DateTime::ISO8601), $expires->getTimezone()); }
php
private function expirationToDateTime($expires): DateTimeInterface { if ($expires instanceof DateTimeImmutable) { return $expires; } if ($expires instanceof DateInterval) { $expires = (new DateTime)->add($expires); } elseif (is_string($expires) || is_int($expires)) { $expires = new DateTime(is_numeric($expires) ? '@' . $expires : $expires); } if (!$expires instanceof DateTimeInterface) { throw new InvalidArgumentException( 'Invalid cookie expiration time. Cannot be converted to DateTimeInterface.' ); } return new DateTimeImmutable($expires->format(DateTime::ISO8601), $expires->getTimezone()); }
[ "private", "function", "expirationToDateTime", "(", "$", "expires", ")", ":", "DateTimeInterface", "{", "if", "(", "$", "expires", "instanceof", "DateTimeImmutable", ")", "{", "return", "$", "expires", ";", "}", "if", "(", "$", "expires", "instanceof", "DateInterval", ")", "{", "$", "expires", "=", "(", "new", "DateTime", ")", "->", "add", "(", "$", "expires", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "expires", ")", "||", "is_int", "(", "$", "expires", ")", ")", "{", "$", "expires", "=", "new", "DateTime", "(", "is_numeric", "(", "$", "expires", ")", "?", "'@'", ".", "$", "expires", ":", "$", "expires", ")", ";", "}", "if", "(", "!", "$", "expires", "instanceof", "DateTimeInterface", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid cookie expiration time. Cannot be converted to DateTimeInterface.'", ")", ";", "}", "return", "new", "DateTimeImmutable", "(", "$", "expires", "->", "format", "(", "DateTime", "::", "ISO8601", ")", ",", "$", "expires", "->", "getTimezone", "(", ")", ")", ";", "}" ]
Parses expiration time and returns valid DateTimeInterface implementation. @param DateTimeInterface|DateInterval|string $expires @return DateTimeInterface @throws InvalidArgumentException
[ "Parses", "expiration", "time", "and", "returns", "valid", "DateTimeInterface", "implementation", "." ]
514a7854cc69f84f47e62a58cc55efd68b7c9f83
https://github.com/venta/framework/blob/514a7854cc69f84f47e62a58cc55efd68b7c9f83/src/Http/src/CookieJar.php#L119-L138
12,995
AymDev/Phunder
src/Config.php
Config.loadParameters
public static function loadParameters() : void { // APPLICATION PARAMETERS // Application root directory defined('PHUNDER_ROOT_DIR') or define('PHUNDER_ROOT_DIR', __DIR__ . '/../'); // template directory path (from root dir) defined('PHUNDER_TEMPLATE_DIRECTORY') or define('PHUNDER_TEMPLATE_DIRECTORY', 'templates'); // SESSION PARAMETERS // session name defined('PHUNDER_SESSION_NAME') or define('PHUNDER_SESSION_NAME', 'PHUNDERSESSIONID'); // session name defined('PHUNDER_SESSION_HTTPS') or define('PHUNDER_SESSION_HTTPS', false); // session regeneration mode defined('PHUNDER_SESSION_REGENERATE_MODE') or define('PHUNDER_SESSION_REGENERATE_MODE', '1'); // session requests amount before regeneration defined('PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT') or define('PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT', '10'); // session time before regeneration (in seconds) defined('PHUNDER_SESSION_REGENERATE_TIME') or define('PHUNDER_SESSION_REGENERATE_TIME', '600'); }
php
public static function loadParameters() : void { // APPLICATION PARAMETERS // Application root directory defined('PHUNDER_ROOT_DIR') or define('PHUNDER_ROOT_DIR', __DIR__ . '/../'); // template directory path (from root dir) defined('PHUNDER_TEMPLATE_DIRECTORY') or define('PHUNDER_TEMPLATE_DIRECTORY', 'templates'); // SESSION PARAMETERS // session name defined('PHUNDER_SESSION_NAME') or define('PHUNDER_SESSION_NAME', 'PHUNDERSESSIONID'); // session name defined('PHUNDER_SESSION_HTTPS') or define('PHUNDER_SESSION_HTTPS', false); // session regeneration mode defined('PHUNDER_SESSION_REGENERATE_MODE') or define('PHUNDER_SESSION_REGENERATE_MODE', '1'); // session requests amount before regeneration defined('PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT') or define('PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT', '10'); // session time before regeneration (in seconds) defined('PHUNDER_SESSION_REGENERATE_TIME') or define('PHUNDER_SESSION_REGENERATE_TIME', '600'); }
[ "public", "static", "function", "loadParameters", "(", ")", ":", "void", "{", "// APPLICATION PARAMETERS", "// Application root directory", "defined", "(", "'PHUNDER_ROOT_DIR'", ")", "or", "define", "(", "'PHUNDER_ROOT_DIR'", ",", "__DIR__", ".", "'/../'", ")", ";", "// template directory path (from root dir)", "defined", "(", "'PHUNDER_TEMPLATE_DIRECTORY'", ")", "or", "define", "(", "'PHUNDER_TEMPLATE_DIRECTORY'", ",", "'templates'", ")", ";", "// SESSION PARAMETERS", "// session name", "defined", "(", "'PHUNDER_SESSION_NAME'", ")", "or", "define", "(", "'PHUNDER_SESSION_NAME'", ",", "'PHUNDERSESSIONID'", ")", ";", "// session name", "defined", "(", "'PHUNDER_SESSION_HTTPS'", ")", "or", "define", "(", "'PHUNDER_SESSION_HTTPS'", ",", "false", ")", ";", "// session regeneration mode", "defined", "(", "'PHUNDER_SESSION_REGENERATE_MODE'", ")", "or", "define", "(", "'PHUNDER_SESSION_REGENERATE_MODE'", ",", "'1'", ")", ";", "// session requests amount before regeneration", "defined", "(", "'PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT'", ")", "or", "define", "(", "'PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT'", ",", "'10'", ")", ";", "// session time before regeneration (in seconds)", "defined", "(", "'PHUNDER_SESSION_REGENERATE_TIME'", ")", "or", "define", "(", "'PHUNDER_SESSION_REGENERATE_TIME'", ",", "'600'", ")", ";", "}" ]
Define undefined Phunder constants @return void
[ "Define", "undefined", "Phunder", "constants" ]
32dbe6c81100f1ac3fc2a0080e323d8ab31cab10
https://github.com/AymDev/Phunder/blob/32dbe6c81100f1ac3fc2a0080e323d8ab31cab10/src/Config.php#L27-L55
12,996
DevGroup-ru/yii2-data-structure-tools
src/searchOld/elastic/Search.php
Search.buildFilterQuery
public static function buildFilterQuery($params, $index, $types) { self::filterInput($params); $storageToId = (new Query()) ->from(PropertyStorage::tableName()) ->select('class_name') ->where(['class_name' => array_keys($types)]) ->indexBy('id') ->column(); $propData = (new Query()) ->from(Property::tableName()) ->select(['id', 'data_type', 'storage_id']) ->where([ 'id' => array_keys($params), 'storage_id' => array_keys($storageToId), 'in_search' => 1 ]) ->indexBy('id') ->all(); $query = ['bool' => ['must' => []]]; $currentLang = LanguageHelper::getCurrent(); foreach ($params as $propId => $values) { $q = ['bool' => ['should' => []]]; switch ($storageToId[$propData[$propId]['storage_id']]) { case EAV::class : foreach ($values as $val) { $q['bool']['should'][] = [ 'bool' => ['must' => [['term' => [self::STATIC_VALUES_FILED . '.prop_id' => $propId]], ['term' => [self::STATIC_VALUES_FILED . '.value_' . $currentLang . '.raw' => $val]]]] ]; } break; case StaticValues::class : foreach ($values as $val) { $q['bool']['should'][] = [ 'bool' => ['must' => [['term' => [self::STATIC_VALUES_FILED . '.prop_id' => $propId]], ['term' => [self::STATIC_VALUES_FILED . '.static_value_id' => $val]]]] ]; } break; } $query['bool']['must'][] = $q; } //will search against all types in given index by default return $a = [ 'index' => $index, 'body' => [ 'query' => [ 'constant_score' => [ 'filter' => $query ] ] ] ]; }
php
public static function buildFilterQuery($params, $index, $types) { self::filterInput($params); $storageToId = (new Query()) ->from(PropertyStorage::tableName()) ->select('class_name') ->where(['class_name' => array_keys($types)]) ->indexBy('id') ->column(); $propData = (new Query()) ->from(Property::tableName()) ->select(['id', 'data_type', 'storage_id']) ->where([ 'id' => array_keys($params), 'storage_id' => array_keys($storageToId), 'in_search' => 1 ]) ->indexBy('id') ->all(); $query = ['bool' => ['must' => []]]; $currentLang = LanguageHelper::getCurrent(); foreach ($params as $propId => $values) { $q = ['bool' => ['should' => []]]; switch ($storageToId[$propData[$propId]['storage_id']]) { case EAV::class : foreach ($values as $val) { $q['bool']['should'][] = [ 'bool' => ['must' => [['term' => [self::STATIC_VALUES_FILED . '.prop_id' => $propId]], ['term' => [self::STATIC_VALUES_FILED . '.value_' . $currentLang . '.raw' => $val]]]] ]; } break; case StaticValues::class : foreach ($values as $val) { $q['bool']['should'][] = [ 'bool' => ['must' => [['term' => [self::STATIC_VALUES_FILED . '.prop_id' => $propId]], ['term' => [self::STATIC_VALUES_FILED . '.static_value_id' => $val]]]] ]; } break; } $query['bool']['must'][] = $q; } //will search against all types in given index by default return $a = [ 'index' => $index, 'body' => [ 'query' => [ 'constant_score' => [ 'filter' => $query ] ] ] ]; }
[ "public", "static", "function", "buildFilterQuery", "(", "$", "params", ",", "$", "index", ",", "$", "types", ")", "{", "self", "::", "filterInput", "(", "$", "params", ")", ";", "$", "storageToId", "=", "(", "new", "Query", "(", ")", ")", "->", "from", "(", "PropertyStorage", "::", "tableName", "(", ")", ")", "->", "select", "(", "'class_name'", ")", "->", "where", "(", "[", "'class_name'", "=>", "array_keys", "(", "$", "types", ")", "]", ")", "->", "indexBy", "(", "'id'", ")", "->", "column", "(", ")", ";", "$", "propData", "=", "(", "new", "Query", "(", ")", ")", "->", "from", "(", "Property", "::", "tableName", "(", ")", ")", "->", "select", "(", "[", "'id'", ",", "'data_type'", ",", "'storage_id'", "]", ")", "->", "where", "(", "[", "'id'", "=>", "array_keys", "(", "$", "params", ")", ",", "'storage_id'", "=>", "array_keys", "(", "$", "storageToId", ")", ",", "'in_search'", "=>", "1", "]", ")", "->", "indexBy", "(", "'id'", ")", "->", "all", "(", ")", ";", "$", "query", "=", "[", "'bool'", "=>", "[", "'must'", "=>", "[", "]", "]", "]", ";", "$", "currentLang", "=", "LanguageHelper", "::", "getCurrent", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "propId", "=>", "$", "values", ")", "{", "$", "q", "=", "[", "'bool'", "=>", "[", "'should'", "=>", "[", "]", "]", "]", ";", "switch", "(", "$", "storageToId", "[", "$", "propData", "[", "$", "propId", "]", "[", "'storage_id'", "]", "]", ")", "{", "case", "EAV", "::", "class", ":", "foreach", "(", "$", "values", "as", "$", "val", ")", "{", "$", "q", "[", "'bool'", "]", "[", "'should'", "]", "[", "]", "=", "[", "'bool'", "=>", "[", "'must'", "=>", "[", "[", "'term'", "=>", "[", "self", "::", "STATIC_VALUES_FILED", ".", "'.prop_id'", "=>", "$", "propId", "]", "]", ",", "[", "'term'", "=>", "[", "self", "::", "STATIC_VALUES_FILED", ".", "'.value_'", ".", "$", "currentLang", ".", "'.raw'", "=>", "$", "val", "]", "]", "]", "]", "]", ";", "}", "break", ";", "case", "StaticValues", "::", "class", ":", "foreach", "(", "$", "values", "as", "$", "val", ")", "{", "$", "q", "[", "'bool'", "]", "[", "'should'", "]", "[", "]", "=", "[", "'bool'", "=>", "[", "'must'", "=>", "[", "[", "'term'", "=>", "[", "self", "::", "STATIC_VALUES_FILED", ".", "'.prop_id'", "=>", "$", "propId", "]", "]", ",", "[", "'term'", "=>", "[", "self", "::", "STATIC_VALUES_FILED", ".", "'.static_value_id'", "=>", "$", "val", "]", "]", "]", "]", "]", ";", "}", "break", ";", "}", "$", "query", "[", "'bool'", "]", "[", "'must'", "]", "[", "]", "=", "$", "q", ";", "}", "//will search against all types in given index by default", "return", "$", "a", "=", "[", "'index'", "=>", "$", "index", ",", "'body'", "=>", "[", "'query'", "=>", "[", "'constant_score'", "=>", "[", "'filter'", "=>", "$", "query", "]", "]", "]", "]", ";", "}" ]
Prepares filter query @param array $params @param string $index @return array
[ "Prepares", "filter", "query" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/searchOld/elastic/Search.php#L486-L540
12,997
DevGroup-ru/yii2-data-structure-tools
src/searchOld/elastic/Search.php
Search.filterInput
protected static function filterInput(&$params) { $params = array_filter($params, function ($v) { if (true === is_array($v)) { $first = reset($v); return (count($v) > 0 && false === empty($first)); } else { return false === empty($v); } }); }
php
protected static function filterInput(&$params) { $params = array_filter($params, function ($v) { if (true === is_array($v)) { $first = reset($v); return (count($v) > 0 && false === empty($first)); } else { return false === empty($v); } }); }
[ "protected", "static", "function", "filterInput", "(", "&", "$", "params", ")", "{", "$", "params", "=", "array_filter", "(", "$", "params", ",", "function", "(", "$", "v", ")", "{", "if", "(", "true", "===", "is_array", "(", "$", "v", ")", ")", "{", "$", "first", "=", "reset", "(", "$", "v", ")", ";", "return", "(", "count", "(", "$", "v", ")", ">", "0", "&&", "false", "===", "empty", "(", "$", "first", ")", ")", ";", "}", "else", "{", "return", "false", "===", "empty", "(", "$", "v", ")", ";", "}", "}", ")", ";", "}" ]
Leave only not empty values to work with @param $params
[ "Leave", "only", "not", "empty", "values", "to", "work", "with" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/searchOld/elastic/Search.php#L547-L557
12,998
DevGroup-ru/yii2-data-structure-tools
src/searchOld/elastic/Search.php
Search.dataTypeToIndexField
protected static function dataTypeToIndexField($type) { $key = ''; $currentLang = LanguageHelper::getCurrent(); switch ($type) { case Property::DATA_TYPE_STRING : $key = 'str_value_' . $currentLang; break; case Property::DATA_TYPE_TEXT : $key = 'txt_value_' . $currentLang; break; case Property::DATA_TYPE_BOOLEAN : case Property::DATA_TYPE_INTEGER : $key = 'value_integer'; break; case Property::DATA_TYPE_FLOAT : $key = 'value_float'; break; case Property::DATA_TYPE_INVARIANT_STRING : case Property::DATA_TYPE_PACKED_JSON : $key = 'utr_text'; break; } return $key; }
php
protected static function dataTypeToIndexField($type) { $key = ''; $currentLang = LanguageHelper::getCurrent(); switch ($type) { case Property::DATA_TYPE_STRING : $key = 'str_value_' . $currentLang; break; case Property::DATA_TYPE_TEXT : $key = 'txt_value_' . $currentLang; break; case Property::DATA_TYPE_BOOLEAN : case Property::DATA_TYPE_INTEGER : $key = 'value_integer'; break; case Property::DATA_TYPE_FLOAT : $key = 'value_float'; break; case Property::DATA_TYPE_INVARIANT_STRING : case Property::DATA_TYPE_PACKED_JSON : $key = 'utr_text'; break; } return $key; }
[ "protected", "static", "function", "dataTypeToIndexField", "(", "$", "type", ")", "{", "$", "key", "=", "''", ";", "$", "currentLang", "=", "LanguageHelper", "::", "getCurrent", "(", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "Property", "::", "DATA_TYPE_STRING", ":", "$", "key", "=", "'str_value_'", ".", "$", "currentLang", ";", "break", ";", "case", "Property", "::", "DATA_TYPE_TEXT", ":", "$", "key", "=", "'txt_value_'", ".", "$", "currentLang", ";", "break", ";", "case", "Property", "::", "DATA_TYPE_BOOLEAN", ":", "case", "Property", "::", "DATA_TYPE_INTEGER", ":", "$", "key", "=", "'value_integer'", ";", "break", ";", "case", "Property", "::", "DATA_TYPE_FLOAT", ":", "$", "key", "=", "'value_float'", ";", "break", ";", "case", "Property", "::", "DATA_TYPE_INVARIANT_STRING", ":", "case", "Property", "::", "DATA_TYPE_PACKED_JSON", ":", "$", "key", "=", "'utr_text'", ";", "break", ";", "}", "return", "$", "key", ";", "}" ]
Cast property data_type to elastic index column @param $type @return string
[ "Cast", "property", "data_type", "to", "elastic", "index", "column" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/searchOld/elastic/Search.php#L565-L589
12,999
DevGroup-ru/yii2-data-structure-tools
src/searchOld/elastic/Search.php
Search.prepareTypes
protected static function prepareTypes($config) { $list = isset($config['storage']) ? $config['storage'] : []; $list = is_array($list) ? $list : [$list]; if (count($list) == 0) { $list[] = StaticValues::class; } foreach ($list as $i => $storageClass) { $list[$storageClass] = IndexHelper::storageClassToType($storageClass); unset($list[$i]); } return $list; }
php
protected static function prepareTypes($config) { $list = isset($config['storage']) ? $config['storage'] : []; $list = is_array($list) ? $list : [$list]; if (count($list) == 0) { $list[] = StaticValues::class; } foreach ($list as $i => $storageClass) { $list[$storageClass] = IndexHelper::storageClassToType($storageClass); unset($list[$i]); } return $list; }
[ "protected", "static", "function", "prepareTypes", "(", "$", "config", ")", "{", "$", "list", "=", "isset", "(", "$", "config", "[", "'storage'", "]", ")", "?", "$", "config", "[", "'storage'", "]", ":", "[", "]", ";", "$", "list", "=", "is_array", "(", "$", "list", ")", "?", "$", "list", ":", "[", "$", "list", "]", ";", "if", "(", "count", "(", "$", "list", ")", "==", "0", ")", "{", "$", "list", "[", "]", "=", "StaticValues", "::", "class", ";", "}", "foreach", "(", "$", "list", "as", "$", "i", "=>", "$", "storageClass", ")", "{", "$", "list", "[", "$", "storageClass", "]", "=", "IndexHelper", "::", "storageClassToType", "(", "$", "storageClass", ")", ";", "unset", "(", "$", "list", "[", "$", "i", "]", ")", ";", "}", "return", "$", "list", ";", "}" ]
Prepares list of types to search against for @param array $config @return array
[ "Prepares", "list", "of", "types", "to", "search", "against", "for" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/searchOld/elastic/Search.php#L597-L609