repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jasny/controller
src/Controller/Input.php
Input.getQueryParams
public function getQueryParams(array $list = null) { return isset($list) ? $this->listQueryParams($list) : (array)$this->getRequest()->getQueryParams(); }
php
public function getQueryParams(array $list = null) { return isset($list) ? $this->listQueryParams($list) : (array)$this->getRequest()->getQueryParams(); }
[ "public", "function", "getQueryParams", "(", "array", "$", "list", "=", "null", ")", "{", "return", "isset", "(", "$", "list", ")", "?", "$", "this", "->", "listQueryParams", "(", "$", "list", ")", ":", "(", "array", ")", "$", "this", "->", "getRequest", "(", ")", "->", "getQueryParams", "(", ")", ";", "}" ]
Get the request query parameters. <code> // Get all parameters $params = $this->getQueryParams(); // Get specific parameters, specifying defaults for 'bar' and 'zoo' list($foo, $bar, $zoo) = $this->getQueryParams(['foo', 'bar' => 10, 'zoo' => 'monkey']); </code> @param array $list @return array
[ "Get", "the", "request", "query", "parameters", "." ]
train
https://github.com/jasny/controller/blob/28edf64343f1d8218c166c0c570128e1ee6153d8/src/Controller/Input.php#L34-L39
jasny/controller
src/Controller/Input.php
Input.listQueryParams
protected function listQueryParams(array $list) { $result = []; $params = $this->getRequest()->getQueryParams(); foreach ($list as $key => $value) { if (is_int($key)) { $key = $value; $value = null; } $result[] = isset($params[$key]) ? $params[$key] : $value; } return $result; }
php
protected function listQueryParams(array $list) { $result = []; $params = $this->getRequest()->getQueryParams(); foreach ($list as $key => $value) { if (is_int($key)) { $key = $value; $value = null; } $result[] = isset($params[$key]) ? $params[$key] : $value; } return $result; }
[ "protected", "function", "listQueryParams", "(", "array", "$", "list", ")", "{", "$", "result", "=", "[", "]", ";", "$", "params", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getQueryParams", "(", ")", ";", "foreach", "(", "$", "list", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "value", ";", "$", "value", "=", "null", ";", "}", "$", "result", "[", "]", "=", "isset", "(", "$", "params", "[", "$", "key", "]", ")", "?", "$", "params", "[", "$", "key", "]", ":", "$", "value", ";", "}", "return", "$", "result", ";", "}" ]
Apply list to query params @param array $list @return array
[ "Apply", "list", "to", "query", "params" ]
train
https://github.com/jasny/controller/blob/28edf64343f1d8218c166c0c570128e1ee6153d8/src/Controller/Input.php#L47-L62
jasny/controller
src/Controller/Input.php
Input.getQueryParam
public function getQueryParam($param, $default = null, $filter = null, $filterOptions = null) { $params = $this->getQueryParams(); $value = isset($params[$param]) ? $params[$param] : $default; if (isset($filter) && isset($value)) { $value = filter_var($value, $filter, $filterOptions); } return $value; }
php
public function getQueryParam($param, $default = null, $filter = null, $filterOptions = null) { $params = $this->getQueryParams(); $value = isset($params[$param]) ? $params[$param] : $default; if (isset($filter) && isset($value)) { $value = filter_var($value, $filter, $filterOptions); } return $value; }
[ "public", "function", "getQueryParam", "(", "$", "param", ",", "$", "default", "=", "null", ",", "$", "filter", "=", "null", ",", "$", "filterOptions", "=", "null", ")", "{", "$", "params", "=", "$", "this", "->", "getQueryParams", "(", ")", ";", "$", "value", "=", "isset", "(", "$", "params", "[", "$", "param", "]", ")", "?", "$", "params", "[", "$", "param", "]", ":", "$", "default", ";", "if", "(", "isset", "(", "$", "filter", ")", "&&", "isset", "(", "$", "value", ")", ")", "{", "$", "value", "=", "filter_var", "(", "$", "value", ",", "$", "filter", ",", "$", "filterOptions", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get a query parameter. Optionally apply filtering to the value. @link http://php.net/manual/en/filter.filters.php @param array $param @param string $default @param int $filter @param mixed $filterOptions @return mixed
[ "Get", "a", "query", "parameter", "." ]
train
https://github.com/jasny/controller/blob/28edf64343f1d8218c166c0c570128e1ee6153d8/src/Controller/Input.php#L89-L99
jasny/controller
src/Controller/Input.php
Input.getInput
public function getInput() { $data = $this->getRequest()->getParsedBody(); if (is_array($data)) { $files = $this->getRequest()->getUploadedFiles(); $data = array_replace_recursive($data, (array)$files); } return $data; }
php
public function getInput() { $data = $this->getRequest()->getParsedBody(); if (is_array($data)) { $files = $this->getRequest()->getUploadedFiles(); $data = array_replace_recursive($data, (array)$files); } return $data; }
[ "public", "function", "getInput", "(", ")", "{", "$", "data", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getParsedBody", "(", ")", ";", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "$", "files", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getUploadedFiles", "(", ")", ";", "$", "data", "=", "array_replace_recursive", "(", "$", "data", ",", "(", "array", ")", "$", "files", ")", ";", "}", "return", "$", "data", ";", "}" ]
Get parsed body and uploaded files as input @return array|mixed
[ "Get", "parsed", "body", "and", "uploaded", "files", "as", "input" ]
train
https://github.com/jasny/controller/blob/28edf64343f1d8218c166c0c570128e1ee6153d8/src/Controller/Input.php#L107-L117
ClementIV/yii-rest-rbac2.0
models/searchs/User.php
User.search
public function search($params) { $query = UserModel::find(); if(array_key_exists("page", $params)&&array_key_exists("pageLimit", $params)){ $query = $query->orderBy('id') ->offset($params["page"]*$params["pageLimit"]) ->limit($params["pageLimit"]); } if(array_key_exists("status",$params)){ $query->where(['status'=>$params["status"]]); } if(array_key_exists("q",$params)){ $query->andFilterWhere(['like','username', $params["q"] ]); } $count = $query->count(); $query=$query->all(); return ['count'=>$count,'items'=>$query]; }
php
public function search($params) { $query = UserModel::find(); if(array_key_exists("page", $params)&&array_key_exists("pageLimit", $params)){ $query = $query->orderBy('id') ->offset($params["page"]*$params["pageLimit"]) ->limit($params["pageLimit"]); } if(array_key_exists("status",$params)){ $query->where(['status'=>$params["status"]]); } if(array_key_exists("q",$params)){ $query->andFilterWhere(['like','username', $params["q"] ]); } $count = $query->count(); $query=$query->all(); return ['count'=>$count,'items'=>$query]; }
[ "public", "function", "search", "(", "$", "params", ")", "{", "$", "query", "=", "UserModel", "::", "find", "(", ")", ";", "if", "(", "array_key_exists", "(", "\"page\"", ",", "$", "params", ")", "&&", "array_key_exists", "(", "\"pageLimit\"", ",", "$", "params", ")", ")", "{", "$", "query", "=", "$", "query", "->", "orderBy", "(", "'id'", ")", "->", "offset", "(", "$", "params", "[", "\"page\"", "]", "*", "$", "params", "[", "\"pageLimit\"", "]", ")", "->", "limit", "(", "$", "params", "[", "\"pageLimit\"", "]", ")", ";", "}", "if", "(", "array_key_exists", "(", "\"status\"", ",", "$", "params", ")", ")", "{", "$", "query", "->", "where", "(", "[", "'status'", "=>", "$", "params", "[", "\"status\"", "]", "]", ")", ";", "}", "if", "(", "array_key_exists", "(", "\"q\"", ",", "$", "params", ")", ")", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'like'", ",", "'username'", ",", "$", "params", "[", "\"q\"", "]", "]", ")", ";", "}", "$", "count", "=", "$", "query", "->", "count", "(", ")", ";", "$", "query", "=", "$", "query", "->", "all", "(", ")", ";", "return", "[", "'count'", "=>", "$", "count", ",", "'items'", "=>", "$", "query", "]", ";", "}" ]
Creates data provider instance with search query applied @param array $params @return ActiveDataProvider
[ "Creates", "data", "provider", "instance", "with", "search", "query", "applied" ]
train
https://github.com/ClementIV/yii-rest-rbac2.0/blob/435ffceca8d51b4d369182db3a06c20f336e9ac4/models/searchs/User.php#L42-L61
php-comp/lite-database
src/LiteMongo.php
LiteMongo.isSupported
public static function isSupported(string $driver): bool { if ($driver === self::DRIVER_MONGO_DB) { return \extension_loaded('mongodb'); } if ($driver === self::DRIVER_MONGO) { return \extension_loaded('mongo'); } return false; }
php
public static function isSupported(string $driver): bool { if ($driver === self::DRIVER_MONGO_DB) { return \extension_loaded('mongodb'); } if ($driver === self::DRIVER_MONGO) { return \extension_loaded('mongo'); } return false; }
[ "public", "static", "function", "isSupported", "(", "string", "$", "driver", ")", ":", "bool", "{", "if", "(", "$", "driver", "===", "self", "::", "DRIVER_MONGO_DB", ")", "{", "return", "\\", "extension_loaded", "(", "'mongodb'", ")", ";", "}", "if", "(", "$", "driver", "===", "self", "::", "DRIVER_MONGO", ")", "{", "return", "\\", "extension_loaded", "(", "'mongo'", ")", ";", "}", "return", "false", ";", "}" ]
Is this driver supported. @param string $driver @return bool
[ "Is", "this", "driver", "supported", "." ]
train
https://github.com/php-comp/lite-database/blob/af5f73cb89e0e6cd24dd464f7a48fb5088eaafca/src/LiteMongo.php#L37-L48
mainio/c5pkg_symfony_forms
src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/DateTimeToFormWidgetTransformer.php
DateTimeToFormWidgetTransformer.transform
public function transform($dateTime) { if ($dateTime === null || trim($dateTime) == '') { return ''; } if (!$dateTime instanceof \DateTime) { throw new TransformationFailedException('Expected a \DateTime.'); } $dateTime = clone $dateTime; if ($this->inputTimezone !== $this->outputTimezone) { try { $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } } // This is passed to the concrete5 DateTime widget, so the format // can be anything that can be parsed with the default PHP datetime // functions. return $dateTime->format('Y-m-d H:i:s'); }
php
public function transform($dateTime) { if ($dateTime === null || trim($dateTime) == '') { return ''; } if (!$dateTime instanceof \DateTime) { throw new TransformationFailedException('Expected a \DateTime.'); } $dateTime = clone $dateTime; if ($this->inputTimezone !== $this->outputTimezone) { try { $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } } // This is passed to the concrete5 DateTime widget, so the format // can be anything that can be parsed with the default PHP datetime // functions. return $dateTime->format('Y-m-d H:i:s'); }
[ "public", "function", "transform", "(", "$", "dateTime", ")", "{", "if", "(", "$", "dateTime", "===", "null", "||", "trim", "(", "$", "dateTime", ")", "==", "''", ")", "{", "return", "''", ";", "}", "if", "(", "!", "$", "dateTime", "instanceof", "\\", "DateTime", ")", "{", "throw", "new", "TransformationFailedException", "(", "'Expected a \\DateTime.'", ")", ";", "}", "$", "dateTime", "=", "clone", "$", "dateTime", ";", "if", "(", "$", "this", "->", "inputTimezone", "!==", "$", "this", "->", "outputTimezone", ")", "{", "try", "{", "$", "dateTime", "->", "setTimezone", "(", "new", "\\", "DateTimeZone", "(", "$", "this", "->", "outputTimezone", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "TransformationFailedException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "}", "// This is passed to the concrete5 DateTime widget, so the format", "// can be anything that can be parsed with the default PHP datetime", "// functions.", "return", "$", "dateTime", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "}" ]
Transforms a normalized date into a the concrete5 datetime widget format. @param \DateTime $dateTime Normalized date. @return string Widget format date. @throws TransformationFailedException If the given value is not an instance of \DateTime or if the output timezone is not supported.
[ "Transforms", "a", "normalized", "date", "into", "a", "the", "concrete5", "datetime", "widget", "format", "." ]
train
https://github.com/mainio/c5pkg_symfony_forms/blob/41a93c293d986574ec5cade8a7c8700e083dbaaa/src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/DateTimeToFormWidgetTransformer.php#L41-L64
mainio/c5pkg_symfony_forms
src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/DateTimeToFormWidgetTransformer.php
DateTimeToFormWidgetTransformer.reverseTransform
public function reverseTransform($value) { if (null === $value) { return; } if (!is_array($value)) { throw new TransformationFailedException('Expected an array.'); } if ('' === implode('', $value)) { return; } if (isset($value['dt']) && !preg_match('/^[\d]{4}-[\d]{2}-[\d]{2}$/', $value['dt'])) { throw new TransformationFailedException('The date time value is invalid'); } if (isset($value['h']) && !ctype_digit((string) $value['h'])) { throw new TransformationFailedException('The hour is invalid'); } if (isset($value['m']) && !ctype_digit((string) $value['m'])) { throw new TransformationFailedException('The minute is invalid'); } $dt = $value['dt']; $h = intval($value['h']); $m = intval($value['m']); $dh = \Core::make('helper/date'); if ($dh->getTimeFormat() == 12) { if (isset($value['a']) && $value['a'] == 'PM') { $h += 12; } } try { $dateTime = new \DateTime(sprintf( '%s %s:%s:00 %s', empty($dt) ? '1970-01-01' : $dt, empty($h) ? '00' : $h, empty($m) ? '00' : $m, $this->outputTimezone )); if ($this->inputTimezone !== $this->outputTimezone) { $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); } } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } return $dateTime; }
php
public function reverseTransform($value) { if (null === $value) { return; } if (!is_array($value)) { throw new TransformationFailedException('Expected an array.'); } if ('' === implode('', $value)) { return; } if (isset($value['dt']) && !preg_match('/^[\d]{4}-[\d]{2}-[\d]{2}$/', $value['dt'])) { throw new TransformationFailedException('The date time value is invalid'); } if (isset($value['h']) && !ctype_digit((string) $value['h'])) { throw new TransformationFailedException('The hour is invalid'); } if (isset($value['m']) && !ctype_digit((string) $value['m'])) { throw new TransformationFailedException('The minute is invalid'); } $dt = $value['dt']; $h = intval($value['h']); $m = intval($value['m']); $dh = \Core::make('helper/date'); if ($dh->getTimeFormat() == 12) { if (isset($value['a']) && $value['a'] == 'PM') { $h += 12; } } try { $dateTime = new \DateTime(sprintf( '%s %s:%s:00 %s', empty($dt) ? '1970-01-01' : $dt, empty($h) ? '00' : $h, empty($m) ? '00' : $m, $this->outputTimezone )); if ($this->inputTimezone !== $this->outputTimezone) { $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); } } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } return $dateTime; }
[ "public", "function", "reverseTransform", "(", "$", "value", ")", "{", "if", "(", "null", "===", "$", "value", ")", "{", "return", ";", "}", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'Expected an array.'", ")", ";", "}", "if", "(", "''", "===", "implode", "(", "''", ",", "$", "value", ")", ")", "{", "return", ";", "}", "if", "(", "isset", "(", "$", "value", "[", "'dt'", "]", ")", "&&", "!", "preg_match", "(", "'/^[\\d]{4}-[\\d]{2}-[\\d]{2}$/'", ",", "$", "value", "[", "'dt'", "]", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'The date time value is invalid'", ")", ";", "}", "if", "(", "isset", "(", "$", "value", "[", "'h'", "]", ")", "&&", "!", "ctype_digit", "(", "(", "string", ")", "$", "value", "[", "'h'", "]", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'The hour is invalid'", ")", ";", "}", "if", "(", "isset", "(", "$", "value", "[", "'m'", "]", ")", "&&", "!", "ctype_digit", "(", "(", "string", ")", "$", "value", "[", "'m'", "]", ")", ")", "{", "throw", "new", "TransformationFailedException", "(", "'The minute is invalid'", ")", ";", "}", "$", "dt", "=", "$", "value", "[", "'dt'", "]", ";", "$", "h", "=", "intval", "(", "$", "value", "[", "'h'", "]", ")", ";", "$", "m", "=", "intval", "(", "$", "value", "[", "'m'", "]", ")", ";", "$", "dh", "=", "\\", "Core", "::", "make", "(", "'helper/date'", ")", ";", "if", "(", "$", "dh", "->", "getTimeFormat", "(", ")", "==", "12", ")", "{", "if", "(", "isset", "(", "$", "value", "[", "'a'", "]", ")", "&&", "$", "value", "[", "'a'", "]", "==", "'PM'", ")", "{", "$", "h", "+=", "12", ";", "}", "}", "try", "{", "$", "dateTime", "=", "new", "\\", "DateTime", "(", "sprintf", "(", "'%s %s:%s:00 %s'", ",", "empty", "(", "$", "dt", ")", "?", "'1970-01-01'", ":", "$", "dt", ",", "empty", "(", "$", "h", ")", "?", "'00'", ":", "$", "h", ",", "empty", "(", "$", "m", ")", "?", "'00'", ":", "$", "m", ",", "$", "this", "->", "outputTimezone", ")", ")", ";", "if", "(", "$", "this", "->", "inputTimezone", "!==", "$", "this", "->", "outputTimezone", ")", "{", "$", "dateTime", "->", "setTimezone", "(", "new", "\\", "DateTimeZone", "(", "$", "this", "->", "inputTimezone", ")", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "TransformationFailedException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "return", "$", "dateTime", ";", "}" ]
Transforms a localized date into a normalized date. @param array $value Localized date @return \DateTime Normalized date @throws TransformationFailedException If the given value is not an array, if the value could not be transformed or if the input timezone is not supported.
[ "Transforms", "a", "localized", "date", "into", "a", "normalized", "date", "." ]
train
https://github.com/mainio/c5pkg_symfony_forms/blob/41a93c293d986574ec5cade8a7c8700e083dbaaa/src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/DateTimeToFormWidgetTransformer.php#L78-L133
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.setPreMessageTemplate
public function setPreMessageTemplate($template = null) { if (null !== $template) { $template = (string) $template; } $this->abstractOptions['messageTemplates'] [self::PRE_MESSAGE_TEMPLATE_KEY] = $template; return $this; }
php
public function setPreMessageTemplate($template = null) { if (null !== $template) { $template = (string) $template; } $this->abstractOptions['messageTemplates'] [self::PRE_MESSAGE_TEMPLATE_KEY] = $template; return $this; }
[ "public", "function", "setPreMessageTemplate", "(", "$", "template", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "template", ")", "{", "$", "template", "=", "(", "string", ")", "$", "template", ";", "}", "$", "this", "->", "abstractOptions", "[", "'messageTemplates'", "]", "[", "self", "::", "PRE_MESSAGE_TEMPLATE_KEY", "]", "=", "$", "template", ";", "return", "$", "this", ";", "}" ]
Sets template of validation failure message to be inserted at beginning of validation failure message map. Use null to specify no message should be inserted. @param string|null $template @return self
[ "Sets", "template", "of", "validation", "failure", "message", "to", "be", "inserted", "at", "beginning", "of", "validation", "failure", "message", "map", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L257-L265
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.setPostMessageTemplate
public function setPostMessageTemplate($postMessage = null) { if (null !== $postMessage) { $postMessage = (string) $postMessage; } $this->abstractOptions['messageTemplates'] [self::POST_MESSAGE_TEMPLATE_KEY] = $postMessage; return $this; }
php
public function setPostMessageTemplate($postMessage = null) { if (null !== $postMessage) { $postMessage = (string) $postMessage; } $this->abstractOptions['messageTemplates'] [self::POST_MESSAGE_TEMPLATE_KEY] = $postMessage; return $this; }
[ "public", "function", "setPostMessageTemplate", "(", "$", "postMessage", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "postMessage", ")", "{", "$", "postMessage", "=", "(", "string", ")", "$", "postMessage", ";", "}", "$", "this", "->", "abstractOptions", "[", "'messageTemplates'", "]", "[", "self", "::", "POST_MESSAGE_TEMPLATE_KEY", "]", "=", "$", "postMessage", ";", "return", "$", "this", ";", "}" ]
Sets template of validation failure message to be inserted at end of validation failure message map. Use null to specify no message should be inserted. @param string|null $postMessage @return self
[ "Sets", "template", "of", "validation", "failure", "message", "to", "be", "inserted", "at", "end", "of", "validation", "failure", "message", "map", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L290-L298
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.attach
public function attach(ValidatorInterface $validator, $showMessages = true, $leadingTemplate = null, $trailingTemplate = null, $priority = self::DEFAULT_PRIORITY) { $this->validators->insert( array( 'instance' => $validator, 'show_messages' => (bool)$showMessages, 'leading_message_template' => $leadingTemplate, 'trailing_message_template' => $trailingTemplate, ), $priority ); return $this; }
php
public function attach(ValidatorInterface $validator, $showMessages = true, $leadingTemplate = null, $trailingTemplate = null, $priority = self::DEFAULT_PRIORITY) { $this->validators->insert( array( 'instance' => $validator, 'show_messages' => (bool)$showMessages, 'leading_message_template' => $leadingTemplate, 'trailing_message_template' => $trailingTemplate, ), $priority ); return $this; }
[ "public", "function", "attach", "(", "ValidatorInterface", "$", "validator", ",", "$", "showMessages", "=", "true", ",", "$", "leadingTemplate", "=", "null", ",", "$", "trailingTemplate", "=", "null", ",", "$", "priority", "=", "self", "::", "DEFAULT_PRIORITY", ")", "{", "$", "this", "->", "validators", "->", "insert", "(", "array", "(", "'instance'", "=>", "$", "validator", ",", "'show_messages'", "=>", "(", "bool", ")", "$", "showMessages", ",", "'leading_message_template'", "=>", "$", "leadingTemplate", ",", "'trailing_message_template'", "=>", "$", "trailingTemplate", ",", ")", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
Attaches validator to end of chain. @param ValidatorInterface $validator @param boolean $showMessages Show messages for this validator on failure. @param string|null $leadingTemplate Validator's leading message template. @param string|null $trailingTemplate Validator's trailing message template. @param int $priority Validator's priority. @throws Exception\InvalidArgumentException @return self
[ "Attaches", "validator", "to", "end", "of", "chain", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L363-L379
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.prependValidator
public function prependValidator(ValidatorInterface $validator, $showMessages = true, $leadingTemplate = null, $trailingTemplate = null) { $priority = self::DEFAULT_PRIORITY; if (!$this->validators->isEmpty()) { $queue = $this->validators->getIterator(); $queue->setExtractFlags(PriorityQueue::EXTR_PRIORITY); $extractedNode = $queue->extract(); $priority = $extractedNode[0] + 1; } $this->validators->insert( array( 'instance' => $validator, 'show_messages' => (bool) $showMessages, 'leading_message_template' => $leadingTemplate, 'trailing_message_template' => $trailingTemplate, ), $priority ); return $this; }
php
public function prependValidator(ValidatorInterface $validator, $showMessages = true, $leadingTemplate = null, $trailingTemplate = null) { $priority = self::DEFAULT_PRIORITY; if (!$this->validators->isEmpty()) { $queue = $this->validators->getIterator(); $queue->setExtractFlags(PriorityQueue::EXTR_PRIORITY); $extractedNode = $queue->extract(); $priority = $extractedNode[0] + 1; } $this->validators->insert( array( 'instance' => $validator, 'show_messages' => (bool) $showMessages, 'leading_message_template' => $leadingTemplate, 'trailing_message_template' => $trailingTemplate, ), $priority ); return $this; }
[ "public", "function", "prependValidator", "(", "ValidatorInterface", "$", "validator", ",", "$", "showMessages", "=", "true", ",", "$", "leadingTemplate", "=", "null", ",", "$", "trailingTemplate", "=", "null", ")", "{", "$", "priority", "=", "self", "::", "DEFAULT_PRIORITY", ";", "if", "(", "!", "$", "this", "->", "validators", "->", "isEmpty", "(", ")", ")", "{", "$", "queue", "=", "$", "this", "->", "validators", "->", "getIterator", "(", ")", ";", "$", "queue", "->", "setExtractFlags", "(", "PriorityQueue", "::", "EXTR_PRIORITY", ")", ";", "$", "extractedNode", "=", "$", "queue", "->", "extract", "(", ")", ";", "$", "priority", "=", "$", "extractedNode", "[", "0", "]", "+", "1", ";", "}", "$", "this", "->", "validators", "->", "insert", "(", "array", "(", "'instance'", "=>", "$", "validator", ",", "'show_messages'", "=>", "(", "bool", ")", "$", "showMessages", ",", "'leading_message_template'", "=>", "$", "leadingTemplate", ",", "'trailing_message_template'", "=>", "$", "trailingTemplate", ",", ")", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
Adds validator to beginning of chain. @param ValidatorInterface $validator @param boolean $showMessages Show messages for this validator on failure. @param string|null $leadingTemplate Validator's leading message template. @param string|null $trailingTemplate Validator's trailing message template. @return self
[ "Adds", "validator", "to", "beginning", "of", "chain", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L393-L416
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.attachByName
public function attachByName($name, $options = array(), $showMessages = true, $leadingTemplate = null, $trailingTemplate = null, $priority = self::DEFAULT_PRIORITY) { $validator = $this->plugin($name, $options); if (isset($options['show_messages'])) { $showMessages = (bool) $options['show_messages']; } if (isset($options['leading_message_template'])) { $leadingTemplate = (string) $options['leading_message_template']; } if (isset($options['trailing_message_template'])) { $trailingTemplate = (string) $options['trailing_message_template']; } if (isset($options['priority'])) { $priority = (int) $options['priority']; } $this->attach($validator, $showMessages, $leadingTemplate, $trailingTemplate, $priority); return $this; }
php
public function attachByName($name, $options = array(), $showMessages = true, $leadingTemplate = null, $trailingTemplate = null, $priority = self::DEFAULT_PRIORITY) { $validator = $this->plugin($name, $options); if (isset($options['show_messages'])) { $showMessages = (bool) $options['show_messages']; } if (isset($options['leading_message_template'])) { $leadingTemplate = (string) $options['leading_message_template']; } if (isset($options['trailing_message_template'])) { $trailingTemplate = (string) $options['trailing_message_template']; } if (isset($options['priority'])) { $priority = (int) $options['priority']; } $this->attach($validator, $showMessages, $leadingTemplate, $trailingTemplate, $priority); return $this; }
[ "public", "function", "attachByName", "(", "$", "name", ",", "$", "options", "=", "array", "(", ")", ",", "$", "showMessages", "=", "true", ",", "$", "leadingTemplate", "=", "null", ",", "$", "trailingTemplate", "=", "null", ",", "$", "priority", "=", "self", "::", "DEFAULT_PRIORITY", ")", "{", "$", "validator", "=", "$", "this", "->", "plugin", "(", "$", "name", ",", "$", "options", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'show_messages'", "]", ")", ")", "{", "$", "showMessages", "=", "(", "bool", ")", "$", "options", "[", "'show_messages'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'leading_message_template'", "]", ")", ")", "{", "$", "leadingTemplate", "=", "(", "string", ")", "$", "options", "[", "'leading_message_template'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'trailing_message_template'", "]", ")", ")", "{", "$", "trailingTemplate", "=", "(", "string", ")", "$", "options", "[", "'trailing_message_template'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'priority'", "]", ")", ")", "{", "$", "priority", "=", "(", "int", ")", "$", "options", "[", "'priority'", "]", ";", "}", "$", "this", "->", "attach", "(", "$", "validator", ",", "$", "showMessages", ",", "$", "leadingTemplate", ",", "$", "trailingTemplate", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
Uses plugin manager to add validator by name. @param string $name @param array $options @param boolean $showMessages Show messages for this validator on failure. @param string|null $leadingTemplate Validator's leading message template. @param string|null $trailingTemplate Validator's trailing message template. @param int $priority Validator's priority. @return self
[ "Uses", "plugin", "manager", "to", "add", "validator", "by", "name", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L432-L458
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.prependByName
public function prependByName($name, $options = array(), $showMessages = true, $leadingTemplate = null, $trailingTemplate = null) { $validator = $this->plugin($name, $options); //To do. Investigate why Zend\Validator\ValidatorChain does not check //for $options['break_on_failure'] in this method. if (isset($options['show_messages'])) { $showMessages = (bool) $options['show_messages']; } if (isset($options['leading_message_template'])) { $leadingTemplate = (string) $options['leading_message_template']; } if (isset($options['trailing_message_template'])) { $trailingTemplate = (string) $options['trailing_message_template']; } $this->prependValidator($validator, $showMessages, $leadingTemplate, $trailingTemplate); return $this; }
php
public function prependByName($name, $options = array(), $showMessages = true, $leadingTemplate = null, $trailingTemplate = null) { $validator = $this->plugin($name, $options); //To do. Investigate why Zend\Validator\ValidatorChain does not check //for $options['break_on_failure'] in this method. if (isset($options['show_messages'])) { $showMessages = (bool) $options['show_messages']; } if (isset($options['leading_message_template'])) { $leadingTemplate = (string) $options['leading_message_template']; } if (isset($options['trailing_message_template'])) { $trailingTemplate = (string) $options['trailing_message_template']; } $this->prependValidator($validator, $showMessages, $leadingTemplate, $trailingTemplate); return $this; }
[ "public", "function", "prependByName", "(", "$", "name", ",", "$", "options", "=", "array", "(", ")", ",", "$", "showMessages", "=", "true", ",", "$", "leadingTemplate", "=", "null", ",", "$", "trailingTemplate", "=", "null", ")", "{", "$", "validator", "=", "$", "this", "->", "plugin", "(", "$", "name", ",", "$", "options", ")", ";", "//To do. Investigate why Zend\\Validator\\ValidatorChain does not check ", "//for $options['break_on_failure'] in this method.", "if", "(", "isset", "(", "$", "options", "[", "'show_messages'", "]", ")", ")", "{", "$", "showMessages", "=", "(", "bool", ")", "$", "options", "[", "'show_messages'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'leading_message_template'", "]", ")", ")", "{", "$", "leadingTemplate", "=", "(", "string", ")", "$", "options", "[", "'leading_message_template'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'trailing_message_template'", "]", ")", ")", "{", "$", "trailingTemplate", "=", "(", "string", ")", "$", "options", "[", "'trailing_message_template'", "]", ";", "}", "$", "this", "->", "prependValidator", "(", "$", "validator", ",", "$", "showMessages", ",", "$", "leadingTemplate", ",", "$", "trailingTemplate", ")", ";", "return", "$", "this", ";", "}" ]
Uses plugin manager to prepend validator by name. @param string $name @param array $options @param boolean $showMessages Show messages for this validator on failure. @param string|null $leadingTemplate Validator's leading message template. @param string|null $trailingTemplate Validator's trailing message template. @return self
[ "Uses", "plugin", "manager", "to", "prepend", "validator", "by", "name", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L473-L497
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.createMessageFromTemplate
protected function createMessageFromTemplate($messageTemplate, $value) { // AbstractValidator::translateMessage does not use first argument. $message = $this->translateMessage('dummyValue', (string) $messageTemplate); if (is_object($value) && !in_array('__toString', get_class_methods($value)) ) { $value = get_class($value) . ' object'; } elseif (is_array($value)) { $value = var_export($value, 1); } else { $value = (string) $value; } if ($this->isValueObscured()) { $value = str_repeat('*', strlen($value)); } $message = str_replace('%value%', (string) $value, $message); $message = str_replace('%count%', (string) $this->count(), $message); $length = self::getMessageLength(); if (($length > -1) && (strlen($message) > $length)) { $message = substr($message, 0, ($length - 3)) . '...'; } return $message; }
php
protected function createMessageFromTemplate($messageTemplate, $value) { // AbstractValidator::translateMessage does not use first argument. $message = $this->translateMessage('dummyValue', (string) $messageTemplate); if (is_object($value) && !in_array('__toString', get_class_methods($value)) ) { $value = get_class($value) . ' object'; } elseif (is_array($value)) { $value = var_export($value, 1); } else { $value = (string) $value; } if ($this->isValueObscured()) { $value = str_repeat('*', strlen($value)); } $message = str_replace('%value%', (string) $value, $message); $message = str_replace('%count%', (string) $this->count(), $message); $length = self::getMessageLength(); if (($length > -1) && (strlen($message) > $length)) { $message = substr($message, 0, ($length - 3)) . '...'; } return $message; }
[ "protected", "function", "createMessageFromTemplate", "(", "$", "messageTemplate", ",", "$", "value", ")", "{", "// AbstractValidator::translateMessage does not use first argument.", "$", "message", "=", "$", "this", "->", "translateMessage", "(", "'dummyValue'", ",", "(", "string", ")", "$", "messageTemplate", ")", ";", "if", "(", "is_object", "(", "$", "value", ")", "&&", "!", "in_array", "(", "'__toString'", ",", "get_class_methods", "(", "$", "value", ")", ")", ")", "{", "$", "value", "=", "get_class", "(", "$", "value", ")", ".", "' object'", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "var_export", "(", "$", "value", ",", "1", ")", ";", "}", "else", "{", "$", "value", "=", "(", "string", ")", "$", "value", ";", "}", "if", "(", "$", "this", "->", "isValueObscured", "(", ")", ")", "{", "$", "value", "=", "str_repeat", "(", "'*'", ",", "strlen", "(", "$", "value", ")", ")", ";", "}", "$", "message", "=", "str_replace", "(", "'%value%'", ",", "(", "string", ")", "$", "value", ",", "$", "message", ")", ";", "$", "message", "=", "str_replace", "(", "'%count%'", ",", "(", "string", ")", "$", "this", "->", "count", "(", ")", ",", "$", "message", ")", ";", "$", "length", "=", "self", "::", "getMessageLength", "(", ")", ";", "if", "(", "(", "$", "length", ">", "-", "1", ")", "&&", "(", "strlen", "(", "$", "message", ")", ">", "$", "length", ")", ")", "{", "$", "message", "=", "substr", "(", "$", "message", ",", "0", ",", "(", "$", "length", "-", "3", ")", ")", ".", "'...'", ";", "}", "return", "$", "message", ";", "}" ]
Constructs and returns validation failure message for specified message template and value. This is used in place of AbstractValidator::createMessage() since leading and trailing union messages are not stored with a message key under abstractOptions['messageTemplates']. If a translator is available and a translation exists for $messageKey, the translation will be used. @param string $messageTemplate @param string|array|object $value @return string
[ "Constructs", "and", "returns", "validation", "failure", "message", "for", "specified", "message", "template", "and", "value", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L514-L543
jim-moser/zf2-validators-empty-or
src/VerboseOrChain.php
VerboseOrChain.merge
public function merge(VerboseOrChain $validatorChain) { foreach ($validatorChain->validators->toArray(PriorityQueue::EXTR_BOTH) as $item) { $this->attach($item['data']['instance'], $item['data']['show_messages'], $item['data']['leading_message_template'], $item['data']['trailing_message_template'], $item['priority']); } return $this; }
php
public function merge(VerboseOrChain $validatorChain) { foreach ($validatorChain->validators->toArray(PriorityQueue::EXTR_BOTH) as $item) { $this->attach($item['data']['instance'], $item['data']['show_messages'], $item['data']['leading_message_template'], $item['data']['trailing_message_template'], $item['priority']); } return $this; }
[ "public", "function", "merge", "(", "VerboseOrChain", "$", "validatorChain", ")", "{", "foreach", "(", "$", "validatorChain", "->", "validators", "->", "toArray", "(", "PriorityQueue", "::", "EXTR_BOTH", ")", "as", "$", "item", ")", "{", "$", "this", "->", "attach", "(", "$", "item", "[", "'data'", "]", "[", "'instance'", "]", ",", "$", "item", "[", "'data'", "]", "[", "'show_messages'", "]", ",", "$", "item", "[", "'data'", "]", "[", "'leading_message_template'", "]", ",", "$", "item", "[", "'data'", "]", "[", "'trailing_message_template'", "]", ",", "$", "item", "[", "'priority'", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Merges in logical "or" validator chain provided as argument. Priorities of validators within the internal priority queues are maintained. Unfortunately this method accesses the OrValidatorChain::validators property which is protected. This means the type hint for the $validatorChain argument is restricted to this class. This was borrowed from Zend\Validator\ValidatorChain and is necessary to obtain the list of validators as a PriorityQueue so that the validators maintain their priority when merged in. A better solution would be to have the getValidators method return a PriorityQueue instead of an array and have the merge method call the public getValidators method instead of accessing the protected validators property. This was not done here in order to keep the API as close as possible to the API of the Zend\Validator\ValidatorChain class. @param OrValidatorChain $validatorChain @return self
[ "Merges", "in", "logical", "or", "validator", "chain", "provided", "as", "argument", "." ]
train
https://github.com/jim-moser/zf2-validators-empty-or/blob/12f799e18ff59986c23ff3f934702834046438f2/src/VerboseOrChain.php#L684-L695
shipcore-nl/data-object
src/DataObject.php
DataObject.getRawType
private function getRawType(\ReflectionProperty $property) { $matches = []; if (preg_match('/@var\s+([^\s]+)/', $property->getDocComment(), $matches)) { list(, $rawType) = $matches; } else { $rawType = 'mixed'; } return $rawType; }
php
private function getRawType(\ReflectionProperty $property) { $matches = []; if (preg_match('/@var\s+([^\s]+)/', $property->getDocComment(), $matches)) { list(, $rawType) = $matches; } else { $rawType = 'mixed'; } return $rawType; }
[ "private", "function", "getRawType", "(", "\\", "ReflectionProperty", "$", "property", ")", "{", "$", "matches", "=", "[", "]", ";", "if", "(", "preg_match", "(", "'/@var\\s+([^\\s]+)/'", ",", "$", "property", "->", "getDocComment", "(", ")", ",", "$", "matches", ")", ")", "{", "list", "(", ",", "$", "rawType", ")", "=", "$", "matches", ";", "}", "else", "{", "$", "rawType", "=", "'mixed'", ";", "}", "return", "$", "rawType", ";", "}" ]
Returns raw string type format from the var annotation @param \ReflectionProperty $property @return string
[ "Returns", "raw", "string", "type", "format", "from", "the", "var", "annotation" ]
train
https://github.com/shipcore-nl/data-object/blob/ad7f43e63e0e149ddb0acaaad7b64466d81da6c6/src/DataObject.php#L80-L89
php-lug/lug
src/Bundle/ResourceBundle/Security/SecurityChecker.php
SecurityChecker.isGranted
public function isGranted($action, $object) { if (!$this->parameterResolver->resolveVoter()) { return true; } return $this->authorizationChecker->isGranted('lug.'.$action, $object); }
php
public function isGranted($action, $object) { if (!$this->parameterResolver->resolveVoter()) { return true; } return $this->authorizationChecker->isGranted('lug.'.$action, $object); }
[ "public", "function", "isGranted", "(", "$", "action", ",", "$", "object", ")", "{", "if", "(", "!", "$", "this", "->", "parameterResolver", "->", "resolveVoter", "(", ")", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "authorizationChecker", "->", "isGranted", "(", "'lug.'", ".", "$", "action", ",", "$", "object", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Security/SecurityChecker.php#L47-L54
WellCommerce/StandardEditionBundle
DataFixtures/ORM/LoadShopData.php
LoadShopData.load
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } /** * @var $theme \WellCommerce\Bundle\AppBundle\Entity\Theme * @var $company \WellCommerce\Bundle\AppBundle\Entity\Company */ $theme = $this->getReference('theme'); $company = $this->getReference('company'); $currency = $this->randomizeSamples('currency', LoadCurrencyData::$samples); $shop = new Shop(); $shop->setName('WellCommerce'); $shop->setCompany($company); $shop->setTheme($theme); $shop->setUrl('localhost'); $shop->setDefaultCountry('US'); $shop->setDefaultCurrency($currency->getCode()); $shop->setClientGroup($this->getReference('client_group')); $shop->getMinimumOrderAmount()->setCurrency($currency->getCode()); $shop->getMinimumOrderAmount()->setValue(0); $shop->setEnableClient(true); foreach ($this->getLocales() as $locale) { $shop->translate($locale->getCode())->getMeta()->setTitle('WellCommerce'); $shop->translate($locale->getCode())->getMeta()->setKeywords('e-commerce, open-source, symfony, framework, shop'); $shop->translate($locale->getCode())->getMeta()->setDescription('Modern e-commerce engine built on top of Symfony 3 full-stack framework'); } $shop->mergeNewTranslations(); $manager->persist($shop); $manager->flush(); $this->get('shop.storage')->setCurrentShop($shop); $this->setReference('shop', $shop); }
php
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } /** * @var $theme \WellCommerce\Bundle\AppBundle\Entity\Theme * @var $company \WellCommerce\Bundle\AppBundle\Entity\Company */ $theme = $this->getReference('theme'); $company = $this->getReference('company'); $currency = $this->randomizeSamples('currency', LoadCurrencyData::$samples); $shop = new Shop(); $shop->setName('WellCommerce'); $shop->setCompany($company); $shop->setTheme($theme); $shop->setUrl('localhost'); $shop->setDefaultCountry('US'); $shop->setDefaultCurrency($currency->getCode()); $shop->setClientGroup($this->getReference('client_group')); $shop->getMinimumOrderAmount()->setCurrency($currency->getCode()); $shop->getMinimumOrderAmount()->setValue(0); $shop->setEnableClient(true); foreach ($this->getLocales() as $locale) { $shop->translate($locale->getCode())->getMeta()->setTitle('WellCommerce'); $shop->translate($locale->getCode())->getMeta()->setKeywords('e-commerce, open-source, symfony, framework, shop'); $shop->translate($locale->getCode())->getMeta()->setDescription('Modern e-commerce engine built on top of Symfony 3 full-stack framework'); } $shop->mergeNewTranslations(); $manager->persist($shop); $manager->flush(); $this->get('shop.storage')->setCurrentShop($shop); $this->setReference('shop', $shop); }
[ "public", "function", "load", "(", "ObjectManager", "$", "manager", ")", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "return", ";", "}", "/**\n * @var $theme \\WellCommerce\\Bundle\\AppBundle\\Entity\\Theme\n * @var $company \\WellCommerce\\Bundle\\AppBundle\\Entity\\Company\n */", "$", "theme", "=", "$", "this", "->", "getReference", "(", "'theme'", ")", ";", "$", "company", "=", "$", "this", "->", "getReference", "(", "'company'", ")", ";", "$", "currency", "=", "$", "this", "->", "randomizeSamples", "(", "'currency'", ",", "LoadCurrencyData", "::", "$", "samples", ")", ";", "$", "shop", "=", "new", "Shop", "(", ")", ";", "$", "shop", "->", "setName", "(", "'WellCommerce'", ")", ";", "$", "shop", "->", "setCompany", "(", "$", "company", ")", ";", "$", "shop", "->", "setTheme", "(", "$", "theme", ")", ";", "$", "shop", "->", "setUrl", "(", "'localhost'", ")", ";", "$", "shop", "->", "setDefaultCountry", "(", "'US'", ")", ";", "$", "shop", "->", "setDefaultCurrency", "(", "$", "currency", "->", "getCode", "(", ")", ")", ";", "$", "shop", "->", "setClientGroup", "(", "$", "this", "->", "getReference", "(", "'client_group'", ")", ")", ";", "$", "shop", "->", "getMinimumOrderAmount", "(", ")", "->", "setCurrency", "(", "$", "currency", "->", "getCode", "(", ")", ")", ";", "$", "shop", "->", "getMinimumOrderAmount", "(", ")", "->", "setValue", "(", "0", ")", ";", "$", "shop", "->", "setEnableClient", "(", "true", ")", ";", "foreach", "(", "$", "this", "->", "getLocales", "(", ")", "as", "$", "locale", ")", "{", "$", "shop", "->", "translate", "(", "$", "locale", "->", "getCode", "(", ")", ")", "->", "getMeta", "(", ")", "->", "setTitle", "(", "'WellCommerce'", ")", ";", "$", "shop", "->", "translate", "(", "$", "locale", "->", "getCode", "(", ")", ")", "->", "getMeta", "(", ")", "->", "setKeywords", "(", "'e-commerce, open-source, symfony, framework, shop'", ")", ";", "$", "shop", "->", "translate", "(", "$", "locale", "->", "getCode", "(", ")", ")", "->", "getMeta", "(", ")", "->", "setDescription", "(", "'Modern e-commerce engine built on top of Symfony 3 full-stack framework'", ")", ";", "}", "$", "shop", "->", "mergeNewTranslations", "(", ")", ";", "$", "manager", "->", "persist", "(", "$", "shop", ")", ";", "$", "manager", "->", "flush", "(", ")", ";", "$", "this", "->", "get", "(", "'shop.storage'", ")", "->", "setCurrentShop", "(", "$", "shop", ")", ";", "$", "this", "->", "setReference", "(", "'shop'", ",", "$", "shop", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/WellCommerce/StandardEditionBundle/blob/6367bd20bbb6bde37c710a6ba87ae72b5f05f61e/DataFixtures/ORM/LoadShopData.php#L29-L67
panlatent/boost
src/BString.php
BString.convertCamel
public static function convertCamel($str, $separators = ['_', '-'], $delimiter = '') { $str = ucwords(str_replace($separators, ' ', $str)); return str_replace(' ', $delimiter, $str); }
php
public static function convertCamel($str, $separators = ['_', '-'], $delimiter = '') { $str = ucwords(str_replace($separators, ' ', $str)); return str_replace(' ', $delimiter, $str); }
[ "public", "static", "function", "convertCamel", "(", "$", "str", ",", "$", "separators", "=", "[", "'_'", ",", "'-'", "]", ",", "$", "delimiter", "=", "''", ")", "{", "$", "str", "=", "ucwords", "(", "str_replace", "(", "$", "separators", ",", "' '", ",", "$", "str", ")", ")", ";", "return", "str_replace", "(", "' '", ",", "$", "delimiter", ",", "$", "str", ")", ";", "}" ]
Convert a string to camel case. @param string $str @param array $separators @param string $delimiter @return string
[ "Convert", "a", "string", "to", "camel", "case", "." ]
train
https://github.com/panlatent/boost/blob/b0970118d15cda1edb2d9dc66f0b575ee9b00b2c/src/BString.php#L25-L30
panlatent/boost
src/BString.php
BString.convertSnake
public static function convertSnake($str, $delimiter = '_') { if (ctype_lower($str)) return $str; return strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $str)); }
php
public static function convertSnake($str, $delimiter = '_') { if (ctype_lower($str)) return $str; return strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $str)); }
[ "public", "static", "function", "convertSnake", "(", "$", "str", ",", "$", "delimiter", "=", "'_'", ")", "{", "if", "(", "ctype_lower", "(", "$", "str", ")", ")", "return", "$", "str", ";", "return", "strtolower", "(", "preg_replace", "(", "'/(.)(?=[A-Z])/'", ",", "'$1'", ".", "$", "delimiter", ",", "$", "str", ")", ")", ";", "}" ]
Convert a string to snake case. @param string $str @param string $delimiter @return string
[ "Convert", "a", "string", "to", "snake", "case", "." ]
train
https://github.com/panlatent/boost/blob/b0970118d15cda1edb2d9dc66f0b575ee9b00b2c/src/BString.php#L39-L44
panlatent/boost
src/BString.php
BString.random
public static function random($length = 6, $pool = self::RANDOM_POOL) { return substr(str_shuffle(str_repeat($pool, 5)), 0, $length); }
php
public static function random($length = 6, $pool = self::RANDOM_POOL) { return substr(str_shuffle(str_repeat($pool, 5)), 0, $length); }
[ "public", "static", "function", "random", "(", "$", "length", "=", "6", ",", "$", "pool", "=", "self", "::", "RANDOM_POOL", ")", "{", "return", "substr", "(", "str_shuffle", "(", "str_repeat", "(", "$", "pool", ",", "5", ")", ")", ",", "0", ",", "$", "length", ")", ";", "}" ]
Make a random string. @param int $length @param string $pool @return string
[ "Make", "a", "random", "string", "." ]
train
https://github.com/panlatent/boost/blob/b0970118d15cda1edb2d9dc66f0b575ee9b00b2c/src/BString.php#L53-L56
spiral-modules/listing
source/Listing/Filters/AbstractFilter.php
AbstractFilter.apply
public function apply($selector) { $this->validateSelector($selector); if ($selector instanceof RecordSelector) { $selector = $this->loadDependencies($selector); return $selector->where($this->whereClause($selector)); } return $selector->where($this->whereClause($selector)); }
php
public function apply($selector) { $this->validateSelector($selector); if ($selector instanceof RecordSelector) { $selector = $this->loadDependencies($selector); return $selector->where($this->whereClause($selector)); } return $selector->where($this->whereClause($selector)); }
[ "public", "function", "apply", "(", "$", "selector", ")", "{", "$", "this", "->", "validateSelector", "(", "$", "selector", ")", ";", "if", "(", "$", "selector", "instanceof", "RecordSelector", ")", "{", "$", "selector", "=", "$", "this", "->", "loadDependencies", "(", "$", "selector", ")", ";", "return", "$", "selector", "->", "where", "(", "$", "this", "->", "whereClause", "(", "$", "selector", ")", ")", ";", "}", "return", "$", "selector", "->", "where", "(", "$", "this", "->", "whereClause", "(", "$", "selector", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral-modules/listing/blob/89abe8939ce91cbf61b51b99e93ce1e57c8af83c/source/Listing/Filters/AbstractFilter.php#L22-L34
WellCommerce/AppBundle
CacheWarmer/TemplatePathsCacheWarmer.php
TemplatePathsCacheWarmer.warmUp
public function warmUp($cacheDir) { $locator = $this->locator->getLocator(); $allTemplates = $this->finder->findAllTemplates(); $templates = []; foreach ($allTemplates as $template) { $this->locateTemplate($locator, $template, $templates); } $this->writeCacheFile($cacheDir . '/templates.php', sprintf('<?php return %s;', var_export($templates, true))); }
php
public function warmUp($cacheDir) { $locator = $this->locator->getLocator(); $allTemplates = $this->finder->findAllTemplates(); $templates = []; foreach ($allTemplates as $template) { $this->locateTemplate($locator, $template, $templates); } $this->writeCacheFile($cacheDir . '/templates.php', sprintf('<?php return %s;', var_export($templates, true))); }
[ "public", "function", "warmUp", "(", "$", "cacheDir", ")", "{", "$", "locator", "=", "$", "this", "->", "locator", "->", "getLocator", "(", ")", ";", "$", "allTemplates", "=", "$", "this", "->", "finder", "->", "findAllTemplates", "(", ")", ";", "$", "templates", "=", "[", "]", ";", "foreach", "(", "$", "allTemplates", "as", "$", "template", ")", "{", "$", "this", "->", "locateTemplate", "(", "$", "locator", ",", "$", "template", ",", "$", "templates", ")", ";", "}", "$", "this", "->", "writeCacheFile", "(", "$", "cacheDir", ".", "'/templates.php'", ",", "sprintf", "(", "'<?php return %s;'", ",", "var_export", "(", "$", "templates", ",", "true", ")", ")", ")", ";", "}" ]
Warms up the cache. @param string $cacheDir The cache directory
[ "Warms", "up", "the", "cache", "." ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/CacheWarmer/TemplatePathsCacheWarmer.php#L40-L50
WellCommerce/AppBundle
CacheWarmer/TemplatePathsCacheWarmer.php
TemplatePathsCacheWarmer.locateTemplate
protected function locateTemplate(FileLocatorInterface $locator, TemplateReference $template, array &$templates) { $templates[$template->getLogicalName()] = $locator->locate($template->getPath()); }
php
protected function locateTemplate(FileLocatorInterface $locator, TemplateReference $template, array &$templates) { $templates[$template->getLogicalName()] = $locator->locate($template->getPath()); }
[ "protected", "function", "locateTemplate", "(", "FileLocatorInterface", "$", "locator", ",", "TemplateReference", "$", "template", ",", "array", "&", "$", "templates", ")", "{", "$", "templates", "[", "$", "template", "->", "getLogicalName", "(", ")", "]", "=", "$", "locator", "->", "locate", "(", "$", "template", "->", "getPath", "(", ")", ")", ";", "}" ]
Locates and appends template to an array @param FileLocatorInterface $locator @param TemplateReference $template @param array $templates
[ "Locates", "and", "appends", "template", "to", "an", "array" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/CacheWarmer/TemplatePathsCacheWarmer.php#L69-L72
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php
AreAllArgumentsValid.validate
public function validate($element) { $docBlock = $element->getDocBlock(); if (null === $docBlock) { throw new \UnexpectedValueException( 'A DocBlock should be present (and validated) before this validator can be applied' ); } if ($docBlock->hasTag('return')) { $returnTag = current($docBlock->getTagsByName('return')); if ($returnTag->getType() == 'type') { return new Error(LogLevel::WARNING, 'PPC:ERR-50017', $element->getLinenumber()); } } return null; }
php
public function validate($element) { $docBlock = $element->getDocBlock(); if (null === $docBlock) { throw new \UnexpectedValueException( 'A DocBlock should be present (and validated) before this validator can be applied' ); } if ($docBlock->hasTag('return')) { $returnTag = current($docBlock->getTagsByName('return')); if ($returnTag->getType() == 'type') { return new Error(LogLevel::WARNING, 'PPC:ERR-50017', $element->getLinenumber()); } } return null; }
[ "public", "function", "validate", "(", "$", "element", ")", "{", "$", "docBlock", "=", "$", "element", "->", "getDocBlock", "(", ")", ";", "if", "(", "null", "===", "$", "docBlock", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'A DocBlock should be present (and validated) before this validator can be applied'", ")", ";", "}", "if", "(", "$", "docBlock", "->", "hasTag", "(", "'return'", ")", ")", "{", "$", "returnTag", "=", "current", "(", "$", "docBlock", "->", "getTagsByName", "(", "'return'", ")", ")", ";", "if", "(", "$", "returnTag", "->", "getType", "(", ")", "==", "'type'", ")", "{", "return", "new", "Error", "(", "LogLevel", "::", "WARNING", ",", "'PPC:ERR-50017'", ",", "$", "element", "->", "getLinenumber", "(", ")", ")", ";", "}", "}", "return", "null", ";", "}" ]
Validates whether the given Reflector's arguments match the business rules of phpDocumentor. @param BaseReflector $element @throws \UnexpectedValueException if no DocBlock is associated with the given Reflector. @return Error|null
[ "Validates", "whether", "the", "given", "Reflector", "s", "arguments", "match", "the", "business", "rules", "of", "phpDocumentor", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php#L36-L53
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php
AreAllArgumentsValid.validateArguments
protected function validateArguments($element) { $params = $element->getDocBlock()->getTagsByName('param'); $arguments = $element->getArguments(); foreach (array_values($arguments) as $key => $argument) { if (!$this->isArgumentInDocBlock($key, $argument, $element, $params)) { continue; } $result = $this->doesArgumentNameMatchParam($params[$key], $argument, $element); if ($result) { return $result; } $result = $this->doesArgumentTypehintMatchParam($params[$key], $argument, $element); if ($result) { return $result; } } /** @var ParamTag $param */ foreach ($params as $param) { $param_name = $param->getVariableName(); if (isset($arguments[$param_name])) { continue; } return new Error( LogLevel::NOTICE, 'PPC:ERR-50013', $element->getLinenumber(), array($param_name, $element->getName()) ); } return null; }
php
protected function validateArguments($element) { $params = $element->getDocBlock()->getTagsByName('param'); $arguments = $element->getArguments(); foreach (array_values($arguments) as $key => $argument) { if (!$this->isArgumentInDocBlock($key, $argument, $element, $params)) { continue; } $result = $this->doesArgumentNameMatchParam($params[$key], $argument, $element); if ($result) { return $result; } $result = $this->doesArgumentTypehintMatchParam($params[$key], $argument, $element); if ($result) { return $result; } } /** @var ParamTag $param */ foreach ($params as $param) { $param_name = $param->getVariableName(); if (isset($arguments[$param_name])) { continue; } return new Error( LogLevel::NOTICE, 'PPC:ERR-50013', $element->getLinenumber(), array($param_name, $element->getName()) ); } return null; }
[ "protected", "function", "validateArguments", "(", "$", "element", ")", "{", "$", "params", "=", "$", "element", "->", "getDocBlock", "(", ")", "->", "getTagsByName", "(", "'param'", ")", ";", "$", "arguments", "=", "$", "element", "->", "getArguments", "(", ")", ";", "foreach", "(", "array_values", "(", "$", "arguments", ")", "as", "$", "key", "=>", "$", "argument", ")", "{", "if", "(", "!", "$", "this", "->", "isArgumentInDocBlock", "(", "$", "key", ",", "$", "argument", ",", "$", "element", ",", "$", "params", ")", ")", "{", "continue", ";", "}", "$", "result", "=", "$", "this", "->", "doesArgumentNameMatchParam", "(", "$", "params", "[", "$", "key", "]", ",", "$", "argument", ",", "$", "element", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "$", "result", "=", "$", "this", "->", "doesArgumentTypehintMatchParam", "(", "$", "params", "[", "$", "key", "]", ",", "$", "argument", ",", "$", "element", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "}", "/** @var ParamTag $param */", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "$", "param_name", "=", "$", "param", "->", "getVariableName", "(", ")", ";", "if", "(", "isset", "(", "$", "arguments", "[", "$", "param_name", "]", ")", ")", "{", "continue", ";", "}", "return", "new", "Error", "(", "LogLevel", "::", "NOTICE", ",", "'PPC:ERR-50013'", ",", "$", "element", "->", "getLinenumber", "(", ")", ",", "array", "(", "$", "param_name", ",", "$", "element", "->", "getName", "(", ")", ")", ")", ";", "}", "return", "null", ";", "}" ]
Returns an error if the given Reflector's arguments do not match expectations. @param FunctionReflector $element @return Error|null
[ "Returns", "an", "error", "if", "the", "given", "Reflector", "s", "arguments", "do", "not", "match", "expectations", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php#L62-L100
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php
AreAllArgumentsValid.isArgumentInDocBlock
protected function isArgumentInDocBlock($index, ArgumentReflector $argument, BaseReflector $element, array $params) { if (isset($params[$index])) { return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50015', $argument->getLinenumber(), array($argument->getName(), $element->getName()) ); }
php
protected function isArgumentInDocBlock($index, ArgumentReflector $argument, BaseReflector $element, array $params) { if (isset($params[$index])) { return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50015', $argument->getLinenumber(), array($argument->getName(), $element->getName()) ); }
[ "protected", "function", "isArgumentInDocBlock", "(", "$", "index", ",", "ArgumentReflector", "$", "argument", ",", "BaseReflector", "$", "element", ",", "array", "$", "params", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "$", "index", "]", ")", ")", "{", "return", "null", ";", "}", "return", "new", "Error", "(", "LogLevel", "::", "ERROR", ",", "'PPC:ERR-50015'", ",", "$", "argument", "->", "getLinenumber", "(", ")", ",", "array", "(", "$", "argument", "->", "getName", "(", ")", ",", "$", "element", "->", "getName", "(", ")", ")", ")", ";", "}" ]
Validates whether an argument is mentioned in the docblock. @param integer $index The position in the argument listing. @param ArgumentReflector $argument The argument itself. @param BaseReflector $element @param Tag[] $params The list of param tags to validate against. @return bool whether an issue occurred.
[ "Validates", "whether", "an", "argument", "is", "mentioned", "in", "the", "docblock", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php#L112-L124
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php
AreAllArgumentsValid.doesArgumentNameMatchParam
protected function doesArgumentNameMatchParam(ParamTag $param, ArgumentReflector $argument, BaseReflector $element) { $param_name = $param->getVariableName(); if ($param_name == $argument->getName()) { return null; } if ($param_name == '') { $param->setVariableName($argument->getName()); return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50014', $argument->getLinenumber(), array($argument->getName(), $param_name, $element->getName()) ); }
php
protected function doesArgumentNameMatchParam(ParamTag $param, ArgumentReflector $argument, BaseReflector $element) { $param_name = $param->getVariableName(); if ($param_name == $argument->getName()) { return null; } if ($param_name == '') { $param->setVariableName($argument->getName()); return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50014', $argument->getLinenumber(), array($argument->getName(), $param_name, $element->getName()) ); }
[ "protected", "function", "doesArgumentNameMatchParam", "(", "ParamTag", "$", "param", ",", "ArgumentReflector", "$", "argument", ",", "BaseReflector", "$", "element", ")", "{", "$", "param_name", "=", "$", "param", "->", "getVariableName", "(", ")", ";", "if", "(", "$", "param_name", "==", "$", "argument", "->", "getName", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "param_name", "==", "''", ")", "{", "$", "param", "->", "setVariableName", "(", "$", "argument", "->", "getName", "(", ")", ")", ";", "return", "null", ";", "}", "return", "new", "Error", "(", "LogLevel", "::", "ERROR", ",", "'PPC:ERR-50014'", ",", "$", "argument", "->", "getLinenumber", "(", ")", ",", "array", "(", "$", "argument", "->", "getName", "(", ")", ",", "$", "param_name", ",", "$", "element", "->", "getName", "(", ")", ")", ")", ";", "}" ]
Validates whether the name of the argument is the same as that of the param tag. If the param tag does not contain a name then this method will set it based on the argument. @param ParamTag $param param to validate with. @param ArgumentReflector $argument Argument to validate against. @param BaseReflector $element @return Error|null whether an issue occurred
[ "Validates", "whether", "the", "name", "of", "the", "argument", "is", "the", "same", "as", "that", "of", "the", "param", "tag", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php#L139-L158
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php
AreAllArgumentsValid.doesArgumentTypehintMatchParam
protected function doesArgumentTypehintMatchParam( ParamTag $param, ArgumentReflector $argument, BaseReflector $element ) { if (!$argument->getType() || in_array($argument->getType(), $param->getTypes())) { return null; } elseif ($argument->getType() == 'array' && substr($param->getType(), -2) == '[]') { return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50016', $argument->getLinenumber(), array($argument->getName(), $element->getName()) ); }
php
protected function doesArgumentTypehintMatchParam( ParamTag $param, ArgumentReflector $argument, BaseReflector $element ) { if (!$argument->getType() || in_array($argument->getType(), $param->getTypes())) { return null; } elseif ($argument->getType() == 'array' && substr($param->getType(), -2) == '[]') { return null; } return new Error( LogLevel::ERROR, 'PPC:ERR-50016', $argument->getLinenumber(), array($argument->getName(), $element->getName()) ); }
[ "protected", "function", "doesArgumentTypehintMatchParam", "(", "ParamTag", "$", "param", ",", "ArgumentReflector", "$", "argument", ",", "BaseReflector", "$", "element", ")", "{", "if", "(", "!", "$", "argument", "->", "getType", "(", ")", "||", "in_array", "(", "$", "argument", "->", "getType", "(", ")", ",", "$", "param", "->", "getTypes", "(", ")", ")", ")", "{", "return", "null", ";", "}", "elseif", "(", "$", "argument", "->", "getType", "(", ")", "==", "'array'", "&&", "substr", "(", "$", "param", "->", "getType", "(", ")", ",", "-", "2", ")", "==", "'[]'", ")", "{", "return", "null", ";", "}", "return", "new", "Error", "(", "LogLevel", "::", "ERROR", ",", "'PPC:ERR-50016'", ",", "$", "argument", "->", "getLinenumber", "(", ")", ",", "array", "(", "$", "argument", "->", "getName", "(", ")", ",", "$", "element", "->", "getName", "(", ")", ")", ")", ";", "}" ]
Checks the typehint of the argument versus the @param tag. If the argument has no typehint we do not check anything. When multiple type are given then the typehint needs to be one of them. @param ParamTag $param @param ArgumentReflector $argument @param BaseReflector $element @return Error|null
[ "Checks", "the", "typehint", "of", "the", "argument", "versus", "the", "@param", "tag", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Functions/AreAllArgumentsValid.php#L172-L189
antaresproject/notifications
src/Http/Datatables/Notifications.php
Notifications.ajax
public function ajax() { $acl = app('antares.acl')->make('antares/notifications'); $canUpdate = $acl->can('notifications-edit'); $canTest = $acl->can('notifications-test'); $canChangeStatus = $acl->can('notifications-change-status'); $canDelete = $acl->can('notifications-delete'); return $this->prepare() ->filter(function ($query) { $request = app('request'); $keyword = array_get($request->get('search'), 'value'); if (is_null($keyword) or is_null($keyword)) { return; } $query ->leftJoin('tbl_notification_categories', 'tbl_notifications.category_id', '=', 'tbl_notification_categories.id') ->leftJoin('tbl_notification_contents', 'tbl_notifications.id', '=', 'tbl_notification_contents.notification_id'); $columns = request()->get('columns'); $typeId = null; $categoryId = null; array_walk($columns, function($item, $index) use(&$typeId, &$categoryId) { if (array_get($item, 'data') == 'type') { $typeId = array_get($item, 'search.value'); } if (array_get($item, 'data') == 'category') { $categoryId = array_get($item, 'search.value'); } return false; }); if (!$categoryId) { $categoryId = NotificationCategory::where('name', 'default')->first()->id; } $query->where('category_id', $categoryId); if (!$typeId) { $typeId = NotificationTypes::where('name', 'email')->first()->id; } $query->where('type_id', $typeId); if ($keyword !== '') { $query->whereRaw("(tbl_notification_contents.title like '%$keyword%' or tbl_notification_categories.title like '%$keyword%')"); } $query->groupBy('tbl_notification_contents.notification_id'); }) ->filterColumn('type', function($query, $keyword) { $query->where('type_id', $keyword); }) ->filterColumn('category', function($query, $keyword) { $columns = request()->get('columns'); $search = null; array_walk($columns, function($item, $index) use(&$search) { if (array_get($item, 'data') == 'type') { $search = array_get($item, 'search.value'); return; } return false; }); if (!$search) { $typeId = NotificationTypes::where('name', 'email')->first()->id; $query->where('type_id', $typeId); } $query->where('category_id', $keyword); }) ->editColumn('category', function ($model) { return $model->category->title; }) ->editColumn('type', function ($model) { return $model->type->title; }) ->editColumn('title', function ($model) { $first = $model->contents->first(); return !is_null($first) ? $first->title : ''; }) ->editColumn('active', function ($model) { return ((int) $model->active) ? '<span class="label-basic label-basic--success">' . trans('Yes') . '</span>' : '<span class="label-basic label-basic--danger">' . trans('No') . '</span>'; }) ->addColumn('action', $this->getActionsColumn($canUpdate, $canTest, $canChangeStatus, $canDelete)) ->make(true); }
php
public function ajax() { $acl = app('antares.acl')->make('antares/notifications'); $canUpdate = $acl->can('notifications-edit'); $canTest = $acl->can('notifications-test'); $canChangeStatus = $acl->can('notifications-change-status'); $canDelete = $acl->can('notifications-delete'); return $this->prepare() ->filter(function ($query) { $request = app('request'); $keyword = array_get($request->get('search'), 'value'); if (is_null($keyword) or is_null($keyword)) { return; } $query ->leftJoin('tbl_notification_categories', 'tbl_notifications.category_id', '=', 'tbl_notification_categories.id') ->leftJoin('tbl_notification_contents', 'tbl_notifications.id', '=', 'tbl_notification_contents.notification_id'); $columns = request()->get('columns'); $typeId = null; $categoryId = null; array_walk($columns, function($item, $index) use(&$typeId, &$categoryId) { if (array_get($item, 'data') == 'type') { $typeId = array_get($item, 'search.value'); } if (array_get($item, 'data') == 'category') { $categoryId = array_get($item, 'search.value'); } return false; }); if (!$categoryId) { $categoryId = NotificationCategory::where('name', 'default')->first()->id; } $query->where('category_id', $categoryId); if (!$typeId) { $typeId = NotificationTypes::where('name', 'email')->first()->id; } $query->where('type_id', $typeId); if ($keyword !== '') { $query->whereRaw("(tbl_notification_contents.title like '%$keyword%' or tbl_notification_categories.title like '%$keyword%')"); } $query->groupBy('tbl_notification_contents.notification_id'); }) ->filterColumn('type', function($query, $keyword) { $query->where('type_id', $keyword); }) ->filterColumn('category', function($query, $keyword) { $columns = request()->get('columns'); $search = null; array_walk($columns, function($item, $index) use(&$search) { if (array_get($item, 'data') == 'type') { $search = array_get($item, 'search.value'); return; } return false; }); if (!$search) { $typeId = NotificationTypes::where('name', 'email')->first()->id; $query->where('type_id', $typeId); } $query->where('category_id', $keyword); }) ->editColumn('category', function ($model) { return $model->category->title; }) ->editColumn('type', function ($model) { return $model->type->title; }) ->editColumn('title', function ($model) { $first = $model->contents->first(); return !is_null($first) ? $first->title : ''; }) ->editColumn('active', function ($model) { return ((int) $model->active) ? '<span class="label-basic label-basic--success">' . trans('Yes') . '</span>' : '<span class="label-basic label-basic--danger">' . trans('No') . '</span>'; }) ->addColumn('action', $this->getActionsColumn($canUpdate, $canTest, $canChangeStatus, $canDelete)) ->make(true); }
[ "public", "function", "ajax", "(", ")", "{", "$", "acl", "=", "app", "(", "'antares.acl'", ")", "->", "make", "(", "'antares/notifications'", ")", ";", "$", "canUpdate", "=", "$", "acl", "->", "can", "(", "'notifications-edit'", ")", ";", "$", "canTest", "=", "$", "acl", "->", "can", "(", "'notifications-test'", ")", ";", "$", "canChangeStatus", "=", "$", "acl", "->", "can", "(", "'notifications-change-status'", ")", ";", "$", "canDelete", "=", "$", "acl", "->", "can", "(", "'notifications-delete'", ")", ";", "return", "$", "this", "->", "prepare", "(", ")", "->", "filter", "(", "function", "(", "$", "query", ")", "{", "$", "request", "=", "app", "(", "'request'", ")", ";", "$", "keyword", "=", "array_get", "(", "$", "request", "->", "get", "(", "'search'", ")", ",", "'value'", ")", ";", "if", "(", "is_null", "(", "$", "keyword", ")", "or", "is_null", "(", "$", "keyword", ")", ")", "{", "return", ";", "}", "$", "query", "->", "leftJoin", "(", "'tbl_notification_categories'", ",", "'tbl_notifications.category_id'", ",", "'='", ",", "'tbl_notification_categories.id'", ")", "->", "leftJoin", "(", "'tbl_notification_contents'", ",", "'tbl_notifications.id'", ",", "'='", ",", "'tbl_notification_contents.notification_id'", ")", ";", "$", "columns", "=", "request", "(", ")", "->", "get", "(", "'columns'", ")", ";", "$", "typeId", "=", "null", ";", "$", "categoryId", "=", "null", ";", "array_walk", "(", "$", "columns", ",", "function", "(", "$", "item", ",", "$", "index", ")", "use", "(", "&", "$", "typeId", ",", "&", "$", "categoryId", ")", "{", "if", "(", "array_get", "(", "$", "item", ",", "'data'", ")", "==", "'type'", ")", "{", "$", "typeId", "=", "array_get", "(", "$", "item", ",", "'search.value'", ")", ";", "}", "if", "(", "array_get", "(", "$", "item", ",", "'data'", ")", "==", "'category'", ")", "{", "$", "categoryId", "=", "array_get", "(", "$", "item", ",", "'search.value'", ")", ";", "}", "return", "false", ";", "}", ")", ";", "if", "(", "!", "$", "categoryId", ")", "{", "$", "categoryId", "=", "NotificationCategory", "::", "where", "(", "'name'", ",", "'default'", ")", "->", "first", "(", ")", "->", "id", ";", "}", "$", "query", "->", "where", "(", "'category_id'", ",", "$", "categoryId", ")", ";", "if", "(", "!", "$", "typeId", ")", "{", "$", "typeId", "=", "NotificationTypes", "::", "where", "(", "'name'", ",", "'email'", ")", "->", "first", "(", ")", "->", "id", ";", "}", "$", "query", "->", "where", "(", "'type_id'", ",", "$", "typeId", ")", ";", "if", "(", "$", "keyword", "!==", "''", ")", "{", "$", "query", "->", "whereRaw", "(", "\"(tbl_notification_contents.title like '%$keyword%' or tbl_notification_categories.title like '%$keyword%')\"", ")", ";", "}", "$", "query", "->", "groupBy", "(", "'tbl_notification_contents.notification_id'", ")", ";", "}", ")", "->", "filterColumn", "(", "'type'", ",", "function", "(", "$", "query", ",", "$", "keyword", ")", "{", "$", "query", "->", "where", "(", "'type_id'", ",", "$", "keyword", ")", ";", "}", ")", "->", "filterColumn", "(", "'category'", ",", "function", "(", "$", "query", ",", "$", "keyword", ")", "{", "$", "columns", "=", "request", "(", ")", "->", "get", "(", "'columns'", ")", ";", "$", "search", "=", "null", ";", "array_walk", "(", "$", "columns", ",", "function", "(", "$", "item", ",", "$", "index", ")", "use", "(", "&", "$", "search", ")", "{", "if", "(", "array_get", "(", "$", "item", ",", "'data'", ")", "==", "'type'", ")", "{", "$", "search", "=", "array_get", "(", "$", "item", ",", "'search.value'", ")", ";", "return", ";", "}", "return", "false", ";", "}", ")", ";", "if", "(", "!", "$", "search", ")", "{", "$", "typeId", "=", "NotificationTypes", "::", "where", "(", "'name'", ",", "'email'", ")", "->", "first", "(", ")", "->", "id", ";", "$", "query", "->", "where", "(", "'type_id'", ",", "$", "typeId", ")", ";", "}", "$", "query", "->", "where", "(", "'category_id'", ",", "$", "keyword", ")", ";", "}", ")", "->", "editColumn", "(", "'category'", ",", "function", "(", "$", "model", ")", "{", "return", "$", "model", "->", "category", "->", "title", ";", "}", ")", "->", "editColumn", "(", "'type'", ",", "function", "(", "$", "model", ")", "{", "return", "$", "model", "->", "type", "->", "title", ";", "}", ")", "->", "editColumn", "(", "'title'", ",", "function", "(", "$", "model", ")", "{", "$", "first", "=", "$", "model", "->", "contents", "->", "first", "(", ")", ";", "return", "!", "is_null", "(", "$", "first", ")", "?", "$", "first", "->", "title", ":", "''", ";", "}", ")", "->", "editColumn", "(", "'active'", ",", "function", "(", "$", "model", ")", "{", "return", "(", "(", "int", ")", "$", "model", "->", "active", ")", "?", "'<span class=\"label-basic label-basic--success\">'", ".", "trans", "(", "'Yes'", ")", ".", "'</span>'", ":", "'<span class=\"label-basic label-basic--danger\">'", ".", "trans", "(", "'No'", ")", ".", "'</span>'", ";", "}", ")", "->", "addColumn", "(", "'action'", ",", "$", "this", "->", "getActionsColumn", "(", "$", "canUpdate", ",", "$", "canTest", ",", "$", "canChangeStatus", ",", "$", "canDelete", ")", ")", "->", "make", "(", "true", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Notifications.php#L63-L143
antaresproject/notifications
src/Http/Datatables/Notifications.php
Notifications.html
public function html() { publish('notifications', ['js/notifications-table.js']); return $this->setName('Notifications List') ->addColumn(['data' => 'id', 'name' => 'id', 'data' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'title', 'name' => 'title', 'title' => trans('antares/notifications::messages.title'), 'className' => 'bolded']) ->addColumn(['data' => 'event', 'name' => 'event', 'title' => trans('Event')]) ->addColumn(['data' => 'category', 'name' => 'category', 'title' => trans('Category')]) ->addColumn(['data' => 'type', 'name' => 'type', 'title' => trans('Type')]) ->addColumn(['data' => 'active', 'name' => 'active', 'title' => trans('Enabled')]) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->setDeferedData() ->addGroupSelect($this->categories(), 3, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_category'), 'class' => 'mr24', 'id' => 'datatables-notification-category']) ->addGroupSelect($this->types(), 4, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_type'), 'class' => 'mr24', 'id' => 'datatables-notification-type']); }
php
public function html() { publish('notifications', ['js/notifications-table.js']); return $this->setName('Notifications List') ->addColumn(['data' => 'id', 'name' => 'id', 'data' => 'id', 'title' => 'Id']) ->addColumn(['data' => 'title', 'name' => 'title', 'title' => trans('antares/notifications::messages.title'), 'className' => 'bolded']) ->addColumn(['data' => 'event', 'name' => 'event', 'title' => trans('Event')]) ->addColumn(['data' => 'category', 'name' => 'category', 'title' => trans('Category')]) ->addColumn(['data' => 'type', 'name' => 'type', 'title' => trans('Type')]) ->addColumn(['data' => 'active', 'name' => 'active', 'title' => trans('Enabled')]) ->addAction(['name' => 'edit', 'title' => '', 'class' => 'mass-actions dt-actions', 'orderable' => false, 'searchable' => false]) ->setDeferedData() ->addGroupSelect($this->categories(), 3, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_category'), 'class' => 'mr24', 'id' => 'datatables-notification-category']) ->addGroupSelect($this->types(), 4, null, ['data-prefix' => trans('antares/notifications::messages.datatables.select_type'), 'class' => 'mr24', 'id' => 'datatables-notification-type']); }
[ "public", "function", "html", "(", ")", "{", "publish", "(", "'notifications'", ",", "[", "'js/notifications-table.js'", "]", ")", ";", "return", "$", "this", "->", "setName", "(", "'Notifications List'", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'id'", ",", "'name'", "=>", "'id'", ",", "'data'", "=>", "'id'", ",", "'title'", "=>", "'Id'", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'title'", ",", "'name'", "=>", "'title'", ",", "'title'", "=>", "trans", "(", "'antares/notifications::messages.title'", ")", ",", "'className'", "=>", "'bolded'", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'event'", ",", "'name'", "=>", "'event'", ",", "'title'", "=>", "trans", "(", "'Event'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'category'", ",", "'name'", "=>", "'category'", ",", "'title'", "=>", "trans", "(", "'Category'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'type'", ",", "'name'", "=>", "'type'", ",", "'title'", "=>", "trans", "(", "'Type'", ")", "]", ")", "->", "addColumn", "(", "[", "'data'", "=>", "'active'", ",", "'name'", "=>", "'active'", ",", "'title'", "=>", "trans", "(", "'Enabled'", ")", "]", ")", "->", "addAction", "(", "[", "'name'", "=>", "'edit'", ",", "'title'", "=>", "''", ",", "'class'", "=>", "'mass-actions dt-actions'", ",", "'orderable'", "=>", "false", ",", "'searchable'", "=>", "false", "]", ")", "->", "setDeferedData", "(", ")", "->", "addGroupSelect", "(", "$", "this", "->", "categories", "(", ")", ",", "3", ",", "null", ",", "[", "'data-prefix'", "=>", "trans", "(", "'antares/notifications::messages.datatables.select_category'", ")", ",", "'class'", "=>", "'mr24'", ",", "'id'", "=>", "'datatables-notification-category'", "]", ")", "->", "addGroupSelect", "(", "$", "this", "->", "types", "(", ")", ",", "4", ",", "null", ",", "[", "'data-prefix'", "=>", "trans", "(", "'antares/notifications::messages.datatables.select_type'", ")", ",", "'class'", "=>", "'mr24'", ",", "'id'", "=>", "'datatables-notification-type'", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Notifications.php#L148-L162
antaresproject/notifications
src/Http/Datatables/Notifications.php
Notifications.getActionsColumn
protected function getActionsColumn($canUpdate, $canTest, $canChangeStatus, $canDelete) { return function ($row) use($canUpdate, $canTest, $canChangeStatus, $canDelete) { $btns = []; $html = app('html'); if ($canUpdate) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/edit/" . $row->id), trans('Edit'), ['data-icon' => 'edit'])); } if ($canChangeStatus) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/changeStatus/" . $row->id), $row->active ? trans('Disable') : trans('Enable'), ['class' => "triggerable confirm", 'data-icon' => $row->active ? 'minus-circle' : 'check-circle', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Changing status of notification') . ' #' . $row->contents[0]->title])); } if ($canTest && in_array($row->type->name, ['email', 'sms'])) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/sendtest/" . $row->id), trans('Send preview'), ['class' => "triggerable confirm", 'data-icon' => 'desktop-windows', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Sending preview notification with item') . ' #' . $row->contents[0]->title])); } if ($canDelete and $row->event == config('antares/notifications::default.custom_event')) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting item #') . ' #' . $row->id])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
php
protected function getActionsColumn($canUpdate, $canTest, $canChangeStatus, $canDelete) { return function ($row) use($canUpdate, $canTest, $canChangeStatus, $canDelete) { $btns = []; $html = app('html'); if ($canUpdate) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/edit/" . $row->id), trans('Edit'), ['data-icon' => 'edit'])); } if ($canChangeStatus) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/changeStatus/" . $row->id), $row->active ? trans('Disable') : trans('Enable'), ['class' => "triggerable confirm", 'data-icon' => $row->active ? 'minus-circle' : 'check-circle', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Changing status of notification') . ' #' . $row->contents[0]->title])); } if ($canTest && in_array($row->type->name, ['email', 'sms'])) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/sendtest/" . $row->id), trans('Send preview'), ['class' => "triggerable confirm", 'data-icon' => 'desktop-windows', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Sending preview notification with item') . ' #' . $row->contents[0]->title])); } if ($canDelete and $row->event == config('antares/notifications::default.custom_event')) { $btns[] = $html->create('li', $html->link(handles("antares::notifications/delete/" . $row->id), trans('Delete'), ['class' => "triggerable confirm", 'data-icon' => 'delete', 'data-title' => trans("Are you sure?"), 'data-description' => trans('Deleting item #') . ' #' . $row->id])); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
[ "protected", "function", "getActionsColumn", "(", "$", "canUpdate", ",", "$", "canTest", ",", "$", "canChangeStatus", ",", "$", "canDelete", ")", "{", "return", "function", "(", "$", "row", ")", "use", "(", "$", "canUpdate", ",", "$", "canTest", ",", "$", "canChangeStatus", ",", "$", "canDelete", ")", "{", "$", "btns", "=", "[", "]", ";", "$", "html", "=", "app", "(", "'html'", ")", ";", "if", "(", "$", "canUpdate", ")", "{", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/edit/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'Edit'", ")", ",", "[", "'data-icon'", "=>", "'edit'", "]", ")", ")", ";", "}", "if", "(", "$", "canChangeStatus", ")", "{", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/changeStatus/\"", ".", "$", "row", "->", "id", ")", ",", "$", "row", "->", "active", "?", "trans", "(", "'Disable'", ")", ":", "trans", "(", "'Enable'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm\"", ",", "'data-icon'", "=>", "$", "row", "->", "active", "?", "'minus-circle'", ":", "'check-circle'", ",", "'data-title'", "=>", "trans", "(", "\"Are you sure?\"", ")", ",", "'data-description'", "=>", "trans", "(", "'Changing status of notification'", ")", ".", "' #'", ".", "$", "row", "->", "contents", "[", "0", "]", "->", "title", "]", ")", ")", ";", "}", "if", "(", "$", "canTest", "&&", "in_array", "(", "$", "row", "->", "type", "->", "name", ",", "[", "'email'", ",", "'sms'", "]", ")", ")", "{", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/sendtest/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'Send preview'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm\"", ",", "'data-icon'", "=>", "'desktop-windows'", ",", "'data-title'", "=>", "trans", "(", "\"Are you sure?\"", ")", ",", "'data-description'", "=>", "trans", "(", "'Sending preview notification with item'", ")", ".", "' #'", ".", "$", "row", "->", "contents", "[", "0", "]", "->", "title", "]", ")", ")", ";", "}", "if", "(", "$", "canDelete", "and", "$", "row", "->", "event", "==", "config", "(", "'antares/notifications::default.custom_event'", ")", ")", "{", "$", "btns", "[", "]", "=", "$", "html", "->", "create", "(", "'li'", ",", "$", "html", "->", "link", "(", "handles", "(", "\"antares::notifications/delete/\"", ".", "$", "row", "->", "id", ")", ",", "trans", "(", "'Delete'", ")", ",", "[", "'class'", "=>", "\"triggerable confirm\"", ",", "'data-icon'", "=>", "'delete'", ",", "'data-title'", "=>", "trans", "(", "\"Are you sure?\"", ")", ",", "'data-description'", "=>", "trans", "(", "'Deleting item #'", ")", ".", "' #'", ".", "$", "row", "->", "id", "]", ")", ")", ";", "}", "if", "(", "empty", "(", "$", "btns", ")", ")", "{", "return", "''", ";", "}", "$", "section", "=", "$", "html", "->", "create", "(", "'div'", ",", "$", "html", "->", "create", "(", "'section'", ",", "$", "html", "->", "create", "(", "'ul'", ",", "$", "html", "->", "raw", "(", "implode", "(", "''", ",", "$", "btns", ")", ")", ")", ")", ",", "[", "'class'", "=>", "'mass-actions-menu'", "]", ")", "->", "get", "(", ")", ";", "return", "'<i class=\"zmdi zmdi-more\"></i>'", ".", "$", "html", "->", "raw", "(", "$", "section", ")", "->", "get", "(", ")", ";", "}", ";", "}" ]
Get actions column for table builder. @return callable
[ "Get", "actions", "column", "for", "table", "builder", "." ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Http/Datatables/Notifications.php#L188-L215
wenbinye/PhalconX
src/Mvc/SimpleModel.php
SimpleModel.assign
public function assign($attrs) { foreach ($attrs as $key => $val) { if (property_exists($this, $key)) { $this->$key = $val; } } }
php
public function assign($attrs) { foreach ($attrs as $key => $val) { if (property_exists($this, $key)) { $this->$key = $val; } } }
[ "public", "function", "assign", "(", "$", "attrs", ")", "{", "foreach", "(", "$", "attrs", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "property_exists", "(", "$", "this", ",", "$", "key", ")", ")", "{", "$", "this", "->", "$", "key", "=", "$", "val", ";", "}", "}", "}" ]
Updates attributes
[ "Updates", "attributes" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/SimpleModel.php#L28-L35
nabab/bbn
src/bbn/mvc/common.php
common.check_path
private function check_path(){ $ar = \func_get_args(); foreach ( $ar as $a ){ $b = bbn\str::parse_path($a, true); if ( empty($b) && !empty($a) ){ $this->error("The path $a is not an acceptable value"); return false; } } return 1; }
php
private function check_path(){ $ar = \func_get_args(); foreach ( $ar as $a ){ $b = bbn\str::parse_path($a, true); if ( empty($b) && !empty($a) ){ $this->error("The path $a is not an acceptable value"); return false; } } return 1; }
[ "private", "function", "check_path", "(", ")", "{", "$", "ar", "=", "\\", "func_get_args", "(", ")", ";", "foreach", "(", "$", "ar", "as", "$", "a", ")", "{", "$", "b", "=", "bbn", "\\", "str", "::", "parse_path", "(", "$", "a", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "b", ")", "&&", "!", "empty", "(", "$", "a", ")", ")", "{", "$", "this", "->", "error", "(", "\"The path $a is not an acceptable value\"", ")", ";", "return", "false", ";", "}", "}", "return", "1", ";", "}" ]
This checks whether an argument used for getting controller, view or model - which are files - doesn't contain malicious content. @param string $p The request path <em>(e.g books/466565 or html/home)</em> @return bool
[ "This", "checks", "whether", "an", "argument", "used", "for", "getting", "controller", "view", "or", "model", "-", "which", "are", "files", "-", "doesn", "t", "contain", "malicious", "content", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc/common.php#L21-L31
ezsystems/ezcomments-ls-extension
classes/ezcomsubscriber.php
ezcomSubscriber.fetchByEmail
static function fetchByEmail( $email ) { $cond = array( 'email' => $email ); $return = eZPersistentObject::fetchObject( self::definition(), null, $cond ); return $return; }
php
static function fetchByEmail( $email ) { $cond = array( 'email' => $email ); $return = eZPersistentObject::fetchObject( self::definition(), null, $cond ); return $return; }
[ "static", "function", "fetchByEmail", "(", "$", "email", ")", "{", "$", "cond", "=", "array", "(", "'email'", "=>", "$", "email", ")", ";", "$", "return", "=", "eZPersistentObject", "::", "fetchObject", "(", "self", "::", "definition", "(", ")", ",", "null", ",", "$", "cond", ")", ";", "return", "$", "return", ";", "}" ]
Fetch ezcomSubscriber by given email @param int $email @return null|ezcomSubscriber
[ "Fetch", "ezcomSubscriber", "by", "given", "email" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomsubscriber.php#L92-L97
ezsystems/ezcomments-ls-extension
classes/ezcomsubscriber.php
ezcomSubscriber.fetchByHashString
static function fetchByHashString( $hashString ) { $cond = array( 'hash_string' => $hashString ); $return = eZPersistentObject::fetchObject( self::definition(), null, $cond ); return $return; }
php
static function fetchByHashString( $hashString ) { $cond = array( 'hash_string' => $hashString ); $return = eZPersistentObject::fetchObject( self::definition(), null, $cond ); return $return; }
[ "static", "function", "fetchByHashString", "(", "$", "hashString", ")", "{", "$", "cond", "=", "array", "(", "'hash_string'", "=>", "$", "hashString", ")", ";", "$", "return", "=", "eZPersistentObject", "::", "fetchObject", "(", "self", "::", "definition", "(", ")", ",", "null", ",", "$", "cond", ")", ";", "return", "$", "return", ";", "}" ]
/* Fetch ezcomSubscriber by given hashstring @param string $hashstring @return null|ezcomSubscriber
[ "/", "*", "Fetch", "ezcomSubscriber", "by", "given", "hashstring" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomsubscriber.php#L105-L110
php-lug/lug
src/Bundle/ResourceBundle/Util/ClassUtils.php
ClassUtils.getRealNamespace
public static function getRealNamespace($class) { if (($lastNsPos = strrpos($realClass = self::getRealClass($class), '\\')) !== false) { return substr($realClass, 0, $lastNsPos); } }
php
public static function getRealNamespace($class) { if (($lastNsPos = strrpos($realClass = self::getRealClass($class), '\\')) !== false) { return substr($realClass, 0, $lastNsPos); } }
[ "public", "static", "function", "getRealNamespace", "(", "$", "class", ")", "{", "if", "(", "(", "$", "lastNsPos", "=", "strrpos", "(", "$", "realClass", "=", "self", "::", "getRealClass", "(", "$", "class", ")", ",", "'\\\\'", ")", ")", "!==", "false", ")", "{", "return", "substr", "(", "$", "realClass", ",", "0", ",", "$", "lastNsPos", ")", ";", "}", "}" ]
@param string $class @return null|string
[ "@param", "string", "$class" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Util/ClassUtils.php#L26-L31
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.setProxy
public function setProxy($ipNumber, $port, $user = '', $pass = '') { $this->proxyIP = $ipNumber; $this->proxyPORT = $port; $this->proxyUSER = $user; $this->proxyPASS = $pass; }
php
public function setProxy($ipNumber, $port, $user = '', $pass = '') { $this->proxyIP = $ipNumber; $this->proxyPORT = $port; $this->proxyUSER = $user; $this->proxyPASS = $pass; }
[ "public", "function", "setProxy", "(", "$", "ipNumber", ",", "$", "port", ",", "$", "user", "=", "''", ",", "$", "pass", "=", "''", ")", "{", "$", "this", "->", "proxyIP", "=", "$", "ipNumber", ";", "$", "this", "->", "proxyPORT", "=", "$", "port", ";", "$", "this", "->", "proxyUSER", "=", "$", "user", ";", "$", "this", "->", "proxyPASS", "=", "$", "pass", ";", "}" ]
/* setProxy Seta o uso do proxy. @param string $ipNumber numero IP do proxy server @param string $port numero da porta usada pelo proxy @param string $user nome do usuário do proxy @param string $pass senha de acesso ao proxy @return bool
[ "/", "*", "setProxy", "Seta", "o", "uso", "do", "proxy", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L121-L127
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.getProxy
public function getProxy() { $aProxy['ip'] = $this->proxyIP; $aProxy['port'] = $this->proxyPORT; $aProxy['username'] = $this->proxyUSER; $aProxy['password'] = $this->proxyPASS; return $aProxy; }
php
public function getProxy() { $aProxy['ip'] = $this->proxyIP; $aProxy['port'] = $this->proxyPORT; $aProxy['username'] = $this->proxyUSER; $aProxy['password'] = $this->proxyPASS; return $aProxy; }
[ "public", "function", "getProxy", "(", ")", "{", "$", "aProxy", "[", "'ip'", "]", "=", "$", "this", "->", "proxyIP", ";", "$", "aProxy", "[", "'port'", "]", "=", "$", "this", "->", "proxyPORT", ";", "$", "aProxy", "[", "'username'", "]", "=", "$", "this", "->", "proxyUSER", ";", "$", "aProxy", "[", "'password'", "]", "=", "$", "this", "->", "proxyPASS", ";", "return", "$", "aProxy", ";", "}" ]
getProxy. Retorna os dados de configuração do Proxy em um array. @return array
[ "getProxy", ".", "Retorna", "os", "dados", "de", "configuração", "do", "Proxy", "em", "um", "array", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L136-L144
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.send
public function send($urlservice, $namespace, $header, $body, $method) { //monta a mensagem ao webservice $data = '<soap12:Envelope '; $data .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '; $data .= 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '; $data .= 'xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'; $data .= '<soap12:Header>' . $header . '</soap12:Header>'; $data .= '<soap12:Body>' . $body . '</soap12:Body>'; $data .= '</soap12:Envelope>'; $data = Strings::clearMsg($data); $this->lastMsg = $data; //tamanho da mensagem $tamanho = strlen($data); //estabelecimento dos parametros da mensagem //$parametros = array( // 'Content-Type: application/soap+xml;charset=utf-8;action="'.$namespace."/".$method.'"', // 'SOAPAction: "'.$method.'"', // "Content-length: $tamanho"); $parametros = [ 'Content-Type: application/soap+xml;charset=utf-8', 'SOAPAction: "' . $namespace . '/' . $method . '"', "Content-length: $tamanho", ]; //solicita comunicação via cURL $resposta = $this->zCommCurl($urlservice, $data, $parametros); if (empty($resposta)) { $msg = "Não houve retorno do Curl.\n $this->errorCurl"; throw new Exception($msg); } //obtem o bloco html da resposta $xPos = stripos($resposta, '<'); $blocoHtml = substr($resposta, 0, $xPos); if ($this->infoCurl['http_code'] != '200') { //se não é igual a 200 houve erro $msg = $blocoHtml; throw new Exception($msg); } //obtem o tamanho da resposta $lenresp = strlen($resposta); //localiza a primeira marca de tag $xPos = stripos($resposta, '<'); //se não existir não é um xml nem um html if ($xPos !== false) { $xml = substr($resposta, $xPos, $lenresp - $xPos); } else { $xml = ''; } //testa para saber se é um xml mesmo ou é um html $result = simplexml_load_string($xml, 'SimpleXmlElement', LIBXML_NOERROR + LIBXML_ERR_FATAL + LIBXML_ERR_NONE); if ($result === false) { //não é um xml então pode limpar $xml = ''; } if ($xml == '') { $msg = 'Não houve retorno de um xml verifique soapDebug!!'; throw new Exception($msg); } if ($xml != '' && substr($xml, 0, 5) != '<?xml') { $xml = '<?xml version="1.0" encoding="utf-8"?>' . $xml; } return $xml; }
php
public function send($urlservice, $namespace, $header, $body, $method) { //monta a mensagem ao webservice $data = '<soap12:Envelope '; $data .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '; $data .= 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '; $data .= 'xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'; $data .= '<soap12:Header>' . $header . '</soap12:Header>'; $data .= '<soap12:Body>' . $body . '</soap12:Body>'; $data .= '</soap12:Envelope>'; $data = Strings::clearMsg($data); $this->lastMsg = $data; //tamanho da mensagem $tamanho = strlen($data); //estabelecimento dos parametros da mensagem //$parametros = array( // 'Content-Type: application/soap+xml;charset=utf-8;action="'.$namespace."/".$method.'"', // 'SOAPAction: "'.$method.'"', // "Content-length: $tamanho"); $parametros = [ 'Content-Type: application/soap+xml;charset=utf-8', 'SOAPAction: "' . $namespace . '/' . $method . '"', "Content-length: $tamanho", ]; //solicita comunicação via cURL $resposta = $this->zCommCurl($urlservice, $data, $parametros); if (empty($resposta)) { $msg = "Não houve retorno do Curl.\n $this->errorCurl"; throw new Exception($msg); } //obtem o bloco html da resposta $xPos = stripos($resposta, '<'); $blocoHtml = substr($resposta, 0, $xPos); if ($this->infoCurl['http_code'] != '200') { //se não é igual a 200 houve erro $msg = $blocoHtml; throw new Exception($msg); } //obtem o tamanho da resposta $lenresp = strlen($resposta); //localiza a primeira marca de tag $xPos = stripos($resposta, '<'); //se não existir não é um xml nem um html if ($xPos !== false) { $xml = substr($resposta, $xPos, $lenresp - $xPos); } else { $xml = ''; } //testa para saber se é um xml mesmo ou é um html $result = simplexml_load_string($xml, 'SimpleXmlElement', LIBXML_NOERROR + LIBXML_ERR_FATAL + LIBXML_ERR_NONE); if ($result === false) { //não é um xml então pode limpar $xml = ''; } if ($xml == '') { $msg = 'Não houve retorno de um xml verifique soapDebug!!'; throw new Exception($msg); } if ($xml != '' && substr($xml, 0, 5) != '<?xml') { $xml = '<?xml version="1.0" encoding="utf-8"?>' . $xml; } return $xml; }
[ "public", "function", "send", "(", "$", "urlservice", ",", "$", "namespace", ",", "$", "header", ",", "$", "body", ",", "$", "method", ")", "{", "//monta a mensagem ao webservice", "$", "data", "=", "'<soap12:Envelope '", ";", "$", "data", ".=", "'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '", ";", "$", "data", ".=", "'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" '", ";", "$", "data", ".=", "'xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">'", ";", "$", "data", ".=", "'<soap12:Header>'", ".", "$", "header", ".", "'</soap12:Header>'", ";", "$", "data", ".=", "'<soap12:Body>'", ".", "$", "body", ".", "'</soap12:Body>'", ";", "$", "data", ".=", "'</soap12:Envelope>'", ";", "$", "data", "=", "Strings", "::", "clearMsg", "(", "$", "data", ")", ";", "$", "this", "->", "lastMsg", "=", "$", "data", ";", "//tamanho da mensagem", "$", "tamanho", "=", "strlen", "(", "$", "data", ")", ";", "//estabelecimento dos parametros da mensagem", "//$parametros = array(", "// 'Content-Type: application/soap+xml;charset=utf-8;action=\"'.$namespace.\"/\".$method.'\"',", "// 'SOAPAction: \"'.$method.'\"',", "// \"Content-length: $tamanho\");", "$", "parametros", "=", "[", "'Content-Type: application/soap+xml;charset=utf-8'", ",", "'SOAPAction: \"'", ".", "$", "namespace", ".", "'/'", ".", "$", "method", ".", "'\"'", ",", "\"Content-length: $tamanho\"", ",", "]", ";", "//solicita comunicação via cURL", "$", "resposta", "=", "$", "this", "->", "zCommCurl", "(", "$", "urlservice", ",", "$", "data", ",", "$", "parametros", ")", ";", "if", "(", "empty", "(", "$", "resposta", ")", ")", "{", "$", "msg", "=", "\"Não houve retorno do Curl.\\n $this->errorCurl\";", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "//obtem o bloco html da resposta", "$", "xPos", "=", "stripos", "(", "$", "resposta", ",", "'<'", ")", ";", "$", "blocoHtml", "=", "substr", "(", "$", "resposta", ",", "0", ",", "$", "xPos", ")", ";", "if", "(", "$", "this", "->", "infoCurl", "[", "'http_code'", "]", "!=", "'200'", ")", "{", "//se não é igual a 200 houve erro", "$", "msg", "=", "$", "blocoHtml", ";", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "//obtem o tamanho da resposta", "$", "lenresp", "=", "strlen", "(", "$", "resposta", ")", ";", "//localiza a primeira marca de tag", "$", "xPos", "=", "stripos", "(", "$", "resposta", ",", "'<'", ")", ";", "//se não existir não é um xml nem um html", "if", "(", "$", "xPos", "!==", "false", ")", "{", "$", "xml", "=", "substr", "(", "$", "resposta", ",", "$", "xPos", ",", "$", "lenresp", "-", "$", "xPos", ")", ";", "}", "else", "{", "$", "xml", "=", "''", ";", "}", "//testa para saber se é um xml mesmo ou é um html", "$", "result", "=", "simplexml_load_string", "(", "$", "xml", ",", "'SimpleXmlElement'", ",", "LIBXML_NOERROR", "+", "LIBXML_ERR_FATAL", "+", "LIBXML_ERR_NONE", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "//não é um xml então pode limpar", "$", "xml", "=", "''", ";", "}", "if", "(", "$", "xml", "==", "''", ")", "{", "$", "msg", "=", "'Não houve retorno de um xml verifique soapDebug!!';", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "if", "(", "$", "xml", "!=", "''", "&&", "substr", "(", "$", "xml", ",", "0", ",", "5", ")", "!=", "'<?xml'", ")", "{", "$", "xml", "=", "'<?xml version=\"1.0\" encoding=\"utf-8\"?>'", ".", "$", "xml", ";", "}", "return", "$", "xml", ";", "}" ]
Envia mensagem ao webservice. @param string $urlsevice @param string $namespace @param string $header @param string $body @param string $method @return bool|string
[ "Envia", "mensagem", "ao", "webservice", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L155-L217
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.getWsdl
public function getWsdl($urlservice) { $aURL = explode('?', $urlservice); if (count($aURL) == 1) { $urlservice .= '?wsdl'; } $resposta = $this->zCommCurl($urlservice); //verifica se foi retornado o wsdl $nPos = strpos($resposta, '<wsdl:def'); if ($nPos === false) { $nPos = strpos($resposta, '<definit'); } if ($nPos === false) { //não retornou um wsdl return false; } $wsdl = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . trim(substr($resposta, $nPos)); return $wsdl; }
php
public function getWsdl($urlservice) { $aURL = explode('?', $urlservice); if (count($aURL) == 1) { $urlservice .= '?wsdl'; } $resposta = $this->zCommCurl($urlservice); //verifica se foi retornado o wsdl $nPos = strpos($resposta, '<wsdl:def'); if ($nPos === false) { $nPos = strpos($resposta, '<definit'); } if ($nPos === false) { //não retornou um wsdl return false; } $wsdl = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . trim(substr($resposta, $nPos)); return $wsdl; }
[ "public", "function", "getWsdl", "(", "$", "urlservice", ")", "{", "$", "aURL", "=", "explode", "(", "'?'", ",", "$", "urlservice", ")", ";", "if", "(", "count", "(", "$", "aURL", ")", "==", "1", ")", "{", "$", "urlservice", ".=", "'?wsdl'", ";", "}", "$", "resposta", "=", "$", "this", "->", "zCommCurl", "(", "$", "urlservice", ")", ";", "//verifica se foi retornado o wsdl", "$", "nPos", "=", "strpos", "(", "$", "resposta", ",", "'<wsdl:def'", ")", ";", "if", "(", "$", "nPos", "===", "false", ")", "{", "$", "nPos", "=", "strpos", "(", "$", "resposta", ",", "'<definit'", ")", ";", "}", "if", "(", "$", "nPos", "===", "false", ")", "{", "//não retornou um wsdl", "return", "false", ";", "}", "$", "wsdl", "=", "\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\"", ".", "trim", "(", "substr", "(", "$", "resposta", ",", "$", "nPos", ")", ")", ";", "return", "$", "wsdl", ";", "}" ]
getWsdl Baixa o arquivo wsdl do webservice. @param string $urlsefaz @return bool|string
[ "getWsdl", "Baixa", "o", "arquivo", "wsdl", "do", "webservice", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L227-L246
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.zCommCurl
protected function zCommCurl($url, $data = '', $parametros = [], $port = 443) { //incializa cURL $oCurl = curl_init(); //setting da seção soap if ($this->proxyIP != '') { curl_setopt($oCurl, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($oCurl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($oCurl, CURLOPT_PROXY, $this->proxyIP . ':' . $this->proxyPORT); if ($this->proxyPASS != '') { curl_setopt($oCurl, CURLOPT_PROXYUSERPWD, $this->proxyUSER . ':' . $this->proxyPASS); curl_setopt($oCurl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); } //fim if senha proxy }//fim if aProxy //força a resolução de nomes com IPV4 e não com IPV6, isso //pode acelerar temporáriamente as falhas ou demoras decorrentes de //ambiente mal preparados como os da SEFAZ GO, porém pode causar //problemas no futuro quando os endereços IPV4 deixarem de ser usados curl_setopt($oCurl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $this->soapTimeout); curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_VERBOSE, 0); curl_setopt($oCurl, CURLOPT_HEADER, 1); //caso não seja setado o protpcolo SSL o php deverá determinar //o protocolo correto durante o handshake. //NOTA : poderão haver alguns problemas no futuro se algum serividor não //estiver bem configurado e não passar o protocolo correto durante o handshake //nesse caso será necessário setar manualmente o protocolo correto //curl_setopt($oCurl, CURLOPT_SSLVERSION, 0); //default //curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //TLSv1 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 2); //SSLv2 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 3); //SSLv3 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 4); //TLSv1.0 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 5); //TLSv1.1 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 6); //TLSv1.2 //se for passado um padrão diferente de zero (default) como protocolo ssl //esse novo padrão deverá se usado if ($this->sslProtocol !== 0) { curl_setopt($oCurl, CURLOPT_SSLVERSION, $this->sslProtocol); } curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, 0); if ($port == 443) { curl_setopt($oCurl, CURLOPT_PORT, 443); curl_setopt($oCurl, CURLOPT_SSLCERT, $this->certKeyPath); curl_setopt($oCurl, CURLOPT_SSLKEY, $this->priKeyPath); } else { $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'; curl_setopt($oCurl, CURLOPT_USERAGENT, $agent); } curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); if ($data != '') { curl_setopt($oCurl, CURLOPT_POST, 1); curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data); } if (! empty($parametros)) { curl_setopt($oCurl, CURLOPT_HTTPHEADER, $parametros); } //inicia a conexão $resposta = curl_exec($oCurl); //obtem as informações da conexão $info = curl_getinfo($oCurl); //carrega os dados para debug $this->zDebug($info, $data, $resposta); $this->errorCurl = curl_error($oCurl); //fecha a conexão curl_close($oCurl); //retorna resposta return $resposta; }
php
protected function zCommCurl($url, $data = '', $parametros = [], $port = 443) { //incializa cURL $oCurl = curl_init(); //setting da seção soap if ($this->proxyIP != '') { curl_setopt($oCurl, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($oCurl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($oCurl, CURLOPT_PROXY, $this->proxyIP . ':' . $this->proxyPORT); if ($this->proxyPASS != '') { curl_setopt($oCurl, CURLOPT_PROXYUSERPWD, $this->proxyUSER . ':' . $this->proxyPASS); curl_setopt($oCurl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); } //fim if senha proxy }//fim if aProxy //força a resolução de nomes com IPV4 e não com IPV6, isso //pode acelerar temporáriamente as falhas ou demoras decorrentes de //ambiente mal preparados como os da SEFAZ GO, porém pode causar //problemas no futuro quando os endereços IPV4 deixarem de ser usados curl_setopt($oCurl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $this->soapTimeout); curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_VERBOSE, 0); curl_setopt($oCurl, CURLOPT_HEADER, 1); //caso não seja setado o protpcolo SSL o php deverá determinar //o protocolo correto durante o handshake. //NOTA : poderão haver alguns problemas no futuro se algum serividor não //estiver bem configurado e não passar o protocolo correto durante o handshake //nesse caso será necessário setar manualmente o protocolo correto //curl_setopt($oCurl, CURLOPT_SSLVERSION, 0); //default //curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //TLSv1 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 2); //SSLv2 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 3); //SSLv3 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 4); //TLSv1.0 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 5); //TLSv1.1 //curl_setopt($oCurl, CURLOPT_SSLVERSION, 6); //TLSv1.2 //se for passado um padrão diferente de zero (default) como protocolo ssl //esse novo padrão deverá se usado if ($this->sslProtocol !== 0) { curl_setopt($oCurl, CURLOPT_SSLVERSION, $this->sslProtocol); } curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, 0); if ($port == 443) { curl_setopt($oCurl, CURLOPT_PORT, 443); curl_setopt($oCurl, CURLOPT_SSLCERT, $this->certKeyPath); curl_setopt($oCurl, CURLOPT_SSLKEY, $this->priKeyPath); } else { $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'; curl_setopt($oCurl, CURLOPT_USERAGENT, $agent); } curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); if ($data != '') { curl_setopt($oCurl, CURLOPT_POST, 1); curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data); } if (! empty($parametros)) { curl_setopt($oCurl, CURLOPT_HTTPHEADER, $parametros); } //inicia a conexão $resposta = curl_exec($oCurl); //obtem as informações da conexão $info = curl_getinfo($oCurl); //carrega os dados para debug $this->zDebug($info, $data, $resposta); $this->errorCurl = curl_error($oCurl); //fecha a conexão curl_close($oCurl); //retorna resposta return $resposta; }
[ "protected", "function", "zCommCurl", "(", "$", "url", ",", "$", "data", "=", "''", ",", "$", "parametros", "=", "[", "]", ",", "$", "port", "=", "443", ")", "{", "//incializa cURL", "$", "oCurl", "=", "curl_init", "(", ")", ";", "//setting da seção soap", "if", "(", "$", "this", "->", "proxyIP", "!=", "''", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_HTTPPROXYTUNNEL", ",", "1", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_PROXYTYPE", ",", "CURLPROXY_HTTP", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_PROXY", ",", "$", "this", "->", "proxyIP", ".", "':'", ".", "$", "this", "->", "proxyPORT", ")", ";", "if", "(", "$", "this", "->", "proxyPASS", "!=", "''", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_PROXYUSERPWD", ",", "$", "this", "->", "proxyUSER", ".", "':'", ".", "$", "this", "->", "proxyPASS", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_PROXYAUTH", ",", "CURLAUTH_BASIC", ")", ";", "}", "//fim if senha proxy", "}", "//fim if aProxy", "//força a resolução de nomes com IPV4 e não com IPV6, isso", "//pode acelerar temporáriamente as falhas ou demoras decorrentes de", "//ambiente mal preparados como os da SEFAZ GO, porém pode causar", "//problemas no futuro quando os endereços IPV4 deixarem de ser usados", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_IPRESOLVE", ",", "CURL_IPRESOLVE_V4", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "this", "->", "soapTimeout", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_VERBOSE", ",", "0", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_HEADER", ",", "1", ")", ";", "//caso não seja setado o protpcolo SSL o php deverá determinar", "//o protocolo correto durante o handshake.", "//NOTA : poderão haver alguns problemas no futuro se algum serividor não", "//estiver bem configurado e não passar o protocolo correto durante o handshake", "//nesse caso será necessário setar manualmente o protocolo correto", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 0); //default", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //TLSv1", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 2); //SSLv2", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 3); //SSLv3", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 4); //TLSv1.0", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 5); //TLSv1.1", "//curl_setopt($oCurl, CURLOPT_SSLVERSION, 6); //TLSv1.2", "//se for passado um padrão diferente de zero (default) como protocolo ssl", "//esse novo padrão deverá se usado", "if", "(", "$", "this", "->", "sslProtocol", "!==", "0", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_SSLVERSION", ",", "$", "this", "->", "sslProtocol", ")", ";", "}", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_SSL_VERIFYHOST", ",", "2", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_SSL_VERIFYPEER", ",", "0", ")", ";", "if", "(", "$", "port", "==", "443", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_PORT", ",", "443", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_SSLCERT", ",", "$", "this", "->", "certKeyPath", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_SSLKEY", ",", "$", "this", "->", "priKeyPath", ")", ";", "}", "else", "{", "$", "agent", "=", "'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_USERAGENT", ",", "$", "agent", ")", ";", "}", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "if", "(", "$", "data", "!=", "''", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_POST", ",", "1", ")", ";", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_POSTFIELDS", ",", "$", "data", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "parametros", ")", ")", "{", "curl_setopt", "(", "$", "oCurl", ",", "CURLOPT_HTTPHEADER", ",", "$", "parametros", ")", ";", "}", "//inicia a conexão", "$", "resposta", "=", "curl_exec", "(", "$", "oCurl", ")", ";", "//obtem as informações da conexão", "$", "info", "=", "curl_getinfo", "(", "$", "oCurl", ")", ";", "//carrega os dados para debug", "$", "this", "->", "zDebug", "(", "$", "info", ",", "$", "data", ",", "$", "resposta", ")", ";", "$", "this", "->", "errorCurl", "=", "curl_error", "(", "$", "oCurl", ")", ";", "//fecha a conexão", "curl_close", "(", "$", "oCurl", ")", ";", "//retorna resposta", "return", "$", "resposta", ";", "}" ]
zCommCurl Realiza da comunicação via cURL. @param string $url @param string $data @param string $parametros @return string
[ "zCommCurl", "Realiza", "da", "comunicação", "via", "cURL", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L256-L325
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.zDebug
private function zDebug($info = [], $data = '', $resposta = '') { $this->infoCurl['url'] = $info['url']; $this->infoCurl['content_type'] = $info['content_type']; $this->infoCurl['http_code'] = $info['http_code']; $this->infoCurl['header_size'] = $info['header_size']; $this->infoCurl['request_size'] = $info['request_size']; $this->infoCurl['filetime'] = $info['filetime']; $this->infoCurl['ssl_verify_result'] = $info['ssl_verify_result']; $this->infoCurl['redirect_count'] = $info['redirect_count']; $this->infoCurl['total_time'] = $info['total_time']; $this->infoCurl['namelookup_time'] = $info['namelookup_time']; $this->infoCurl['connect_time'] = $info['connect_time']; $this->infoCurl['pretransfer_time'] = $info['pretransfer_time']; $this->infoCurl['size_upload'] = $info['size_upload']; $this->infoCurl['size_download'] = $info['size_download']; $this->infoCurl['speed_download'] = $info['speed_download']; $this->infoCurl['speed_upload'] = $info['speed_upload']; $this->infoCurl['download_content_length'] = $info['download_content_length']; $this->infoCurl['upload_content_length'] = $info['upload_content_length']; $this->infoCurl['starttransfer_time'] = $info['starttransfer_time']; $this->infoCurl['redirect_time'] = $info['redirect_time']; //coloca as informações em uma variável $txtInfo = ''; foreach ($info as $key => $content) { if (is_string($content)) { $txtInfo .= strtoupper($key) . '=' . $content . "\n"; } } //carrega a variavel debug $this->soapDebug = $data . "\n\n" . $txtInfo . "\n" . $resposta; }
php
private function zDebug($info = [], $data = '', $resposta = '') { $this->infoCurl['url'] = $info['url']; $this->infoCurl['content_type'] = $info['content_type']; $this->infoCurl['http_code'] = $info['http_code']; $this->infoCurl['header_size'] = $info['header_size']; $this->infoCurl['request_size'] = $info['request_size']; $this->infoCurl['filetime'] = $info['filetime']; $this->infoCurl['ssl_verify_result'] = $info['ssl_verify_result']; $this->infoCurl['redirect_count'] = $info['redirect_count']; $this->infoCurl['total_time'] = $info['total_time']; $this->infoCurl['namelookup_time'] = $info['namelookup_time']; $this->infoCurl['connect_time'] = $info['connect_time']; $this->infoCurl['pretransfer_time'] = $info['pretransfer_time']; $this->infoCurl['size_upload'] = $info['size_upload']; $this->infoCurl['size_download'] = $info['size_download']; $this->infoCurl['speed_download'] = $info['speed_download']; $this->infoCurl['speed_upload'] = $info['speed_upload']; $this->infoCurl['download_content_length'] = $info['download_content_length']; $this->infoCurl['upload_content_length'] = $info['upload_content_length']; $this->infoCurl['starttransfer_time'] = $info['starttransfer_time']; $this->infoCurl['redirect_time'] = $info['redirect_time']; //coloca as informações em uma variável $txtInfo = ''; foreach ($info as $key => $content) { if (is_string($content)) { $txtInfo .= strtoupper($key) . '=' . $content . "\n"; } } //carrega a variavel debug $this->soapDebug = $data . "\n\n" . $txtInfo . "\n" . $resposta; }
[ "private", "function", "zDebug", "(", "$", "info", "=", "[", "]", ",", "$", "data", "=", "''", ",", "$", "resposta", "=", "''", ")", "{", "$", "this", "->", "infoCurl", "[", "'url'", "]", "=", "$", "info", "[", "'url'", "]", ";", "$", "this", "->", "infoCurl", "[", "'content_type'", "]", "=", "$", "info", "[", "'content_type'", "]", ";", "$", "this", "->", "infoCurl", "[", "'http_code'", "]", "=", "$", "info", "[", "'http_code'", "]", ";", "$", "this", "->", "infoCurl", "[", "'header_size'", "]", "=", "$", "info", "[", "'header_size'", "]", ";", "$", "this", "->", "infoCurl", "[", "'request_size'", "]", "=", "$", "info", "[", "'request_size'", "]", ";", "$", "this", "->", "infoCurl", "[", "'filetime'", "]", "=", "$", "info", "[", "'filetime'", "]", ";", "$", "this", "->", "infoCurl", "[", "'ssl_verify_result'", "]", "=", "$", "info", "[", "'ssl_verify_result'", "]", ";", "$", "this", "->", "infoCurl", "[", "'redirect_count'", "]", "=", "$", "info", "[", "'redirect_count'", "]", ";", "$", "this", "->", "infoCurl", "[", "'total_time'", "]", "=", "$", "info", "[", "'total_time'", "]", ";", "$", "this", "->", "infoCurl", "[", "'namelookup_time'", "]", "=", "$", "info", "[", "'namelookup_time'", "]", ";", "$", "this", "->", "infoCurl", "[", "'connect_time'", "]", "=", "$", "info", "[", "'connect_time'", "]", ";", "$", "this", "->", "infoCurl", "[", "'pretransfer_time'", "]", "=", "$", "info", "[", "'pretransfer_time'", "]", ";", "$", "this", "->", "infoCurl", "[", "'size_upload'", "]", "=", "$", "info", "[", "'size_upload'", "]", ";", "$", "this", "->", "infoCurl", "[", "'size_download'", "]", "=", "$", "info", "[", "'size_download'", "]", ";", "$", "this", "->", "infoCurl", "[", "'speed_download'", "]", "=", "$", "info", "[", "'speed_download'", "]", ";", "$", "this", "->", "infoCurl", "[", "'speed_upload'", "]", "=", "$", "info", "[", "'speed_upload'", "]", ";", "$", "this", "->", "infoCurl", "[", "'download_content_length'", "]", "=", "$", "info", "[", "'download_content_length'", "]", ";", "$", "this", "->", "infoCurl", "[", "'upload_content_length'", "]", "=", "$", "info", "[", "'upload_content_length'", "]", ";", "$", "this", "->", "infoCurl", "[", "'starttransfer_time'", "]", "=", "$", "info", "[", "'starttransfer_time'", "]", ";", "$", "this", "->", "infoCurl", "[", "'redirect_time'", "]", "=", "$", "info", "[", "'redirect_time'", "]", ";", "//coloca as informações em uma variável", "$", "txtInfo", "=", "''", ";", "foreach", "(", "$", "info", "as", "$", "key", "=>", "$", "content", ")", "{", "if", "(", "is_string", "(", "$", "content", ")", ")", "{", "$", "txtInfo", ".=", "strtoupper", "(", "$", "key", ")", ".", "'='", ".", "$", "content", ".", "\"\\n\"", ";", "}", "}", "//carrega a variavel debug", "$", "this", "->", "soapDebug", "=", "$", "data", ".", "\"\\n\\n\"", ".", "$", "txtInfo", ".", "\"\\n\"", ".", "$", "resposta", ";", "}" ]
zDebug. @param array $info @param string $data @param string $resposta
[ "zDebug", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L333-L364
phpnfe/tools
src/Soap/CurlSoap.php
CurlSoap.getIBPTProd
public function getIBPTProd( $cnpj = '', $tokenIBPT = '', $ncm = '', $siglaUF = '', $exTarif = '0' ) { $url = "http://iws.ibpt.org.br/api/Produtos?token=$tokenIBPT&cnpj=$cnpj&codigo=$ncm&uf=$siglaUF&ex=$exTarif"; $resposta = $this->zCommCurl($url, '', [], 80); $retorno = str_replace("\r\n", '|', $resposta); $aResp = explode('||', $retorno); if (! empty($aResp[1])) { if (substr($aResp[1], 0, 1) == '{') { $json = $aResp[1]; return (array) json_decode($json, true); } } return []; }
php
public function getIBPTProd( $cnpj = '', $tokenIBPT = '', $ncm = '', $siglaUF = '', $exTarif = '0' ) { $url = "http://iws.ibpt.org.br/api/Produtos?token=$tokenIBPT&cnpj=$cnpj&codigo=$ncm&uf=$siglaUF&ex=$exTarif"; $resposta = $this->zCommCurl($url, '', [], 80); $retorno = str_replace("\r\n", '|', $resposta); $aResp = explode('||', $retorno); if (! empty($aResp[1])) { if (substr($aResp[1], 0, 1) == '{') { $json = $aResp[1]; return (array) json_decode($json, true); } } return []; }
[ "public", "function", "getIBPTProd", "(", "$", "cnpj", "=", "''", ",", "$", "tokenIBPT", "=", "''", ",", "$", "ncm", "=", "''", ",", "$", "siglaUF", "=", "''", ",", "$", "exTarif", "=", "'0'", ")", "{", "$", "url", "=", "\"http://iws.ibpt.org.br/api/Produtos?token=$tokenIBPT&cnpj=$cnpj&codigo=$ncm&uf=$siglaUF&ex=$exTarif\"", ";", "$", "resposta", "=", "$", "this", "->", "zCommCurl", "(", "$", "url", ",", "''", ",", "[", "]", ",", "80", ")", ";", "$", "retorno", "=", "str_replace", "(", "\"\\r\\n\"", ",", "'|'", ",", "$", "resposta", ")", ";", "$", "aResp", "=", "explode", "(", "'||'", ",", "$", "retorno", ")", ";", "if", "(", "!", "empty", "(", "$", "aResp", "[", "1", "]", ")", ")", "{", "if", "(", "substr", "(", "$", "aResp", "[", "1", "]", ",", "0", ",", "1", ")", "==", "'{'", ")", "{", "$", "json", "=", "$", "aResp", "[", "1", "]", ";", "return", "(", "array", ")", "json_decode", "(", "$", "json", ",", "true", ")", ";", "}", "}", "return", "[", "]", ";", "}" ]
getIBPTProd Consulta o serviço do IBPT para obter os impostos ao consumidor. conforme Lei 12.741/2012. @param string $cnpj @param string $tokenIBPT @param string $ncm @param string $siglaUF @param string $exTarif @return array
[ "getIBPTProd", "Consulta", "o", "serviço", "do", "IBPT", "para", "obter", "os", "impostos", "ao", "consumidor", ".", "conforme", "Lei", "12", ".", "741", "/", "2012", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/CurlSoap.php#L377-L397
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_config_value
protected function get_config_value( $key, $default = null ) { return $this->app->utility->array_get( $this->get_configs(), $key, $default ); }
php
protected function get_config_value( $key, $default = null ) { return $this->app->utility->array_get( $this->get_configs(), $key, $default ); }
[ "protected", "function", "get_config_value", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "return", "$", "this", "->", "app", "->", "utility", "->", "array_get", "(", "$", "this", "->", "get_configs", "(", ")", ",", "$", "key", ",", "$", "default", ")", ";", "}" ]
@param string $key @param mixed $default @return mixed
[ "@param", "string", "$key", "@param", "mixed", "$default" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L76-L78
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_oauth_link_query
protected function get_oauth_link_query( $client_id ) { return $this->filter_oauth_link_query( [ 'client_id' => $client_id, 'redirect_uri' => $this->apply_filters( $this->get_service_name() . '_oauth_redirect_uri' ), 'scope' => $this->get_config_value( 'scope' ), 'response_type' => 'code', 'state' => $this->get_state(), ], $client_id ); }
php
protected function get_oauth_link_query( $client_id ) { return $this->filter_oauth_link_query( [ 'client_id' => $client_id, 'redirect_uri' => $this->apply_filters( $this->get_service_name() . '_oauth_redirect_uri' ), 'scope' => $this->get_config_value( 'scope' ), 'response_type' => 'code', 'state' => $this->get_state(), ], $client_id ); }
[ "protected", "function", "get_oauth_link_query", "(", "$", "client_id", ")", "{", "return", "$", "this", "->", "filter_oauth_link_query", "(", "[", "'client_id'", "=>", "$", "client_id", ",", "'redirect_uri'", "=>", "$", "this", "->", "apply_filters", "(", "$", "this", "->", "get_service_name", "(", ")", ".", "'_oauth_redirect_uri'", ")", ",", "'scope'", "=>", "$", "this", "->", "get_config_value", "(", "'scope'", ")", ",", "'response_type'", "=>", "'code'", ",", "'state'", "=>", "$", "this", "->", "get_state", "(", ")", ",", "]", ",", "$", "client_id", ")", ";", "}" ]
@param string $client_id @return array
[ "@param", "string", "$client_id" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L94-L102
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_url
protected function get_url( $url, $params ) { if ( empty( $params ) ) { return $url; } $q = strpos( $url, '?' ) !== false ? '&' : '?'; return $url . $q . http_build_query( $params ); }
php
protected function get_url( $url, $params ) { if ( empty( $params ) ) { return $url; } $q = strpos( $url, '?' ) !== false ? '&' : '?'; return $url . $q . http_build_query( $params ); }
[ "protected", "function", "get_url", "(", "$", "url", ",", "$", "params", ")", "{", "if", "(", "empty", "(", "$", "params", ")", ")", "{", "return", "$", "url", ";", "}", "$", "q", "=", "strpos", "(", "$", "url", ",", "'?'", ")", "!==", "false", "?", "'&'", ":", "'?'", ";", "return", "$", "url", ".", "$", "q", ".", "http_build_query", "(", "$", "params", ")", ";", "}" ]
@param $url @param array $params @return string
[ "@param", "$url", "@param", "array", "$params" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L123-L130
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.check_state_params
public function check_state_params( $params ) { if ( empty( $params ) || empty( $params['uuid'] ) || empty( $params['redirect'] ) || ! preg_match( '#\A/[^/]+#', $params['redirect'] ) || ! $this->app->session->exists( $this->get_auth_session_name() ) ) { return false; } $hash = $this->app->get_session( $this->get_auth_session_name() ); $this->app->session->delete( $this->get_auth_session_name() ); return $hash === $this->create_hash( $params['uuid'] ); }
php
public function check_state_params( $params ) { if ( empty( $params ) || empty( $params['uuid'] ) || empty( $params['redirect'] ) || ! preg_match( '#\A/[^/]+#', $params['redirect'] ) || ! $this->app->session->exists( $this->get_auth_session_name() ) ) { return false; } $hash = $this->app->get_session( $this->get_auth_session_name() ); $this->app->session->delete( $this->get_auth_session_name() ); return $hash === $this->create_hash( $params['uuid'] ); }
[ "public", "function", "check_state_params", "(", "$", "params", ")", "{", "if", "(", "empty", "(", "$", "params", ")", "||", "empty", "(", "$", "params", "[", "'uuid'", "]", ")", "||", "empty", "(", "$", "params", "[", "'redirect'", "]", ")", "||", "!", "preg_match", "(", "'#\\A/[^/]+#'", ",", "$", "params", "[", "'redirect'", "]", ")", "||", "!", "$", "this", "->", "app", "->", "session", "->", "exists", "(", "$", "this", "->", "get_auth_session_name", "(", ")", ")", ")", "{", "return", "false", ";", "}", "$", "hash", "=", "$", "this", "->", "app", "->", "get_session", "(", "$", "this", "->", "get_auth_session_name", "(", ")", ")", ";", "$", "this", "->", "app", "->", "session", "->", "delete", "(", "$", "this", "->", "get_auth_session_name", "(", ")", ")", ";", "return", "$", "hash", "===", "$", "this", "->", "create_hash", "(", "$", "params", "[", "'uuid'", "]", ")", ";", "}" ]
@param array $params @return bool|false|int
[ "@param", "array", "$params" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L203-L218
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_access_token_params
protected function get_access_token_params( $code, $client_id, $client_secret ) { return $this->filter_access_token_params( [ 'code' => $code, 'redirect_uri' => $this->apply_filters( $this->get_service_name() . '_oauth_redirect_uri' ), 'client_id' => $client_id, 'client_secret' => $client_secret, ], $code, $client_id, $client_secret ); }
php
protected function get_access_token_params( $code, $client_id, $client_secret ) { return $this->filter_access_token_params( [ 'code' => $code, 'redirect_uri' => $this->apply_filters( $this->get_service_name() . '_oauth_redirect_uri' ), 'client_id' => $client_id, 'client_secret' => $client_secret, ], $code, $client_id, $client_secret ); }
[ "protected", "function", "get_access_token_params", "(", "$", "code", ",", "$", "client_id", ",", "$", "client_secret", ")", "{", "return", "$", "this", "->", "filter_access_token_params", "(", "[", "'code'", "=>", "$", "code", ",", "'redirect_uri'", "=>", "$", "this", "->", "apply_filters", "(", "$", "this", "->", "get_service_name", "(", ")", ".", "'_oauth_redirect_uri'", ")", ",", "'client_id'", "=>", "$", "client_id", ",", "'client_secret'", "=>", "$", "client_secret", ",", "]", ",", "$", "code", ",", "$", "client_id", ",", "$", "client_secret", ")", ";", "}" ]
@param string $code @param string $client_id @param string $client_secret @return array
[ "@param", "string", "$code", "@param", "string", "$client_id", "@param", "string", "$client_secret" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L227-L234
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_access_token
public function get_access_token( $code, $client_id, $client_secret ) { $contents = $this->get_contents( 'token_url', $this->get_access_token_params( $code, $client_id, $client_secret ) ); $response = @json_decode( $contents, true ); if ( empty( $response ) || ! empty( $response['error'] ) ) { $this->app->log( 'social response error', [ '$contents' => $contents, '$response' => $response, ] ); return false; } return $response['access_token']; }
php
public function get_access_token( $code, $client_id, $client_secret ) { $contents = $this->get_contents( 'token_url', $this->get_access_token_params( $code, $client_id, $client_secret ) ); $response = @json_decode( $contents, true ); if ( empty( $response ) || ! empty( $response['error'] ) ) { $this->app->log( 'social response error', [ '$contents' => $contents, '$response' => $response, ] ); return false; } return $response['access_token']; }
[ "public", "function", "get_access_token", "(", "$", "code", ",", "$", "client_id", ",", "$", "client_secret", ")", "{", "$", "contents", "=", "$", "this", "->", "get_contents", "(", "'token_url'", ",", "$", "this", "->", "get_access_token_params", "(", "$", "code", ",", "$", "client_id", ",", "$", "client_secret", ")", ")", ";", "$", "response", "=", "@", "json_decode", "(", "$", "contents", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "response", ")", "||", "!", "empty", "(", "$", "response", "[", "'error'", "]", ")", ")", "{", "$", "this", "->", "app", "->", "log", "(", "'social response error'", ",", "[", "'$contents'", "=>", "$", "contents", ",", "'$response'", "=>", "$", "response", ",", "]", ")", ";", "return", "false", ";", "}", "return", "$", "response", "[", "'access_token'", "]", ";", "}" ]
@param string $code @param string $client_id @param string $client_secret @return false|string
[ "@param", "string", "$code", "@param", "string", "$client_id", "@param", "string", "$client_secret" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L258-L271
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_user_info
public function get_user_info( $access_token ) { $contents = $this->get_contents( 'user_info_url', [ 'access_token' => $access_token ] ); $info = @json_decode( $contents, true ); if ( empty( $info ) ) { $this->app->log( 'social response error', [ '$contents' => $contents, '$info' => $info, ] ); return null; } return $info; }
php
public function get_user_info( $access_token ) { $contents = $this->get_contents( 'user_info_url', [ 'access_token' => $access_token ] ); $info = @json_decode( $contents, true ); if ( empty( $info ) ) { $this->app->log( 'social response error', [ '$contents' => $contents, '$info' => $info, ] ); return null; } return $info; }
[ "public", "function", "get_user_info", "(", "$", "access_token", ")", "{", "$", "contents", "=", "$", "this", "->", "get_contents", "(", "'user_info_url'", ",", "[", "'access_token'", "=>", "$", "access_token", "]", ")", ";", "$", "info", "=", "@", "json_decode", "(", "$", "contents", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "info", ")", ")", "{", "$", "this", "->", "app", "->", "log", "(", "'social response error'", ",", "[", "'$contents'", "=>", "$", "contents", ",", "'$info'", "=>", "$", "info", ",", "]", ")", ";", "return", "null", ";", "}", "return", "$", "info", ";", "}" ]
@param $access_token @return array|null
[ "@param", "$access_token" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L278-L291
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_contents
protected function get_contents( $key, $query = [] ) { $url = $this->get_config_value( $key ); if ( empty( $url ) ) { return false; } $options['ssl']['verify_peer'] = false; $options['ssl']['verify_peer_name'] = false; $options['http']['ignore_errors'] = true; if ( $this->is_post_access( $key ) ) { $options['http'] = [ 'method' => 'POST', 'header' => implode( "\r\n", [ 'Content-Type: application/x-www-form-urlencoded', 'Accept: application/json', 'User-Agent: ' . $this->get_user_agent(), ] ), ]; if ( ! empty( $query ) ) { $options['http']['content'] = http_build_query( $query ); } } else { $url = $this->get_url( $url, $query ); $options['http']['header'] = 'User-Agent: ' . $this->get_user_agent(); } return @file_get_contents( $url, false, stream_context_create( $options ) ); }
php
protected function get_contents( $key, $query = [] ) { $url = $this->get_config_value( $key ); if ( empty( $url ) ) { return false; } $options['ssl']['verify_peer'] = false; $options['ssl']['verify_peer_name'] = false; $options['http']['ignore_errors'] = true; if ( $this->is_post_access( $key ) ) { $options['http'] = [ 'method' => 'POST', 'header' => implode( "\r\n", [ 'Content-Type: application/x-www-form-urlencoded', 'Accept: application/json', 'User-Agent: ' . $this->get_user_agent(), ] ), ]; if ( ! empty( $query ) ) { $options['http']['content'] = http_build_query( $query ); } } else { $url = $this->get_url( $url, $query ); $options['http']['header'] = 'User-Agent: ' . $this->get_user_agent(); } return @file_get_contents( $url, false, stream_context_create( $options ) ); }
[ "protected", "function", "get_contents", "(", "$", "key", ",", "$", "query", "=", "[", "]", ")", "{", "$", "url", "=", "$", "this", "->", "get_config_value", "(", "$", "key", ")", ";", "if", "(", "empty", "(", "$", "url", ")", ")", "{", "return", "false", ";", "}", "$", "options", "[", "'ssl'", "]", "[", "'verify_peer'", "]", "=", "false", ";", "$", "options", "[", "'ssl'", "]", "[", "'verify_peer_name'", "]", "=", "false", ";", "$", "options", "[", "'http'", "]", "[", "'ignore_errors'", "]", "=", "true", ";", "if", "(", "$", "this", "->", "is_post_access", "(", "$", "key", ")", ")", "{", "$", "options", "[", "'http'", "]", "=", "[", "'method'", "=>", "'POST'", ",", "'header'", "=>", "implode", "(", "\"\\r\\n\"", ",", "[", "'Content-Type: application/x-www-form-urlencoded'", ",", "'Accept: application/json'", ",", "'User-Agent: '", ".", "$", "this", "->", "get_user_agent", "(", ")", ",", "]", ")", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "query", ")", ")", "{", "$", "options", "[", "'http'", "]", "[", "'content'", "]", "=", "http_build_query", "(", "$", "query", ")", ";", "}", "}", "else", "{", "$", "url", "=", "$", "this", "->", "get_url", "(", "$", "url", ",", "$", "query", ")", ";", "$", "options", "[", "'http'", "]", "[", "'header'", "]", "=", "'User-Agent: '", ".", "$", "this", "->", "get_user_agent", "(", ")", ";", "}", "return", "@", "file_get_contents", "(", "$", "url", ",", "false", ",", "stream_context_create", "(", "$", "options", ")", ")", ";", "}" ]
@param array $query @param string $key @return bool|string
[ "@param", "array", "$query", "@param", "string", "$key" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L315-L341
technote-space/wordpress-plugin-base
src/traits/helper/social.php
Social.get_user_data
protected function get_user_data( $user ) { if ( ! isset( $user['last_name'] ) && ! isset( $user['family_name'] ) ) { if ( ! empty( $user['name'] ) ) { $exploded = array_filter( explode( ' ', $user['name'] ) ); if ( count( $exploded ) > 0 ) { $user['last_name'] = $exploded[0]; if ( count( $exploded ) > 1 ) { $user['first_name'] = $exploded[1]; } } } } return [ isset( $user['last_name'] ) ? $user['last_name'] : ( isset( $user['family_name'] ) ? $user['family_name'] : '' ), isset( $user['first_name'] ) ? $user['first_name'] : ( isset( $user['given_name'] ) ? $user['given_name'] : '' ), $user['email'], ]; }
php
protected function get_user_data( $user ) { if ( ! isset( $user['last_name'] ) && ! isset( $user['family_name'] ) ) { if ( ! empty( $user['name'] ) ) { $exploded = array_filter( explode( ' ', $user['name'] ) ); if ( count( $exploded ) > 0 ) { $user['last_name'] = $exploded[0]; if ( count( $exploded ) > 1 ) { $user['first_name'] = $exploded[1]; } } } } return [ isset( $user['last_name'] ) ? $user['last_name'] : ( isset( $user['family_name'] ) ? $user['family_name'] : '' ), isset( $user['first_name'] ) ? $user['first_name'] : ( isset( $user['given_name'] ) ? $user['given_name'] : '' ), $user['email'], ]; }
[ "protected", "function", "get_user_data", "(", "$", "user", ")", "{", "if", "(", "!", "isset", "(", "$", "user", "[", "'last_name'", "]", ")", "&&", "!", "isset", "(", "$", "user", "[", "'family_name'", "]", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "user", "[", "'name'", "]", ")", ")", "{", "$", "exploded", "=", "array_filter", "(", "explode", "(", "' '", ",", "$", "user", "[", "'name'", "]", ")", ")", ";", "if", "(", "count", "(", "$", "exploded", ")", ">", "0", ")", "{", "$", "user", "[", "'last_name'", "]", "=", "$", "exploded", "[", "0", "]", ";", "if", "(", "count", "(", "$", "exploded", ")", ">", "1", ")", "{", "$", "user", "[", "'first_name'", "]", "=", "$", "exploded", "[", "1", "]", ";", "}", "}", "}", "}", "return", "[", "isset", "(", "$", "user", "[", "'last_name'", "]", ")", "?", "$", "user", "[", "'last_name'", "]", ":", "(", "isset", "(", "$", "user", "[", "'family_name'", "]", ")", "?", "$", "user", "[", "'family_name'", "]", ":", "''", ")", ",", "isset", "(", "$", "user", "[", "'first_name'", "]", ")", "?", "$", "user", "[", "'first_name'", "]", ":", "(", "isset", "(", "$", "user", "[", "'given_name'", "]", ")", "?", "$", "user", "[", "'given_name'", "]", ":", "''", ")", ",", "$", "user", "[", "'email'", "]", ",", "]", ";", "}" ]
@param array $user @return array
[ "@param", "array", "$user" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/traits/helper/social.php#L348-L366
ronaldborla/chikka
src/Borla/Chikka/Support/Http/Http.php
Http.post
public function post($url, $body, array $headers = array()) { // If body is array if (is_array($body)) { // Convert to string $body = http_build_query($body); } // Do post and get response $response = $this->getClient()->post($url, $body, $headers); // If not response if ( ! $response instanceof Response) { // Throw error throw new InvalidType('HttpInterface post method must return an instance of \Borla\Chikka\Support\Http\Response'); } // Return response return $response; }
php
public function post($url, $body, array $headers = array()) { // If body is array if (is_array($body)) { // Convert to string $body = http_build_query($body); } // Do post and get response $response = $this->getClient()->post($url, $body, $headers); // If not response if ( ! $response instanceof Response) { // Throw error throw new InvalidType('HttpInterface post method must return an instance of \Borla\Chikka\Support\Http\Response'); } // Return response return $response; }
[ "public", "function", "post", "(", "$", "url", ",", "$", "body", ",", "array", "$", "headers", "=", "array", "(", ")", ")", "{", "// If body is array", "if", "(", "is_array", "(", "$", "body", ")", ")", "{", "// Convert to string", "$", "body", "=", "http_build_query", "(", "$", "body", ")", ";", "}", "// Do post and get response", "$", "response", "=", "$", "this", "->", "getClient", "(", ")", "->", "post", "(", "$", "url", ",", "$", "body", ",", "$", "headers", ")", ";", "// If not response", "if", "(", "!", "$", "response", "instanceof", "Response", ")", "{", "// Throw error", "throw", "new", "InvalidType", "(", "'HttpInterface post method must return an instance of \\Borla\\Chikka\\Support\\Http\\Response'", ")", ";", "}", "// Return response", "return", "$", "response", ";", "}" ]
Create post request @return \Borla\Chikka\Support\Http\Response
[ "Create", "post", "request" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Http/Http.php#L24-L39
ronaldborla/chikka
src/Borla/Chikka/Support/Http/Http.php
Http.getClient
protected function getClient() { // If there's already a client if ($this->client) { // Use client return $this->client; } // Prioritize guzzle if (class_exists('\GuzzleHttp\Client')) { // Use guzzle return $this->client = new Guzzle(); } // Otherwise, curl elseif (function_exists('curl_init')) { // Use curl return $this->client = new Curl(); } }
php
protected function getClient() { // If there's already a client if ($this->client) { // Use client return $this->client; } // Prioritize guzzle if (class_exists('\GuzzleHttp\Client')) { // Use guzzle return $this->client = new Guzzle(); } // Otherwise, curl elseif (function_exists('curl_init')) { // Use curl return $this->client = new Curl(); } }
[ "protected", "function", "getClient", "(", ")", "{", "// If there's already a client", "if", "(", "$", "this", "->", "client", ")", "{", "// Use client", "return", "$", "this", "->", "client", ";", "}", "// Prioritize guzzle", "if", "(", "class_exists", "(", "'\\GuzzleHttp\\Client'", ")", ")", "{", "// Use guzzle", "return", "$", "this", "->", "client", "=", "new", "Guzzle", "(", ")", ";", "}", "// Otherwise, curl", "elseif", "(", "function_exists", "(", "'curl_init'", ")", ")", "{", "// Use curl", "return", "$", "this", "->", "client", "=", "new", "Curl", "(", ")", ";", "}", "}" ]
Get client
[ "Get", "client" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Http/Http.php#L44-L60
zhouyl/mellivora
Mellivora/Console/App.php
App.registerFacades
protected function registerFacades() { if (isset($this->container['facades'])) { foreach ($this->container['facades'] as $alias => $abstract) { class_alias($abstract, $alias); } } }
php
protected function registerFacades() { if (isset($this->container['facades'])) { foreach ($this->container['facades'] as $alias => $abstract) { class_alias($abstract, $alias); } } }
[ "protected", "function", "registerFacades", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "container", "[", "'facades'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "container", "[", "'facades'", "]", "as", "$", "alias", "=>", "$", "abstract", ")", "{", "class_alias", "(", "$", "abstract", ",", "$", "alias", ")", ";", "}", "}", "}" ]
注册类别名
[ "注册类别名" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/App.php#L76-L83
zhouyl/mellivora
Mellivora/Console/App.php
App.registerProviders
protected function registerProviders() { if (isset($this->container['providers'])) { foreach ($this->container['providers'] as $provider) { if (!is_subclass_of($provider, ServiceProvider::class)) { throw new UnexpectedValueException($provider . ' must return instance of ' . ServiceProvider::class); } (new $provider($this))->register(); } } }
php
protected function registerProviders() { if (isset($this->container['providers'])) { foreach ($this->container['providers'] as $provider) { if (!is_subclass_of($provider, ServiceProvider::class)) { throw new UnexpectedValueException($provider . ' must return instance of ' . ServiceProvider::class); } (new $provider($this))->register(); } } }
[ "protected", "function", "registerProviders", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "container", "[", "'providers'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "container", "[", "'providers'", "]", "as", "$", "provider", ")", "{", "if", "(", "!", "is_subclass_of", "(", "$", "provider", ",", "ServiceProvider", "::", "class", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "$", "provider", ".", "' must return instance of '", ".", "ServiceProvider", "::", "class", ")", ";", "}", "(", "new", "$", "provider", "(", "$", "this", ")", ")", "->", "register", "(", ")", ";", "}", "}", "}" ]
注册 Service Providers
[ "注册", "Service", "Providers" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/App.php#L88-L100
zhouyl/mellivora
Mellivora/Console/App.php
App.addCommands
public function addCommands(array $commands) { foreach ($commands as $command) { if ($command instanceof Command) { $this->add($command); } else { $ref = new ReflectionClass($command); if ($ref->isInstantiable() && $ref->isSubclassOf(Command::class)) { $this->add($ref->newInstance($this->getContainer())); } } } }
php
public function addCommands(array $commands) { foreach ($commands as $command) { if ($command instanceof Command) { $this->add($command); } else { $ref = new ReflectionClass($command); if ($ref->isInstantiable() && $ref->isSubclassOf(Command::class)) { $this->add($ref->newInstance($this->getContainer())); } } } }
[ "public", "function", "addCommands", "(", "array", "$", "commands", ")", "{", "foreach", "(", "$", "commands", "as", "$", "command", ")", "{", "if", "(", "$", "command", "instanceof", "Command", ")", "{", "$", "this", "->", "add", "(", "$", "command", ")", ";", "}", "else", "{", "$", "ref", "=", "new", "ReflectionClass", "(", "$", "command", ")", ";", "if", "(", "$", "ref", "->", "isInstantiable", "(", ")", "&&", "$", "ref", "->", "isSubclassOf", "(", "Command", "::", "class", ")", ")", "{", "$", "this", "->", "add", "(", "$", "ref", "->", "newInstance", "(", "$", "this", "->", "getContainer", "(", ")", ")", ")", ";", "}", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/App.php#L113-L125
zhouyl/mellivora
Mellivora/Console/App.php
App.registerDefaultCommands
protected function registerDefaultCommands() { $this->addCommands([ \Mellivora\Console\Commands\ViewClearCommand::class, \Mellivora\Console\Commands\TestMakeCommand::class, \Mellivora\Console\Commands\ConsoleMakeCommand::class, \Mellivora\Console\Commands\ProviderMakeCommand::class, \Mellivora\Console\Commands\MiddlewareMakeCommand::class, \Mellivora\Console\Commands\ControllerMakeCommand::class, \Mellivora\Console\Commands\ModelMakeCommand::class, \Mellivora\Database\Console\Seeds\SeedCommand::class, \Mellivora\Database\Console\Seeds\SeederMakeCommand::class, \Mellivora\Database\Console\Migrations\InstallCommand::class, \Mellivora\Database\Console\Migrations\MigrateCommand::class, \Mellivora\Database\Console\Migrations\MigrateMakeCommand::class, \Mellivora\Database\Console\Migrations\ResetCommand::class, \Mellivora\Database\Console\Migrations\RollbackCommand::class, \Mellivora\Database\Console\Migrations\RefreshCommand::class, \Mellivora\Database\Console\Migrations\StatusCommand::class, ]); }
php
protected function registerDefaultCommands() { $this->addCommands([ \Mellivora\Console\Commands\ViewClearCommand::class, \Mellivora\Console\Commands\TestMakeCommand::class, \Mellivora\Console\Commands\ConsoleMakeCommand::class, \Mellivora\Console\Commands\ProviderMakeCommand::class, \Mellivora\Console\Commands\MiddlewareMakeCommand::class, \Mellivora\Console\Commands\ControllerMakeCommand::class, \Mellivora\Console\Commands\ModelMakeCommand::class, \Mellivora\Database\Console\Seeds\SeedCommand::class, \Mellivora\Database\Console\Seeds\SeederMakeCommand::class, \Mellivora\Database\Console\Migrations\InstallCommand::class, \Mellivora\Database\Console\Migrations\MigrateCommand::class, \Mellivora\Database\Console\Migrations\MigrateMakeCommand::class, \Mellivora\Database\Console\Migrations\ResetCommand::class, \Mellivora\Database\Console\Migrations\RollbackCommand::class, \Mellivora\Database\Console\Migrations\RefreshCommand::class, \Mellivora\Database\Console\Migrations\StatusCommand::class, ]); }
[ "protected", "function", "registerDefaultCommands", "(", ")", "{", "$", "this", "->", "addCommands", "(", "[", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "ViewClearCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "TestMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "ConsoleMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "ProviderMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "MiddlewareMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "ControllerMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Console", "\\", "Commands", "\\", "ModelMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Seeds", "\\", "SeedCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Seeds", "\\", "SeederMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "InstallCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "MigrateCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "MigrateMakeCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "ResetCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "RollbackCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "RefreshCommand", "::", "class", ",", "\\", "Mellivora", "\\", "Database", "\\", "Console", "\\", "Migrations", "\\", "StatusCommand", "::", "class", ",", "]", ")", ";", "}" ]
注册默认的 Commands
[ "注册默认的", "Commands" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/App.php#L140-L160
zhouyl/mellivora
Mellivora/Console/App.php
App.renderException
public function renderException(\Exception $e, OutputInterface $output) { parent::renderException($e, $output); if (is_callable($this->exceptionHandler)) { try { if (method_exists($this->exceptionHandler, '__invoke')) { $this->exceptionHandler->__invoke($e); } else { call_user_func($this->exceptionHandler, $e); } } catch (\Exception $e) { } } }
php
public function renderException(\Exception $e, OutputInterface $output) { parent::renderException($e, $output); if (is_callable($this->exceptionHandler)) { try { if (method_exists($this->exceptionHandler, '__invoke')) { $this->exceptionHandler->__invoke($e); } else { call_user_func($this->exceptionHandler, $e); } } catch (\Exception $e) { } } }
[ "public", "function", "renderException", "(", "\\", "Exception", "$", "e", ",", "OutputInterface", "$", "output", ")", "{", "parent", "::", "renderException", "(", "$", "e", ",", "$", "output", ")", ";", "if", "(", "is_callable", "(", "$", "this", "->", "exceptionHandler", ")", ")", "{", "try", "{", "if", "(", "method_exists", "(", "$", "this", "->", "exceptionHandler", ",", "'__invoke'", ")", ")", "{", "$", "this", "->", "exceptionHandler", "->", "__invoke", "(", "$", "e", ")", ";", "}", "else", "{", "call_user_func", "(", "$", "this", "->", "exceptionHandler", ",", "$", "e", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}", "}" ]
Renders a caught exception. @param \Exception $e An exception instance @param OutputInterface $output An OutputInterface instance
[ "Renders", "a", "caught", "exception", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/App.php#L192-L206
flowcode/AmulenUserBundle
src/Flowcode/UserBundle/Repository/UserRepository.php
UserRepository.findByUsername
public function findByUsername($username) { $qb = $this->createQueryBuilder("u"); $qb->where("(u.username = :username OR u.email = :email)") ->setParameter("username", $username) ->setParameter("email", $username); $qb->andWhere("u.status = :status")->setParameter("status", 1); $qb->setMaxResults(1); return $qb->getQuery()->getOneOrNullResult(); }
php
public function findByUsername($username) { $qb = $this->createQueryBuilder("u"); $qb->where("(u.username = :username OR u.email = :email)") ->setParameter("username", $username) ->setParameter("email", $username); $qb->andWhere("u.status = :status")->setParameter("status", 1); $qb->setMaxResults(1); return $qb->getQuery()->getOneOrNullResult(); }
[ "public", "function", "findByUsername", "(", "$", "username", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "\"u\"", ")", ";", "$", "qb", "->", "where", "(", "\"(u.username = :username OR u.email = :email)\"", ")", "->", "setParameter", "(", "\"username\"", ",", "$", "username", ")", "->", "setParameter", "(", "\"email\"", ",", "$", "username", ")", ";", "$", "qb", "->", "andWhere", "(", "\"u.status = :status\"", ")", "->", "setParameter", "(", "\"status\"", ",", "1", ")", ";", "$", "qb", "->", "setMaxResults", "(", "1", ")", ";", "return", "$", "qb", "->", "getQuery", "(", ")", "->", "getOneOrNullResult", "(", ")", ";", "}" ]
Find by username. @param string $username A username. @return User The user.
[ "Find", "by", "username", "." ]
train
https://github.com/flowcode/AmulenUserBundle/blob/00055834d9f094e63dcd8d66e2fedb822fcddee0/src/Flowcode/UserBundle/Repository/UserRepository.php#L22-L31
ShaoZeMing/laravel-merchant
src/Controllers/RoleController.php
RoleController.grid
protected function grid() { return Merchant::grid(Role::class, function (Grid $grid) { $grid->id('ID')->sortable(); $grid->slug(trans('merchant.slug')); $grid->name(trans('merchant.name')); $grid->permissions(trans('merchant.permission'))->pluck('name')->label(); $grid->created_at(trans('merchant.created_at')); $grid->updated_at(trans('merchant.updated_at')); $grid->actions(function (Grid\Displayers\Actions $actions) { if ($actions->row->slug == 'administrator') { $actions->disableDelete(); } }); $grid->tools(function (Grid\Tools $tools) { $tools->batch(function (Grid\Tools\BatchActions $actions) { $actions->disableDelete(); }); }); }); }
php
protected function grid() { return Merchant::grid(Role::class, function (Grid $grid) { $grid->id('ID')->sortable(); $grid->slug(trans('merchant.slug')); $grid->name(trans('merchant.name')); $grid->permissions(trans('merchant.permission'))->pluck('name')->label(); $grid->created_at(trans('merchant.created_at')); $grid->updated_at(trans('merchant.updated_at')); $grid->actions(function (Grid\Displayers\Actions $actions) { if ($actions->row->slug == 'administrator') { $actions->disableDelete(); } }); $grid->tools(function (Grid\Tools $tools) { $tools->batch(function (Grid\Tools\BatchActions $actions) { $actions->disableDelete(); }); }); }); }
[ "protected", "function", "grid", "(", ")", "{", "return", "Merchant", "::", "grid", "(", "Role", "::", "class", ",", "function", "(", "Grid", "$", "grid", ")", "{", "$", "grid", "->", "id", "(", "'ID'", ")", "->", "sortable", "(", ")", ";", "$", "grid", "->", "slug", "(", "trans", "(", "'merchant.slug'", ")", ")", ";", "$", "grid", "->", "name", "(", "trans", "(", "'merchant.name'", ")", ")", ";", "$", "grid", "->", "permissions", "(", "trans", "(", "'merchant.permission'", ")", ")", "->", "pluck", "(", "'name'", ")", "->", "label", "(", ")", ";", "$", "grid", "->", "created_at", "(", "trans", "(", "'merchant.created_at'", ")", ")", ";", "$", "grid", "->", "updated_at", "(", "trans", "(", "'merchant.updated_at'", ")", ")", ";", "$", "grid", "->", "actions", "(", "function", "(", "Grid", "\\", "Displayers", "\\", "Actions", "$", "actions", ")", "{", "if", "(", "$", "actions", "->", "row", "->", "slug", "==", "'administrator'", ")", "{", "$", "actions", "->", "disableDelete", "(", ")", ";", "}", "}", ")", ";", "$", "grid", "->", "tools", "(", "function", "(", "Grid", "\\", "Tools", "$", "tools", ")", "{", "$", "tools", "->", "batch", "(", "function", "(", "Grid", "\\", "Tools", "\\", "BatchActions", "$", "actions", ")", "{", "$", "actions", "->", "disableDelete", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Make a grid builder. @return Grid
[ "Make", "a", "grid", "builder", "." ]
train
https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Controllers/RoleController.php#L66-L90
ShaoZeMing/laravel-merchant
src/Controllers/RoleController.php
RoleController.form
public function form() { return Merchant::form(Role::class, function (Form $form) { $form->display('id', 'ID'); $form->text('slug', trans('merchant.slug'))->rules('required'); $form->text('name', trans('merchant.name'))->rules('required'); $form->listbox('permissions', trans('merchant.permissions'))->options(Permission::all()->pluck('name', 'id')); $form->display('created_at', trans('merchant.created_at')); $form->display('updated_at', trans('merchant.updated_at')); }); }
php
public function form() { return Merchant::form(Role::class, function (Form $form) { $form->display('id', 'ID'); $form->text('slug', trans('merchant.slug'))->rules('required'); $form->text('name', trans('merchant.name'))->rules('required'); $form->listbox('permissions', trans('merchant.permissions'))->options(Permission::all()->pluck('name', 'id')); $form->display('created_at', trans('merchant.created_at')); $form->display('updated_at', trans('merchant.updated_at')); }); }
[ "public", "function", "form", "(", ")", "{", "return", "Merchant", "::", "form", "(", "Role", "::", "class", ",", "function", "(", "Form", "$", "form", ")", "{", "$", "form", "->", "display", "(", "'id'", ",", "'ID'", ")", ";", "$", "form", "->", "text", "(", "'slug'", ",", "trans", "(", "'merchant.slug'", ")", ")", "->", "rules", "(", "'required'", ")", ";", "$", "form", "->", "text", "(", "'name'", ",", "trans", "(", "'merchant.name'", ")", ")", "->", "rules", "(", "'required'", ")", ";", "$", "form", "->", "listbox", "(", "'permissions'", ",", "trans", "(", "'merchant.permissions'", ")", ")", "->", "options", "(", "Permission", "::", "all", "(", ")", "->", "pluck", "(", "'name'", ",", "'id'", ")", ")", ";", "$", "form", "->", "display", "(", "'created_at'", ",", "trans", "(", "'merchant.created_at'", ")", ")", ";", "$", "form", "->", "display", "(", "'updated_at'", ",", "trans", "(", "'merchant.updated_at'", ")", ")", ";", "}", ")", ";", "}" ]
Make a form builder. @return Form
[ "Make", "a", "form", "builder", "." ]
train
https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Controllers/RoleController.php#L97-L109
Eresus/EresusCMS
src/core/Exception/InvalidArgumentType.php
Eresus_Exception_InvalidArgumentType.factory
public static function factory($method, $argNum, $expectedType, $actualArg) { return new self(sprintf( 'Argument %d of %s expected to be a %s, %s given', $argNum, $method, $expectedType, is_object($actualArg) ? 'instance of ' . get_class($actualArg) : gettype($actualArg) )); }
php
public static function factory($method, $argNum, $expectedType, $actualArg) { return new self(sprintf( 'Argument %d of %s expected to be a %s, %s given', $argNum, $method, $expectedType, is_object($actualArg) ? 'instance of ' . get_class($actualArg) : gettype($actualArg) )); }
[ "public", "static", "function", "factory", "(", "$", "method", ",", "$", "argNum", ",", "$", "expectedType", ",", "$", "actualArg", ")", "{", "return", "new", "self", "(", "sprintf", "(", "'Argument %d of %s expected to be a %s, %s given'", ",", "$", "argNum", ",", "$", "method", ",", "$", "expectedType", ",", "is_object", "(", "$", "actualArg", ")", "?", "'instance of '", ".", "get_class", "(", "$", "actualArg", ")", ":", "gettype", "(", "$", "actualArg", ")", ")", ")", ";", "}" ]
Фабрика исключений @param string $method метод, где произошла ошибка @param int $argNum порядковый номер аргумента @param string $expectedType ожидаемый тип аргумента @param mixed $actualArg аргумент, вызвавший ошибку @return Eresus_Exception_InvalidArgumentType
[ "Фабрика", "исключений" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Exception/InvalidArgumentType.php#L47-L56
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.fileExistFormatLink
public function fileExistFormatLink( $path , $user , $event , $view , $name , $class = NULL){ $link = $path.$user.'/'.$view.'_'.$event.'-'.$user.'.pdf'; $url = getcwd().'/'.$link; $add = ''; if ( \File::exists($url) ) { $asset = asset($link); if($class){ $add = ' class="'.$class.'" '; } return '<a target="_blank" href="'.$asset.'"'.$add.'>'.$name.'</a>'; } return ''; }
php
public function fileExistFormatLink( $path , $user , $event , $view , $name , $class = NULL){ $link = $path.$user.'/'.$view.'_'.$event.'-'.$user.'.pdf'; $url = getcwd().'/'.$link; $add = ''; if ( \File::exists($url) ) { $asset = asset($link); if($class){ $add = ' class="'.$class.'" '; } return '<a target="_blank" href="'.$asset.'"'.$add.'>'.$name.'</a>'; } return ''; }
[ "public", "function", "fileExistFormatLink", "(", "$", "path", ",", "$", "user", ",", "$", "event", ",", "$", "view", ",", "$", "name", ",", "$", "class", "=", "NULL", ")", "{", "$", "link", "=", "$", "path", ".", "$", "user", ".", "'/'", ".", "$", "view", ".", "'_'", ".", "$", "event", ".", "'-'", ".", "$", "user", ".", "'.pdf'", ";", "$", "url", "=", "getcwd", "(", ")", ".", "'/'", ".", "$", "link", ";", "$", "add", "=", "''", ";", "if", "(", "\\", "File", "::", "exists", "(", "$", "url", ")", ")", "{", "$", "asset", "=", "asset", "(", "$", "link", ")", ";", "if", "(", "$", "class", ")", "{", "$", "add", "=", "' class=\"'", ".", "$", "class", ".", "'\" '", ";", "}", "return", "'<a target=\"_blank\" href=\"'", ".", "$", "asset", ".", "'\"'", ".", "$", "add", ".", "'>'", ".", "$", "name", ".", "'</a>'", ";", "}", "return", "''", ";", "}" ]
/* Files functions
[ "/", "*", "Files", "functions" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L30-L49
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.getMimeType
public function getMimeType($filename) { $mimetype = false; if(function_exists('finfo_fopen')) { $mimetype = finfo_fopen($filename); } elseif(function_exists('getimagesize')) { $mimetype = getimagesize($filename); } elseif(function_exists('exif_imagetype')) { $mimetype = exif_imagetype($filename); } elseif(function_exists('mime_content_type')) { $mimetype = mime_content_type($filename); } return $mimetype['mime']; }
php
public function getMimeType($filename) { $mimetype = false; if(function_exists('finfo_fopen')) { $mimetype = finfo_fopen($filename); } elseif(function_exists('getimagesize')) { $mimetype = getimagesize($filename); } elseif(function_exists('exif_imagetype')) { $mimetype = exif_imagetype($filename); } elseif(function_exists('mime_content_type')) { $mimetype = mime_content_type($filename); } return $mimetype['mime']; }
[ "public", "function", "getMimeType", "(", "$", "filename", ")", "{", "$", "mimetype", "=", "false", ";", "if", "(", "function_exists", "(", "'finfo_fopen'", ")", ")", "{", "$", "mimetype", "=", "finfo_fopen", "(", "$", "filename", ")", ";", "}", "elseif", "(", "function_exists", "(", "'getimagesize'", ")", ")", "{", "$", "mimetype", "=", "getimagesize", "(", "$", "filename", ")", ";", "}", "elseif", "(", "function_exists", "(", "'exif_imagetype'", ")", ")", "{", "$", "mimetype", "=", "exif_imagetype", "(", "$", "filename", ")", ";", "}", "elseif", "(", "function_exists", "(", "'mime_content_type'", ")", ")", "{", "$", "mimetype", "=", "mime_content_type", "(", "$", "filename", ")", ";", "}", "return", "$", "mimetype", "[", "'mime'", "]", ";", "}" ]
/* Get mime-type of file
[ "/", "*", "Get", "mime", "-", "type", "of", "file" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L52-L74
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.ifExist
public static function ifExist(&$argument, $default="") { if(!isset($argument)) { $argument = $default; return $argument; } $argument = trim($argument); return $argument; }
php
public static function ifExist(&$argument, $default="") { if(!isset($argument)) { $argument = $default; return $argument; } $argument = trim($argument); return $argument; }
[ "public", "static", "function", "ifExist", "(", "&", "$", "argument", ",", "$", "default", "=", "\"\"", ")", "{", "if", "(", "!", "isset", "(", "$", "argument", ")", ")", "{", "$", "argument", "=", "$", "default", ";", "return", "$", "argument", ";", "}", "$", "argument", "=", "trim", "(", "$", "argument", ")", ";", "return", "$", "argument", ";", "}" ]
/* Misc functions
[ "/", "*", "Misc", "functions" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L101-L111
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper._removeAccents
public function _removeAccents ($text) { $alphabet = array( 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f', 'ü'=>'u' ); $text = strtr ($text, $alphabet); // replace all non letters or digits by - $text = preg_replace('/\W+/', '', $text); return $text; }
php
public function _removeAccents ($text) { $alphabet = array( 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f', 'ü'=>'u' ); $text = strtr ($text, $alphabet); // replace all non letters or digits by - $text = preg_replace('/\W+/', '', $text); return $text; }
[ "public", "function", "_removeAccents", "(", "$", "text", ")", "{", "$", "alphabet", "=", "array", "(", "'Š'=", ">'", "S',", " ", "š'=>", "'s", "', ", "'", "'=>'", "Dj", "','Ž", "'", "=>'Z", "',", " 'ž", "'", ">'z'", ", ", "'À'", "=", "'A',", " '", "Á'=", ">", "A', ", "'Â", "'=>", "'", "', '", "Ã'", "=>'", "A", ", 'Ä", "'=", ">'A", "'", "", "", "", "", "'Å'=", ">'", "A',", " ", "Æ'=>", "'A", "', ", "'", "'=>'", "C'", ", '", "È", "=>'E", "',", " 'É", "'", ">'E'", ", ", "'Ê'", "=", "'E',", " '", "Ë'=", ">", "E', ", "'Ì", "'=>", "'", "', '", "Í'", "=>'", "I", ", 'Î", "'=", ">'I", "'", "", "", "", "", "'Ï'=", ">'", "I',", " ", "Ñ'=>", "'N", "', ", "'", "'=>'", "O'", ", '", "Ó", "=>'O", "',", " 'Ô", "'", ">'O'", ", ", "'Õ'", "=", "'O',", " '", "Ö'=", ">", "O', ", "'Ø", "'=>", "'", "', '", "Ù'", "=>'", "U", ", 'Ú", "'=", ">'U", "'", "", "", "", "", "'Û'=", ">'", "U',", " ", "Ü'=>", "'U", "', ", "'", "'=>'", "Y'", ", '", "Þ", "=>'B", "',", " 'ß", "'", ">'Ss", "',", "'à'=", ">", "'a',", " '", "á'=", ">", "a', ", "'â", "'=>", "'", "', '", "ã'", "=>'", "a", ", 'ä", "'=", ">'a", "'", "", "", "", "", "'å'=", ">'", "a',", " ", "æ'=>", "'a", "', ", "'", "'=>'", "c'", ", '", "è", "=>'e", "',", " 'é", "'", ">'e'", ", ", "'ê'", "=", "'e',", " '", "ë'=", ">", "e', ", "'ì", "'=>", "'", "', '", "í'", "=>'", "i", ", 'î", "'=", ">'i", "'", "", "", "", "", "'ï'=", ">'", "i',", " ", "ð'=>", "'o", "', ", "'", "'=>'", "n'", ", '", "ò", "=>'o", "',", " 'ó", "'", ">'o'", ", ", "'ô'", "=", "'o',", " '", "õ'=", ">", "o', ", "'ö", "'=>", "'", "', '", "ø'", "=>'", "o", ", 'ù", "'=", ">'u", "'", "", "", "", "", "'ú'=", ">'", "u',", " ", "û'=>", "'u", "', ", "'", "'=>'", "y'", ", '", "ý", "=>'y", "',", " 'þ", "'", ">'b'", ", ", "'ÿ'", "=", "'y',", " '", "ƒ'=", ">", "f', ", "'ü", "'=>", "'", "'", "", "", ")", ";", "$", "text", "=", "strtr", "(", "$", "text", ",", "$", "alphabet", ")", ";", "// replace all non letters or digits by -", "$", "text", "=", "preg_replace", "(", "'/\\W+/'", ",", "''", ",", "$", "text", ")", ";", "return", "$", "text", ";", "}" ]
/* Remove accents
[ "/", "*", "Remove", "accents" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L130-L147
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper._removeNonAlphanumericLetters
public function _removeNonAlphanumericLetters($sString) { //Conversion des majuscules en minuscule $string = strtolower(htmlentities($sString)); //Listez ici tous les balises HTML que vous pourriez rencontrer $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $string); //Tout ce qui n'est pas caractère alphanumérique -> _ $string = preg_replace("/([^a-z0-9]+)/", "_", html_entity_decode($string)); return $string; }
php
public function _removeNonAlphanumericLetters($sString) { //Conversion des majuscules en minuscule $string = strtolower(htmlentities($sString)); //Listez ici tous les balises HTML que vous pourriez rencontrer $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $string); //Tout ce qui n'est pas caractère alphanumérique -> _ $string = preg_replace("/([^a-z0-9]+)/", "_", html_entity_decode($string)); return $string; }
[ "public", "function", "_removeNonAlphanumericLetters", "(", "$", "sString", ")", "{", "//Conversion des majuscules en minuscule", "$", "string", "=", "strtolower", "(", "htmlentities", "(", "$", "sString", ")", ")", ";", "//Listez ici tous les balises HTML que vous pourriez rencontrer", "$", "string", "=", "preg_replace", "(", "\"/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/\"", ",", "\"$1\"", ",", "$", "string", ")", ";", "//Tout ce qui n'est pas caractère alphanumérique -> _", "$", "string", "=", "preg_replace", "(", "\"/([^a-z0-9]+)/\"", ",", "\"_\"", ",", "html_entity_decode", "(", "$", "string", ")", ")", ";", "return", "$", "string", ";", "}" ]
/* remove html tags and non alphanumerics letters
[ "/", "*", "remove", "html", "tags", "and", "non", "alphanumerics", "letters" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L152-L160
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.knatsort
public function knatsort(&$karr) { $kkeyarr = array_keys($karr); $ksortedarr = array(); natcasesort($kkeyarr); foreach($kkeyarr as $kcurrkey) { $ksortedarr[$kcurrkey] = $karr[$kcurrkey]; } $karr = $ksortedarr; return true; }
php
public function knatsort(&$karr) { $kkeyarr = array_keys($karr); $ksortedarr = array(); natcasesort($kkeyarr); foreach($kkeyarr as $kcurrkey) { $ksortedarr[$kcurrkey] = $karr[$kcurrkey]; } $karr = $ksortedarr; return true; }
[ "public", "function", "knatsort", "(", "&", "$", "karr", ")", "{", "$", "kkeyarr", "=", "array_keys", "(", "$", "karr", ")", ";", "$", "ksortedarr", "=", "array", "(", ")", ";", "natcasesort", "(", "$", "kkeyarr", ")", ";", "foreach", "(", "$", "kkeyarr", "as", "$", "kcurrkey", ")", "{", "$", "ksortedarr", "[", "$", "kcurrkey", "]", "=", "$", "karr", "[", "$", "kcurrkey", "]", ";", "}", "$", "karr", "=", "$", "ksortedarr", ";", "return", "true", ";", "}" ]
/* Sort array by key
[ "/", "*", "Sort", "array", "by", "key" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L183-L198
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.keysort
public function keysort($karr){ $ksortedarr = array(); foreach($karr as $id => $kcurrkey) { // remove accents $currkey = $this->_removeAccents($kcurrkey); $currkey = strtolower($currkey); $ksortedarr[$currkey]['title'] = $kcurrkey; $ksortedarr[$currkey]['id'] = $id; } return $ksortedarr; }
php
public function keysort($karr){ $ksortedarr = array(); foreach($karr as $id => $kcurrkey) { // remove accents $currkey = $this->_removeAccents($kcurrkey); $currkey = strtolower($currkey); $ksortedarr[$currkey]['title'] = $kcurrkey; $ksortedarr[$currkey]['id'] = $id; } return $ksortedarr; }
[ "public", "function", "keysort", "(", "$", "karr", ")", "{", "$", "ksortedarr", "=", "array", "(", ")", ";", "foreach", "(", "$", "karr", "as", "$", "id", "=>", "$", "kcurrkey", ")", "{", "// remove accents", "$", "currkey", "=", "$", "this", "->", "_removeAccents", "(", "$", "kcurrkey", ")", ";", "$", "currkey", "=", "strtolower", "(", "$", "currkey", ")", ";", "$", "ksortedarr", "[", "$", "currkey", "]", "[", "'title'", "]", "=", "$", "kcurrkey", ";", "$", "ksortedarr", "[", "$", "currkey", "]", "[", "'id'", "]", "=", "$", "id", ";", "}", "return", "$", "ksortedarr", ";", "}" ]
/* Sort by keys
[ "/", "*", "Sort", "by", "keys" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L201-L217
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.findAllItemsInArray
public function findAllItemsInArray( $in , $search ){ $need = count($in); $find = count(array_intersect($search, $in)); if($need == $find) { return TRUE; } return FALSE; }
php
public function findAllItemsInArray( $in , $search ){ $need = count($in); $find = count(array_intersect($search, $in)); if($need == $find) { return TRUE; } return FALSE; }
[ "public", "function", "findAllItemsInArray", "(", "$", "in", ",", "$", "search", ")", "{", "$", "need", "=", "count", "(", "$", "in", ")", ";", "$", "find", "=", "count", "(", "array_intersect", "(", "$", "search", ",", "$", "in", ")", ")", ";", "if", "(", "$", "need", "==", "$", "find", ")", "{", "return", "TRUE", ";", "}", "return", "FALSE", ";", "}" ]
/* Find all items in array
[ "/", "*", "Find", "all", "items", "in", "array" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L220-L231
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.compare
public function compare($selected, $result) { $compare = array_intersect($selected, $result); return ($compare == $selected ? true : false); }
php
public function compare($selected, $result) { $compare = array_intersect($selected, $result); return ($compare == $selected ? true : false); }
[ "public", "function", "compare", "(", "$", "selected", ",", "$", "result", ")", "{", "$", "compare", "=", "array_intersect", "(", "$", "selected", ",", "$", "result", ")", ";", "return", "(", "$", "compare", "==", "$", "selected", "?", "true", ":", "false", ")", ";", "}" ]
Compare two arrays @return
[ "Compare", "two", "arrays" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L248-L253
DesignPond/newsletter
src/Newsletter/Helper/Helper.php
Helper.getPrefixString
public function getPrefixString($array, $prefix) { $items = array(); if(!empty($array)){ foreach($array as $item){ preg_match('/'.$prefix.'(.*)/', $item, $results); if(isset($results[1])){ $items[] = $results[1]; } } } return $items; }
php
public function getPrefixString($array, $prefix) { $items = array(); if(!empty($array)){ foreach($array as $item){ preg_match('/'.$prefix.'(.*)/', $item, $results); if(isset($results[1])){ $items[] = $results[1]; } } } return $items; }
[ "public", "function", "getPrefixString", "(", "$", "array", ",", "$", "prefix", ")", "{", "$", "items", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "array", ")", ")", "{", "foreach", "(", "$", "array", "as", "$", "item", ")", "{", "preg_match", "(", "'/'", ".", "$", "prefix", ".", "'(.*)/'", ",", "$", "item", ",", "$", "results", ")", ";", "if", "(", "isset", "(", "$", "results", "[", "1", "]", ")", ")", "{", "$", "items", "[", "]", "=", "$", "results", "[", "1", "]", ";", "}", "}", "}", "return", "$", "items", ";", "}" ]
Get array of string using prefix @return
[ "Get", "array", "of", "string", "using", "prefix" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Helper/Helper.php#L260-L274
Danzabar/config-builder
src/Data/Reader.php
Reader.read
public function read($file) { $this->file = $file; if($this->fs->exists($this->file)) { $this->data = file_get_contents($this->file); return $this; } // Throw exception throw new Exceptions\FileNotExists($this->file); }
php
public function read($file) { $this->file = $file; if($this->fs->exists($this->file)) { $this->data = file_get_contents($this->file); return $this; } // Throw exception throw new Exceptions\FileNotExists($this->file); }
[ "public", "function", "read", "(", "$", "file", ")", "{", "$", "this", "->", "file", "=", "$", "file", ";", "if", "(", "$", "this", "->", "fs", "->", "exists", "(", "$", "this", "->", "file", ")", ")", "{", "$", "this", "->", "data", "=", "file_get_contents", "(", "$", "this", "->", "file", ")", ";", "return", "$", "this", ";", "}", "// Throw exception", "throw", "new", "Exceptions", "\\", "FileNotExists", "(", "$", "this", "->", "file", ")", ";", "}" ]
Read from the file @param String $file @return Reader @author Dan Cox @throws Exceptions\FileNotExists
[ "Read", "from", "the", "file" ]
train
https://github.com/Danzabar/config-builder/blob/3b237be578172c32498bbcdfb360e69a6243739d/src/Data/Reader.php#L56-L69
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.fromString
public static function fromString($json, $directory = ".") { $json = json_decode($json, true); if (is_null($json)) throw new SettingsException("invalid json"); return new static($json, $directory); }
php
public static function fromString($json, $directory = ".") { $json = json_decode($json, true); if (is_null($json)) throw new SettingsException("invalid json"); return new static($json, $directory); }
[ "public", "static", "function", "fromString", "(", "$", "json", ",", "$", "directory", "=", "\".\"", ")", "{", "$", "json", "=", "json_decode", "(", "$", "json", ",", "true", ")", ";", "if", "(", "is_null", "(", "$", "json", ")", ")", "throw", "new", "SettingsException", "(", "\"invalid json\"", ")", ";", "return", "new", "static", "(", "$", "json", ",", "$", "directory", ")", ";", "}" ]
Creates settings from a JSON-encoded string. @param string $json @param string $directory the directory the settings apply to @return Settings
[ "Creates", "settings", "from", "a", "JSON", "-", "encoded", "string", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L74-L79
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.fromFile
public static function fromFile($fileName) { if (!file_exists($fileName)) throw new SettingsException("file $fileName does not exist"); return static::fromString(file_get_contents($fileName), dirname($fileName)); }
php
public static function fromFile($fileName) { if (!file_exists($fileName)) throw new SettingsException("file $fileName does not exist"); return static::fromString(file_get_contents($fileName), dirname($fileName)); }
[ "public", "static", "function", "fromFile", "(", "$", "fileName", ")", "{", "if", "(", "!", "file_exists", "(", "$", "fileName", ")", ")", "throw", "new", "SettingsException", "(", "\"file $fileName does not exist\"", ")", ";", "return", "static", "::", "fromString", "(", "file_get_contents", "(", "$", "fileName", ")", ",", "dirname", "(", "$", "fileName", ")", ")", ";", "}" ]
Creates settings from a JSON-encoded file. @param string $fileName @return Settings
[ "Creates", "settings", "from", "a", "JSON", "-", "encoded", "file", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L86-L90
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.getInstance
public function getInstance($object, $klass) { if ($object === true) $object = array(); if (is_string($object) && method_exists($klass, "fromFile")) return $klass::fromFile($this->getPath($object)); else if (is_array($object) && $this->has("data", $object) && method_exists($klass, "fromString")) return $klass::fromString($object["data"], $this->cfg["directory"]); else if (is_array($object) && method_exists($klass, "fromArray")) return $klass::fromArray($object, $this->cfg["directory"]); else throw new InvalidSettingsException($object, $klass); }
php
public function getInstance($object, $klass) { if ($object === true) $object = array(); if (is_string($object) && method_exists($klass, "fromFile")) return $klass::fromFile($this->getPath($object)); else if (is_array($object) && $this->has("data", $object) && method_exists($klass, "fromString")) return $klass::fromString($object["data"], $this->cfg["directory"]); else if (is_array($object) && method_exists($klass, "fromArray")) return $klass::fromArray($object, $this->cfg["directory"]); else throw new InvalidSettingsException($object, $klass); }
[ "public", "function", "getInstance", "(", "$", "object", ",", "$", "klass", ")", "{", "if", "(", "$", "object", "===", "true", ")", "$", "object", "=", "array", "(", ")", ";", "if", "(", "is_string", "(", "$", "object", ")", "&&", "method_exists", "(", "$", "klass", ",", "\"fromFile\"", ")", ")", "return", "$", "klass", "::", "fromFile", "(", "$", "this", "->", "getPath", "(", "$", "object", ")", ")", ";", "else", "if", "(", "is_array", "(", "$", "object", ")", "&&", "$", "this", "->", "has", "(", "\"data\"", ",", "$", "object", ")", "&&", "method_exists", "(", "$", "klass", ",", "\"fromString\"", ")", ")", "return", "$", "klass", "::", "fromString", "(", "$", "object", "[", "\"data\"", "]", ",", "$", "this", "->", "cfg", "[", "\"directory\"", "]", ")", ";", "else", "if", "(", "is_array", "(", "$", "object", ")", "&&", "method_exists", "(", "$", "klass", ",", "\"fromArray\"", ")", ")", "return", "$", "klass", "::", "fromArray", "(", "$", "object", ",", "$", "this", "->", "cfg", "[", "\"directory\"", "]", ")", ";", "else", "throw", "new", "InvalidSettingsException", "(", "$", "object", ",", "$", "klass", ")", ";", "}" ]
Creates an instance of a class from a plain settings array. If a string is given, the class is instantiated from a file. If an array("data" => ...) is given, the class is instantiated from a string. If another array is given, the class is instantiated from that array. If true is given, the class is instantiated from an empty array. @param string|array|bool $object @param string $klass @return $class
[ "Creates", "an", "instance", "of", "a", "class", "from", "a", "plain", "settings", "array", ".", "If", "a", "string", "is", "given", "the", "class", "is", "instantiated", "from", "a", "file", ".", "If", "an", "array", "(", "data", "=", ">", "...", ")", "is", "given", "the", "class", "is", "instantiated", "from", "a", "string", ".", "If", "another", "array", "is", "given", "the", "class", "is", "instantiated", "from", "that", "array", ".", "If", "true", "is", "given", "the", "class", "is", "instantiated", "from", "an", "empty", "array", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L138-L150
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.has
protected function has($key, $cfg = null) { if (!$cfg) $cfg = $this->cfg; return array_key_exists($key, $cfg); }
php
protected function has($key, $cfg = null) { if (!$cfg) $cfg = $this->cfg; return array_key_exists($key, $cfg); }
[ "protected", "function", "has", "(", "$", "key", ",", "$", "cfg", "=", "null", ")", "{", "if", "(", "!", "$", "cfg", ")", "$", "cfg", "=", "$", "this", "->", "cfg", ";", "return", "array_key_exists", "(", "$", "key", ",", "$", "cfg", ")", ";", "}" ]
Returns whether a plain settings array has a key. If no settings array is given, the internal settings array is assumed. @param string $key @param array $cfg @return bool
[ "Returns", "whether", "a", "plain", "settings", "array", "has", "a", "key", ".", "If", "no", "settings", "array", "is", "given", "the", "internal", "settings", "array", "is", "assumed", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L160-L164
ekuiter/feature-php
FeaturePhp/Settings.php
Settings._get
private function _get($cfg/*, ... */) { $args = array_slice(func_get_args(), 1); if (count($args) === 0) return $cfg; else { if (!is_array($cfg) || !$this->has($args[0], $cfg)) throw new NotFoundSettingsException($args[0]); $args[0] = $cfg[$args[0]]; return call_user_func_array(array($this, "_get"), $args); } }
php
private function _get($cfg/*, ... */) { $args = array_slice(func_get_args(), 1); if (count($args) === 0) return $cfg; else { if (!is_array($cfg) || !$this->has($args[0], $cfg)) throw new NotFoundSettingsException($args[0]); $args[0] = $cfg[$args[0]]; return call_user_func_array(array($this, "_get"), $args); } }
[ "private", "function", "_get", "(", "$", "cfg", "/*, ... */", ")", "{", "$", "args", "=", "array_slice", "(", "func_get_args", "(", ")", ",", "1", ")", ";", "if", "(", "count", "(", "$", "args", ")", "===", "0", ")", "return", "$", "cfg", ";", "else", "{", "if", "(", "!", "is_array", "(", "$", "cfg", ")", "||", "!", "$", "this", "->", "has", "(", "$", "args", "[", "0", "]", ",", "$", "cfg", ")", ")", "throw", "new", "NotFoundSettingsException", "(", "$", "args", "[", "0", "]", ")", ";", "$", "args", "[", "0", "]", "=", "$", "cfg", "[", "$", "args", "[", "0", "]", "]", ";", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "\"_get\"", ")", ",", "$", "args", ")", ";", "}", "}" ]
Returns a setting in a plain settings array. A setting path can be supplied variadically. @param array $cfg @return mixed
[ "Returns", "a", "setting", "in", "a", "plain", "settings", "array", ".", "A", "setting", "path", "can", "be", "supplied", "variadically", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L172-L182
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.get
public function get(/* ... */) { $args = func_get_args(); array_unshift($args, $this->cfg); return call_user_func_array(array($this, "_get"), $args); }
php
public function get(/* ... */) { $args = func_get_args(); array_unshift($args, $this->cfg); return call_user_func_array(array($this, "_get"), $args); }
[ "public", "function", "get", "(", "/* ... */", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "array_unshift", "(", "$", "args", ",", "$", "this", "->", "cfg", ")", ";", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "\"_get\"", ")", ",", "$", "args", ")", ";", "}" ]
Returns a setting. A setting path can be supplied variadically. @return mixed
[ "Returns", "a", "setting", ".", "A", "setting", "path", "can", "be", "supplied", "variadically", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L189-L193
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.getWith
public function getWith($key, $predicate) { $object = $this->get($key); if (!call_user_func($predicate, $object)) throw new fphp\InvalidSettingsException($object, $key); return $object; }
php
public function getWith($key, $predicate) { $object = $this->get($key); if (!call_user_func($predicate, $object)) throw new fphp\InvalidSettingsException($object, $key); return $object; }
[ "public", "function", "getWith", "(", "$", "key", ",", "$", "predicate", ")", "{", "$", "object", "=", "$", "this", "->", "get", "(", "$", "key", ")", ";", "if", "(", "!", "call_user_func", "(", "$", "predicate", ",", "$", "object", ")", ")", "throw", "new", "fphp", "\\", "InvalidSettingsException", "(", "$", "object", ",", "$", "key", ")", ";", "return", "$", "object", ";", "}" ]
Returns a setting if a predicate is satisfied. Throws {@see \FeaturePhp\InvalidSettingsException} if the predicate fails. @param string $key @param callable $predicate @return mixed
[ "Returns", "a", "setting", "if", "a", "predicate", "is", "satisfied", ".", "Throws", "{" ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L213-L218
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.getOptional
public function getOptional(/* ..., */$defaultValue) { $args = func_get_args(); try { return call_user_func_array(array($this, "get"), array_slice($args, 0, -1)); } catch (fphp\NotFoundSettingsException $e) { return $args[count($args) - 1]; } }
php
public function getOptional(/* ..., */$defaultValue) { $args = func_get_args(); try { return call_user_func_array(array($this, "get"), array_slice($args, 0, -1)); } catch (fphp\NotFoundSettingsException $e) { return $args[count($args) - 1]; } }
[ "public", "function", "getOptional", "(", "/* ..., */", "$", "defaultValue", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "try", "{", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "\"get\"", ")", ",", "array_slice", "(", "$", "args", ",", "0", ",", "-", "1", ")", ")", ";", "}", "catch", "(", "fphp", "\\", "NotFoundSettingsException", "$", "e", ")", "{", "return", "$", "args", "[", "count", "(", "$", "args", ")", "-", "1", "]", ";", "}", "}" ]
Returns an optional setting, defaulting to a value. A setting path can be supplied variadically. @param mixed $defaultValue @return mixed
[ "Returns", "an", "optional", "setting", "defaulting", "to", "a", "value", ".", "A", "setting", "path", "can", "be", "supplied", "variadically", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L226-L233
ekuiter/feature-php
FeaturePhp/Settings.php
Settings._set
private function _set(&$cfg, $args) { if (count($args) === 2) { $key = $args[count($args) - 2]; $value = $args[count($args) - 1]; $cfg[$key] = $value; } else { if (!is_array($cfg) || !$this->has($args[0], $cfg)) throw new NotFoundSettingsException($args[0]); // Evil, but I found no other way to pass $cfg as reference via call_user_func_array. eval('$this->_set($cfg[$args[0]], array_slice($args, 1));'); } }
php
private function _set(&$cfg, $args) { if (count($args) === 2) { $key = $args[count($args) - 2]; $value = $args[count($args) - 1]; $cfg[$key] = $value; } else { if (!is_array($cfg) || !$this->has($args[0], $cfg)) throw new NotFoundSettingsException($args[0]); // Evil, but I found no other way to pass $cfg as reference via call_user_func_array. eval('$this->_set($cfg[$args[0]], array_slice($args, 1));'); } }
[ "private", "function", "_set", "(", "&", "$", "cfg", ",", "$", "args", ")", "{", "if", "(", "count", "(", "$", "args", ")", "===", "2", ")", "{", "$", "key", "=", "$", "args", "[", "count", "(", "$", "args", ")", "-", "2", "]", ";", "$", "value", "=", "$", "args", "[", "count", "(", "$", "args", ")", "-", "1", "]", ";", "$", "cfg", "[", "$", "key", "]", "=", "$", "value", ";", "}", "else", "{", "if", "(", "!", "is_array", "(", "$", "cfg", ")", "||", "!", "$", "this", "->", "has", "(", "$", "args", "[", "0", "]", ",", "$", "cfg", ")", ")", "throw", "new", "NotFoundSettingsException", "(", "$", "args", "[", "0", "]", ")", ";", "// Evil, but I found no other way to pass $cfg as reference via call_user_func_array.", "eval", "(", "'$this->_set($cfg[$args[0]], array_slice($args, 1));'", ")", ";", "}", "}" ]
Sets a setting in a plain settings array. @param array $cfg @param array $args a setting path followed by the setting's new value
[ "Sets", "a", "setting", "in", "a", "plain", "settings", "array", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L240-L251
ekuiter/feature-php
FeaturePhp/Settings.php
Settings.setOptional
protected function setOptional($key, $value) { if (!$this->has($key)) $this->set($key, $value); }
php
protected function setOptional($key, $value) { if (!$this->has($key)) $this->set($key, $value); }
[ "protected", "function", "setOptional", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "key", ")", ")", "$", "this", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}" ]
Sets a setting if it is not already set. @param string $key @param mixed $value
[ "Sets", "a", "setting", "if", "it", "is", "not", "already", "set", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Settings.php#L269-L272
zicht/z
src/Zicht/Tool/Script/TokenStream.php
TokenStream.current
public function current() { if (!isset($this->tokenList[$this->ptr])) { throw new \UnexpectedValueException("Unexpected input at offset {$this->ptr}, unexpected end of stream"); } return $this->tokenList[$this->ptr]; }
php
public function current() { if (!isset($this->tokenList[$this->ptr])) { throw new \UnexpectedValueException("Unexpected input at offset {$this->ptr}, unexpected end of stream"); } return $this->tokenList[$this->ptr]; }
[ "public", "function", "current", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "tokenList", "[", "$", "this", "->", "ptr", "]", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"Unexpected input at offset {$this->ptr}, unexpected end of stream\"", ")", ";", "}", "return", "$", "this", "->", "tokenList", "[", "$", "this", "->", "ptr", "]", ";", "}" ]
Returns the current token @return Token @throws \UnexpectedValueException
[ "Returns", "the", "current", "token" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/TokenStream.php#L73-L79
zicht/z
src/Zicht/Tool/Script/TokenStream.php
TokenStream.expect
public function expect($type, $value = null) { if (!$this->match($type, $value)) { $msg = "Unexpected token {$this->current()->type} '{$this->current()->value}', expected {$type}"; throw new \UnexpectedValueException($msg); } $current = $this->current(); $this->next(); return $current; }
php
public function expect($type, $value = null) { if (!$this->match($type, $value)) { $msg = "Unexpected token {$this->current()->type} '{$this->current()->value}', expected {$type}"; throw new \UnexpectedValueException($msg); } $current = $this->current(); $this->next(); return $current; }
[ "public", "function", "expect", "(", "$", "type", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "match", "(", "$", "type", ",", "$", "value", ")", ")", "{", "$", "msg", "=", "\"Unexpected token {$this->current()->type} '{$this->current()->value}', expected {$type}\"", ";", "throw", "new", "\\", "UnexpectedValueException", "(", "$", "msg", ")", ";", "}", "$", "current", "=", "$", "this", "->", "current", "(", ")", ";", "$", "this", "->", "next", "(", ")", ";", "return", "$", "current", ";", "}" ]
Asserts the current token matches the specified value and/or type. Throws an exception if it doesn't @param string $type @param string $value @return Token @throws \UnexpectedValueException
[ "Asserts", "the", "current", "token", "matches", "the", "specified", "value", "and", "/", "or", "type", ".", "Throws", "an", "exception", "if", "it", "doesn", "t" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/TokenStream.php#L115-L124
brianium/nomnom
src/Nomnom/Nomnom.php
Nomnom.to
public function to($unit, $precision = null) { $fromUnit = UnitResolver::resolve($this->from); $toUnit = UnitResolver::resolve($unit); $this->setBase($unit); $base = $this->getBase() == 2 ? 1024 : 1000; //some funky stuff with negative exponents and pow if ($toUnit > $fromUnit) return $this->div($this->start, pow($base, $toUnit - $fromUnit), $precision); return $this->mul($this->start, pow($base, $fromUnit - $toUnit), $precision); }
php
public function to($unit, $precision = null) { $fromUnit = UnitResolver::resolve($this->from); $toUnit = UnitResolver::resolve($unit); $this->setBase($unit); $base = $this->getBase() == 2 ? 1024 : 1000; //some funky stuff with negative exponents and pow if ($toUnit > $fromUnit) return $this->div($this->start, pow($base, $toUnit - $fromUnit), $precision); return $this->mul($this->start, pow($base, $fromUnit - $toUnit), $precision); }
[ "public", "function", "to", "(", "$", "unit", ",", "$", "precision", "=", "null", ")", "{", "$", "fromUnit", "=", "UnitResolver", "::", "resolve", "(", "$", "this", "->", "from", ")", ";", "$", "toUnit", "=", "UnitResolver", "::", "resolve", "(", "$", "unit", ")", ";", "$", "this", "->", "setBase", "(", "$", "unit", ")", ";", "$", "base", "=", "$", "this", "->", "getBase", "(", ")", "==", "2", "?", "1024", ":", "1000", ";", "//some funky stuff with negative exponents and pow", "if", "(", "$", "toUnit", ">", "$", "fromUnit", ")", "return", "$", "this", "->", "div", "(", "$", "this", "->", "start", ",", "pow", "(", "$", "base", ",", "$", "toUnit", "-", "$", "fromUnit", ")", ",", "$", "precision", ")", ";", "return", "$", "this", "->", "mul", "(", "$", "this", "->", "start", ",", "pow", "(", "$", "base", ",", "$", "fromUnit", "-", "$", "toUnit", ")", ",", "$", "precision", ")", ";", "}" ]
Convert the start value to the given unit. Accepts an optional precision for how many significant digits to retain @param $unit @param int|null $precision @return float
[ "Convert", "the", "start", "value", "to", "the", "given", "unit", ".", "Accepts", "an", "optional", "precision", "for", "how", "many", "significant", "digits", "to", "retain" ]
train
https://github.com/brianium/nomnom/blob/012e3a6ad17fe2393b6a9db1a4b14c91ab91adcd/src/Nomnom/Nomnom.php#L77-L87
brianium/nomnom
src/Nomnom/Nomnom.php
Nomnom.toBest
public function toBest($precision = null) { $fromUnit = UnitResolver::resolve($this->from); $base = $this->getBase() == 2 ? 1024 : 1000; $converted = $this->start; while ($converted >= 1) { $fromUnit++; $result = $this->div($this->start, pow($base, $fromUnit), $precision); if ($result <= 1) return $converted; $converted = $result; } return $converted; }
php
public function toBest($precision = null) { $fromUnit = UnitResolver::resolve($this->from); $base = $this->getBase() == 2 ? 1024 : 1000; $converted = $this->start; while ($converted >= 1) { $fromUnit++; $result = $this->div($this->start, pow($base, $fromUnit), $precision); if ($result <= 1) return $converted; $converted = $result; } return $converted; }
[ "public", "function", "toBest", "(", "$", "precision", "=", "null", ")", "{", "$", "fromUnit", "=", "UnitResolver", "::", "resolve", "(", "$", "this", "->", "from", ")", ";", "$", "base", "=", "$", "this", "->", "getBase", "(", ")", "==", "2", "?", "1024", ":", "1000", ";", "$", "converted", "=", "$", "this", "->", "start", ";", "while", "(", "$", "converted", ">=", "1", ")", "{", "$", "fromUnit", "++", ";", "$", "result", "=", "$", "this", "->", "div", "(", "$", "this", "->", "start", ",", "pow", "(", "$", "base", ",", "$", "fromUnit", ")", ",", "$", "precision", ")", ";", "if", "(", "$", "result", "<=", "1", ")", "return", "$", "converted", ";", "$", "converted", "=", "$", "result", ";", "}", "return", "$", "converted", ";", "}" ]
Convert the start value to it's highest whole unit. Accespts an optional precision for how many significant digits to retain @param int|null $precision @return float
[ "Convert", "the", "start", "value", "to", "it", "s", "highest", "whole", "unit", ".", "Accespts", "an", "optional", "precision", "for", "how", "many", "significant", "digits", "to", "retain" ]
train
https://github.com/brianium/nomnom/blob/012e3a6ad17fe2393b6a9db1a4b14c91ab91adcd/src/Nomnom/Nomnom.php#L97-L109
brianium/nomnom
src/Nomnom/Nomnom.php
Nomnom.div
protected function div($left, $right, $precision) { if (is_null($precision)) return $left / $right; return floatval(\bcdiv($left, $right, $precision)); }
php
protected function div($left, $right, $precision) { if (is_null($precision)) return $left / $right; return floatval(\bcdiv($left, $right, $precision)); }
[ "protected", "function", "div", "(", "$", "left", ",", "$", "right", ",", "$", "precision", ")", "{", "if", "(", "is_null", "(", "$", "precision", ")", ")", "return", "$", "left", "/", "$", "right", ";", "return", "floatval", "(", "\\", "bcdiv", "(", "$", "left", ",", "$", "right", ",", "$", "precision", ")", ")", ";", "}" ]
Use bcdiv if precision is specified otherwise use native division operator @param $left @param $right @param $precision @return float
[ "Use", "bcdiv", "if", "precision", "is", "specified", "otherwise", "use", "native", "division", "operator" ]
train
https://github.com/brianium/nomnom/blob/012e3a6ad17fe2393b6a9db1a4b14c91ab91adcd/src/Nomnom/Nomnom.php#L152-L156
brianium/nomnom
src/Nomnom/Nomnom.php
Nomnom.mul
protected function mul($left, $right, $precision) { if (is_null($precision)) return $left * $right; return floatval(\bcmul($left, $right, $precision)); }
php
protected function mul($left, $right, $precision) { if (is_null($precision)) return $left * $right; return floatval(\bcmul($left, $right, $precision)); }
[ "protected", "function", "mul", "(", "$", "left", ",", "$", "right", ",", "$", "precision", ")", "{", "if", "(", "is_null", "(", "$", "precision", ")", ")", "return", "$", "left", "*", "$", "right", ";", "return", "floatval", "(", "\\", "bcmul", "(", "$", "left", ",", "$", "right", ",", "$", "precision", ")", ")", ";", "}" ]
Use bcmul if precision is specified otherwise use native multiplication operator @param $left @param $right @param $precision @return float
[ "Use", "bcmul", "if", "precision", "is", "specified", "otherwise", "use", "native", "multiplication", "operator" ]
train
https://github.com/brianium/nomnom/blob/012e3a6ad17fe2393b6a9db1a4b14c91ab91adcd/src/Nomnom/Nomnom.php#L167-L171
brianium/nomnom
src/Nomnom/Nomnom.php
Nomnom.shouldSetBaseTen
protected function shouldSetBaseTen($unit) { $unitMatchesIec = preg_match(UnitResolver::IEC_PATTERN, $unit); return ($this->from == 'B' && !$unitMatchesIec) || (preg_match(UnitResolver::SI_PATTERN, $this->from) && !$unitMatchesIec); }
php
protected function shouldSetBaseTen($unit) { $unitMatchesIec = preg_match(UnitResolver::IEC_PATTERN, $unit); return ($this->from == 'B' && !$unitMatchesIec) || (preg_match(UnitResolver::SI_PATTERN, $this->from) && !$unitMatchesIec); }
[ "protected", "function", "shouldSetBaseTen", "(", "$", "unit", ")", "{", "$", "unitMatchesIec", "=", "preg_match", "(", "UnitResolver", "::", "IEC_PATTERN", ",", "$", "unit", ")", ";", "return", "(", "$", "this", "->", "from", "==", "'B'", "&&", "!", "$", "unitMatchesIec", ")", "||", "(", "preg_match", "(", "UnitResolver", "::", "SI_PATTERN", ",", "$", "this", "->", "from", ")", "&&", "!", "$", "unitMatchesIec", ")", ";", "}" ]
Match from against the unit to see if the base should be set to 10 @param $unit @return bool
[ "Match", "from", "against", "the", "unit", "to", "see", "if", "the", "base", "should", "be", "set", "to", "10" ]
train
https://github.com/brianium/nomnom/blob/012e3a6ad17fe2393b6a9db1a4b14c91ab91adcd/src/Nomnom/Nomnom.php#L192-L198
aalfiann/json-class-php
src/JSON.php
JSON.encode
public function encode($data,$options=0,$depth=512){ if($this->debug) return $this->debug_encode($data,$options,$depth); if($this->trim) $data = $this->trimValue($data); if($this->withlog && is_array($data)) $data['logger'] = ['timestamp' => date('Y-m-d H:i:s', time()),'uniqid'=>uniqid()]; if ($this->sanitize) { return json_encode((($this->ansii)?$this->convertToUTF8Ansii($data):$this->convertToUTF8($data)),$options,$depth); } return json_encode($data,$options,$depth); }
php
public function encode($data,$options=0,$depth=512){ if($this->debug) return $this->debug_encode($data,$options,$depth); if($this->trim) $data = $this->trimValue($data); if($this->withlog && is_array($data)) $data['logger'] = ['timestamp' => date('Y-m-d H:i:s', time()),'uniqid'=>uniqid()]; if ($this->sanitize) { return json_encode((($this->ansii)?$this->convertToUTF8Ansii($data):$this->convertToUTF8($data)),$options,$depth); } return json_encode($data,$options,$depth); }
[ "public", "function", "encode", "(", "$", "data", ",", "$", "options", "=", "0", ",", "$", "depth", "=", "512", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "return", "$", "this", "->", "debug_encode", "(", "$", "data", ",", "$", "options", ",", "$", "depth", ")", ";", "if", "(", "$", "this", "->", "trim", ")", "$", "data", "=", "$", "this", "->", "trimValue", "(", "$", "data", ")", ";", "if", "(", "$", "this", "->", "withlog", "&&", "is_array", "(", "$", "data", ")", ")", "$", "data", "[", "'logger'", "]", "=", "[", "'timestamp'", "=>", "date", "(", "'Y-m-d H:i:s'", ",", "time", "(", ")", ")", ",", "'uniqid'", "=>", "uniqid", "(", ")", "]", ";", "if", "(", "$", "this", "->", "sanitize", ")", "{", "return", "json_encode", "(", "(", "(", "$", "this", "->", "ansii", ")", "?", "$", "this", "->", "convertToUTF8Ansii", "(", "$", "data", ")", ":", "$", "this", "->", "convertToUTF8", "(", "$", "data", ")", ")", ",", "$", "options", ",", "$", "depth", ")", ";", "}", "return", "json_encode", "(", "$", "data", ",", "$", "options", ",", "$", "depth", ")", ";", "}" ]
Encode Array or string value to json (faster with no any conversion to utf8) @param data is the array or string value @param options is to set the options of json_encode. Ex: JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_HEX_TAG|JSON_HEX_APOS @param depth is to set the recursion depth. Default is 512. @return json string
[ "Encode", "Array", "or", "string", "value", "to", "json", "(", "faster", "with", "no", "any", "conversion", "to", "utf8", ")" ]
train
https://github.com/aalfiann/json-class-php/blob/524be94b162031946137ea1b729ba390d83dc41e/src/JSON.php#L95-L103
aalfiann/json-class-php
src/JSON.php
JSON.decode
public function decode($json,$assoc=false,$depth=512,$options=0){ if($this->debug) return $this->debug_decode($json,$assoc,$depth,$options); if($this->trim) { $json = json_encode($this->trimValue(json_decode($json,1,$depth))); return json_decode($json,$assoc,$depth,$options); } return json_decode($json,$assoc,$depth,$options); }
php
public function decode($json,$assoc=false,$depth=512,$options=0){ if($this->debug) return $this->debug_decode($json,$assoc,$depth,$options); if($this->trim) { $json = json_encode($this->trimValue(json_decode($json,1,$depth))); return json_decode($json,$assoc,$depth,$options); } return json_decode($json,$assoc,$depth,$options); }
[ "public", "function", "decode", "(", "$", "json", ",", "$", "assoc", "=", "false", ",", "$", "depth", "=", "512", ",", "$", "options", "=", "0", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "return", "$", "this", "->", "debug_decode", "(", "$", "json", ",", "$", "assoc", ",", "$", "depth", ",", "$", "options", ")", ";", "if", "(", "$", "this", "->", "trim", ")", "{", "$", "json", "=", "json_encode", "(", "$", "this", "->", "trimValue", "(", "json_decode", "(", "$", "json", ",", "1", ",", "$", "depth", ")", ")", ")", ";", "return", "json_decode", "(", "$", "json", ",", "$", "assoc", ",", "$", "depth", ",", "$", "options", ")", ";", "}", "return", "json_decode", "(", "$", "json", ",", "$", "assoc", ",", "$", "depth", ",", "$", "options", ")", ";", "}" ]
Decode json string (if fail will return null) @param json is the json string @param assoc if set to true then will return as array() @param depth is to set the recursion depth. Default is 512. @param options is to set the options of json_decode. Ex: JSON_BIGINT_AS_STRING|JSON_OBJECT_AS_ARRAY @return mixed stdClass/array
[ "Decode", "json", "string", "(", "if", "fail", "will", "return", "null", ")" ]
train
https://github.com/aalfiann/json-class-php/blob/524be94b162031946137ea1b729ba390d83dc41e/src/JSON.php#L115-L122
aalfiann/json-class-php
src/JSON.php
JSON.isValid
public function isValid($json=null) { if (empty($json) || ctype_space($json)) return false; json_decode($json); return (json_last_error() === JSON_ERROR_NONE); }
php
public function isValid($json=null) { if (empty($json) || ctype_space($json)) return false; json_decode($json); return (json_last_error() === JSON_ERROR_NONE); }
[ "public", "function", "isValid", "(", "$", "json", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "json", ")", "||", "ctype_space", "(", "$", "json", ")", ")", "return", "false", ";", "json_decode", "(", "$", "json", ")", ";", "return", "(", "json_last_error", "(", ")", "===", "JSON_ERROR_NONE", ")", ";", "}" ]
Determine is valid json or not @param json is the json string @return bool
[ "Determine", "is", "valid", "json", "or", "not" ]
train
https://github.com/aalfiann/json-class-php/blob/524be94b162031946137ea1b729ba390d83dc41e/src/JSON.php#L131-L135
heidelpay/PhpDoc
src/phpDocumentor/Transformer/Router/Renderer.php
Renderer.render
public function render($value, $presentation) { if (is_array($value) || $value instanceof \Traversable || $value instanceof Collection) { return $this->renderASeriesOfLinks($value, $presentation); } if ($value instanceof CollectionDescriptor) { return $this->renderTypeCollection($value, $presentation); } return $this->renderLink($value, $presentation); }
php
public function render($value, $presentation) { if (is_array($value) || $value instanceof \Traversable || $value instanceof Collection) { return $this->renderASeriesOfLinks($value, $presentation); } if ($value instanceof CollectionDescriptor) { return $this->renderTypeCollection($value, $presentation); } return $this->renderLink($value, $presentation); }
[ "public", "function", "render", "(", "$", "value", ",", "$", "presentation", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "||", "$", "value", "instanceof", "\\", "Traversable", "||", "$", "value", "instanceof", "Collection", ")", "{", "return", "$", "this", "->", "renderASeriesOfLinks", "(", "$", "value", ",", "$", "presentation", ")", ";", "}", "if", "(", "$", "value", "instanceof", "CollectionDescriptor", ")", "{", "return", "$", "this", "->", "renderTypeCollection", "(", "$", "value", ",", "$", "presentation", ")", ";", "}", "return", "$", "this", "->", "renderLink", "(", "$", "value", ",", "$", "presentation", ")", ";", "}" ]
@param string|DescriptorAbstract $value @param string $presentation @return bool|mixed|string|\string[]
[ "@param", "string|DescriptorAbstract", "$value", "@param", "string", "$presentation" ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Transformer/Router/Renderer.php#L90-L101
alevilar/ristorantino-vendor
Comanda/Model/Comanda.php
Comanda.listado_de_productos_con_sabores
public function listado_de_productos_con_sabores($id, $con_entrada = DETALLE_COMANDA_TRAER_TODOS, $contain = null){ //inicialiozo variable return $items = array(); if($id != 0){ $this->id = $id; } $this->DetalleComanda->order = 'Producto.categoria_id'; /* $this->DetalleComanda->recursive = 2; // le saco todos los modelos que no necesito paraqe haga mas rapido la consulta $this->DetalleComanda->Producto->unBindModel(array('hasMany' => array('DetalleComanda'), 'belongsTo'=> array('Categoria'))); $this->DetalleComanda->DetalleSabor->unBindModel(array('belongsTo' => array('DetalleComanda'))); */ unset($condiciones); $condiciones[]['DetalleComanda.comanda_id'] = $this->id; switch($con_entrada){ case DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES: // si quiero solo platos principales $condiciones[]['DetalleComanda.es_entrada'] = 0; break; case DETALLE_COMANDA_TRAER_ENTRADAS: // si quiero solo entradas $condiciones[]['DetalleComanda.es_entrada'] = 1; break; default: // si quiero todo = DETALLE_COMANDA_TRAER_TODoS break; } if (empty($contain) ) { $contain = array( 'Producto'=>array('Printer'), 'Comanda'=> array('Mesa'=>array('Mozo')), 'DetalleSabor'=>array('Sabor') ); } $items = $this->DetalleComanda->find('all',array('conditions'=>$condiciones, 'contain'=>$contain)); return $items; }
php
public function listado_de_productos_con_sabores($id, $con_entrada = DETALLE_COMANDA_TRAER_TODOS, $contain = null){ //inicialiozo variable return $items = array(); if($id != 0){ $this->id = $id; } $this->DetalleComanda->order = 'Producto.categoria_id'; /* $this->DetalleComanda->recursive = 2; // le saco todos los modelos que no necesito paraqe haga mas rapido la consulta $this->DetalleComanda->Producto->unBindModel(array('hasMany' => array('DetalleComanda'), 'belongsTo'=> array('Categoria'))); $this->DetalleComanda->DetalleSabor->unBindModel(array('belongsTo' => array('DetalleComanda'))); */ unset($condiciones); $condiciones[]['DetalleComanda.comanda_id'] = $this->id; switch($con_entrada){ case DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES: // si quiero solo platos principales $condiciones[]['DetalleComanda.es_entrada'] = 0; break; case DETALLE_COMANDA_TRAER_ENTRADAS: // si quiero solo entradas $condiciones[]['DetalleComanda.es_entrada'] = 1; break; default: // si quiero todo = DETALLE_COMANDA_TRAER_TODoS break; } if (empty($contain) ) { $contain = array( 'Producto'=>array('Printer'), 'Comanda'=> array('Mesa'=>array('Mozo')), 'DetalleSabor'=>array('Sabor') ); } $items = $this->DetalleComanda->find('all',array('conditions'=>$condiciones, 'contain'=>$contain)); return $items; }
[ "public", "function", "listado_de_productos_con_sabores", "(", "$", "id", ",", "$", "con_entrada", "=", "DETALLE_COMANDA_TRAER_TODOS", ",", "$", "contain", "=", "null", ")", "{", "//inicialiozo variable return", "$", "items", "=", "array", "(", ")", ";", "if", "(", "$", "id", "!=", "0", ")", "{", "$", "this", "->", "id", "=", "$", "id", ";", "}", "$", "this", "->", "DetalleComanda", "->", "order", "=", "'Producto.categoria_id'", ";", "/*\n\t\t$this->DetalleComanda->recursive = 2;\n\t\t\n\t\t// le saco todos los modelos que no necesito paraqe haga mas rapido la consulta\n\t\t$this->DetalleComanda->Producto->unBindModel(array('hasMany' => array('DetalleComanda'), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'belongsTo'=> array('Categoria')));\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t$this->DetalleComanda->DetalleSabor->unBindModel(array('belongsTo' => array('DetalleComanda')));\n\t\t*/", "unset", "(", "$", "condiciones", ")", ";", "$", "condiciones", "[", "]", "[", "'DetalleComanda.comanda_id'", "]", "=", "$", "this", "->", "id", ";", "switch", "(", "$", "con_entrada", ")", "{", "case", "DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES", ":", "// si quiero solo platos principales", "$", "condiciones", "[", "]", "[", "'DetalleComanda.es_entrada'", "]", "=", "0", ";", "break", ";", "case", "DETALLE_COMANDA_TRAER_ENTRADAS", ":", "// si quiero solo entradas", "$", "condiciones", "[", "]", "[", "'DetalleComanda.es_entrada'", "]", "=", "1", ";", "break", ";", "default", ":", "// si quiero todo = DETALLE_COMANDA_TRAER_TODoS", "break", ";", "}", "if", "(", "empty", "(", "$", "contain", ")", ")", "{", "$", "contain", "=", "array", "(", "'Producto'", "=>", "array", "(", "'Printer'", ")", ",", "'Comanda'", "=>", "array", "(", "'Mesa'", "=>", "array", "(", "'Mozo'", ")", ")", ",", "'DetalleSabor'", "=>", "array", "(", "'Sabor'", ")", ")", ";", "}", "$", "items", "=", "$", "this", "->", "DetalleComanda", "->", "find", "(", "'all'", ",", "array", "(", "'conditions'", "=>", "$", "condiciones", ",", "'contain'", "=>", "$", "contain", ")", ")", ";", "return", "$", "items", ";", "}" ]
@param comanda_id @param con_entrada 0 DETALLE_COMANDA_TRAER_TODOS si quiero todos los productos 1 DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES si quiero solo platos principales 2 DETALLE_COMANDA_TRAER_ENTRADAS si quiero solo las entradas
[ "@param", "comanda_id", "@param", "con_entrada", "0", "DETALLE_COMANDA_TRAER_TODOS", "si", "quiero", "todos", "los", "productos", "1", "DETALLE_COMANDA_TRAER_PLATOS_PRINCIPALES", "si", "quiero", "solo", "platos", "principales", "2", "DETALLE_COMANDA_TRAER_ENTRADAS", "si", "quiero", "solo", "las", "entradas" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Comanda/Model/Comanda.php#L145-L189
WellCommerce/AppBundle
Service/Theme/Locator/FileLocator.php
FileLocator.locate
public function locate($name, $dir = null, $first = true) { if ('@' === $name[0]) { return $this->themeLocator->locateTemplate($name); } return parent::locate($name, $dir, $first); }
php
public function locate($name, $dir = null, $first = true) { if ('@' === $name[0]) { return $this->themeLocator->locateTemplate($name); } return parent::locate($name, $dir, $first); }
[ "public", "function", "locate", "(", "$", "name", ",", "$", "dir", "=", "null", ",", "$", "first", "=", "true", ")", "{", "if", "(", "'@'", "===", "$", "name", "[", "0", "]", ")", "{", "return", "$", "this", "->", "themeLocator", "->", "locateTemplate", "(", "$", "name", ")", ";", "}", "return", "parent", "::", "locate", "(", "$", "name", ",", "$", "dir", ",", "$", "first", ")", ";", "}" ]
Returns a full path for a given template @param mixed $name @param string|null $dir @param bool $first @return array|string
[ "Returns", "a", "full", "path", "for", "a", "given", "template" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Service/Theme/Locator/FileLocator.php#L50-L57
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_sqlite.php
ezcQuerySelectSqlite.from
public function from() { $args = func_get_args(); $tables = self::arrayFlatten( $args ); if ( count( $tables ) < 1 ) { throw new ezcQueryVariableParameterException( 'from', count( $args ), 1 ); } $this->lastInvokedMethod = 'from'; $tables = $this->getIdentifiers( $tables ); $tables = $this->getPrefixedTableNames($tables); $this->fromTables = array_merge( $this->fromTables, $tables ); $this->fromString ='FROM '.join( ', ', $this->fromTables ); // adding right join part of query to the end of fromString. $rightJoinPart = $this->buildRightJoins(); if ( $rightJoinPart != '' ) { $this->fromString .= ', '.$rightJoinPart; } // adding new empty entry to $rightJoins if last entry was already filled $lastRightJoin = end( $this->rightJoins ); if ( $lastRightJoin != null ) { $this->rightJoins[] = null; // adding empty stub to the rightJoins // it could be filled by next rightJoin() } return $this; }
php
public function from() { $args = func_get_args(); $tables = self::arrayFlatten( $args ); if ( count( $tables ) < 1 ) { throw new ezcQueryVariableParameterException( 'from', count( $args ), 1 ); } $this->lastInvokedMethod = 'from'; $tables = $this->getIdentifiers( $tables ); $tables = $this->getPrefixedTableNames($tables); $this->fromTables = array_merge( $this->fromTables, $tables ); $this->fromString ='FROM '.join( ', ', $this->fromTables ); // adding right join part of query to the end of fromString. $rightJoinPart = $this->buildRightJoins(); if ( $rightJoinPart != '' ) { $this->fromString .= ', '.$rightJoinPart; } // adding new empty entry to $rightJoins if last entry was already filled $lastRightJoin = end( $this->rightJoins ); if ( $lastRightJoin != null ) { $this->rightJoins[] = null; // adding empty stub to the rightJoins // it could be filled by next rightJoin() } return $this; }
[ "public", "function", "from", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "tables", "=", "self", "::", "arrayFlatten", "(", "$", "args", ")", ";", "if", "(", "count", "(", "$", "tables", ")", "<", "1", ")", "{", "throw", "new", "ezcQueryVariableParameterException", "(", "'from'", ",", "count", "(", "$", "args", ")", ",", "1", ")", ";", "}", "$", "this", "->", "lastInvokedMethod", "=", "'from'", ";", "$", "tables", "=", "$", "this", "->", "getIdentifiers", "(", "$", "tables", ")", ";", "$", "tables", "=", "$", "this", "->", "getPrefixedTableNames", "(", "$", "tables", ")", ";", "$", "this", "->", "fromTables", "=", "array_merge", "(", "$", "this", "->", "fromTables", ",", "$", "tables", ")", ";", "$", "this", "->", "fromString", "=", "'FROM '", ".", "join", "(", "', '", ",", "$", "this", "->", "fromTables", ")", ";", "// adding right join part of query to the end of fromString.", "$", "rightJoinPart", "=", "$", "this", "->", "buildRightJoins", "(", ")", ";", "if", "(", "$", "rightJoinPart", "!=", "''", ")", "{", "$", "this", "->", "fromString", ".=", "', '", ".", "$", "rightJoinPart", ";", "}", "// adding new empty entry to $rightJoins if last entry was already filled", "$", "lastRightJoin", "=", "end", "(", "$", "this", "->", "rightJoins", ")", ";", "if", "(", "$", "lastRightJoin", "!=", "null", ")", "{", "$", "this", "->", "rightJoins", "[", "]", "=", "null", ";", "// adding empty stub to the rightJoins", "// it could be filled by next rightJoin()", "}", "return", "$", "this", ";", "}" ]
Select which tables you want to select from. from() accepts an arbitrary number of parameters. Each parameter must contain either the name of a table or an array containing the names of tables.. from() could be invoked several times. All provided arguments added to the end of $fromString. Additional actions performed to emulate right joins in SQLite. Example: <code> // the following code will produce the SQL // SELECT id FROM t2 LEFT JOIN t1 ON t1.id = t2.id $q->select( 'id' )->from( $q->rightJoin( 't1', 't2', 't1.id', 't2.id' ) ); // the following code will produce the same SQL // SELECT id FROM t2 LEFT JOIN t1 ON t1.id = t2.id $q->select( 'id' )->from( 't1' )->rightJoin( 't2', 't1.id', 't2.id' ); </code> @throws ezcQueryVariableParameterException if called with no parameters. @param string|array(string) $... Either a string with a table name or an array of table names. @return a pointer to $this
[ "Select", "which", "tables", "you", "want", "to", "select", "from", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_sqlite.php#L90-L121