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
39
1.84M
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
luyadev/luya
core/components/Mail.php
Mail.ccAddress
public function ccAddress($email, $name = null) { $this->getMailer()->addCC($email, (empty($name)) ? $email : $name); return $this; }
php
public function ccAddress($email, $name = null) { $this->getMailer()->addCC($email, (empty($name)) ? $email : $name); return $this; }
[ "public", "function", "ccAddress", "(", "$", "email", ",", "$", "name", "=", "null", ")", "{", "$", "this", "->", "getMailer", "(", ")", "->", "addCC", "(", "$", "email", ",", "(", "empty", "(", "$", "name", ")", ")", "?", "$", "email", ":", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Add a single CC address with optional name @param string $email The email address e.g. [email protected] @param string $name The name for the address e.g. John Doe @return \luya\components\Mail
[ "Add", "a", "single", "CC", "address", "with", "optional", "name" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L374-L379
luyadev/luya
core/components/Mail.php
Mail.bccAddresses
public function bccAddresses(array $emails) { foreach ($emails as $name => $mail) { if (is_int($name)) { $this->bccAddress($mail); } else { $this->bccAddress($mail, $name); } } return $this; }
php
public function bccAddresses(array $emails) { foreach ($emails as $name => $mail) { if (is_int($name)) { $this->bccAddress($mail); } else { $this->bccAddress($mail, $name); } } return $this; }
[ "public", "function", "bccAddresses", "(", "array", "$", "emails", ")", "{", "foreach", "(", "$", "emails", "as", "$", "name", "=>", "$", "mail", ")", "{", "if", "(", "is_int", "(", "$", "name", ")", ")", "{", "$", "this", "->", "bccAddress", "(", "$", "mail", ")", ";", "}", "else", "{", "$", "this", "->", "bccAddress", "(", "$", "mail", ",", "$", "name", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Add multiple BCC addresses into the mailer object. If no key is used, the name is going to be ignored, if a string key is available it represents the name. ```php bccAddresses(['[email protected]', '[email protected]']); ``` or with names ```php bccAddresses(['John Doe' => '[email protected]', 'Jane Doe' => '[email protected]']); ``` @return \luya\components\Mail @param array $emails An array with email addresses or name => email paring to use names.
[ "Add", "multiple", "BCC", "addresses", "into", "the", "mailer", "object", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L399-L410
luyadev/luya
core/components/Mail.php
Mail.bccAddress
public function bccAddress($email, $name = null) { $this->getMailer()->addBCC($email, (empty($name)) ? $email : $name); return $this; }
php
public function bccAddress($email, $name = null) { $this->getMailer()->addBCC($email, (empty($name)) ? $email : $name); return $this; }
[ "public", "function", "bccAddress", "(", "$", "email", ",", "$", "name", "=", "null", ")", "{", "$", "this", "->", "getMailer", "(", ")", "->", "addBCC", "(", "$", "email", ",", "(", "empty", "(", "$", "name", ")", ")", "?", "$", "email", ":", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Add a single BCC address with optional name @param string $email The email address e.g. [email protected] @param string $name The name for the address e.g. John Doe @return \luya\components\Mail
[ "Add", "a", "single", "BCC", "address", "with", "optional", "name" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L419-L424
luyadev/luya
core/components/Mail.php
Mail.addAttachment
public function addAttachment($filePath, $name = null) { $this->getMailer()->addAttachment($filePath, empty($name) ? pathinfo($filePath, PATHINFO_BASENAME) : $name); return $this; }
php
public function addAttachment($filePath, $name = null) { $this->getMailer()->addAttachment($filePath, empty($name) ? pathinfo($filePath, PATHINFO_BASENAME) : $name); return $this; }
[ "public", "function", "addAttachment", "(", "$", "filePath", ",", "$", "name", "=", "null", ")", "{", "$", "this", "->", "getMailer", "(", ")", "->", "addAttachment", "(", "$", "filePath", ",", "empty", "(", "$", "name", ")", "?", "pathinfo", "(", "$", "filePath", ",", "PATHINFO_BASENAME", ")", ":", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Add attachment. @param string $filePath The path to the file, will be checked with `is_file`. @param string $name An optional name to use for the Attachment. @return \luya\components\Mail
[ "Add", "attachment", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L433-L438
luyadev/luya
core/components/Mail.php
Mail.addReplyTo
public function addReplyTo($email, $name = null) { $this->getMailer()->addReplyTo($email, empty($name) ? $email : $name); return $this; }
php
public function addReplyTo($email, $name = null) { $this->getMailer()->addReplyTo($email, empty($name) ? $email : $name); return $this; }
[ "public", "function", "addReplyTo", "(", "$", "email", ",", "$", "name", "=", "null", ")", "{", "$", "this", "->", "getMailer", "(", ")", "->", "addReplyTo", "(", "$", "email", ",", "empty", "(", "$", "name", ")", "?", "$", "email", ":", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Add ReplyTo Address. @param string $email @param string $name @return \luya\components\Mail
[ "Add", "ReplyTo", "Address", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L447-L452
luyadev/luya
core/components/Mail.php
Mail.send
public function send() { if (empty($this->mailer->Subject) || empty($this->mailer->Body)) { throw new Exception("Mail subject() and body() can not be empty in order to send mail."); } if (!$this->getMailer()->send()) { Yii::error($this->getError(), __METHOD__); return false; } return true; }
php
public function send() { if (empty($this->mailer->Subject) || empty($this->mailer->Body)) { throw new Exception("Mail subject() and body() can not be empty in order to send mail."); } if (!$this->getMailer()->send()) { Yii::error($this->getError(), __METHOD__); return false; } return true; }
[ "public", "function", "send", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "mailer", "->", "Subject", ")", "||", "empty", "(", "$", "this", "->", "mailer", "->", "Body", ")", ")", "{", "throw", "new", "Exception", "(", "\"Mail subject() and body() can not be empty in order to send mail.\"", ")", ";", "}", "if", "(", "!", "$", "this", "->", "getMailer", "(", ")", "->", "send", "(", ")", ")", "{", "Yii", "::", "error", "(", "$", "this", "->", "getError", "(", ")", ",", "__METHOD__", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Trigger the send event of the mailer @return bool @throws Exception
[ "Trigger", "the", "send", "event", "of", "the", "mailer" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Mail.php#L459-L469
luyadev/luya
core/traits/RestBehaviorsTrait.php
RestBehaviorsTrait.getUserAuthClass
private function getUserAuthClass() { if ($this instanceof UserBehaviorInterface) { $class = $this->userAuthClass(); if (!$class) { // return false; return false; } if (!is_object($class)) { return Yii::createObject($class); } return $class; } return false; }
php
private function getUserAuthClass() { if ($this instanceof UserBehaviorInterface) { $class = $this->userAuthClass(); if (!$class) { return false; } if (!is_object($class)) { return Yii::createObject($class); } return $class; } return false; }
[ "private", "function", "getUserAuthClass", "(", ")", "{", "if", "(", "$", "this", "instanceof", "UserBehaviorInterface", ")", "{", "$", "class", "=", "$", "this", "->", "userAuthClass", "(", ")", ";", "if", "(", "!", "$", "class", ")", "{", "// return false;", "return", "false", ";", "}", "if", "(", "!", "is_object", "(", "$", "class", ")", ")", "{", "return", "Yii", "::", "createObject", "(", "$", "class", ")", ";", "}", "return", "$", "class", ";", "}", "return", "false", ";", "}" ]
Whether the rest controller is protected or not. @return boolean|\yii\web\User
[ "Whether", "the", "rest", "controller", "is", "protected", "or", "not", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/RestBehaviorsTrait.php#L66-L83
luyadev/luya
core/traits/RestBehaviorsTrait.php
RestBehaviorsTrait.behaviors
public function behaviors() { $behaviors = parent::behaviors(); if (!$this->getUserAuthClass()) { unset($behaviors['authenticator']); } else { // change to admin user auth class $behaviors['authenticator'] = [ 'class' => CompositeAuth::className(), 'user' => $this->getUserAuthClass(), 'authMethods' => [ QueryParamAuth::className(), HttpBearerAuth::className(), ], ]; if ($this->enableCors) { $behaviors['authenticator']['except'] = ['options']; } } if ($this->enableCors) { $behaviors['cors'] = Cors::class; } $behaviors['contentNegotiator'] = [ 'class' => ContentNegotiator::className(), 'formats' => [ 'application/json' => Response::FORMAT_JSON, 'application/xml' => Response::FORMAT_XML, ], 'languages' => $this->languages, ]; // by default rate limiter behavior is removed as it requires a database // user given from the admin module. if (isset($behaviors['rateLimiter'])) { unset($behaviors['rateLimiter']); } if ($this->jsonCruft) { $behaviors['cruft'] = JsonCruftFilter::class; } return $behaviors; }
php
public function behaviors() { $behaviors = parent::behaviors(); if (!$this->getUserAuthClass()) { unset($behaviors['authenticator']); } else { $behaviors['authenticator'] = [ 'class' => CompositeAuth::className(), 'user' => $this->getUserAuthClass(), 'authMethods' => [ QueryParamAuth::className(), HttpBearerAuth::className(), ], ]; if ($this->enableCors) { $behaviors['authenticator']['except'] = ['options']; } } if ($this->enableCors) { $behaviors['cors'] = Cors::class; } $behaviors['contentNegotiator'] = [ 'class' => ContentNegotiator::className(), 'formats' => [ 'application/json' => Response::FORMAT_JSON, 'application/xml' => Response::FORMAT_XML, ], 'languages' => $this->languages, ]; if (isset($behaviors['rateLimiter'])) { unset($behaviors['rateLimiter']); } if ($this->jsonCruft) { $behaviors['cruft'] = JsonCruftFilter::class; } return $behaviors; }
[ "public", "function", "behaviors", "(", ")", "{", "$", "behaviors", "=", "parent", "::", "behaviors", "(", ")", ";", "if", "(", "!", "$", "this", "->", "getUserAuthClass", "(", ")", ")", "{", "unset", "(", "$", "behaviors", "[", "'authenticator'", "]", ")", ";", "}", "else", "{", "// change to admin user auth class", "$", "behaviors", "[", "'authenticator'", "]", "=", "[", "'class'", "=>", "CompositeAuth", "::", "className", "(", ")", ",", "'user'", "=>", "$", "this", "->", "getUserAuthClass", "(", ")", ",", "'authMethods'", "=>", "[", "QueryParamAuth", "::", "className", "(", ")", ",", "HttpBearerAuth", "::", "className", "(", ")", ",", "]", ",", "]", ";", "if", "(", "$", "this", "->", "enableCors", ")", "{", "$", "behaviors", "[", "'authenticator'", "]", "[", "'except'", "]", "=", "[", "'options'", "]", ";", "}", "}", "if", "(", "$", "this", "->", "enableCors", ")", "{", "$", "behaviors", "[", "'cors'", "]", "=", "Cors", "::", "class", ";", "}", "$", "behaviors", "[", "'contentNegotiator'", "]", "=", "[", "'class'", "=>", "ContentNegotiator", "::", "className", "(", ")", ",", "'formats'", "=>", "[", "'application/json'", "=>", "Response", "::", "FORMAT_JSON", ",", "'application/xml'", "=>", "Response", "::", "FORMAT_XML", ",", "]", ",", "'languages'", "=>", "$", "this", "->", "languages", ",", "]", ";", "// by default rate limiter behavior is removed as it requires a database", "// user given from the admin module.", "if", "(", "isset", "(", "$", "behaviors", "[", "'rateLimiter'", "]", ")", ")", "{", "unset", "(", "$", "behaviors", "[", "'rateLimiter'", "]", ")", ";", "}", "if", "(", "$", "this", "->", "jsonCruft", ")", "{", "$", "behaviors", "[", "'cruft'", "]", "=", "JsonCruftFilter", "::", "class", ";", "}", "return", "$", "behaviors", ";", "}" ]
Override the default {{yii\rest\Controller::behaviors()}} method. The following changes are differ to the base implementation: + If {{luya\rest\UserBehaviorInterface}} is **not** implemented, the `authenticator` behavior ({{yii\filters\auth\CompositeAuth}}) is removed. + If {{luya\rest\UserBehaviorInterface}} **is** implemented, the `authenticator` behavior ({{yii\filters\auth\CompositeAuth}}) is enabled. + If {{luya\rest\UserBehaviorInterface}} **is** implemented, the `contentNegotiator` behavior ({{yii\filters\ContentNegotiator}}) is enabled. + The `rateLimiter` behavior filter is **removed** by default. @return array Returns an array with registered behavior filters based on the implementation type.
[ "Override", "the", "default", "{{", "yii", "\\", "rest", "\\", "Controller", "::", "behaviors", "()", "}}", "method", ".", "The", "following", "changes", "are", "differ", "to", "the", "base", "implementation", ":" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/RestBehaviorsTrait.php#L96-L145
luyadev/luya
core/traits/RestBehaviorsTrait.php
RestBehaviorsTrait.sendModelError
public function sendModelError(Model $model) { if (!$model->hasErrors()) { throw new InvalidParamException('The model as thrown an uknown Error.'); } Yii::$app->response->setStatusCode(422, 'Data Validation Failed.'); $result = []; foreach ($model->getFirstErrors() as $name => $message) { $result[] = [ 'field' => $name, 'message' => $message, ]; } return $result; }
php
public function sendModelError(Model $model) { if (!$model->hasErrors()) { throw new InvalidParamException('The model as thrown an uknown Error.'); } Yii::$app->response->setStatusCode(422, 'Data Validation Failed.'); $result = []; foreach ($model->getFirstErrors() as $name => $message) { $result[] = [ 'field' => $name, 'message' => $message, ]; } return $result; }
[ "public", "function", "sendModelError", "(", "Model", "$", "model", ")", "{", "if", "(", "!", "$", "model", "->", "hasErrors", "(", ")", ")", "{", "throw", "new", "InvalidParamException", "(", "'The model as thrown an uknown Error.'", ")", ";", "}", "Yii", "::", "$", "app", "->", "response", "->", "setStatusCode", "(", "422", ",", "'Data Validation Failed.'", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "model", "->", "getFirstErrors", "(", ")", "as", "$", "name", "=>", "$", "message", ")", "{", "$", "result", "[", "]", "=", "[", "'field'", "=>", "$", "name", ",", "'message'", "=>", "$", "message", ",", "]", ";", "}", "return", "$", "result", ";", "}" ]
Send Model errors with correct headers. Helper method to correctly send model errors with the correct response headers. Example return value: ```php Array ( [0] => Array ( [field] => firstname [message] => Firstname cannot be blank. ) [1] => Array ( [field] => email [message] => Email cannot be blank. ) ) ``` @param \yii\base\Model $model The model to find the first error. @throws \yii\base\InvalidParamException @return array If the model has errors InvalidParamException will be thrown, otherwise an array with message and field key.
[ "Send", "Model", "errors", "with", "correct", "headers", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/RestBehaviorsTrait.php#L174-L190
luyadev/luya
core/traits/RestBehaviorsTrait.php
RestBehaviorsTrait.sendArrayError
public function sendArrayError(array $errors) { Yii::$app->response->setStatusCode(422, 'Data Validation Failed.'); $result = []; foreach ($errors as $key => $value) { $messages = (array) $value; foreach ($messages as $msg) { $result[] = ['field' => $key, 'message' => $msg]; } } return $result; }
php
public function sendArrayError(array $errors) { Yii::$app->response->setStatusCode(422, 'Data Validation Failed.'); $result = []; foreach ($errors as $key => $value) { $messages = (array) $value; foreach ($messages as $msg) { $result[] = ['field' => $key, 'message' => $msg]; } } return $result; }
[ "public", "function", "sendArrayError", "(", "array", "$", "errors", ")", "{", "Yii", "::", "$", "app", "->", "response", "->", "setStatusCode", "(", "422", ",", "'Data Validation Failed.'", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "errors", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "messages", "=", "(", "array", ")", "$", "value", ";", "foreach", "(", "$", "messages", "as", "$", "msg", ")", "{", "$", "result", "[", "]", "=", "[", "'field'", "=>", "$", "key", ",", "'message'", "=>", "$", "msg", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Send Array validation error. Example input: ```php return $this->sendArrayError(['firstname' => 'Firstname cannot be blank']); ``` Example return value: ```php Array ( [0] => Array ( [field] => firstname [message] => Firstname cannot be blank. ) ) ``` @param array $errors Provide an array with messages. Where key is the field and value the message. @return array Returns an array with field and message keys for each item. @since 1.0.3
[ "Send", "Array", "validation", "error", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/RestBehaviorsTrait.php#L217-L230
luyadev/luya
core/tag/tags/MailTag.php
MailTag.parse
public function parse($value, $sub) { $label = $sub ?: $value; // if obfuscation is enabled generate tag string due to yii tag method will encode attributes. if ($this->obfuscate) { if (!$sub) { $label = $this->obfuscate($label); } return '<a href="'.$this->obfuscate("mailto:{$value}").'" rel="nofollow">'.$label.'</a>'; } return Html::mailto($label, $value, [ 'rel' => 'nofollow', ]); }
php
public function parse($value, $sub) { $label = $sub ?: $value; if ($this->obfuscate) { if (!$sub) { $label = $this->obfuscate($label); } return '<a href="'.$this->obfuscate("mailto:{$value}").'" rel="nofollow">'.$label.'</a>'; } return Html::mailto($label, $value, [ 'rel' => 'nofollow', ]); }
[ "public", "function", "parse", "(", "$", "value", ",", "$", "sub", ")", "{", "$", "label", "=", "$", "sub", "?", ":", "$", "value", ";", "// if obfuscation is enabled generate tag string due to yii tag method will encode attributes.", "if", "(", "$", "this", "->", "obfuscate", ")", "{", "if", "(", "!", "$", "sub", ")", "{", "$", "label", "=", "$", "this", "->", "obfuscate", "(", "$", "label", ")", ";", "}", "return", "'<a href=\"'", ".", "$", "this", "->", "obfuscate", "(", "\"mailto:{$value}\"", ")", ".", "'\" rel=\"nofollow\">'", ".", "$", "label", ".", "'</a>'", ";", "}", "return", "Html", "::", "mailto", "(", "$", "label", ",", "$", "value", ",", "[", "'rel'", "=>", "'nofollow'", ",", "]", ")", ";", "}" ]
Generate the Mail Tag. @param string $value The Brackets value `[]`. @param string $sub The optional Parentheses value `()` @see \luya\tag\TagInterface::parse() @return string The parser tag.
[ "Generate", "the", "Mail", "Tag", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/tag/tags/MailTag.php#L56-L71
luyadev/luya
core/tag/tags/MailTag.php
MailTag.obfuscate
public function obfuscate($email) { $output = null; for ($i = 0; $i < strlen($email); $i++) { $output .= '&#'.ord($email[$i]).';'; } return $output; }
php
public function obfuscate($email) { $output = null; for ($i = 0; $i < strlen($email); $i++) { $output .= '& } return $output; }
[ "public", "function", "obfuscate", "(", "$", "email", ")", "{", "$", "output", "=", "null", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "email", ")", ";", "$", "i", "++", ")", "{", "$", "output", ".=", "'&#'", ".", "ord", "(", "$", "email", "[", "$", "i", "]", ")", ".", "';'", ";", "}", "return", "$", "output", ";", "}" ]
Obfucscate email adresse @param string $email @return string @see http://php.net/manual/de/function.bin2hex.php#11027
[ "Obfucscate", "email", "adresse" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/tag/tags/MailTag.php#L80-L88
luyadev/luya
core/components/Formatter.php
Formatter.autoFormat
public function autoFormat($value) { // email validation if ((new EmailValidator())->validate($value)) { return $this->asEmail($value); } // url validator if ((new UrlValidator())->validate($value)) { return $this->asUrl($value); } // boolean type if (is_bool($value)) { return $this->asBoolean($value); } return $value; }
php
public function autoFormat($value) { if ((new EmailValidator())->validate($value)) { return $this->asEmail($value); } if ((new UrlValidator())->validate($value)) { return $this->asUrl($value); } if (is_bool($value)) { return $this->asBoolean($value); } return $value; }
[ "public", "function", "autoFormat", "(", "$", "value", ")", "{", "// email validation", "if", "(", "(", "new", "EmailValidator", "(", ")", ")", "->", "validate", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "asEmail", "(", "$", "value", ")", ";", "}", "// url validator", "if", "(", "(", "new", "UrlValidator", "(", ")", ")", "->", "validate", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "asUrl", "(", "$", "value", ")", ";", "}", "// boolean type", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "asBoolean", "(", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Auto format the value to a given format like url, email. The following rules will apply to auto format the value: + boolean: asBool + email: asEmail + url: asUrl @param mixed $value Returns the formated value otherwise the original input value. @since 1.0.9
[ "Auto", "format", "the", "value", "to", "a", "given", "format", "like", "url", "email", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/components/Formatter.php#L112-L130
luyadev/luya
core/helpers/ExportHelper.php
ExportHelper.csv
public static function csv($input, array $keys = [], $header = true) { $delimiter = ","; $input = self::transformInput($input); $array = self::generateContentArray($input, $keys, $header); return self::generateOutputString($array, $delimiter); }
php
public static function csv($input, array $keys = [], $header = true) { $delimiter = ","; $input = self::transformInput($input); $array = self::generateContentArray($input, $keys, $header); return self::generateOutputString($array, $delimiter); }
[ "public", "static", "function", "csv", "(", "$", "input", ",", "array", "$", "keys", "=", "[", "]", ",", "$", "header", "=", "true", ")", "{", "$", "delimiter", "=", "\",\"", ";", "$", "input", "=", "self", "::", "transformInput", "(", "$", "input", ")", ";", "$", "array", "=", "self", "::", "generateContentArray", "(", "$", "input", ",", "$", "keys", ",", "$", "header", ")", ";", "return", "self", "::", "generateOutputString", "(", "$", "array", ",", "$", "delimiter", ")", ";", "}" ]
Export an Array or ActiveQuery instance into a CSV formated string. @param array|ActiveQueryInterface $input The data to export into a csv @param array $keys Defines which keys should be packed into the generated CSV. The defined keys does not change the sort behavior of the generated csv. @param string $header Whether the column name should be set as header inside the csv or not. @return string The generated CSV as string.
[ "Export", "an", "Array", "or", "ActiveQuery", "instance", "into", "a", "CSV", "formated", "string", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ExportHelper.php#L26-L33
luyadev/luya
core/helpers/ExportHelper.php
ExportHelper.xlsx
public static function xlsx($input, array $keys = [], $header = true) { $input = self::transformInput($input); $array = self::generateContentArray($input, $keys, $header); $writer = new XLSXWriter(); $writer->writeSheet($array); return $writer->writeToString(); }
php
public static function xlsx($input, array $keys = [], $header = true) { $input = self::transformInput($input); $array = self::generateContentArray($input, $keys, $header); $writer = new XLSXWriter(); $writer->writeSheet($array); return $writer->writeToString(); }
[ "public", "static", "function", "xlsx", "(", "$", "input", ",", "array", "$", "keys", "=", "[", "]", ",", "$", "header", "=", "true", ")", "{", "$", "input", "=", "self", "::", "transformInput", "(", "$", "input", ")", ";", "$", "array", "=", "self", "::", "generateContentArray", "(", "$", "input", ",", "$", "keys", ",", "$", "header", ")", ";", "$", "writer", "=", "new", "XLSXWriter", "(", ")", ";", "$", "writer", "->", "writeSheet", "(", "$", "array", ")", ";", "return", "$", "writer", "->", "writeToString", "(", ")", ";", "}" ]
Export an Array or ActiveQuery instance into a Excel formatted string. @param array|ActiveQueryInterface $input @param array $keys Defines which keys should be packed into the generated xlsx. The defined keys does not change the sort behavior of the generated xls. @param bool $header @return mixed @throws Exception @since 1.0.4
[ "Export", "an", "Array", "or", "ActiveQuery", "instance", "into", "a", "Excel", "formatted", "string", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ExportHelper.php#L45-L55
luyadev/luya
core/helpers/ExportHelper.php
ExportHelper.generateContentArray
protected static function generateContentArray($contentRows, $keys, $generateHeader = true) { if (is_scalar($contentRows)) { throw new Exception("Content must be either an array, object or traversable"); } $attributeKeys = $keys; $header = []; $rows = []; $i = 0; foreach ($contentRows as $content) { // handle rows content if (!empty($keys) && is_array($content)) { foreach ($content as $k => $v) { if (!in_array($k, $keys)) { unset($content[$k]); } } } elseif (!empty($keys) && is_object($content)) { $attributeKeys[get_class($content)] = $keys; } $rows[$i] = ArrayHelper::toArray($content, $attributeKeys, false); // handler header if ($i == 0 && $generateHeader) { if ($content instanceof ActiveRecordInterface) { foreach ($content as $k => $v) { if (empty($keys)) { $header[] = $content->getAttributeLabel($k); } elseif (in_array($k, $keys)) { $header[] = $content->getAttributeLabel($k); } } } else { $header = array_keys($rows[0]); } } $i++; } if ($generateHeader) { return ArrayHelper::merge([$header], $rows); } return $rows; }
php
protected static function generateContentArray($contentRows, $keys, $generateHeader = true) { if (is_scalar($contentRows)) { throw new Exception("Content must be either an array, object or traversable"); } $attributeKeys = $keys; $header = []; $rows = []; $i = 0; foreach ($contentRows as $content) { if (!empty($keys) && is_array($content)) { foreach ($content as $k => $v) { if (!in_array($k, $keys)) { unset($content[$k]); } } } elseif (!empty($keys) && is_object($content)) { $attributeKeys[get_class($content)] = $keys; } $rows[$i] = ArrayHelper::toArray($content, $attributeKeys, false); if ($i == 0 && $generateHeader) { if ($content instanceof ActiveRecordInterface) { foreach ($content as $k => $v) { if (empty($keys)) { $header[] = $content->getAttributeLabel($k); } elseif (in_array($k, $keys)) { $header[] = $content->getAttributeLabel($k); } } } else { $header = array_keys($rows[0]); } } $i++; } if ($generateHeader) { return ArrayHelper::merge([$header], $rows); } return $rows; }
[ "protected", "static", "function", "generateContentArray", "(", "$", "contentRows", ",", "$", "keys", ",", "$", "generateHeader", "=", "true", ")", "{", "if", "(", "is_scalar", "(", "$", "contentRows", ")", ")", "{", "throw", "new", "Exception", "(", "\"Content must be either an array, object or traversable\"", ")", ";", "}", "$", "attributeKeys", "=", "$", "keys", ";", "$", "header", "=", "[", "]", ";", "$", "rows", "=", "[", "]", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "contentRows", "as", "$", "content", ")", "{", "// handle rows content", "if", "(", "!", "empty", "(", "$", "keys", ")", "&&", "is_array", "(", "$", "content", ")", ")", "{", "foreach", "(", "$", "content", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "!", "in_array", "(", "$", "k", ",", "$", "keys", ")", ")", "{", "unset", "(", "$", "content", "[", "$", "k", "]", ")", ";", "}", "}", "}", "elseif", "(", "!", "empty", "(", "$", "keys", ")", "&&", "is_object", "(", "$", "content", ")", ")", "{", "$", "attributeKeys", "[", "get_class", "(", "$", "content", ")", "]", "=", "$", "keys", ";", "}", "$", "rows", "[", "$", "i", "]", "=", "ArrayHelper", "::", "toArray", "(", "$", "content", ",", "$", "attributeKeys", ",", "false", ")", ";", "// handler header", "if", "(", "$", "i", "==", "0", "&&", "$", "generateHeader", ")", "{", "if", "(", "$", "content", "instanceof", "ActiveRecordInterface", ")", "{", "foreach", "(", "$", "content", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "$", "header", "[", "]", "=", "$", "content", "->", "getAttributeLabel", "(", "$", "k", ")", ";", "}", "elseif", "(", "in_array", "(", "$", "k", ",", "$", "keys", ")", ")", "{", "$", "header", "[", "]", "=", "$", "content", "->", "getAttributeLabel", "(", "$", "k", ")", ";", "}", "}", "}", "else", "{", "$", "header", "=", "array_keys", "(", "$", "rows", "[", "0", "]", ")", ";", "}", "}", "$", "i", "++", ";", "}", "if", "(", "$", "generateHeader", ")", "{", "return", "ArrayHelper", "::", "merge", "(", "[", "$", "header", "]", ",", "$", "rows", ")", ";", "}", "return", "$", "rows", ";", "}" ]
Generate content by rows. @param array $contentRows @param string$delimiter @param string $keys @param bool $generateHeader @return array @throws Exception @since 1.0.4
[ "Generate", "content", "by", "rows", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ExportHelper.php#L84-L130
luyadev/luya
core/helpers/ExportHelper.php
ExportHelper.generateRow
protected static function generateRow(array $row, $delimiter, $enclose) { array_walk($row, function (&$item) use ($enclose) { if (is_bool($item)) { $item = (int) $item; } elseif (is_null($item)) { $item = ''; } elseif (!is_scalar($item)) { $item = "[array]"; } $item = $enclose.Html::encode($item).$enclose; }); return implode($delimiter, $row) . PHP_EOL; }
php
protected static function generateRow(array $row, $delimiter, $enclose) { array_walk($row, function (&$item) use ($enclose) { if (is_bool($item)) { $item = (int) $item; } elseif (is_null($item)) { $item = ''; } elseif (!is_scalar($item)) { $item = "[array]"; } $item = $enclose.Html::encode($item).$enclose; }); return implode($delimiter, $row) . PHP_EOL; }
[ "protected", "static", "function", "generateRow", "(", "array", "$", "row", ",", "$", "delimiter", ",", "$", "enclose", ")", "{", "array_walk", "(", "$", "row", ",", "function", "(", "&", "$", "item", ")", "use", "(", "$", "enclose", ")", "{", "if", "(", "is_bool", "(", "$", "item", ")", ")", "{", "$", "item", "=", "(", "int", ")", "$", "item", ";", "}", "elseif", "(", "is_null", "(", "$", "item", ")", ")", "{", "$", "item", "=", "''", ";", "}", "elseif", "(", "!", "is_scalar", "(", "$", "item", ")", ")", "{", "$", "item", "=", "\"[array]\"", ";", "}", "$", "item", "=", "$", "enclose", ".", "Html", "::", "encode", "(", "$", "item", ")", ".", "$", "enclose", ";", "}", ")", ";", "return", "implode", "(", "$", "delimiter", ",", "$", "row", ")", ".", "PHP_EOL", ";", "}" ]
Generate a row by its items. @param array $row @param string $delimiter @param string $enclose @return string @since 1.0.4
[ "Generate", "a", "row", "by", "its", "items", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ExportHelper.php#L157-L171
luyadev/luya
core/web/jsonld/OpeningHoursValue.php
OpeningHoursValue.setDay
public function setDay($name, array $time) { if (is_numeric($name)) { if (!array_key_exists($name, $this->_dayMap)) { throw new InvalidConfigException("The given day numeric value {$name} is not available in the list of valid day values."); } $name = $this->_dayMap[$name]; } if (!array_search($name, $this->_dayMap)) { throw new InvalidConfigException("The given day {$name} is not in the list of valid day names."); } foreach ($time as $from => $to) { $this->_days[] = "{$name} {$from}-{$to}"; } }
php
public function setDay($name, array $time) { if (is_numeric($name)) { if (!array_key_exists($name, $this->_dayMap)) { throw new InvalidConfigException("The given day numeric value {$name} is not available in the list of valid day values."); } $name = $this->_dayMap[$name]; } if (!array_search($name, $this->_dayMap)) { throw new InvalidConfigException("The given day {$name} is not in the list of valid day names."); } foreach ($time as $from => $to) { $this->_days[] = "{$name} {$from}-{$to}"; } }
[ "public", "function", "setDay", "(", "$", "name", ",", "array", "$", "time", ")", "{", "if", "(", "is_numeric", "(", "$", "name", ")", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "_dayMap", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"The given day numeric value {$name} is not available in the list of valid day values.\"", ")", ";", "}", "$", "name", "=", "$", "this", "->", "_dayMap", "[", "$", "name", "]", ";", "}", "if", "(", "!", "array_search", "(", "$", "name", ",", "$", "this", "->", "_dayMap", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"The given day {$name} is not in the list of valid day names.\")", ";", "", "}", "foreach", "(", "$", "time", "as", "$", "from", "=>", "$", "to", ")", "{", "$", "this", "->", "_days", "[", "]", "=", "\"{$name} {$from}-{$to}\"", ";", "}", "}" ]
Set a a value for a day. ```php setDay(OpeningHoursValue::DAY_MONDAY, ['08:00' => '12:00', '14:00' => '20:00']); ``` @param [type] $name @param array $time @return void
[ "Set", "a", "a", "value", "for", "a", "day", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/OpeningHoursValue.php#L51-L68
luyadev/luya
core/web/TelephoneLink.php
TelephoneLink.setTelephone
public function setTelephone($telephone) { /** * Hack to support leading + sign * @see \luya\cms\models\NavItemPageBlockItem::rules() * @link https://github.com/luyadev/luya/pull/1815 */ $telephone = ltrim($telephone, '\\'); $validator = new RegularExpressionValidator([ 'pattern' => '#^(?:0|\+[0-9]{2})[\d\- ()]+$#' ]); if ($validator->validate($telephone, $error)) { $this->_telephone = $telephone; } else { $this->_telephone = false; } }
php
public function setTelephone($telephone) { $telephone = ltrim($telephone, '\\'); $validator = new RegularExpressionValidator([ 'pattern' => ' ]); if ($validator->validate($telephone, $error)) { $this->_telephone = $telephone; } else { $this->_telephone = false; } }
[ "public", "function", "setTelephone", "(", "$", "telephone", ")", "{", "/**\n * Hack to support leading + sign\n * @see \\luya\\cms\\models\\NavItemPageBlockItem::rules()\n * @link https://github.com/luyadev/luya/pull/1815\n */", "$", "telephone", "=", "ltrim", "(", "$", "telephone", ",", "'\\\\'", ")", ";", "$", "validator", "=", "new", "RegularExpressionValidator", "(", "[", "'pattern'", "=>", "'#^(?:0|\\+[0-9]{2})[\\d\\- ()]+$#'", "]", ")", ";", "if", "(", "$", "validator", "->", "validate", "(", "$", "telephone", ",", "$", "error", ")", ")", "{", "$", "this", "->", "_telephone", "=", "$", "telephone", ";", "}", "else", "{", "$", "this", "->", "_telephone", "=", "false", ";", "}", "}" ]
Setter method for telephone number. If no valid telephone is provided, not value is set. @param string|boolean $telephone The telephone number which should be used for the tel link.
[ "Setter", "method", "for", "telephone", "number", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/TelephoneLink.php#L41-L58
luyadev/luya
core/helpers/ZipHelper.php
ZipHelper.dir
public static function dir($sourcePath, $outZipPath) { $pathInfo = pathInfo($sourcePath); $parentPath = $pathInfo['dirname']; $dirName = $pathInfo['basename']; $z = new ZipArchive(); $z->open($outZipPath, ZIPARCHIVE::CREATE); $z->addEmptyDir($dirName); self::folderToZip($sourcePath, $z, strlen("$parentPath/")); $z->close(); return true; }
php
public static function dir($sourcePath, $outZipPath) { $pathInfo = pathInfo($sourcePath); $parentPath = $pathInfo['dirname']; $dirName = $pathInfo['basename']; $z = new ZipArchive(); $z->open($outZipPath, ZIPARCHIVE::CREATE); $z->addEmptyDir($dirName); self::folderToZip($sourcePath, $z, strlen("$parentPath/")); $z->close(); return true; }
[ "public", "static", "function", "dir", "(", "$", "sourcePath", ",", "$", "outZipPath", ")", "{", "$", "pathInfo", "=", "pathInfo", "(", "$", "sourcePath", ")", ";", "$", "parentPath", "=", "$", "pathInfo", "[", "'dirname'", "]", ";", "$", "dirName", "=", "$", "pathInfo", "[", "'basename'", "]", ";", "$", "z", "=", "new", "ZipArchive", "(", ")", ";", "$", "z", "->", "open", "(", "$", "outZipPath", ",", "ZIPARCHIVE", "::", "CREATE", ")", ";", "$", "z", "->", "addEmptyDir", "(", "$", "dirName", ")", ";", "self", "::", "folderToZip", "(", "$", "sourcePath", ",", "$", "z", ",", "strlen", "(", "\"$parentPath/\"", ")", ")", ";", "$", "z", "->", "close", "(", ")", ";", "return", "true", ";", "}" ]
Zip a folder (include itself). ```php \luya\helper\Zip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); ``` @param string $sourcePath Path of directory to be zip. @param string $outZipPath Path of output zip file.
[ "Zip", "a", "folder", "(", "include", "itself", ")", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ZipHelper.php#L52-L65
luyadev/luya
core/console/commands/MigrateController.php
MigrateController.actionCreate
public function actionCreate($name, $module = false) { if (empty($module)) { return parent::actionCreate($name); } if (!isset($this->migrationPath[$module])) { throw new Exception("The module \"$module\" does not exist in the application modules configuration."); } // apply custom migration code to generate new migrations for a module specific path if (!preg_match('/^[\w\\\\]+$/', $name)) { throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.'); } $className = 'm'.gmdate('ymd_His').'_'.$name; $migrationPath = $this->migrationPath[$module]; $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php'; if ($this->confirm("Create new migration '$file'?")) { $content = $this->generateMigrationSourceCode([ 'name' => $name, 'className' => $className, 'namespace' => null, ]); FileHelper::createDirectory($migrationPath); file_put_contents($file, $content); $this->stdout("New migration created successfully.\n", Console::FG_GREEN); } }
php
public function actionCreate($name, $module = false) { if (empty($module)) { return parent::actionCreate($name); } if (!isset($this->migrationPath[$module])) { throw new Exception("The module \"$module\" does not exist in the application modules configuration."); } if (!preg_match('/^[\w\\\\]+$/', $name)) { throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.'); } $className = 'm'.gmdate('ymd_His').'_'.$name; $migrationPath = $this->migrationPath[$module]; $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php'; if ($this->confirm("Create new migration '$file'?")) { $content = $this->generateMigrationSourceCode([ 'name' => $name, 'className' => $className, 'namespace' => null, ]); FileHelper::createDirectory($migrationPath); file_put_contents($file, $content); $this->stdout("New migration created successfully.\n", Console::FG_GREEN); } }
[ "public", "function", "actionCreate", "(", "$", "name", ",", "$", "module", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "module", ")", ")", "{", "return", "parent", "::", "actionCreate", "(", "$", "name", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "migrationPath", "[", "$", "module", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"The module \\\"$module\\\" does not exist in the application modules configuration.\"", ")", ";", "}", "// apply custom migration code to generate new migrations for a module specific path", "if", "(", "!", "preg_match", "(", "'/^[\\w\\\\\\\\]+$/'", ",", "$", "name", ")", ")", "{", "throw", "new", "Exception", "(", "'The migration name should contain letters, digits, underscore and/or backslash characters only.'", ")", ";", "}", "$", "className", "=", "'m'", ".", "gmdate", "(", "'ymd_His'", ")", ".", "'_'", ".", "$", "name", ";", "$", "migrationPath", "=", "$", "this", "->", "migrationPath", "[", "$", "module", "]", ";", "$", "file", "=", "$", "migrationPath", ".", "DIRECTORY_SEPARATOR", ".", "$", "className", ".", "'.php'", ";", "if", "(", "$", "this", "->", "confirm", "(", "\"Create new migration '$file'?\"", ")", ")", "{", "$", "content", "=", "$", "this", "->", "generateMigrationSourceCode", "(", "[", "'name'", "=>", "$", "name", ",", "'className'", "=>", "$", "className", ",", "'namespace'", "=>", "null", ",", "]", ")", ";", "FileHelper", "::", "createDirectory", "(", "$", "migrationPath", ")", ";", "file_put_contents", "(", "$", "file", ",", "$", "content", ")", ";", "$", "this", "->", "stdout", "(", "\"New migration created successfully.\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "}", "}" ]
@inheritDoc @see https://github.com/yiisoft/yii2/issues/384 @see \yii\console\controllers\BaseMigrateController::actionCreate()
[ "@inheritDoc" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/commands/MigrateController.php#L39-L70
luyadev/luya
core/traits/ErrorHandlerTrait.php
ErrorHandlerTrait.transferMessage
public function transferMessage($message, $file = __FILE__, $line = __LINE__) { return $this->apiServerSendData($this->getExceptionArray([ 'message' => $message, 'file' => $file, 'line' => $line, ])); }
php
public function transferMessage($message, $file = __FILE__, $line = __LINE__) { return $this->apiServerSendData($this->getExceptionArray([ 'message' => $message, 'file' => $file, 'line' => $line, ])); }
[ "public", "function", "transferMessage", "(", "$", "message", ",", "$", "file", "=", "__FILE__", ",", "$", "line", "=", "__LINE__", ")", "{", "return", "$", "this", "->", "apiServerSendData", "(", "$", "this", "->", "getExceptionArray", "(", "[", "'message'", "=>", "$", "message", ",", "'file'", "=>", "$", "file", ",", "'line'", "=>", "$", "line", ",", "]", ")", ")", ";", "}" ]
Send a custom message to the api server event its not related to an exception. Sometimes you just want to pass informations from your application, this method allows you to transfer a message to the error api server. Example of sending a message ```php Yii::$app->errorHandler->transferMessage('Something went wrong here!', __FILE__, __LINE__); ``` @param string $message The message you want to send to the error api server. @param string $file The you are currently send the message (use __FILE__) @param string $line The line you want to submit (use __LINE__) @return bool|null
[ "Send", "a", "custom", "message", "to", "the", "api", "server", "event", "its", "not", "related", "to", "an", "exception", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/ErrorHandlerTrait.php#L70-L77
luyadev/luya
core/traits/ErrorHandlerTrait.php
ErrorHandlerTrait.apiServerSendData
private function apiServerSendData(array $data) { if ($this->transferException) { $curl = new Curl(); $curl->setOpt(CURLOPT_CONNECTTIMEOUT, 2); $curl->setOpt(CURLOPT_TIMEOUT, 2); $curl->post(Url::ensureHttp(rtrim($this->api, '/')).'/create', [ 'error_json' => Json::encode($data), ]); $this->lastTransferCall = $curl; return $curl->isSuccess(); } return null; }
php
private function apiServerSendData(array $data) { if ($this->transferException) { $curl = new Curl(); $curl->setOpt(CURLOPT_CONNECTTIMEOUT, 2); $curl->setOpt(CURLOPT_TIMEOUT, 2); $curl->post(Url::ensureHttp(rtrim($this->api, '/')).'/create', [ 'error_json' => Json::encode($data), ]); $this->lastTransferCall = $curl; return $curl->isSuccess(); } return null; }
[ "private", "function", "apiServerSendData", "(", "array", "$", "data", ")", "{", "if", "(", "$", "this", "->", "transferException", ")", "{", "$", "curl", "=", "new", "Curl", "(", ")", ";", "$", "curl", "->", "setOpt", "(", "CURLOPT_CONNECTTIMEOUT", ",", "2", ")", ";", "$", "curl", "->", "setOpt", "(", "CURLOPT_TIMEOUT", ",", "2", ")", ";", "$", "curl", "->", "post", "(", "Url", "::", "ensureHttp", "(", "rtrim", "(", "$", "this", "->", "api", ",", "'/'", ")", ")", ".", "'/create'", ",", "[", "'error_json'", "=>", "Json", "::", "encode", "(", "$", "data", ")", ",", "]", ")", ";", "$", "this", "->", "lastTransferCall", "=", "$", "curl", ";", "return", "$", "curl", "->", "isSuccess", "(", ")", ";", "}", "return", "null", ";", "}" ]
Send the array data to the api server. @param array $data The array to be sent to the server. @return boolean|null true/false if data has been sent to the api successfull or not, null if the transfer is disabled.
[ "Send", "the", "array", "data", "to", "the", "api", "server", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/ErrorHandlerTrait.php#L85-L101
luyadev/luya
core/traits/ErrorHandlerTrait.php
ErrorHandlerTrait.getExceptionArray
public function getExceptionArray($exception) { $_message = 'Uknonwn exception object, not instance of \Exception.'; $_file = 'unknown'; $_line = 0; $_trace = []; $_previousException = []; if (is_object($exception)) { $prev = $exception->getPrevious(); if (!empty($prev)) { $_previousException = [ 'message' => $prev->getMessage(), 'file' => $prev->getFile(), 'line' => $prev->getLine(), 'trace' => $this->buildTrace($prev), ]; } $_trace = $this->buildTrace($exception); $_message = $exception->getMessage(); $_file = $exception->getFile(); $_line = $exception->getLine(); } elseif (is_string($exception)) { $_message = 'exception string: ' . $exception; } elseif (is_array($exception)) { $_message = isset($exception['message']) ? $exception['message'] : 'exception array dump: ' . print_r($exception, true); $_file = isset($exception['file']) ? $exception['file'] : __FILE__; $_line = isset($exception['line']) ? $exception['line'] : __LINE__; } return [ 'message' => $_message, 'file' => $_file, 'line' => $_line, 'requestUri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null, 'serverName' => isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null, 'date' => date('d.m.Y H:i'), 'trace' => $_trace, 'previousException' => $_previousException, 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null, 'get' => isset($_GET) ? ArrayHelper::coverSensitiveValues($_GET, $this->sensitiveKeys) : [], 'post' => isset($_POST) ? ArrayHelper::coverSensitiveValues($_POST, $this->sensitiveKeys) : [], 'bodyParams' => Yii::$app instanceof Application ? ArrayHelper::coverSensitiveValues(Yii::$app->request->bodyParams) : [], 'session' => isset($_SESSION) ? ArrayHelper::coverSensitiveValues($_SESSION, $this->sensitiveKeys) : [], 'server' => isset($_SERVER) ? ArrayHelper::coverSensitiveValues($_SERVER, $this->sensitiveKeys) : [], 'profiling' => Yii::getLogger()->profiling, 'logger' => Yii::getLogger()->messages, ]; }
php
public function getExceptionArray($exception) { $_message = 'Uknonwn exception object, not instance of \Exception.'; $_file = 'unknown'; $_line = 0; $_trace = []; $_previousException = []; if (is_object($exception)) { $prev = $exception->getPrevious(); if (!empty($prev)) { $_previousException = [ 'message' => $prev->getMessage(), 'file' => $prev->getFile(), 'line' => $prev->getLine(), 'trace' => $this->buildTrace($prev), ]; } $_trace = $this->buildTrace($exception); $_message = $exception->getMessage(); $_file = $exception->getFile(); $_line = $exception->getLine(); } elseif (is_string($exception)) { $_message = 'exception string: ' . $exception; } elseif (is_array($exception)) { $_message = isset($exception['message']) ? $exception['message'] : 'exception array dump: ' . print_r($exception, true); $_file = isset($exception['file']) ? $exception['file'] : __FILE__; $_line = isset($exception['line']) ? $exception['line'] : __LINE__; } return [ 'message' => $_message, 'file' => $_file, 'line' => $_line, 'requestUri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null, 'serverName' => isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null, 'date' => date('d.m.Y H:i'), 'trace' => $_trace, 'previousException' => $_previousException, 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null, 'get' => isset($_GET) ? ArrayHelper::coverSensitiveValues($_GET, $this->sensitiveKeys) : [], 'post' => isset($_POST) ? ArrayHelper::coverSensitiveValues($_POST, $this->sensitiveKeys) : [], 'bodyParams' => Yii::$app instanceof Application ? ArrayHelper::coverSensitiveValues(Yii::$app->request->bodyParams) : [], 'session' => isset($_SESSION) ? ArrayHelper::coverSensitiveValues($_SESSION, $this->sensitiveKeys) : [], 'server' => isset($_SERVER) ? ArrayHelper::coverSensitiveValues($_SERVER, $this->sensitiveKeys) : [], 'profiling' => Yii::getLogger()->profiling, 'logger' => Yii::getLogger()->messages, ]; }
[ "public", "function", "getExceptionArray", "(", "$", "exception", ")", "{", "$", "_message", "=", "'Uknonwn exception object, not instance of \\Exception.'", ";", "$", "_file", "=", "'unknown'", ";", "$", "_line", "=", "0", ";", "$", "_trace", "=", "[", "]", ";", "$", "_previousException", "=", "[", "]", ";", "if", "(", "is_object", "(", "$", "exception", ")", ")", "{", "$", "prev", "=", "$", "exception", "->", "getPrevious", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "prev", ")", ")", "{", "$", "_previousException", "=", "[", "'message'", "=>", "$", "prev", "->", "getMessage", "(", ")", ",", "'file'", "=>", "$", "prev", "->", "getFile", "(", ")", ",", "'line'", "=>", "$", "prev", "->", "getLine", "(", ")", ",", "'trace'", "=>", "$", "this", "->", "buildTrace", "(", "$", "prev", ")", ",", "]", ";", "}", "$", "_trace", "=", "$", "this", "->", "buildTrace", "(", "$", "exception", ")", ";", "$", "_message", "=", "$", "exception", "->", "getMessage", "(", ")", ";", "$", "_file", "=", "$", "exception", "->", "getFile", "(", ")", ";", "$", "_line", "=", "$", "exception", "->", "getLine", "(", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "exception", ")", ")", "{", "$", "_message", "=", "'exception string: '", ".", "$", "exception", ";", "}", "elseif", "(", "is_array", "(", "$", "exception", ")", ")", "{", "$", "_message", "=", "isset", "(", "$", "exception", "[", "'message'", "]", ")", "?", "$", "exception", "[", "'message'", "]", ":", "'exception array dump: '", ".", "print_r", "(", "$", "exception", ",", "true", ")", ";", "$", "_file", "=", "isset", "(", "$", "exception", "[", "'file'", "]", ")", "?", "$", "exception", "[", "'file'", "]", ":", "__FILE__", ";", "$", "_line", "=", "isset", "(", "$", "exception", "[", "'line'", "]", ")", "?", "$", "exception", "[", "'line'", "]", ":", "__LINE__", ";", "}", "return", "[", "'message'", "=>", "$", "_message", ",", "'file'", "=>", "$", "_file", ",", "'line'", "=>", "$", "_line", ",", "'requestUri'", "=>", "isset", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", "?", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ":", "null", ",", "'serverName'", "=>", "isset", "(", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ")", "?", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ":", "null", ",", "'date'", "=>", "date", "(", "'d.m.Y H:i'", ")", ",", "'trace'", "=>", "$", "_trace", ",", "'previousException'", "=>", "$", "_previousException", ",", "'ip'", "=>", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", "?", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ":", "null", ",", "'get'", "=>", "isset", "(", "$", "_GET", ")", "?", "ArrayHelper", "::", "coverSensitiveValues", "(", "$", "_GET", ",", "$", "this", "->", "sensitiveKeys", ")", ":", "[", "]", ",", "'post'", "=>", "isset", "(", "$", "_POST", ")", "?", "ArrayHelper", "::", "coverSensitiveValues", "(", "$", "_POST", ",", "$", "this", "->", "sensitiveKeys", ")", ":", "[", "]", ",", "'bodyParams'", "=>", "Yii", "::", "$", "app", "instanceof", "Application", "?", "ArrayHelper", "::", "coverSensitiveValues", "(", "Yii", "::", "$", "app", "->", "request", "->", "bodyParams", ")", ":", "[", "]", ",", "'session'", "=>", "isset", "(", "$", "_SESSION", ")", "?", "ArrayHelper", "::", "coverSensitiveValues", "(", "$", "_SESSION", ",", "$", "this", "->", "sensitiveKeys", ")", ":", "[", "]", ",", "'server'", "=>", "isset", "(", "$", "_SERVER", ")", "?", "ArrayHelper", "::", "coverSensitiveValues", "(", "$", "_SERVER", ",", "$", "this", "->", "sensitiveKeys", ")", ":", "[", "]", ",", "'profiling'", "=>", "Yii", "::", "getLogger", "(", ")", "->", "profiling", ",", "'logger'", "=>", "Yii", "::", "getLogger", "(", ")", "->", "messages", ",", "]", ";", "}" ]
Get an readable array to transfer from an exception @param mixed $exception Exception object @return array An array with transformed exception data
[ "Get", "an", "readable", "array", "to", "transfer", "from", "an", "exception" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/ErrorHandlerTrait.php#L121-L171
luyadev/luya
core/traits/ErrorHandlerTrait.php
ErrorHandlerTrait.buildTrace
private function buildTrace($exception) { $_trace = []; foreach ($exception->getTrace() as $key => $item) { $_trace[$key] = [ 'file' => isset($item['file']) ? $item['file'] : null, 'line' => isset($item['line']) ? $item['line'] : null, 'function' => isset($item['function']) ? $item['function'] : null, 'class' => isset($item['class']) ? $item['class'] : null, ]; } return $_trace; }
php
private function buildTrace($exception) { $_trace = []; foreach ($exception->getTrace() as $key => $item) { $_trace[$key] = [ 'file' => isset($item['file']) ? $item['file'] : null, 'line' => isset($item['line']) ? $item['line'] : null, 'function' => isset($item['function']) ? $item['function'] : null, 'class' => isset($item['class']) ? $item['class'] : null, ]; } return $_trace; }
[ "private", "function", "buildTrace", "(", "$", "exception", ")", "{", "$", "_trace", "=", "[", "]", ";", "foreach", "(", "$", "exception", "->", "getTrace", "(", ")", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "_trace", "[", "$", "key", "]", "=", "[", "'file'", "=>", "isset", "(", "$", "item", "[", "'file'", "]", ")", "?", "$", "item", "[", "'file'", "]", ":", "null", ",", "'line'", "=>", "isset", "(", "$", "item", "[", "'line'", "]", ")", "?", "$", "item", "[", "'line'", "]", ":", "null", ",", "'function'", "=>", "isset", "(", "$", "item", "[", "'function'", "]", ")", "?", "$", "item", "[", "'function'", "]", ":", "null", ",", "'class'", "=>", "isset", "(", "$", "item", "[", "'class'", "]", ")", "?", "$", "item", "[", "'class'", "]", ":", "null", ",", "]", ";", "}", "return", "$", "_trace", ";", "}" ]
Build trace array from exception. @param object $exception @return array
[ "Build", "trace", "array", "from", "exception", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/traits/ErrorHandlerTrait.php#L179-L192
luyadev/luya
core/web/Request.php
Request.getIsAdmin
public function getIsAdmin() { if ($this->_isAdmin === null) { if ($this->getIsConsoleRequest() && !$this->forceWebRequest && !Yii::$app->hasModule('admin')) { $this->_isAdmin = false; } else { // if there is only an application with admin module and set as default route // this might by the admin module even when pathInfo is empty if (Yii::$app->defaultRoute == 'admin' && empty($this->pathInfo)) { $this->_isAdmin = true; } else { $resolver = Yii::$app->composition->getResolvedPathInfo($this); $parts = explode('/', $resolver->resolvedPath); $first = reset($parts); if (preg_match('/admin/i', $first, $results)) { $this->_isAdmin = true; } else { $this->_isAdmin = false; } } } } return $this->_isAdmin; }
php
public function getIsAdmin() { if ($this->_isAdmin === null) { if ($this->getIsConsoleRequest() && !$this->forceWebRequest && !Yii::$app->hasModule('admin')) { $this->_isAdmin = false; } else { if (Yii::$app->defaultRoute == 'admin' && empty($this->pathInfo)) { $this->_isAdmin = true; } else { $resolver = Yii::$app->composition->getResolvedPathInfo($this); $parts = explode('/', $resolver->resolvedPath); $first = reset($parts); if (preg_match('/admin/i', $first, $results)) { $this->_isAdmin = true; } else { $this->_isAdmin = false; } } } } return $this->_isAdmin; }
[ "public", "function", "getIsAdmin", "(", ")", "{", "if", "(", "$", "this", "->", "_isAdmin", "===", "null", ")", "{", "if", "(", "$", "this", "->", "getIsConsoleRequest", "(", ")", "&&", "!", "$", "this", "->", "forceWebRequest", "&&", "!", "Yii", "::", "$", "app", "->", "hasModule", "(", "'admin'", ")", ")", "{", "$", "this", "->", "_isAdmin", "=", "false", ";", "}", "else", "{", "// if there is only an application with admin module and set as default route", "// this might by the admin module even when pathInfo is empty", "if", "(", "Yii", "::", "$", "app", "->", "defaultRoute", "==", "'admin'", "&&", "empty", "(", "$", "this", "->", "pathInfo", ")", ")", "{", "$", "this", "->", "_isAdmin", "=", "true", ";", "}", "else", "{", "$", "resolver", "=", "Yii", "::", "$", "app", "->", "composition", "->", "getResolvedPathInfo", "(", "$", "this", ")", ";", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "resolver", "->", "resolvedPath", ")", ";", "$", "first", "=", "reset", "(", "$", "parts", ")", ";", "if", "(", "preg_match", "(", "'/admin/i'", ",", "$", "first", ",", "$", "results", ")", ")", "{", "$", "this", "->", "_isAdmin", "=", "true", ";", "}", "else", "{", "$", "this", "->", "_isAdmin", "=", "false", ";", "}", "}", "}", "}", "return", "$", "this", "->", "_isAdmin", ";", "}" ]
Getter method resolves the current url request and check if admin context. This is mostly used in order to bootstrap more modules and application logic in admin context. @return boolean If the current request is in admin context return value is true, otherwise false.
[ "Getter", "method", "resolves", "the", "current", "url", "request", "and", "check", "if", "admin", "context", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/Request.php#L59-L83
luyadev/luya
core/console/Command.php
Command.verbosePrint
public function verbosePrint($message, $section = null) { if ($this->verbose) { $this->output((!empty($section)) ? $section . ': ' . $message : $message); } }
php
public function verbosePrint($message, $section = null) { if ($this->verbose) { $this->output((!empty($section)) ? $section . ': ' . $message : $message); } }
[ "public", "function", "verbosePrint", "(", "$", "message", ",", "$", "section", "=", "null", ")", "{", "if", "(", "$", "this", "->", "verbose", ")", "{", "$", "this", "->", "output", "(", "(", "!", "empty", "(", "$", "section", ")", ")", "?", "$", "section", ".", "': '", ".", "$", "message", ":", "$", "message", ")", ";", "}", "}" ]
Method to print informations directly when verbose is enabled. @param string $message @param string $section
[ "Method", "to", "print", "informations", "directly", "when", "verbose", "is", "enabled", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/Command.php#L39-L44
luyadev/luya
core/console/Command.php
Command.selectModule
public function selectModule(array $options = []) { $modules = []; foreach (Yii::$app->getModules() as $id => $object) { if (!$object instanceof \luya\base\Module) { continue; } if (isset($options['onlyAdmin']) && $options['onlyAdmin']) { if (!$object instanceof AdminModuleInterface) { continue; } } if (isset($options['hideCore']) && $options['hideCore']) { if ($object instanceof CoreModuleInterface) { continue; } } $modules[$id] = $id; } $text = (isset($options['text'])) ? $options['text'] : 'Please select a module:'; return $this->select($text, $modules); }
php
public function selectModule(array $options = []) { $modules = []; foreach (Yii::$app->getModules() as $id => $object) { if (!$object instanceof \luya\base\Module) { continue; } if (isset($options['onlyAdmin']) && $options['onlyAdmin']) { if (!$object instanceof AdminModuleInterface) { continue; } } if (isset($options['hideCore']) && $options['hideCore']) { if ($object instanceof CoreModuleInterface) { continue; } } $modules[$id] = $id; } $text = (isset($options['text'])) ? $options['text'] : 'Please select a module:'; return $this->select($text, $modules); }
[ "public", "function", "selectModule", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "modules", "=", "[", "]", ";", "foreach", "(", "Yii", "::", "$", "app", "->", "getModules", "(", ")", "as", "$", "id", "=>", "$", "object", ")", "{", "if", "(", "!", "$", "object", "instanceof", "\\", "luya", "\\", "base", "\\", "Module", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'onlyAdmin'", "]", ")", "&&", "$", "options", "[", "'onlyAdmin'", "]", ")", "{", "if", "(", "!", "$", "object", "instanceof", "AdminModuleInterface", ")", "{", "continue", ";", "}", "}", "if", "(", "isset", "(", "$", "options", "[", "'hideCore'", "]", ")", "&&", "$", "options", "[", "'hideCore'", "]", ")", "{", "if", "(", "$", "object", "instanceof", "CoreModuleInterface", ")", "{", "continue", ";", "}", "}", "$", "modules", "[", "$", "id", "]", "=", "$", "id", ";", "}", "$", "text", "=", "(", "isset", "(", "$", "options", "[", "'text'", "]", ")", ")", "?", "$", "options", "[", "'text'", "]", ":", "'Please select a module:'", ";", "return", "$", "this", "->", "select", "(", "$", "text", ",", "$", "modules", ")", ";", "}" ]
Get selection list for console commands with defined options. @param array $options Define behavior of the module selector prompt, options are name-value pairs. The following options are available: - onlyAdmin: boolean, if enabled all not admin modules will not be included - hideCore: boolean, if enabled all core modules (from luya dev team) will be hidden. @return string The name (ID) of the selected module.
[ "Get", "selection", "list", "for", "console", "commands", "with", "defined", "options", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/Command.php#L79-L103
luyadev/luya
core/console/Command.php
Command.createClassName
public function createClassName($string, $suffix = false) { $name = Inflector::camelize($string); if ($suffix !== false && StringHelper::endsWith($name, $suffix, false)) { $name = substr($name, 0, -(strlen($suffix))); } return $name . $suffix; }
php
public function createClassName($string, $suffix = false) { $name = Inflector::camelize($string); if ($suffix !== false && StringHelper::endsWith($name, $suffix, false)) { $name = substr($name, 0, -(strlen($suffix))); } return $name . $suffix; }
[ "public", "function", "createClassName", "(", "$", "string", ",", "$", "suffix", "=", "false", ")", "{", "$", "name", "=", "Inflector", "::", "camelize", "(", "$", "string", ")", ";", "if", "(", "$", "suffix", "!==", "false", "&&", "StringHelper", "::", "endsWith", "(", "$", "name", ",", "$", "suffix", ",", "false", ")", ")", "{", "$", "name", "=", "substr", "(", "$", "name", ",", "0", ",", "-", "(", "strlen", "(", "$", "suffix", ")", ")", ")", ";", "}", "return", "$", "name", ".", "$", "suffix", ";", "}" ]
Generates a class name with camelcase style and specific suffix, if not already provided @param string $string The name of the class, e.g.: hello_word would @param string $suffix The suffix to append on the class name if not eixsts, e.g.: MySuffix @return string The class name e.g. HelloWorldMySuffix
[ "Generates", "a", "class", "name", "with", "camelcase", "style", "and", "specific", "suffix", "if", "not", "already", "provided" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/Command.php#L112-L121
luyadev/luya
core/console/commands/BaseCrudController.php
BaseCrudController.getSqlTablesArray
public function getSqlTablesArray() { $names = Yii::$app->db->schema->tableNames; return array_combine($names, $names); }
php
public function getSqlTablesArray() { $names = Yii::$app->db->schema->tableNames; return array_combine($names, $names); }
[ "public", "function", "getSqlTablesArray", "(", ")", "{", "$", "names", "=", "Yii", "::", "$", "app", "->", "db", "->", "schema", "->", "tableNames", ";", "return", "array_combine", "(", "$", "names", ",", "$", "names", ")", ";", "}" ]
Get the sql tables from the current database connection @return array An array with all sql tables.
[ "Get", "the", "sql", "tables", "from", "the", "current", "database", "connection" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/commands/BaseCrudController.php#L52-L57
luyadev/luya
core/console/commands/BaseCrudController.php
BaseCrudController.generateRules
public function generateRules($table) { $types = []; $lengths = []; foreach ($table->columns as $column) { if ($column->autoIncrement) { continue; } if (!$column->allowNull && $column->defaultValue === null) { $types['required'][] = $column->name; } switch ($column->type) { case Schema::TYPE_SMALLINT: case Schema::TYPE_INTEGER: case Schema::TYPE_BIGINT: $types['integer'][] = $column->name; break; case Schema::TYPE_BOOLEAN: $types['boolean'][] = $column->name; break; case Schema::TYPE_FLOAT: case 'double': // Schema::TYPE_DOUBLE, which is available since Yii 2.0.3 case Schema::TYPE_DECIMAL: case Schema::TYPE_MONEY: $types['number'][] = $column->name; break; case Schema::TYPE_DATE: case Schema::TYPE_TIME: case Schema::TYPE_DATETIME: case Schema::TYPE_TIMESTAMP: $types['safe'][] = $column->name; break; default: // strings if ($column->size > 0) { $lengths[$column->size][] = $column->name; } else { $types['string'][] = $column->name; } } } $rules = []; foreach ($types as $type => $columns) { $rules[] = "[['" . implode("', '", $columns) . "'], '$type']"; } foreach ($lengths as $length => $columns) { $rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]"; } $db = $this->getDbConnection(); // Unique indexes rules try { $uniqueIndexes = $db->getSchema()->findUniqueIndexes($table); foreach ($uniqueIndexes as $uniqueColumns) { // Avoid validating auto incremental columns if (!$this->isColumnAutoIncremental($table, $uniqueColumns)) { $attributesCount = count($uniqueColumns); if ($attributesCount === 1) { $rules[] = "[['" . $uniqueColumns[0] . "'], 'unique']"; } elseif ($attributesCount > 1) { $labels = array_intersect_key($this->generateLabels($table), array_flip($uniqueColumns)); $lastLabel = array_pop($labels); $columnsList = implode("', '", $uniqueColumns); $rules[] = "[['$columnsList'], 'unique', 'targetAttribute' => ['$columnsList'], 'message' => 'The combination of " . implode(', ', $labels) . " and $lastLabel has already been taken.']"; } } } } catch (NotSupportedException $e) { // doesn't support unique indexes information...do nothing } // Exist rules for foreign keys foreach ($table->foreignKeys as $refs) { $refTable = $refs[0]; $refTableSchema = $db->getTableSchema($refTable); if ($refTableSchema === null) { // Foreign key could point to non-existing table: https://github.com/yiisoft/yii2-gii/issues/34 continue; } $refClassName = $this->generateClassName($refTable); unset($refs[0]); $attributes = implode("', '", array_keys($refs)); $targetAttributes = []; foreach ($refs as $key => $value) { $targetAttributes[] = "'$key' => '$value'"; } $targetAttributes = implode(', ', $targetAttributes); $rules[] = "[['$attributes'], 'exist', 'skipOnError' => true, 'targetClass' => $refClassName::className(), 'targetAttribute' => [$targetAttributes]]"; } return $rules; }
php
public function generateRules($table) { $types = []; $lengths = []; foreach ($table->columns as $column) { if ($column->autoIncrement) { continue; } if (!$column->allowNull && $column->defaultValue === null) { $types['required'][] = $column->name; } switch ($column->type) { case Schema::TYPE_SMALLINT: case Schema::TYPE_INTEGER: case Schema::TYPE_BIGINT: $types['integer'][] = $column->name; break; case Schema::TYPE_BOOLEAN: $types['boolean'][] = $column->name; break; case Schema::TYPE_FLOAT: case 'double': case Schema::TYPE_DECIMAL: case Schema::TYPE_MONEY: $types['number'][] = $column->name; break; case Schema::TYPE_DATE: case Schema::TYPE_TIME: case Schema::TYPE_DATETIME: case Schema::TYPE_TIMESTAMP: $types['safe'][] = $column->name; break; default: if ($column->size > 0) { $lengths[$column->size][] = $column->name; } else { $types['string'][] = $column->name; } } } $rules = []; foreach ($types as $type => $columns) { $rules[] = "[['" . implode("', '", $columns) . "'], '$type']"; } foreach ($lengths as $length => $columns) { $rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]"; } $db = $this->getDbConnection(); try { $uniqueIndexes = $db->getSchema()->findUniqueIndexes($table); foreach ($uniqueIndexes as $uniqueColumns) { if (!$this->isColumnAutoIncremental($table, $uniqueColumns)) { $attributesCount = count($uniqueColumns); if ($attributesCount === 1) { $rules[] = "[['" . $uniqueColumns[0] . "'], 'unique']"; } elseif ($attributesCount > 1) { $labels = array_intersect_key($this->generateLabels($table), array_flip($uniqueColumns)); $lastLabel = array_pop($labels); $columnsList = implode("', '", $uniqueColumns); $rules[] = "[['$columnsList'], 'unique', 'targetAttribute' => ['$columnsList'], 'message' => 'The combination of " . implode(', ', $labels) . " and $lastLabel has already been taken.']"; } } } } catch (NotSupportedException $e) { } foreach ($table->foreignKeys as $refs) { $refTable = $refs[0]; $refTableSchema = $db->getTableSchema($refTable); if ($refTableSchema === null) { continue; } $refClassName = $this->generateClassName($refTable); unset($refs[0]); $attributes = implode("', '", array_keys($refs)); $targetAttributes = []; foreach ($refs as $key => $value) { $targetAttributes[] = "'$key' => '$value'"; } $targetAttributes = implode(', ', $targetAttributes); $rules[] = "[['$attributes'], 'exist', 'skipOnError' => true, 'targetClass' => $refClassName::className(), 'targetAttribute' => [$targetAttributes]]"; } return $rules; }
[ "public", "function", "generateRules", "(", "$", "table", ")", "{", "$", "types", "=", "[", "]", ";", "$", "lengths", "=", "[", "]", ";", "foreach", "(", "$", "table", "->", "columns", "as", "$", "column", ")", "{", "if", "(", "$", "column", "->", "autoIncrement", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "column", "->", "allowNull", "&&", "$", "column", "->", "defaultValue", "===", "null", ")", "{", "$", "types", "[", "'required'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "}", "switch", "(", "$", "column", "->", "type", ")", "{", "case", "Schema", "::", "TYPE_SMALLINT", ":", "case", "Schema", "::", "TYPE_INTEGER", ":", "case", "Schema", "::", "TYPE_BIGINT", ":", "$", "types", "[", "'integer'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "break", ";", "case", "Schema", "::", "TYPE_BOOLEAN", ":", "$", "types", "[", "'boolean'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "break", ";", "case", "Schema", "::", "TYPE_FLOAT", ":", "case", "'double'", ":", "// Schema::TYPE_DOUBLE, which is available since Yii 2.0.3", "case", "Schema", "::", "TYPE_DECIMAL", ":", "case", "Schema", "::", "TYPE_MONEY", ":", "$", "types", "[", "'number'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "break", ";", "case", "Schema", "::", "TYPE_DATE", ":", "case", "Schema", "::", "TYPE_TIME", ":", "case", "Schema", "::", "TYPE_DATETIME", ":", "case", "Schema", "::", "TYPE_TIMESTAMP", ":", "$", "types", "[", "'safe'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "break", ";", "default", ":", "// strings", "if", "(", "$", "column", "->", "size", ">", "0", ")", "{", "$", "lengths", "[", "$", "column", "->", "size", "]", "[", "]", "=", "$", "column", "->", "name", ";", "}", "else", "{", "$", "types", "[", "'string'", "]", "[", "]", "=", "$", "column", "->", "name", ";", "}", "}", "}", "$", "rules", "=", "[", "]", ";", "foreach", "(", "$", "types", "as", "$", "type", "=>", "$", "columns", ")", "{", "$", "rules", "[", "]", "=", "\"[['\"", ".", "implode", "(", "\"', '\"", ",", "$", "columns", ")", ".", "\"'], '$type']\"", ";", "}", "foreach", "(", "$", "lengths", "as", "$", "length", "=>", "$", "columns", ")", "{", "$", "rules", "[", "]", "=", "\"[['\"", ".", "implode", "(", "\"', '\"", ",", "$", "columns", ")", ".", "\"'], 'string', 'max' => $length]\"", ";", "}", "$", "db", "=", "$", "this", "->", "getDbConnection", "(", ")", ";", "// Unique indexes rules", "try", "{", "$", "uniqueIndexes", "=", "$", "db", "->", "getSchema", "(", ")", "->", "findUniqueIndexes", "(", "$", "table", ")", ";", "foreach", "(", "$", "uniqueIndexes", "as", "$", "uniqueColumns", ")", "{", "// Avoid validating auto incremental columns", "if", "(", "!", "$", "this", "->", "isColumnAutoIncremental", "(", "$", "table", ",", "$", "uniqueColumns", ")", ")", "{", "$", "attributesCount", "=", "count", "(", "$", "uniqueColumns", ")", ";", "if", "(", "$", "attributesCount", "===", "1", ")", "{", "$", "rules", "[", "]", "=", "\"[['\"", ".", "$", "uniqueColumns", "[", "0", "]", ".", "\"'], 'unique']\"", ";", "}", "elseif", "(", "$", "attributesCount", ">", "1", ")", "{", "$", "labels", "=", "array_intersect_key", "(", "$", "this", "->", "generateLabels", "(", "$", "table", ")", ",", "array_flip", "(", "$", "uniqueColumns", ")", ")", ";", "$", "lastLabel", "=", "array_pop", "(", "$", "labels", ")", ";", "$", "columnsList", "=", "implode", "(", "\"', '\"", ",", "$", "uniqueColumns", ")", ";", "$", "rules", "[", "]", "=", "\"[['$columnsList'], 'unique', 'targetAttribute' => ['$columnsList'], 'message' => 'The combination of \"", ".", "implode", "(", "', '", ",", "$", "labels", ")", ".", "\" and $lastLabel has already been taken.']\"", ";", "}", "}", "}", "}", "catch", "(", "NotSupportedException", "$", "e", ")", "{", "// doesn't support unique indexes information...do nothing", "}", "// Exist rules for foreign keys", "foreach", "(", "$", "table", "->", "foreignKeys", "as", "$", "refs", ")", "{", "$", "refTable", "=", "$", "refs", "[", "0", "]", ";", "$", "refTableSchema", "=", "$", "db", "->", "getTableSchema", "(", "$", "refTable", ")", ";", "if", "(", "$", "refTableSchema", "===", "null", ")", "{", "// Foreign key could point to non-existing table: https://github.com/yiisoft/yii2-gii/issues/34", "continue", ";", "}", "$", "refClassName", "=", "$", "this", "->", "generateClassName", "(", "$", "refTable", ")", ";", "unset", "(", "$", "refs", "[", "0", "]", ")", ";", "$", "attributes", "=", "implode", "(", "\"', '\"", ",", "array_keys", "(", "$", "refs", ")", ")", ";", "$", "targetAttributes", "=", "[", "]", ";", "foreach", "(", "$", "refs", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "targetAttributes", "[", "]", "=", "\"'$key' => '$value'\"", ";", "}", "$", "targetAttributes", "=", "implode", "(", "', '", ",", "$", "targetAttributes", ")", ";", "$", "rules", "[", "]", "=", "\"[['$attributes'], 'exist', 'skipOnError' => true, 'targetClass' => $refClassName::className(), 'targetAttribute' => [$targetAttributes]]\"", ";", "}", "return", "$", "rules", ";", "}" ]
Generates validation rules for the specified table. @param \yii\db\TableSchema $table the table schema @return array the generated validation rules
[ "Generates", "validation", "rules", "for", "the", "specified", "table", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/commands/BaseCrudController.php#L63-L150
luyadev/luya
core/console/commands/BaseCrudController.php
BaseCrudController.isColumnAutoIncremental
protected function isColumnAutoIncremental($table, $columns) { foreach ($columns as $column) { if (isset($table->columns[$column]) && $table->columns[$column]->autoIncrement) { return true; } } return false; }
php
protected function isColumnAutoIncremental($table, $columns) { foreach ($columns as $column) { if (isset($table->columns[$column]) && $table->columns[$column]->autoIncrement) { return true; } } return false; }
[ "protected", "function", "isColumnAutoIncremental", "(", "$", "table", ",", "$", "columns", ")", "{", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "if", "(", "isset", "(", "$", "table", "->", "columns", "[", "$", "column", "]", ")", "&&", "$", "table", "->", "columns", "[", "$", "column", "]", "->", "autoIncrement", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if any of the specified columns is auto incremental. @param \yii\db\TableSchema $table the table schema @param array $columns columns to check for autoIncrement property @return boolean whether any of the specified columns is auto incremental.
[ "Checks", "if", "any", "of", "the", "specified", "columns", "is", "auto", "incremental", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/console/commands/BaseCrudController.php#L198-L206
luyadev/luya
core/behaviors/JsonBehavior.php
JsonBehavior.autoEncodeAttributes
public function autoEncodeAttributes() { foreach ($this->attributes as $name) { if (!isset($this->owner->getDirtyAttributes()[$name])) { continue; } $value = $this->owner->{$name}; if (is_array($value)) { $this->owner->{$name} = $this->jsonEncode($name); } } }
php
public function autoEncodeAttributes() { foreach ($this->attributes as $name) { if (!isset($this->owner->getDirtyAttributes()[$name])) { continue; } $value = $this->owner->{$name}; if (is_array($value)) { $this->owner->{$name} = $this->jsonEncode($name); } } }
[ "public", "function", "autoEncodeAttributes", "(", ")", "{", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "owner", "->", "getDirtyAttributes", "(", ")", "[", "$", "name", "]", ")", ")", "{", "continue", ";", "}", "$", "value", "=", "$", "this", "->", "owner", "->", "{", "$", "name", "}", ";", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "owner", "->", "{", "$", "name", "}", "=", "$", "this", "->", "jsonEncode", "(", "$", "name", ")", ";", "}", "}", "}" ]
Encode attributes.
[ "Encode", "attributes", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/behaviors/JsonBehavior.php#L34-L47
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.coverSensitiveValues
public static function coverSensitiveValues(array $data, array $keys = []) { if (empty($keys)) { $keys = self::$sensitiveDefaultKeys; } $clean = []; foreach ($keys as $key) { $kw = strtolower($key); foreach ($data as $k => $v) { if (is_array($v)) { $clean[$k] = static::coverSensitiveValues($v, $keys); } elseif (is_scalar($v) && ($kw == strtolower($k) || StringHelper::startsWith(strtolower($k), $kw))) { $v = str_repeat("*", strlen($v)); $clean[$k] = $v; } } } // the later overrides the former return array_replace($data, $clean); }
php
public static function coverSensitiveValues(array $data, array $keys = []) { if (empty($keys)) { $keys = self::$sensitiveDefaultKeys; } $clean = []; foreach ($keys as $key) { $kw = strtolower($key); foreach ($data as $k => $v) { if (is_array($v)) { $clean[$k] = static::coverSensitiveValues($v, $keys); } elseif (is_scalar($v) && ($kw == strtolower($k) || StringHelper::startsWith(strtolower($k), $kw))) { $v = str_repeat("*", strlen($v)); $clean[$k] = $v; } } } return array_replace($data, $clean); }
[ "public", "static", "function", "coverSensitiveValues", "(", "array", "$", "data", ",", "array", "$", "keys", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "keys", ")", ")", "{", "$", "keys", "=", "self", "::", "$", "sensitiveDefaultKeys", ";", "}", "$", "clean", "=", "[", "]", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "kw", "=", "strtolower", "(", "$", "key", ")", ";", "foreach", "(", "$", "data", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "clean", "[", "$", "k", "]", "=", "static", "::", "coverSensitiveValues", "(", "$", "v", ",", "$", "keys", ")", ";", "}", "elseif", "(", "is_scalar", "(", "$", "v", ")", "&&", "(", "$", "kw", "==", "strtolower", "(", "$", "k", ")", "||", "StringHelper", "::", "startsWith", "(", "strtolower", "(", "$", "k", ")", ",", "$", "kw", ")", ")", ")", "{", "$", "v", "=", "str_repeat", "(", "\"*\"", ",", "strlen", "(", "$", "v", ")", ")", ";", "$", "clean", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", "}", "// the later overrides the former", "return", "array_replace", "(", "$", "data", ",", "$", "clean", ")", ";", "}" ]
Cover senstive values from a given list of keys. The main purpose is to remove passwords transferd to api when existing in post, get or session. Example: ```php $data = ArrayHelper::coverSensitiveValues(['username' => 'foo', 'password' => 'bar'], ['password']]; var_dump($data); // array('username' => 'foo', 'password' => '***'); ``` @param array $data The input data to cover given sensitive key values. `['username' => 'foo', 'password' => 'bar']`. @param array $key The keys which can contain sensitive data inside the $data array. `['password', 'pwd', 'pass']` if no keys provided the {{luya\helpers\ArrayHelper::$sensitiveDefaultKeys}} is used. @since 1.0.6
[ "Cover", "senstive", "values", "from", "a", "given", "list", "of", "keys", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L59-L80
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.arrayUnshiftAssoc
public static function arrayUnshiftAssoc(&$arr, $key, $val) { $arr = array_reverse($arr, true); $arr[$key] = $val; return array_reverse($arr, true); }
php
public static function arrayUnshiftAssoc(&$arr, $key, $val) { $arr = array_reverse($arr, true); $arr[$key] = $val; return array_reverse($arr, true); }
[ "public", "static", "function", "arrayUnshiftAssoc", "(", "&", "$", "arr", ",", "$", "key", ",", "$", "val", ")", "{", "$", "arr", "=", "array_reverse", "(", "$", "arr", ",", "true", ")", ";", "$", "arr", "[", "$", "key", "]", "=", "$", "val", ";", "return", "array_reverse", "(", "$", "arr", ",", "true", ")", ";", "}" ]
Prepend an assoc array item as first entry for a given array. @param array $arr The array where the value should be prepend @param string $key The new array key @param mixed $val The value for the new key @return array
[ "Prepend", "an", "assoc", "array", "item", "as", "first", "entry", "for", "a", "given", "array", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L90-L95
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.typeCast
public static function typeCast(array $array) { $return = []; foreach ($array as $k => $v) { if (is_numeric($v)) { $return[$k] = StringHelper::typeCastNumeric($v); } elseif (is_array($v)) { $return[$k] = self::typeCast($v); } else { $return[$k] = $v; } } return $return; }
php
public static function typeCast(array $array) { $return = []; foreach ($array as $k => $v) { if (is_numeric($v)) { $return[$k] = StringHelper::typeCastNumeric($v); } elseif (is_array($v)) { $return[$k] = self::typeCast($v); } else { $return[$k] = $v; } } return $return; }
[ "public", "static", "function", "typeCast", "(", "array", "$", "array", ")", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "is_numeric", "(", "$", "v", ")", ")", "{", "$", "return", "[", "$", "k", "]", "=", "StringHelper", "::", "typeCastNumeric", "(", "$", "v", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "v", ")", ")", "{", "$", "return", "[", "$", "k", "]", "=", "self", "::", "typeCast", "(", "$", "v", ")", ";", "}", "else", "{", "$", "return", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", "return", "$", "return", ";", "}" ]
TypeCast values from a mixed array source. numeric values will be casted as integer. This method is often used to convert corect json respons arrays @param array $array The array which should be type casted @return array An array with type casted values
[ "TypeCast", "values", "from", "a", "mixed", "array", "source", ".", "numeric", "values", "will", "be", "casted", "as", "integer", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L105-L120
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.search
public static function search(array $array, $searchText, $sensitive = false) { $function = ($sensitive) ? 'strpos' : 'stripos'; return array_filter($array, function ($item) use ($searchText, $function) { $response = false; foreach ($item as $key => $value) { if ($response) { continue; } if ($function($value, "$searchText") !== false) { $response = true; } } return $response; }); }
php
public static function search(array $array, $searchText, $sensitive = false) { $function = ($sensitive) ? 'strpos' : 'stripos'; return array_filter($array, function ($item) use ($searchText, $function) { $response = false; foreach ($item as $key => $value) { if ($response) { continue; } if ($function($value, "$searchText") !== false) { $response = true; } } return $response; }); }
[ "public", "static", "function", "search", "(", "array", "$", "array", ",", "$", "searchText", ",", "$", "sensitive", "=", "false", ")", "{", "$", "function", "=", "(", "$", "sensitive", ")", "?", "'strpos'", ":", "'stripos'", ";", "return", "array_filter", "(", "$", "array", ",", "function", "(", "$", "item", ")", "use", "(", "$", "searchText", ",", "$", "function", ")", "{", "$", "response", "=", "false", ";", "foreach", "(", "$", "item", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "response", ")", "{", "continue", ";", "}", "if", "(", "$", "function", "(", "$", "value", ",", "\"$searchText\"", ")", "!==", "false", ")", "{", "$", "response", "=", "true", ";", "}", "}", "return", "$", "response", ";", "}", ")", ";", "}" ]
Search trough all keys inside of an array, any occurence will return the rest of the array. ```php $data = [ ['name' => 'Foo Bar', 'id' => 1], ['name' => 'Bar Baz', 'id' => 2], ]; ``` Assuming the above array parameter searching for `1` would return: ```php $data = [ ['name' => 'Foo Bar', 'id' => 1], ]; ``` Searching for the string `Bar` would return the the orignal array is bar would be found in both. @param array $array The multidimensional array keys. @param string $searchText The text you where search inside the rows. @param boolean $sensitive Whether to use strict sensitive search (true) or case insenstivie search (false). @return array The modified array depending on the search result hits.
[ "Search", "trough", "all", "keys", "inside", "of", "an", "array", "any", "occurence", "will", "return", "the", "rest", "of", "the", "array", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L147-L162
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.searchColumn
public static function searchColumn(array $array, $column, $search) { $array = array_values($array); // align array keys $columns = array_column($array, $column); $key = array_search($search, $columns); return ($key !== false) ? $array[$key] : false; }
php
public static function searchColumn(array $array, $column, $search) { $array = array_values($array); $columns = array_column($array, $column); $key = array_search($search, $columns); return ($key !== false) ? $array[$key] : false; }
[ "public", "static", "function", "searchColumn", "(", "array", "$", "array", ",", "$", "column", ",", "$", "search", ")", "{", "$", "array", "=", "array_values", "(", "$", "array", ")", ";", "// align array keys", "$", "columns", "=", "array_column", "(", "$", "array", ",", "$", "column", ")", ";", "$", "key", "=", "array_search", "(", "$", "search", ",", "$", "columns", ")", ";", "return", "(", "$", "key", "!==", "false", ")", "?", "$", "array", "[", "$", "key", "]", ":", "false", ";", "}" ]
Search for a Column Value inside a Multidimension array and return the array with the found key. Compare to searchColumns() this function return will return the first found result. ```php $array = [ ['name' => 'luya', 'userId' => 1], ['name' => 'nadar', 'userId' => 2], ]; $result = ArrayHelper::searchColumn($array, 'name', 'nadar'); // output: // array ('name' => 'nadar', 'userId' => 2); ``` > This will not work with assoc keys @param array $array The array with the multimensional array values. @param string $column The column to lookup and compare with the $search string. @param string $search The string to search inside the provided column. @return array|boolean
[ "Search", "for", "a", "Column", "Value", "inside", "a", "Multidimension", "array", "and", "return", "the", "array", "with", "the", "found", "key", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L188-L194
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.searchColumns
public static function searchColumns(array $array, $column, $search) { $keys = array_filter($array, function ($var) use ($column, $search) { return strcasecmp($search, $var[$column]) == 0 ? true : false; }); return $keys; }
php
public static function searchColumns(array $array, $column, $search) { $keys = array_filter($array, function ($var) use ($column, $search) { return strcasecmp($search, $var[$column]) == 0 ? true : false; }); return $keys; }
[ "public", "static", "function", "searchColumns", "(", "array", "$", "array", ",", "$", "column", ",", "$", "search", ")", "{", "$", "keys", "=", "array_filter", "(", "$", "array", ",", "function", "(", "$", "var", ")", "use", "(", "$", "column", ",", "$", "search", ")", "{", "return", "strcasecmp", "(", "$", "search", ",", "$", "var", "[", "$", "column", "]", ")", "==", "0", "?", "true", ":", "false", ";", "}", ")", ";", "return", "$", "keys", ";", "}" ]
Search for columns with the given search value, returns the full array with all valid items. Compare to searchColumn() this function return will return all found results. > This function is not casesensitive, which means FOO will match Foo, foo and FOO ```php $array = [ ['name' => 'luya', 'userId' => 1], ['name' => 'nadar', 'userId' => 1], ]; $result = ArrayHelper::searchColumns($array, 'userId', '1'); // output: // array ( // array ('name' => 'luya', 'userId' => 1), // array ('name' => 'nadar', 'userId' => 1) // ); ``` @param array $array The multidimensional array input @param string $column The column to compare with $search string @param mixed $search The search string to compare with the column value. @return array Returns an array with all valid elements.
[ "Search", "for", "columns", "with", "the", "given", "search", "value", "returns", "the", "full", "array", "with", "all", "valid", "items", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L223-L230
luyadev/luya
core/helpers/ArrayHelper.php
ArrayHelper.generateRange
public static function generateRange($from, $to, $text = null) { $range = range($from, $to); $array = array_combine($range, $range); if ($text) { array_walk($array, function (&$item, $key) use ($text) { if (is_array($text)) { list($singular, $plural) = $text; if ($key == 1) { $item = "{$key} {$singular}"; } else { $item = "{$key} {$plural}"; } } else { $item = "{$key} {$text}"; } }); } return $array; }
php
public static function generateRange($from, $to, $text = null) { $range = range($from, $to); $array = array_combine($range, $range); if ($text) { array_walk($array, function (&$item, $key) use ($text) { if (is_array($text)) { list($singular, $plural) = $text; if ($key == 1) { $item = "{$key} {$singular}"; } else { $item = "{$key} {$plural}"; } } else { $item = "{$key} {$text}"; } }); } return $array; }
[ "public", "static", "function", "generateRange", "(", "$", "from", ",", "$", "to", ",", "$", "text", "=", "null", ")", "{", "$", "range", "=", "range", "(", "$", "from", ",", "$", "to", ")", ";", "$", "array", "=", "array_combine", "(", "$", "range", ",", "$", "range", ")", ";", "if", "(", "$", "text", ")", "{", "array_walk", "(", "$", "array", ",", "function", "(", "&", "$", "item", ",", "$", "key", ")", "use", "(", "$", "text", ")", "{", "if", "(", "is_array", "(", "$", "text", ")", ")", "{", "list", "(", "$", "singular", ",", "$", "plural", ")", "=", "$", "text", ";", "if", "(", "$", "key", "==", "1", ")", "{", "$", "item", "=", "\"{$key} {$singular}\"", ";", "}", "else", "{", "$", "item", "=", "\"{$key} {$plural}\"", ";", "}", "}", "else", "{", "$", "item", "=", "\"{$key} {$text}\"", ";", "}", "}", ")", ";", "}", "return", "$", "array", ";", "}" ]
Generate an Array from a Rang with an appending optional Text. This is commonly used when generate dropDowns in forms to select a number of something. When $text is an array, the first key is the singular value to use, the second is the pluralized value. ```php $range = ArrayHelper::generateRange(1, 3, 'ticket'); // array (1 => "1 ticket", 2 => "2 ticket", 3 => "3 ticket") ``` Using the pluralized texts: ```php $range = ArrayHelper::generateRange(1, 3, ['ticket', 'tickets']); // array (1 => "1 ticket", 2 => "2 tickets", 3 => "3 tickets") ``` In php range() function is used to generate the array range. @param string|integer $from The range starts from @param string|integer $to The range ends @param string|array $text Optinal text to append to each element. If an array is given the first value is used for the singular value, the second will be used for the pluralized values. @return array An array where the key is the number and value the number with optional text.
[ "Generate", "an", "Array", "from", "a", "Rang", "with", "an", "appending", "optional", "Text", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ArrayHelper.php#L259-L280
luyadev/luya
core/helpers/FileHelper.php
FileHelper.humanReadableFilesize
public static function humanReadableFilesize($size) { $mod = 1024; $units = explode(' ', 'B KB MB GB TB PB'); for ($i = 0; $size > $mod; ++$i) { $size /= $mod; } return round($size, 2).' '.$units[$i]; }
php
public static function humanReadableFilesize($size) { $mod = 1024; $units = explode(' ', 'B KB MB GB TB PB'); for ($i = 0; $size > $mod; ++$i) { $size /= $mod; } return round($size, 2).' '.$units[$i]; }
[ "public", "static", "function", "humanReadableFilesize", "(", "$", "size", ")", "{", "$", "mod", "=", "1024", ";", "$", "units", "=", "explode", "(", "' '", ",", "'B KB MB GB TB PB'", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "size", ">", "$", "mod", ";", "++", "$", "i", ")", "{", "$", "size", "/=", "$", "mod", ";", "}", "return", "round", "(", "$", "size", ",", "2", ")", ".", "' '", ".", "$", "units", "[", "$", "i", "]", ";", "}" ]
Generate a human readable size informations from provided Byte/s size @param integer $size The size to convert in Byte @return string The readable size definition
[ "Generate", "a", "human", "readable", "size", "informations", "from", "provided", "Byte", "/", "s", "size" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L31-L40
luyadev/luya
core/helpers/FileHelper.php
FileHelper.ensureExtension
public static function ensureExtension($file, $extension) { $info = pathinfo($file); if (!isset($info['extension']) || empty($info['extension'])) { $file = rtrim($file, '.') . '.' . $extension; } return $file; }
php
public static function ensureExtension($file, $extension) { $info = pathinfo($file); if (!isset($info['extension']) || empty($info['extension'])) { $file = rtrim($file, '.') . '.' . $extension; } return $file; }
[ "public", "static", "function", "ensureExtension", "(", "$", "file", ",", "$", "extension", ")", "{", "$", "info", "=", "pathinfo", "(", "$", "file", ")", ";", "if", "(", "!", "isset", "(", "$", "info", "[", "'extension'", "]", ")", "||", "empty", "(", "$", "info", "[", "'extension'", "]", ")", ")", "{", "$", "file", "=", "rtrim", "(", "$", "file", ",", "'.'", ")", ".", "'.'", ".", "$", "extension", ";", "}", "return", "$", "file", ";", "}" ]
Append a file extension to a path/file if there is no or an empty extension provided, this helper methods is used to make sure the right extension existing on files. @param string $file The file where extension should be append if not existing @param string $extension @return string the ensured file/path with extension
[ "Append", "a", "file", "extension", "to", "a", "path", "/", "file", "if", "there", "is", "no", "or", "an", "empty", "extension", "provided", "this", "helper", "methods", "is", "used", "to", "make", "sure", "the", "right", "extension", "existing", "on", "files", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L50-L58
luyadev/luya
core/helpers/FileHelper.php
FileHelper.classInfo
public static function classInfo($file) { if (is_file($file)) { $phpCode = file_get_contents($file); } else { $phpCode = $file; } $namespace = false; if (preg_match('/^namespace\s+(.+?);(\s+|\r\n)?$/sm', $phpCode, $results)) { $namespace = $results[1]; } $classes = self::classNameByTokens($phpCode); return ['namespace' => $namespace, 'class' => end($classes)]; }
php
public static function classInfo($file) { if (is_file($file)) { $phpCode = file_get_contents($file); } else { $phpCode = $file; } $namespace = false; if (preg_match('/^namespace\s+(.+?);(\s+|\r\n)?$/sm', $phpCode, $results)) { $namespace = $results[1]; } $classes = self::classNameByTokens($phpCode); return ['namespace' => $namespace, 'class' => end($classes)]; }
[ "public", "static", "function", "classInfo", "(", "$", "file", ")", "{", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "$", "phpCode", "=", "file_get_contents", "(", "$", "file", ")", ";", "}", "else", "{", "$", "phpCode", "=", "$", "file", ";", "}", "$", "namespace", "=", "false", ";", "if", "(", "preg_match", "(", "'/^namespace\\s+(.+?);(\\s+|\\r\\n)?$/sm'", ",", "$", "phpCode", ",", "$", "results", ")", ")", "{", "$", "namespace", "=", "$", "results", "[", "1", "]", ";", "}", "$", "classes", "=", "self", "::", "classNameByTokens", "(", "$", "phpCode", ")", ";", "return", "[", "'namespace'", "=>", "$", "namespace", ",", "'class'", "=>", "end", "(", "$", "classes", ")", "]", ";", "}" ]
Provide class informations from a file path or file content. This is used when working with file paths from composer, in order to detect class and namespace from a given file. @param string $file The file path to the class into order to get infos from, could also be the content directly from a given file. @return array If the given filepath is a file, it will return an array with the keys: + namespace: the namespace of the file, if false no namespace could have been determined. + class: the class name of the file, if false no class could have been determined.
[ "Provide", "class", "informations", "from", "a", "file", "path", "or", "file", "content", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L72-L89
luyadev/luya
core/helpers/FileHelper.php
FileHelper.classNameByTokens
private static function classNameByTokens($phpCode) { $classes = []; $tokens = token_get_all($phpCode); $count = count($tokens); for ($i = 2; $i < $count; $i++) { if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) { $classes[] = $tokens[$i][1]; } } return $classes; }
php
private static function classNameByTokens($phpCode) { $classes = []; $tokens = token_get_all($phpCode); $count = count($tokens); for ($i = 2; $i < $count; $i++) { if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) { $classes[] = $tokens[$i][1]; } } return $classes; }
[ "private", "static", "function", "classNameByTokens", "(", "$", "phpCode", ")", "{", "$", "classes", "=", "[", "]", ";", "$", "tokens", "=", "token_get_all", "(", "$", "phpCode", ")", ";", "$", "count", "=", "count", "(", "$", "tokens", ")", ";", "for", "(", "$", "i", "=", "2", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "if", "(", "$", "tokens", "[", "$", "i", "-", "2", "]", "[", "0", "]", "==", "T_CLASS", "&&", "$", "tokens", "[", "$", "i", "-", "1", "]", "[", "0", "]", "==", "T_WHITESPACE", "&&", "$", "tokens", "[", "$", "i", "]", "[", "0", "]", "==", "T_STRING", ")", "{", "$", "classes", "[", "]", "=", "$", "tokens", "[", "$", "i", "]", "[", "1", "]", ";", "}", "}", "return", "$", "classes", ";", "}" ]
Tokenize the php code from a given class in in order to determine the class name. @param string $phpCode The php code to tokenize and find the clas name from @return array
[ "Tokenize", "the", "php", "code", "from", "a", "given", "class", "in", "in", "order", "to", "determine", "the", "class", "name", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L97-L109
luyadev/luya
core/helpers/FileHelper.php
FileHelper.getFileInfo
public static function getFileInfo($sourceFile) { $path = pathinfo($sourceFile); return (object) [ 'extension' => (isset($path['extension']) && !empty($path['extension'])) ? mb_strtolower($path['extension'], 'UTF-8') : false, 'name' => (isset($path['filename']) && !empty($path['filename'])) ? $path['filename'] : false, 'source' => $sourceFile, 'sourceFilename' => (isset($path['dirname']) && isset($path['filename'])) ? $path['dirname'] . DIRECTORY_SEPARATOR . $path['filename'] : false, ]; }
php
public static function getFileInfo($sourceFile) { $path = pathinfo($sourceFile); return (object) [ 'extension' => (isset($path['extension']) && !empty($path['extension'])) ? mb_strtolower($path['extension'], 'UTF-8') : false, 'name' => (isset($path['filename']) && !empty($path['filename'])) ? $path['filename'] : false, 'source' => $sourceFile, 'sourceFilename' => (isset($path['dirname']) && isset($path['filename'])) ? $path['dirname'] . DIRECTORY_SEPARATOR . $path['filename'] : false, ]; }
[ "public", "static", "function", "getFileInfo", "(", "$", "sourceFile", ")", "{", "$", "path", "=", "pathinfo", "(", "$", "sourceFile", ")", ";", "return", "(", "object", ")", "[", "'extension'", "=>", "(", "isset", "(", "$", "path", "[", "'extension'", "]", ")", "&&", "!", "empty", "(", "$", "path", "[", "'extension'", "]", ")", ")", "?", "mb_strtolower", "(", "$", "path", "[", "'extension'", "]", ",", "'UTF-8'", ")", ":", "false", ",", "'name'", "=>", "(", "isset", "(", "$", "path", "[", "'filename'", "]", ")", "&&", "!", "empty", "(", "$", "path", "[", "'filename'", "]", ")", ")", "?", "$", "path", "[", "'filename'", "]", ":", "false", ",", "'source'", "=>", "$", "sourceFile", ",", "'sourceFilename'", "=>", "(", "isset", "(", "$", "path", "[", "'dirname'", "]", ")", "&&", "isset", "(", "$", "path", "[", "'filename'", "]", ")", ")", "?", "$", "path", "[", "'dirname'", "]", ".", "DIRECTORY_SEPARATOR", ".", "$", "path", "[", "'filename'", "]", ":", "false", ",", "]", ";", "}" ]
Get extension and name from a file for the provided source/path of the file. @param string $sourceFile The path of the file @return object With extension and name keys.
[ "Get", "extension", "and", "name", "from", "a", "file", "for", "the", "provided", "source", "/", "path", "of", "the", "file", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L132-L142
luyadev/luya
core/helpers/FileHelper.php
FileHelper.writeFile
public static function writeFile($fileName, $content) { try { $response = file_put_contents(Yii::getAlias($fileName), $content); if ($response === false) { return false; } } catch (Exception $error) { return false; } return true; }
php
public static function writeFile($fileName, $content) { try { $response = file_put_contents(Yii::getAlias($fileName), $content); if ($response === false) { return false; } } catch (Exception $error) { return false; } return true; }
[ "public", "static", "function", "writeFile", "(", "$", "fileName", ",", "$", "content", ")", "{", "try", "{", "$", "response", "=", "file_put_contents", "(", "Yii", "::", "getAlias", "(", "$", "fileName", ")", ",", "$", "content", ")", ";", "if", "(", "$", "response", "===", "false", ")", "{", "return", "false", ";", "}", "}", "catch", "(", "Exception", "$", "error", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Basic helper method to write files with exception capture. The fileName will auto wrapped trough the Yii::getAlias function. @param string $fileName The path to the file with file name @param string $content The content to store in this File @return boolean
[ "Basic", "helper", "method", "to", "write", "files", "with", "exception", "capture", ".", "The", "fileName", "will", "auto", "wrapped", "trough", "the", "Yii", "::", "getAlias", "function", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L163-L175
luyadev/luya
core/helpers/FileHelper.php
FileHelper.unlink
public static function unlink($file) { // no errors should be thrown, return false instead. try { if (parent::unlink($file)) { return true; } } catch (\Exception $e) {} // try to force symlinks if (is_link($file)) { $sym = @readlink($file); if ($sym) { if (@unlink($file)) { return true; } } } // try to use realpath if (realpath($file) && realpath($file) !== $file) { if (@unlink(realpath($file))) { return true; } } return false; }
php
public static function unlink($file) { try { if (parent::unlink($file)) { return true; } } catch (\Exception $e) {} if (is_link($file)) { $sym = @readlink($file); if ($sym) { if (@unlink($file)) { return true; } } } if (realpath($file) && realpath($file) !== $file) { if (@unlink(realpath($file))) { return true; } } return false; }
[ "public", "static", "function", "unlink", "(", "$", "file", ")", "{", "// no errors should be thrown, return false instead.", "try", "{", "if", "(", "parent", "::", "unlink", "(", "$", "file", ")", ")", "{", "return", "true", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "// try to force symlinks", "if", "(", "is_link", "(", "$", "file", ")", ")", "{", "$", "sym", "=", "@", "readlink", "(", "$", "file", ")", ";", "if", "(", "$", "sym", ")", "{", "if", "(", "@", "unlink", "(", "$", "file", ")", ")", "{", "return", "true", ";", "}", "}", "}", "// try to use realpath", "if", "(", "realpath", "(", "$", "file", ")", "&&", "realpath", "(", "$", "file", ")", "!==", "$", "file", ")", "{", "if", "(", "@", "unlink", "(", "realpath", "(", "$", "file", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Unlink a file, which handles symlinks. @param string $file The file path to the file to delete. @return boolean Whether the file has been removed or not.
[ "Unlink", "a", "file", "which", "handles", "symlinks", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/FileHelper.php#L199-L226
luyadev/luya
core/web/UrlManager.php
UrlManager.routeHasLanguageCompositionPrefix
public function routeHasLanguageCompositionPrefix($route, $language) { $parts = explode("/", $route); if (isset($parts[0]) && $parts[0] == $language) { return true; } return false; }
php
public function routeHasLanguageCompositionPrefix($route, $language) { $parts = explode("/", $route); if (isset($parts[0]) && $parts[0] == $language) { return true; } return false; }
[ "public", "function", "routeHasLanguageCompositionPrefix", "(", "$", "route", ",", "$", "language", ")", "{", "$", "parts", "=", "explode", "(", "\"/\"", ",", "$", "route", ")", ";", "if", "(", "isset", "(", "$", "parts", "[", "0", "]", ")", "&&", "$", "parts", "[", "0", "]", "==", "$", "language", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Ensure whether a route starts with a language short key or not. @param string $route The route to check `en/module/controller/action` or without `module/controller/action` @param string $language The language to check whether it exists or not `en`. @return boolean
[ "Ensure", "whether", "a", "route", "starts", "with", "a", "language", "short", "key", "or", "not", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L56-L64
luyadev/luya
core/web/UrlManager.php
UrlManager.parseRequest
public function parseRequest($request) { // extra data from request to composition, which changes the pathInfo of the Request-Object. $resolver = $this->getComposition()->getResolvedPathInfo($request); try { $request->setPathInfo($resolver->resolvedPath); } catch (NotFoundHttpException $error) { // the resolver has thrown an 404 excpetion, stop parsing request and return false (which is: page not found) return false; } $parsedRequest = parent::parseRequest($request); // ensure if the parsed route first match equals the composition pattern. // This can be the case when composition is hidden, but not default language is loaded and a // url composition route is loaded! // @see https://github.com/luyadev/luya/issues/1146 $res = $this->routeHasLanguageCompositionPrefix($parsedRequest[0], $resolver->getResolvedKeyValue('langShortCode')); // set the application language based from the parsed composition request: Yii::$app->setLocale($this->composition->langShortCode); // if enableStrictParsing is enabled and the route is not found, $parsedRequest will return `false`. if ($res === false && ($this->composition->hidden || $parsedRequest === false)) { return $parsedRequest; } $composition = $this->composition->createRoute(); $length = strlen($composition); $route = $parsedRequest[0]; if (substr($route, 0, $length+1) == $composition.'/') { $parsedRequest[0] = substr($parsedRequest[0], $length); } // remove start trailing slashes from route. $parsedRequest[0] = ltrim($parsedRequest[0], '/'); return $parsedRequest; }
php
public function parseRequest($request) { $resolver = $this->getComposition()->getResolvedPathInfo($request); try { $request->setPathInfo($resolver->resolvedPath); } catch (NotFoundHttpException $error) { return false; } $parsedRequest = parent::parseRequest($request); $res = $this->routeHasLanguageCompositionPrefix($parsedRequest[0], $resolver->getResolvedKeyValue('langShortCode')); Yii::$app->setLocale($this->composition->langShortCode); if ($res === false && ($this->composition->hidden || $parsedRequest === false)) { return $parsedRequest; } $composition = $this->composition->createRoute(); $length = strlen($composition); $route = $parsedRequest[0]; if (substr($route, 0, $length+1) == $composition.'/') { $parsedRequest[0] = substr($parsedRequest[0], $length); } $parsedRequest[0] = ltrim($parsedRequest[0], '/'); return $parsedRequest; }
[ "public", "function", "parseRequest", "(", "$", "request", ")", "{", "// extra data from request to composition, which changes the pathInfo of the Request-Object.", "$", "resolver", "=", "$", "this", "->", "getComposition", "(", ")", "->", "getResolvedPathInfo", "(", "$", "request", ")", ";", "try", "{", "$", "request", "->", "setPathInfo", "(", "$", "resolver", "->", "resolvedPath", ")", ";", "}", "catch", "(", "NotFoundHttpException", "$", "error", ")", "{", "// the resolver has thrown an 404 excpetion, stop parsing request and return false (which is: page not found)", "return", "false", ";", "}", "$", "parsedRequest", "=", "parent", "::", "parseRequest", "(", "$", "request", ")", ";", "// ensure if the parsed route first match equals the composition pattern.", "// This can be the case when composition is hidden, but not default language is loaded and a", "// url composition route is loaded!", "// @see https://github.com/luyadev/luya/issues/1146", "$", "res", "=", "$", "this", "->", "routeHasLanguageCompositionPrefix", "(", "$", "parsedRequest", "[", "0", "]", ",", "$", "resolver", "->", "getResolvedKeyValue", "(", "'langShortCode'", ")", ")", ";", "// set the application language based from the parsed composition request:", "Yii", "::", "$", "app", "->", "setLocale", "(", "$", "this", "->", "composition", "->", "langShortCode", ")", ";", "// if enableStrictParsing is enabled and the route is not found, $parsedRequest will return `false`.", "if", "(", "$", "res", "===", "false", "&&", "(", "$", "this", "->", "composition", "->", "hidden", "||", "$", "parsedRequest", "===", "false", ")", ")", "{", "return", "$", "parsedRequest", ";", "}", "$", "composition", "=", "$", "this", "->", "composition", "->", "createRoute", "(", ")", ";", "$", "length", "=", "strlen", "(", "$", "composition", ")", ";", "$", "route", "=", "$", "parsedRequest", "[", "0", "]", ";", "if", "(", "substr", "(", "$", "route", ",", "0", ",", "$", "length", "+", "1", ")", "==", "$", "composition", ".", "'/'", ")", "{", "$", "parsedRequest", "[", "0", "]", "=", "substr", "(", "$", "parsedRequest", "[", "0", "]", ",", "$", "length", ")", ";", "}", "// remove start trailing slashes from route.", "$", "parsedRequest", "[", "0", "]", "=", "ltrim", "(", "$", "parsedRequest", "[", "0", "]", ",", "'/'", ")", ";", "return", "$", "parsedRequest", ";", "}" ]
Extend functionality of parent::parseRequest() by verify and resolve the composition informations. @inheritDoc @see \yii\web\UrlManager::parseRequest() @param \luya\web\Request $request The request component.
[ "Extend", "functionality", "of", "parent", "::", "parseRequest", "()", "by", "verify", "and", "resolve", "the", "composition", "informations", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L74-L114
luyadev/luya
core/web/UrlManager.php
UrlManager.addRules
public function addRules($rules, $append = true) { foreach ($rules as $key => $rule) { if (is_array($rule) && isset($rule['composition'])) { foreach ($rule['composition'] as $composition => $pattern) { $rules[] = [ 'pattern' => $pattern, 'route' => $composition.'/'.$rule['route'], ]; } } } return parent::addRules($rules, $append); }
php
public function addRules($rules, $append = true) { foreach ($rules as $key => $rule) { if (is_array($rule) && isset($rule['composition'])) { foreach ($rule['composition'] as $composition => $pattern) { $rules[] = [ 'pattern' => $pattern, 'route' => $composition.'/'.$rule['route'], ]; } } } return parent::addRules($rules, $append); }
[ "public", "function", "addRules", "(", "$", "rules", ",", "$", "append", "=", "true", ")", "{", "foreach", "(", "$", "rules", "as", "$", "key", "=>", "$", "rule", ")", "{", "if", "(", "is_array", "(", "$", "rule", ")", "&&", "isset", "(", "$", "rule", "[", "'composition'", "]", ")", ")", "{", "foreach", "(", "$", "rule", "[", "'composition'", "]", "as", "$", "composition", "=>", "$", "pattern", ")", "{", "$", "rules", "[", "]", "=", "[", "'pattern'", "=>", "$", "pattern", ",", "'route'", "=>", "$", "composition", ".", "'/'", ".", "$", "rule", "[", "'route'", "]", ",", "]", ";", "}", "}", "}", "return", "parent", "::", "addRules", "(", "$", "rules", ",", "$", "append", ")", ";", "}" ]
Extend functionality of parent::addRules by the ability to add composition routes. @see \yii\web\UrlManager::addRules() @param array $rules An array wil rules @param boolean $append Append to the end of the rules or not.
[ "Extend", "functionality", "of", "parent", "::", "addRules", "by", "the", "ability", "to", "add", "composition", "routes", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L123-L137
luyadev/luya
core/web/UrlManager.php
UrlManager.getMenu
public function getMenu() { if ($this->_menu === null) { $menu = Yii::$app->get('menu', false); if ($menu) { $this->_menu = $menu; } else { $this->_menu = false; } } return $this->_menu; }
php
public function getMenu() { if ($this->_menu === null) { $menu = Yii::$app->get('menu', false); if ($menu) { $this->_menu = $menu; } else { $this->_menu = false; } } return $this->_menu; }
[ "public", "function", "getMenu", "(", ")", "{", "if", "(", "$", "this", "->", "_menu", "===", "null", ")", "{", "$", "menu", "=", "Yii", "::", "$", "app", "->", "get", "(", "'menu'", ",", "false", ")", ";", "if", "(", "$", "menu", ")", "{", "$", "this", "->", "_menu", "=", "$", "menu", ";", "}", "else", "{", "$", "this", "->", "_menu", "=", "false", ";", "}", "}", "return", "$", "this", "->", "_menu", ";", "}" ]
Get the menu component if its registered in the current applications. The menu component is only registered when the cms module is registered. @return boolean|\luya\cms\Menu The menu component object or false if not available.
[ "Get", "the", "menu", "component", "if", "its", "registered", "in", "the", "current", "applications", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L146-L158
luyadev/luya
core/web/UrlManager.php
UrlManager.getComposition
public function getComposition() { if ($this->_composition === null) { $this->_composition = Yii::$app->get('composition'); } return $this->_composition; }
php
public function getComposition() { if ($this->_composition === null) { $this->_composition = Yii::$app->get('composition'); } return $this->_composition; }
[ "public", "function", "getComposition", "(", ")", "{", "if", "(", "$", "this", "->", "_composition", "===", "null", ")", "{", "$", "this", "->", "_composition", "=", "Yii", "::", "$", "app", "->", "get", "(", "'composition'", ")", ";", "}", "return", "$", "this", "->", "_composition", ";", "}" ]
Get the composition component @return \luya\web\Composition Get the composition component to resolve multi lingual handling.
[ "Get", "the", "composition", "component" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L175-L182
luyadev/luya
core/web/UrlManager.php
UrlManager.createUrl
public function createUrl($params) { $response = $this->internalCreateUrl($params); if ($this->contextNavItemId) { return $this->urlReplaceModule($response, $this->contextNavItemId, $this->getComposition()); } return $response; }
php
public function createUrl($params) { $response = $this->internalCreateUrl($params); if ($this->contextNavItemId) { return $this->urlReplaceModule($response, $this->contextNavItemId, $this->getComposition()); } return $response; }
[ "public", "function", "createUrl", "(", "$", "params", ")", "{", "$", "response", "=", "$", "this", "->", "internalCreateUrl", "(", "$", "params", ")", ";", "if", "(", "$", "this", "->", "contextNavItemId", ")", "{", "return", "$", "this", "->", "urlReplaceModule", "(", "$", "response", ",", "$", "this", "->", "contextNavItemId", ",", "$", "this", "->", "getComposition", "(", ")", ")", ";", "}", "return", "$", "response", ";", "}" ]
Extend createUrl method by verify its context implementation to add cms urls prepand to the requested createurl params. From the original create url function of Yii: You may specify the route as a string, e.g., `site/index`. You may also use an array if you want to specify additional query parameters for the URL being created. The array format must be: ```php // generates: /index.php?r=site%2Findex&param1=value1&param2=value2 ['site/index', 'param1' => 'value1', 'param2' => 'value2'] ``` If you want to create a URL with an anchor, you can use the array format with a `#` parameter. For example, ```php // generates: /index.php?r=site%2Findex&param1=value1#name ['site/index', 'param1' => 'value1', '#' => 'name'] ``` The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL. Note that unlike {{luya\helpers\Url::toRoute()}}, this method always treats the given route as an absolute route. @see \yii\web\UrlManager::createUrl() @param string|array $params use a string to represent a route (e.g. `site/index`), or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`). @return string the created URL.
[ "Extend", "createUrl", "method", "by", "verify", "its", "context", "implementation", "to", "add", "cms", "urls", "prepand", "to", "the", "requested", "createurl", "params", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L238-L247
luyadev/luya
core/web/UrlManager.php
UrlManager.createMenuItemUrl
public function createMenuItemUrl($params, $navItemId, $composition = null) { $composition = empty($composition) ? $this->getComposition() : $composition; $url = $this->internalCreateUrl($params, $composition); if (!$this->menu) { return $url; } return $this->urlReplaceModule($url, $navItemId, $composition); }
php
public function createMenuItemUrl($params, $navItemId, $composition = null) { $composition = empty($composition) ? $this->getComposition() : $composition; $url = $this->internalCreateUrl($params, $composition); if (!$this->menu) { return $url; } return $this->urlReplaceModule($url, $navItemId, $composition); }
[ "public", "function", "createMenuItemUrl", "(", "$", "params", ",", "$", "navItemId", ",", "$", "composition", "=", "null", ")", "{", "$", "composition", "=", "empty", "(", "$", "composition", ")", "?", "$", "this", "->", "getComposition", "(", ")", ":", "$", "composition", ";", "$", "url", "=", "$", "this", "->", "internalCreateUrl", "(", "$", "params", ",", "$", "composition", ")", ";", "if", "(", "!", "$", "this", "->", "menu", ")", "{", "return", "$", "url", ";", "}", "return", "$", "this", "->", "urlReplaceModule", "(", "$", "url", ",", "$", "navItemId", ",", "$", "composition", ")", ";", "}" ]
Create an url for a menu item. @param string|array $params Use a string to represent a route (e.g. `site/index`), or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`). @param integer $navItemId The nav item Id @param null|\luya\web\Composition $composition Optional other composition config instead of using the default composition @return string
[ "Create", "an", "url", "for", "a", "menu", "item", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L257-L267
luyadev/luya
core/web/UrlManager.php
UrlManager.internalCreateUrl
public function internalCreateUrl($params, $composition = null) { $params = (array) $params; $composition = empty($composition) ? $this->getComposition() : $composition; $originalParams = $params; // prepand the original route, whether is hidden or not! // https://github.com/luyadev/luya/issues/1146 $params[0] = $composition->prependTo($params[0], $composition->createRoute()); $response = parent::createUrl($params); // Check if the parsed route with the prepand composition has been found or not. if (strpos($response, rtrim($params[0], '/')) !== false) { // we got back the same url from the createUrl, no match against composition route. $response = parent::createUrl($originalParams); } $response = $this->removeBaseUrl($response); $response = $composition->prependTo($response); return $this->prependBaseUrl($response); }
php
public function internalCreateUrl($params, $composition = null) { $params = (array) $params; $composition = empty($composition) ? $this->getComposition() : $composition; $originalParams = $params; $params[0] = $composition->prependTo($params[0], $composition->createRoute()); $response = parent::createUrl($params); if (strpos($response, rtrim($params[0], '/')) !== false) { $response = parent::createUrl($originalParams); } $response = $this->removeBaseUrl($response); $response = $composition->prependTo($response); return $this->prependBaseUrl($response); }
[ "public", "function", "internalCreateUrl", "(", "$", "params", ",", "$", "composition", "=", "null", ")", "{", "$", "params", "=", "(", "array", ")", "$", "params", ";", "$", "composition", "=", "empty", "(", "$", "composition", ")", "?", "$", "this", "->", "getComposition", "(", ")", ":", "$", "composition", ";", "$", "originalParams", "=", "$", "params", ";", "// prepand the original route, whether is hidden or not!", "// https://github.com/luyadev/luya/issues/1146", "$", "params", "[", "0", "]", "=", "$", "composition", "->", "prependTo", "(", "$", "params", "[", "0", "]", ",", "$", "composition", "->", "createRoute", "(", ")", ")", ";", "$", "response", "=", "parent", "::", "createUrl", "(", "$", "params", ")", ";", "// Check if the parsed route with the prepand composition has been found or not.", "if", "(", "strpos", "(", "$", "response", ",", "rtrim", "(", "$", "params", "[", "0", "]", ",", "'/'", ")", ")", "!==", "false", ")", "{", "// we got back the same url from the createUrl, no match against composition route.", "$", "response", "=", "parent", "::", "createUrl", "(", "$", "originalParams", ")", ";", "}", "$", "response", "=", "$", "this", "->", "removeBaseUrl", "(", "$", "response", ")", ";", "$", "response", "=", "$", "composition", "->", "prependTo", "(", "$", "response", ")", ";", "return", "$", "this", "->", "prependBaseUrl", "(", "$", "response", ")", ";", "}" ]
Yii2 createUrl base implementation extends the prepand of the comosition @param string|array $params An array with params or not (e.g. `['module/controller/action', 'param1' => 'value1']`) @param null|\luya\web\Composition $composition Composition instance to change the route behavior @return string
[ "Yii2", "createUrl", "base", "implementation", "extends", "the", "prepand", "of", "the", "comosition" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L276-L300
luyadev/luya
core/web/UrlManager.php
UrlManager.internalCreateAbsoluteUrl
public function internalCreateAbsoluteUrl($params, $scheme = null) { $params = (array) $params; $url = $this->internalCreateUrl($params); if (strpos($url, '://') === false) { $url = $this->getHostInfo() . $url; } if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) { $url = $scheme . substr($url, $pos); } return $url; }
php
public function internalCreateAbsoluteUrl($params, $scheme = null) { $params = (array) $params; $url = $this->internalCreateUrl($params); if (strpos($url, ': $url = $this->getHostInfo() . $url; } if (is_string($scheme) && ($pos = strpos($url, ': $url = $scheme . substr($url, $pos); } return $url; }
[ "public", "function", "internalCreateAbsoluteUrl", "(", "$", "params", ",", "$", "scheme", "=", "null", ")", "{", "$", "params", "=", "(", "array", ")", "$", "params", ";", "$", "url", "=", "$", "this", "->", "internalCreateUrl", "(", "$", "params", ")", ";", "if", "(", "strpos", "(", "$", "url", ",", "'://'", ")", "===", "false", ")", "{", "$", "url", "=", "$", "this", "->", "getHostInfo", "(", ")", ".", "$", "url", ";", "}", "if", "(", "is_string", "(", "$", "scheme", ")", "&&", "(", "$", "pos", "=", "strpos", "(", "$", "url", ",", "'://'", ")", ")", "!==", "false", ")", "{", "$", "url", "=", "$", "scheme", ".", "substr", "(", "$", "url", ",", "$", "pos", ")", ";", "}", "return", "$", "url", ";", "}" ]
Create absolute url from the given route params. @param string|array $params The see createUrl @param boolean $scheme Whether to use absolute scheme path or not. @return string The created url
[ "Create", "absolute", "url", "from", "the", "given", "route", "params", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L309-L320
luyadev/luya
core/web/UrlManager.php
UrlManager.findModuleInRoute
private function findModuleInRoute($route) { $route = parse_url($route, PHP_URL_PATH); $parts = array_values(array_filter(explode('/', $route))); if (isset($parts[0]) && array_key_exists($parts[0], Yii::$app->getApplicationModules())) { return $parts[0]; } return false; }
php
private function findModuleInRoute($route) { $route = parse_url($route, PHP_URL_PATH); $parts = array_values(array_filter(explode('/', $route))); if (isset($parts[0]) && array_key_exists($parts[0], Yii::$app->getApplicationModules())) { return $parts[0]; } return false; }
[ "private", "function", "findModuleInRoute", "(", "$", "route", ")", "{", "$", "route", "=", "parse_url", "(", "$", "route", ",", "PHP_URL_PATH", ")", ";", "$", "parts", "=", "array_values", "(", "array_filter", "(", "explode", "(", "'/'", ",", "$", "route", ")", ")", ")", ";", "if", "(", "isset", "(", "$", "parts", "[", "0", "]", ")", "&&", "array_key_exists", "(", "$", "parts", "[", "0", "]", ",", "Yii", "::", "$", "app", "->", "getApplicationModules", "(", ")", ")", ")", "{", "return", "$", "parts", "[", "0", "]", ";", "}", "return", "false", ";", "}" ]
See if the module of a provided route exists in the luya application list. The module to test must be an instance of `luya\base\Module`. @param string $route @return boolean|string
[ "See", "if", "the", "module", "of", "a", "provided", "route", "exists", "in", "the", "luya", "application", "list", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L330-L341
luyadev/luya
core/web/UrlManager.php
UrlManager.urlReplaceModule
private function urlReplaceModule($url, $navItemId, Composition $composition) { $route = $composition->removeFrom($this->removeBaseUrl($url)); $moduleName = $this->findModuleInRoute($route); if ($moduleName === false || $this->menu === false) { return $url; } $item = $this->menu->find()->where(['id' => $navItemId])->with('hidden')->lang($composition['langShortCode'])->one(); if (!$item) { throw new BadRequestHttpException("Unable to find nav_item_id '$navItemId' to generate the module link for url '$url'."); } $isOutgoingModulePage = $item->type == 2 && $moduleName !== $item->moduleName; // 1. if the current page is a module and the requested url is not the same module, its an outgoing link to // another module which should not be modificated. // 2. If the current page (nav) context is the homepage, we have to keep the original link as it wont work because the homepage // does not have a route prefix. if ($isOutgoingModulePage || $item->isHome) { return $url; } // 1. if the current page is a module and the requested url is not the same module, its an outgoing link to // another module and ... // 2. if current controller context has an other module as the requested url, its an outgoing link to another module which should not be modificated. if ($isOutgoingModulePage && $moduleName !== Yii::$app->controller->module->id) { return $url; } return preg_replace("/$moduleName/", rtrim($item->link, '/'), ltrim($route, '/'), 1); }
php
private function urlReplaceModule($url, $navItemId, Composition $composition) { $route = $composition->removeFrom($this->removeBaseUrl($url)); $moduleName = $this->findModuleInRoute($route); if ($moduleName === false || $this->menu === false) { return $url; } $item = $this->menu->find()->where(['id' => $navItemId])->with('hidden')->lang($composition['langShortCode'])->one(); if (!$item) { throw new BadRequestHttpException("Unable to find nav_item_id '$navItemId' to generate the module link for url '$url'."); } $isOutgoingModulePage = $item->type == 2 && $moduleName !== $item->moduleName; if ($isOutgoingModulePage || $item->isHome) { return $url; } if ($isOutgoingModulePage && $moduleName !== Yii::$app->controller->module->id) { return $url; } return preg_replace("/$moduleName/", rtrim($item->link, '/'), ltrim($route, '/'), 1); }
[ "private", "function", "urlReplaceModule", "(", "$", "url", ",", "$", "navItemId", ",", "Composition", "$", "composition", ")", "{", "$", "route", "=", "$", "composition", "->", "removeFrom", "(", "$", "this", "->", "removeBaseUrl", "(", "$", "url", ")", ")", ";", "$", "moduleName", "=", "$", "this", "->", "findModuleInRoute", "(", "$", "route", ")", ";", "if", "(", "$", "moduleName", "===", "false", "||", "$", "this", "->", "menu", "===", "false", ")", "{", "return", "$", "url", ";", "}", "$", "item", "=", "$", "this", "->", "menu", "->", "find", "(", ")", "->", "where", "(", "[", "'id'", "=>", "$", "navItemId", "]", ")", "->", "with", "(", "'hidden'", ")", "->", "lang", "(", "$", "composition", "[", "'langShortCode'", "]", ")", "->", "one", "(", ")", ";", "if", "(", "!", "$", "item", ")", "{", "throw", "new", "BadRequestHttpException", "(", "\"Unable to find nav_item_id '$navItemId' to generate the module link for url '$url'.\"", ")", ";", "}", "$", "isOutgoingModulePage", "=", "$", "item", "->", "type", "==", "2", "&&", "$", "moduleName", "!==", "$", "item", "->", "moduleName", ";", "// 1. if the current page is a module and the requested url is not the same module, its an outgoing link to", "// another module which should not be modificated.", "// 2. If the current page (nav) context is the homepage, we have to keep the original link as it wont work because the homepage", "// does not have a route prefix.", "if", "(", "$", "isOutgoingModulePage", "||", "$", "item", "->", "isHome", ")", "{", "return", "$", "url", ";", "}", "// 1. if the current page is a module and the requested url is not the same module, its an outgoing link to", "// another module and ...", "// 2. if current controller context has an other module as the requested url, its an outgoing link to another module which should not be modificated.", "if", "(", "$", "isOutgoingModulePage", "&&", "$", "moduleName", "!==", "Yii", "::", "$", "app", "->", "controller", "->", "module", "->", "id", ")", "{", "return", "$", "url", ";", "}", "return", "preg_replace", "(", "\"/$moduleName/\"", ",", "rtrim", "(", "$", "item", "->", "link", ",", "'/'", ")", ",", "ltrim", "(", "$", "route", ",", "'/'", ")", ",", "1", ")", ";", "}" ]
Replace the url with the current module context. @param string $url The url to replace @param integer $navItemId The navigation item where the context url to be found. @param \luya\web\Composition $composition Composition component object to resolve language context. @throws \yii\web\BadRequestHttpException @return string The replaced string.
[ "Replace", "the", "url", "with", "the", "current", "module", "context", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/UrlManager.php#L352-L385
luyadev/luya
core/web/jsonld/ContactPoint.php
ContactPoint.setAreaServed
public function setAreaServed($areaServed) { ObjectHelper::isInstanceOf($areaServed, [Place::class, TextValue::class]); $this->_areaServed = $areaServed; return $this; }
php
public function setAreaServed($areaServed) { ObjectHelper::isInstanceOf($areaServed, [Place::class, TextValue::class]); $this->_areaServed = $areaServed; return $this; }
[ "public", "function", "setAreaServed", "(", "$", "areaServed", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "areaServed", ",", "[", "Place", "::", "class", ",", "TextValue", "::", "class", "]", ")", ";", "$", "this", "->", "_areaServed", "=", "$", "areaServed", ";", "return", "$", "this", ";", "}" ]
Set Area Served. The geographic area where a service or offered item is provided. Supersedes serviceArea. @param Place|TextValue $areaServed @return static
[ "Set", "Area", "Served", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/ContactPoint.php#L82-L88
luyadev/luya
core/web/GroupUser.php
GroupUser.inGroup
public function inGroup($alias) { if ($this->isGuest) { return false; } $identity = $this->identity; if (!$identity instanceof GroupUserIdentityInterface) { throw new InvalidConfigException('The $identityClass must be instance of luya\web\GroupUserIdentityInterface.'); } $groups = (array) $alias; foreach ($groups as $groupAlias) { if (in_array($groupAlias, $identity->authGroups())) { return true; } } return false; }
php
public function inGroup($alias) { if ($this->isGuest) { return false; } $identity = $this->identity; if (!$identity instanceof GroupUserIdentityInterface) { throw new InvalidConfigException('The $identityClass must be instance of luya\web\GroupUserIdentityInterface.'); } $groups = (array) $alias; foreach ($groups as $groupAlias) { if (in_array($groupAlias, $identity->authGroups())) { return true; } } return false; }
[ "public", "function", "inGroup", "(", "$", "alias", ")", "{", "if", "(", "$", "this", "->", "isGuest", ")", "{", "return", "false", ";", "}", "$", "identity", "=", "$", "this", "->", "identity", ";", "if", "(", "!", "$", "identity", "instanceof", "GroupUserIdentityInterface", ")", "{", "throw", "new", "InvalidConfigException", "(", "'The $identityClass must be instance of luya\\web\\GroupUserIdentityInterface.'", ")", ";", "}", "$", "groups", "=", "(", "array", ")", "$", "alias", ";", "foreach", "(", "$", "groups", "as", "$", "groupAlias", ")", "{", "if", "(", "in_array", "(", "$", "groupAlias", ",", "$", "identity", "->", "authGroups", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether a user exists for the provided group based on the GroupUserIdentityInterface implementation @param string|array $alias @return bool @throws InvalidConfigException
[ "Checks", "whether", "a", "user", "exists", "for", "the", "provided", "group", "based", "on", "the", "GroupUserIdentityInterface", "implementation" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/GroupUser.php#L114-L135
luyadev/luya
core/helpers/ObjectHelper.php
ObjectHelper.isInstanceOf
public static function isInstanceOf($object, $haystack, $throwException = true) { // if instances is an object (compare object directly) we have to get the class name to compare with instanceof later if (is_object($haystack)) { $haystack = get_class($haystack); } $haystack = (array) $haystack; foreach ($haystack as $class) { if ($object instanceof $class) { return true; } } if ($throwException) { throw new Exception("The given object must be an instance of: " . implode(",", $haystack)); } return false; }
php
public static function isInstanceOf($object, $haystack, $throwException = true) { if (is_object($haystack)) { $haystack = get_class($haystack); } $haystack = (array) $haystack; foreach ($haystack as $class) { if ($object instanceof $class) { return true; } } if ($throwException) { throw new Exception("The given object must be an instance of: " . implode(",", $haystack)); } return false; }
[ "public", "static", "function", "isInstanceOf", "(", "$", "object", ",", "$", "haystack", ",", "$", "throwException", "=", "true", ")", "{", "// if instances is an object (compare object directly) we have to get the class name to compare with instanceof later", "if", "(", "is_object", "(", "$", "haystack", ")", ")", "{", "$", "haystack", "=", "get_class", "(", "$", "haystack", ")", ";", "}", "$", "haystack", "=", "(", "array", ")", "$", "haystack", ";", "foreach", "(", "$", "haystack", "as", "$", "class", ")", "{", "if", "(", "$", "object", "instanceof", "$", "class", ")", "{", "return", "true", ";", "}", "}", "if", "(", "$", "throwException", ")", "{", "throw", "new", "Exception", "(", "\"The given object must be an instance of: \"", ".", "implode", "(", "\",\"", ",", "$", "haystack", ")", ")", ";", "}", "return", "false", ";", "}" ]
Checks a given variable if its an instance of an element in the $instances list. ```php $object = new \Exception(); ObjectHelper::isInstanceOf($object, '\Exception'); ``` @param object $object The object to type check against haystack. @param string|array|object $haystack A list of classes, a string for a given class, or an object. @param boolean $throwException Whether an exception should be thrown or not. @throws \luya\Exception @return boolean @since 1.0.3
[ "Checks", "a", "given", "variable", "if", "its", "an", "instance", "of", "an", "element", "in", "the", "$instances", "list", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ObjectHelper.php#L32-L52
luyadev/luya
core/helpers/ObjectHelper.php
ObjectHelper.isTraitInstanceOf
public static function isTraitInstanceOf($object, $haystack) { $traits = static::traitsList($object); // if its an object, the all traits for the given object. if (is_object($haystack)) { $haystack = static::traitsList($haystack); } foreach ((array) $haystack as $stack) { if (in_array($stack, $traits)) { return true; } } return false; }
php
public static function isTraitInstanceOf($object, $haystack) { $traits = static::traitsList($object); if (is_object($haystack)) { $haystack = static::traitsList($haystack); } foreach ((array) $haystack as $stack) { if (in_array($stack, $traits)) { return true; } } return false; }
[ "public", "static", "function", "isTraitInstanceOf", "(", "$", "object", ",", "$", "haystack", ")", "{", "$", "traits", "=", "static", "::", "traitsList", "(", "$", "object", ")", ";", "// if its an object, the all traits for the given object.", "if", "(", "is_object", "(", "$", "haystack", ")", ")", "{", "$", "haystack", "=", "static", "::", "traitsList", "(", "$", "haystack", ")", ";", "}", "foreach", "(", "(", "array", ")", "$", "haystack", "as", "$", "stack", ")", "{", "if", "(", "in_array", "(", "$", "stack", ",", "$", "traits", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether a given object contains a trait. ```php trait XYZ { } class ABC { use XYZ; } $object = new ABC(); ObjectHelper::isTraitInstanceOf($object, XYZ::class); ``` @param object $object @param string|array|object $haystack @return boolean @since 1.0.17
[ "Check", "whether", "a", "given", "object", "contains", "a", "trait", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ObjectHelper.php#L76-L92
luyadev/luya
core/helpers/ObjectHelper.php
ObjectHelper.traitsList
public static function traitsList($object, $autoload = true) { $traits = []; // Get traits of all parent classes do { $traits = array_merge(class_uses($object, $autoload), $traits); } while ($object = get_parent_class($object)); // Get traits of all parent traits $traitsToSearch = $traits; while (!empty($traitsToSearch)) { $newTraits = class_uses(array_pop($traitsToSearch), $autoload); $traits = array_merge($newTraits, $traits); $traitsToSearch = array_merge($newTraits, $traitsToSearch); }; foreach ($traits as $trait => $same) { $traits = array_merge(class_uses($trait, $autoload), $traits); } return $traits; }
php
public static function traitsList($object, $autoload = true) { $traits = []; do { $traits = array_merge(class_uses($object, $autoload), $traits); } while ($object = get_parent_class($object)); $traitsToSearch = $traits; while (!empty($traitsToSearch)) { $newTraits = class_uses(array_pop($traitsToSearch), $autoload); $traits = array_merge($newTraits, $traits); $traitsToSearch = array_merge($newTraits, $traitsToSearch); }; foreach ($traits as $trait => $same) { $traits = array_merge(class_uses($trait, $autoload), $traits); } return $traits; }
[ "public", "static", "function", "traitsList", "(", "$", "object", ",", "$", "autoload", "=", "true", ")", "{", "$", "traits", "=", "[", "]", ";", "// Get traits of all parent classes", "do", "{", "$", "traits", "=", "array_merge", "(", "class_uses", "(", "$", "object", ",", "$", "autoload", ")", ",", "$", "traits", ")", ";", "}", "while", "(", "$", "object", "=", "get_parent_class", "(", "$", "object", ")", ")", ";", "// Get traits of all parent traits", "$", "traitsToSearch", "=", "$", "traits", ";", "while", "(", "!", "empty", "(", "$", "traitsToSearch", ")", ")", "{", "$", "newTraits", "=", "class_uses", "(", "array_pop", "(", "$", "traitsToSearch", ")", ",", "$", "autoload", ")", ";", "$", "traits", "=", "array_merge", "(", "$", "newTraits", ",", "$", "traits", ")", ";", "$", "traitsToSearch", "=", "array_merge", "(", "$", "newTraits", ",", "$", "traitsToSearch", ")", ";", "}", ";", "foreach", "(", "$", "traits", "as", "$", "trait", "=>", "$", "same", ")", "{", "$", "traits", "=", "array_merge", "(", "class_uses", "(", "$", "trait", ",", "$", "autoload", ")", ",", "$", "traits", ")", ";", "}", "return", "$", "traits", ";", "}" ]
Get an array with all traits for a given object @param object $object @param boolean $autoload @return array @since 1.0.17 @see https://www.php.net/manual/en/function.class-uses.php#122427
[ "Get", "an", "array", "with", "all", "traits", "for", "a", "given", "object" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ObjectHelper.php#L103-L125
luyadev/luya
core/helpers/ObjectHelper.php
ObjectHelper.callMethodSanitizeArguments
public static function callMethodSanitizeArguments($object, $method, array $argumentsList = []) { // get class reflection object $reflection = new ReflectionMethod($object, $method); // array where the sanitized arguemnts will be stored $methodArgs = []; foreach ($reflection->getParameters() as $param) { // add the argument into the method list when existing if (array_key_exists($param->name, $argumentsList)) { $methodArgs[] = $argumentsList[$param->name]; } // check if the provided arguemnt is optional or not if (!$param->isOptional() && !array_key_exists($param->name, $argumentsList)) { throw new Exception(sprintf("The argument '%s' is required for method '%s' in class '%s'.", $param->name, $method, get_class($object))); } } return call_user_func_array([$object, $method], $methodArgs); }
php
public static function callMethodSanitizeArguments($object, $method, array $argumentsList = []) { $reflection = new ReflectionMethod($object, $method); $methodArgs = []; foreach ($reflection->getParameters() as $param) { if (array_key_exists($param->name, $argumentsList)) { $methodArgs[] = $argumentsList[$param->name]; } if (!$param->isOptional() && !array_key_exists($param->name, $argumentsList)) { throw new Exception(sprintf("The argument '%s' is required for method '%s' in class '%s'.", $param->name, $method, get_class($object))); } } return call_user_func_array([$object, $method], $methodArgs); }
[ "public", "static", "function", "callMethodSanitizeArguments", "(", "$", "object", ",", "$", "method", ",", "array", "$", "argumentsList", "=", "[", "]", ")", "{", "// get class reflection object", "$", "reflection", "=", "new", "ReflectionMethod", "(", "$", "object", ",", "$", "method", ")", ";", "// array where the sanitized arguemnts will be stored", "$", "methodArgs", "=", "[", "]", ";", "foreach", "(", "$", "reflection", "->", "getParameters", "(", ")", "as", "$", "param", ")", "{", "// add the argument into the method list when existing", "if", "(", "array_key_exists", "(", "$", "param", "->", "name", ",", "$", "argumentsList", ")", ")", "{", "$", "methodArgs", "[", "]", "=", "$", "argumentsList", "[", "$", "param", "->", "name", "]", ";", "}", "// check if the provided arguemnt is optional or not", "if", "(", "!", "$", "param", "->", "isOptional", "(", ")", "&&", "!", "array_key_exists", "(", "$", "param", "->", "name", ",", "$", "argumentsList", ")", ")", "{", "throw", "new", "Exception", "(", "sprintf", "(", "\"The argument '%s' is required for method '%s' in class '%s'.\"", ",", "$", "param", "->", "name", ",", "$", "method", ",", "get_class", "(", "$", "object", ")", ")", ")", ";", "}", "}", "return", "call_user_func_array", "(", "[", "$", "object", ",", "$", "method", "]", ",", "$", "methodArgs", ")", ";", "}" ]
Call a method and ensure arguments. Call a class method with arguments and verify the arguments if they are in the list of method arguments or not. ```php ObjectHelper::callMethodSanitizeArguments(new MyClass(), 'methodToCall', ['paramName' => 'paramValue']); ``` The response is the return value from the called method of the object. @param object $object The class object where the method must be found. @param string $method The class method to call inside the object. @param array $argumentsList A massiv assigned list of array items, where the key is bind to the method argument and the value to be passed in the method on call. @throws \luya\Exception Throws an exception if a argument coult not be found. @return mixed
[ "Call", "a", "method", "and", "ensure", "arguments", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/ObjectHelper.php#L155-L174
luyadev/luya
core/base/Module.php
Module.resolveRoute
public function resolveRoute($route) { $routeParts = explode('/', $route); foreach ($routeParts as $k => $v) { if (($k == 0 && $v == $this->id) || (empty($v))) { unset($routeParts[$k]); } } if (count($routeParts) == 0) { return $this->defaultRoute; } return implode('/', $routeParts); }
php
public function resolveRoute($route) { $routeParts = explode('/', $route); foreach ($routeParts as $k => $v) { if (($k == 0 && $v == $this->id) || (empty($v))) { unset($routeParts[$k]); } } if (count($routeParts) == 0) { return $this->defaultRoute; } return implode('/', $routeParts); }
[ "public", "function", "resolveRoute", "(", "$", "route", ")", "{", "$", "routeParts", "=", "explode", "(", "'/'", ",", "$", "route", ")", ";", "foreach", "(", "$", "routeParts", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "(", "$", "k", "==", "0", "&&", "$", "v", "==", "$", "this", "->", "id", ")", "||", "(", "empty", "(", "$", "v", ")", ")", ")", "{", "unset", "(", "$", "routeParts", "[", "$", "k", "]", ")", ";", "}", "}", "if", "(", "count", "(", "$", "routeParts", ")", "==", "0", ")", "{", "return", "$", "this", "->", "defaultRoute", ";", "}", "return", "implode", "(", "'/'", ",", "$", "routeParts", ")", ";", "}" ]
Extract the current module from the route and return the new resolved route. @param string $route Route to resolve, e.g. `admin/default/index` @return string The resolved route without the module id `default/index` when input was `admin/default/index` and the current module id is `admin`.
[ "Extract", "the", "current", "module", "from", "the", "route", "and", "return", "the", "new", "resolved", "route", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/Module.php#L221-L234
luyadev/luya
core/base/Module.php
Module.getControllerFiles
public function getControllerFiles() { $files = []; try { // https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php#L253 foreach (FileHelper::findFiles($this->controllerPath) as $file) { $files[$this->fileToName($this->controllerPath, $file)] = $file; } } catch (InvalidParamException $e) { try { $staticPath = static::staticBasePath() . DIRECTORY_SEPARATOR . 'controllers'; foreach (FileHelper::findFiles($staticPath) as $file) { $files[$this->fileToName($staticPath, $file)] = $file; } } catch (InvalidParamException $e) { // catch if folder not found. } }; return $files; }
php
public function getControllerFiles() { $files = []; try { foreach (FileHelper::findFiles($this->controllerPath) as $file) { $files[$this->fileToName($this->controllerPath, $file)] = $file; } } catch (InvalidParamException $e) { try { $staticPath = static::staticBasePath() . DIRECTORY_SEPARATOR . 'controllers'; foreach (FileHelper::findFiles($staticPath) as $file) { $files[$this->fileToName($staticPath, $file)] = $file; } } catch (InvalidParamException $e) { } }; return $files; }
[ "public", "function", "getControllerFiles", "(", ")", "{", "$", "files", "=", "[", "]", ";", "try", "{", "// https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php#L253", "foreach", "(", "FileHelper", "::", "findFiles", "(", "$", "this", "->", "controllerPath", ")", "as", "$", "file", ")", "{", "$", "files", "[", "$", "this", "->", "fileToName", "(", "$", "this", "->", "controllerPath", ",", "$", "file", ")", "]", "=", "$", "file", ";", "}", "}", "catch", "(", "InvalidParamException", "$", "e", ")", "{", "try", "{", "$", "staticPath", "=", "static", "::", "staticBasePath", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "'controllers'", ";", "foreach", "(", "FileHelper", "::", "findFiles", "(", "$", "staticPath", ")", "as", "$", "file", ")", "{", "$", "files", "[", "$", "this", "->", "fileToName", "(", "$", "staticPath", ",", "$", "file", ")", "]", "=", "$", "file", ";", "}", "}", "catch", "(", "InvalidParamException", "$", "e", ")", "{", "// catch if folder not found.", "}", "}", ";", "return", "$", "files", ";", "}" ]
Returns all controller files of this module from the `getControllerPath()` folder, where the key is the reusable id of this controller and value the file on the server. @return array Returns an array where the key is the controller id and value the original file.
[ "Returns", "all", "controller", "files", "of", "this", "module", "from", "the", "getControllerPath", "()", "folder", "where", "the", "key", "is", "the", "reusable", "id", "of", "this", "controller", "and", "value", "the", "file", "on", "the", "server", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/Module.php#L296-L315
luyadev/luya
core/base/Module.php
Module.registerTranslation
public static function registerTranslation($prefix, $basePath, array $fileMap) { if (!isset(Yii::$app->i18n->translations[$prefix])) { Yii::$app->i18n->translations[$prefix] = [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => $basePath, 'fileMap' => $fileMap, ]; } }
php
public static function registerTranslation($prefix, $basePath, array $fileMap) { if (!isset(Yii::$app->i18n->translations[$prefix])) { Yii::$app->i18n->translations[$prefix] = [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => $basePath, 'fileMap' => $fileMap, ]; } }
[ "public", "static", "function", "registerTranslation", "(", "$", "prefix", ",", "$", "basePath", ",", "array", "$", "fileMap", ")", "{", "if", "(", "!", "isset", "(", "Yii", "::", "$", "app", "->", "i18n", "->", "translations", "[", "$", "prefix", "]", ")", ")", "{", "Yii", "::", "$", "app", "->", "i18n", "->", "translations", "[", "$", "prefix", "]", "=", "[", "'class'", "=>", "'yii\\i18n\\PhpMessageSource'", ",", "'basePath'", "=>", "$", "basePath", ",", "'fileMap'", "=>", "$", "fileMap", ",", "]", ";", "}", "}" ]
Register a Translation to the i18n component. In order to register Translations you can register them inside the {{luya\base\Module::onLoad()}} method. ```php public static function onLoad() { $this->registerTranslation('mymodule*', static::staticBasePath() . '/messages', [ 'mymodule' => 'mymodule.php', 'mymodule/sub' => 'sub.php', ]); } ``` @param string $prefix The prefix of which the messages are indicated @param string $basePath The path to the messages folder where the messages are located. @param array $fileMap The files mapping inside the messages folder.
[ "Register", "a", "Translation", "to", "the", "i18n", "component", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/Module.php#L369-L378
luyadev/luya
core/base/Module.php
Module.baseT
public static function baseT($category, $message, array $params = [], $language = null) { static::onLoad(); return Yii::t($category, $message, $params, $language); }
php
public static function baseT($category, $message, array $params = [], $language = null) { static::onLoad(); return Yii::t($category, $message, $params, $language); }
[ "public", "static", "function", "baseT", "(", "$", "category", ",", "$", "message", ",", "array", "$", "params", "=", "[", "]", ",", "$", "language", "=", "null", ")", "{", "static", "::", "onLoad", "(", ")", ";", "return", "Yii", "::", "t", "(", "$", "category", ",", "$", "message", ",", "$", "params", ",", "$", "language", ")", ";", "}" ]
Base translation method which invokes the onLoad function. This makes it possible to register module translations without adding the module to the components list. This is very important for luya extensions. @param string $category the message category. @param string $message the message to be translated. @param array $params the parameters that will be used to replace the corresponding placeholders in the message. @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current [[\yii\base\Application::language|application language]] will be used. @return string the translated message.
[ "Base", "translation", "method", "which", "invokes", "the", "onLoad", "function", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/Module.php#L405-L409
luyadev/luya
core/base/ModuleReflection.php
ModuleReflection.setSuffix
public function setSuffix($suffix) { $this->_suffix = $suffix; $this->request->setPathInfo(implode('/', [$this->module->id, $suffix])); }
php
public function setSuffix($suffix) { $this->_suffix = $suffix; $this->request->setPathInfo(implode('/', [$this->module->id, $suffix])); }
[ "public", "function", "setSuffix", "(", "$", "suffix", ")", "{", "$", "this", "->", "_suffix", "=", "$", "suffix", ";", "$", "this", "->", "request", "->", "setPathInfo", "(", "implode", "(", "'/'", ",", "[", "$", "this", "->", "module", "->", "id", ",", "$", "suffix", "]", ")", ")", ";", "}" ]
Setter for the suffix property. @param string $suffix
[ "Setter", "for", "the", "suffix", "property", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/ModuleReflection.php#L115-L119
luyadev/luya
core/base/ModuleReflection.php
ModuleReflection.getRequestRoute
public function getRequestRoute() { if ($this->_requestRoute !== null) { return $this->_requestRoute; } if ($this->_defaultRoute !== null && empty($this->getSuffix())) { $array = $this->_defaultRoute; } else { // parse request against urlManager $route = $this->urlManager->parseRequest($this->request); // return human readable array $array = [ 'route' => $route[0], 'args' => $route[1], 'originalArgs' => $route[1], ]; } // resolve the current route by the module $array['route'] = $this->module->resolveRoute($array['route']); // if there are no arguments, all get params are assigned. In order to use the original arguments from parse request use `originalArgs` instead of `args`. if (empty($array['args'])) { $array['args'] = $this->request->get(); } // @see https://github.com/luyadev/luya/issues/1267 if ($this->_defaultRoute !== null) { $array['args'] = array_merge($this->_defaultRoute['args'], $array['args']); } $this->_requestRoute = $array; return $array; }
php
public function getRequestRoute() { if ($this->_requestRoute !== null) { return $this->_requestRoute; } if ($this->_defaultRoute !== null && empty($this->getSuffix())) { $array = $this->_defaultRoute; } else { $route = $this->urlManager->parseRequest($this->request); $array = [ 'route' => $route[0], 'args' => $route[1], 'originalArgs' => $route[1], ]; } $array['route'] = $this->module->resolveRoute($array['route']); if (empty($array['args'])) { $array['args'] = $this->request->get(); } if ($this->_defaultRoute !== null) { $array['args'] = array_merge($this->_defaultRoute['args'], $array['args']); } $this->_requestRoute = $array; return $array; }
[ "public", "function", "getRequestRoute", "(", ")", "{", "if", "(", "$", "this", "->", "_requestRoute", "!==", "null", ")", "{", "return", "$", "this", "->", "_requestRoute", ";", "}", "if", "(", "$", "this", "->", "_defaultRoute", "!==", "null", "&&", "empty", "(", "$", "this", "->", "getSuffix", "(", ")", ")", ")", "{", "$", "array", "=", "$", "this", "->", "_defaultRoute", ";", "}", "else", "{", "// parse request against urlManager", "$", "route", "=", "$", "this", "->", "urlManager", "->", "parseRequest", "(", "$", "this", "->", "request", ")", ";", "// return human readable array", "$", "array", "=", "[", "'route'", "=>", "$", "route", "[", "0", "]", ",", "'args'", "=>", "$", "route", "[", "1", "]", ",", "'originalArgs'", "=>", "$", "route", "[", "1", "]", ",", "]", ";", "}", "// resolve the current route by the module", "$", "array", "[", "'route'", "]", "=", "$", "this", "->", "module", "->", "resolveRoute", "(", "$", "array", "[", "'route'", "]", ")", ";", "// if there are no arguments, all get params are assigned. In order to use the original arguments from parse request use `originalArgs` instead of `args`.", "if", "(", "empty", "(", "$", "array", "[", "'args'", "]", ")", ")", "{", "$", "array", "[", "'args'", "]", "=", "$", "this", "->", "request", "->", "get", "(", ")", ";", "}", "// @see https://github.com/luyadev/luya/issues/1267", "if", "(", "$", "this", "->", "_defaultRoute", "!==", "null", ")", "{", "$", "array", "[", "'args'", "]", "=", "array_merge", "(", "$", "this", "->", "_defaultRoute", "[", "'args'", "]", ",", "$", "array", "[", "'args'", "]", ")", ";", "}", "$", "this", "->", "_requestRoute", "=", "$", "array", ";", "return", "$", "array", ";", "}" ]
Determine the default route based on current defaultRoutes or parsedRequested by the UrlManager. @return array An array with + route: The path/route to the controller + args: If the url has no params, it returns all params from get request. + originalArgs: The arguments (params) parsed from the url trogh url manager @see Related problems and changes: + https://github.com/luyadev/luya/issues/1885 + https://github.com/luyadev/luya/issues/1267 + https://github.com/luyadev/luya/issues/754
[ "Determine", "the", "default", "route", "based", "on", "current", "defaultRoutes", "or", "parsedRequested", "by", "the", "UrlManager", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/ModuleReflection.php#L146-L180
luyadev/luya
core/base/ModuleReflection.php
ModuleReflection.defaultRoute
public function defaultRoute($controller, $action = null, array $args = []) { $this->_defaultRoute = [ 'route' => implode('/', [$this->module->id, $controller, (empty($action)) ? 'index' : $action]), 'args' => $args, 'originalArgs' => $args, ]; }
php
public function defaultRoute($controller, $action = null, array $args = []) { $this->_defaultRoute = [ 'route' => implode('/', [$this->module->id, $controller, (empty($action)) ? 'index' : $action]), 'args' => $args, 'originalArgs' => $args, ]; }
[ "public", "function", "defaultRoute", "(", "$", "controller", ",", "$", "action", "=", "null", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "this", "->", "_defaultRoute", "=", "[", "'route'", "=>", "implode", "(", "'/'", ",", "[", "$", "this", "->", "module", "->", "id", ",", "$", "controller", ",", "(", "empty", "(", "$", "action", ")", ")", "?", "'index'", ":", "$", "action", "]", ")", ",", "'args'", "=>", "$", "args", ",", "'originalArgs'", "=>", "$", "args", ",", "]", ";", "}" ]
Inject a defaultRoute. @param string $controller @param string $action @param array $args
[ "Inject", "a", "defaultRoute", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/ModuleReflection.php#L199-L206
luyadev/luya
core/base/ModuleReflection.php
ModuleReflection.getUrlRule
public function getUrlRule() { $request = $this->getRequestRoute(); return [ 'module' => $this->module->id, 'route' => $this->module->id . '/' . $request['route'], 'params' => $request['originalArgs'], ]; }
php
public function getUrlRule() { $request = $this->getRequestRoute(); return [ 'module' => $this->module->id, 'route' => $this->module->id . '/' . $request['route'], 'params' => $request['originalArgs'], ]; }
[ "public", "function", "getUrlRule", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequestRoute", "(", ")", ";", "return", "[", "'module'", "=>", "$", "this", "->", "module", "->", "id", ",", "'route'", "=>", "$", "this", "->", "module", "->", "id", ".", "'/'", ".", "$", "request", "[", "'route'", "]", ",", "'params'", "=>", "$", "request", "[", "'originalArgs'", "]", ",", "]", ";", "}" ]
Returns the url rule parameters which are taken from the requested route. @return array
[ "Returns", "the", "url", "rule", "parameters", "which", "are", "taken", "from", "the", "requested", "route", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/ModuleReflection.php#L213-L222
luyadev/luya
core/base/ModuleReflection.php
ModuleReflection.run
public function run() { $requestRoute = $this->getRequestRoute(); // create controller object $controller = $this->module->createController($requestRoute['route']); // throw error if the requests request does not returns a valid controller object if (!isset($controller[0]) && !is_object($controller[0])) { throw new NotFoundHttpException(sprintf("Unable to create controller '%s' for module '%s'.", $requestRoute['route'], $this->module->id)); } Yii::debug('LUYA module run module "'.$this->module->id.'" route ' . $requestRoute['route'], __METHOD__); $this->controller = $controller[0]; $originalController = Yii::$app->controller; /** * Override the current application controller in order to ensure current() url handling which is used * for relativ urls/rules. * * @see https://github.com/luyadev/luya/issues/1730 */ $this->controller->on(Controller::EVENT_BEFORE_ACTION, function ($event) { Yii::$app->controller = $this->controller; }); /** * Restore the original controller instance after rendering. * * @see https://github.com/luyadev/luya/issues/1768 */ $this->controller->on(Controller::EVENT_AFTER_ACTION, function ($event) use ($originalController) { Yii::$app->controller = $originalController; }); // run the action on the provided controller object return $this->controller->runAction($controller[1], $requestRoute['args']); }
php
public function run() { $requestRoute = $this->getRequestRoute(); $controller = $this->module->createController($requestRoute['route']); if (!isset($controller[0]) && !is_object($controller[0])) { throw new NotFoundHttpException(sprintf("Unable to create controller '%s' for module '%s'.", $requestRoute['route'], $this->module->id)); } Yii::debug('LUYA module run module "'.$this->module->id.'" route ' . $requestRoute['route'], __METHOD__); $this->controller = $controller[0]; $originalController = Yii::$app->controller; $this->controller->on(Controller::EVENT_BEFORE_ACTION, function ($event) { Yii::$app->controller = $this->controller; }); $this->controller->on(Controller::EVENT_AFTER_ACTION, function ($event) use ($originalController) { Yii::$app->controller = $originalController; }); return $this->controller->runAction($controller[1], $requestRoute['args']); }
[ "public", "function", "run", "(", ")", "{", "$", "requestRoute", "=", "$", "this", "->", "getRequestRoute", "(", ")", ";", "// create controller object", "$", "controller", "=", "$", "this", "->", "module", "->", "createController", "(", "$", "requestRoute", "[", "'route'", "]", ")", ";", "// throw error if the requests request does not returns a valid controller object", "if", "(", "!", "isset", "(", "$", "controller", "[", "0", "]", ")", "&&", "!", "is_object", "(", "$", "controller", "[", "0", "]", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", "sprintf", "(", "\"Unable to create controller '%s' for module '%s'.\"", ",", "$", "requestRoute", "[", "'route'", "]", ",", "$", "this", "->", "module", "->", "id", ")", ")", ";", "}", "Yii", "::", "debug", "(", "'LUYA module run module \"'", ".", "$", "this", "->", "module", "->", "id", ".", "'\" route '", ".", "$", "requestRoute", "[", "'route'", "]", ",", "__METHOD__", ")", ";", "$", "this", "->", "controller", "=", "$", "controller", "[", "0", "]", ";", "$", "originalController", "=", "Yii", "::", "$", "app", "->", "controller", ";", "/**\n * Override the current application controller in order to ensure current() url handling which is used\n * for relativ urls/rules.\n *\n * @see https://github.com/luyadev/luya/issues/1730\n */", "$", "this", "->", "controller", "->", "on", "(", "Controller", "::", "EVENT_BEFORE_ACTION", ",", "function", "(", "$", "event", ")", "{", "Yii", "::", "$", "app", "->", "controller", "=", "$", "this", "->", "controller", ";", "}", ")", ";", "/**\n * Restore the original controller instance after rendering.\n *\n * @see https://github.com/luyadev/luya/issues/1768\n */", "$", "this", "->", "controller", "->", "on", "(", "Controller", "::", "EVENT_AFTER_ACTION", ",", "function", "(", "$", "event", ")", "use", "(", "$", "originalController", ")", "{", "Yii", "::", "$", "app", "->", "controller", "=", "$", "originalController", ";", "}", ")", ";", "// run the action on the provided controller object", "return", "$", "this", "->", "controller", "->", "runAction", "(", "$", "controller", "[", "1", "]", ",", "$", "requestRoute", "[", "'args'", "]", ")", ";", "}" ]
Run the route based on the values. @return string|\yii\web\Response The response of the action, can be either a string or an object from response. @throws \yii\web\NotFoundHttpException
[ "Run", "the", "route", "based", "on", "the", "values", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/ModuleReflection.php#L230-L265
luyadev/luya
core/base/HookEvent.php
HookEvent.iteration
public function iteration($value, $key = null) { if (is_null($key)) { $this->_iterations[] = $value; } else { $this->_iterations[$key] = $value; } }
php
public function iteration($value, $key = null) { if (is_null($key)) { $this->_iterations[] = $value; } else { $this->_iterations[$key] = $value; } }
[ "public", "function", "iteration", "(", "$", "value", ",", "$", "key", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "key", ")", ")", "{", "$", "this", "->", "_iterations", "[", "]", "=", "$", "value", ";", "}", "else", "{", "$", "this", "->", "_iterations", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}" ]
Add Iteration @param mixed $value The value of the key @param string $key The key of the array
[ "Add", "Iteration" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/base/HookEvent.php#L54-L61
luyadev/luya
core/web/CompositionResolver.php
CompositionResolver.getResolvedKeyValue
public function getResolvedKeyValue($key) { $keys = $this->resolvedValues; return isset($keys[$key]) ? $keys[$key] : false; }
php
public function getResolvedKeyValue($key) { $keys = $this->resolvedValues; return isset($keys[$key]) ? $keys[$key] : false; }
[ "public", "function", "getResolvedKeyValue", "(", "$", "key", ")", "{", "$", "keys", "=", "$", "this", "->", "resolvedValues", ";", "return", "isset", "(", "$", "keys", "[", "$", "key", "]", ")", "?", "$", "keys", "[", "$", "key", "]", ":", "false", ";", "}" ]
Get a value for a given resolved pattern key. @param string $key @return boolean|mixed
[ "Get", "a", "value", "for", "a", "given", "resolved", "pattern", "key", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/CompositionResolver.php#L87-L92
luyadev/luya
core/web/CompositionResolver.php
CompositionResolver.getInternalResolverArray
protected function getInternalResolverArray() { if ($this->_resolved === null) { $requestPathInfo = $this->trailingPathInfo(); $newRegex = $this->buildRegexPattern(); // extract the rules from the regex pattern, this means you get array with keys for every rule inside the pattern string // example pattern: <langShortCode:[a-z]{2}>-<countryShortCode:[a-z]{2}> /* [0]=> array(3) { [0]=> string(24) "<langShortCode:[a-z]{2}>" [1]=> string(13) "langShortCode" [2]=> string(8) "[a-z]{2}" } [1]=> array(3) { [0]=> string(27) "<countryShortCode:[a-z]{2}>" [1]=> string(16) "countryShortCode" [2]=> string(8) "[a-z]{2}" } */ preg_match_all(static::VAR_MATCH_REGEX, $this->composition->pattern, $patternDefinitions, PREG_SET_ORDER); foreach ($patternDefinitions as $definition) { $newRegex = str_replace($definition[0], '('.rtrim(ltrim($definition[2], '('), ')').')', $newRegex); } preg_match_all($newRegex, $requestPathInfo, $matches, PREG_SET_ORDER); if (isset($matches[0]) && !empty($matches[0])) { $keys = []; $matches = $matches[0]; $compositionPrefix = $matches[0]; unset($matches[0]); $matches = array_values($matches); foreach ($matches as $k => $v) { $keys[$patternDefinitions[$k][1]] = $v; } $route = StringHelper::replaceFirst($compositionPrefix, '', $requestPathInfo); } else { $matches = []; $keys = $this->composition->default; $route = $requestPathInfo; } // the validation check for validates composition values is enabled if ($this->composition->expectedValues) { foreach ($keys as $k => $v) { $possibleValues = $this->composition->expectedValues[$k]; if (!in_array($v, $possibleValues)) { throw new NotFoundHttpException("The requested composition key \"{$k}\" with value \"{$v}\" is not in the possible values list."); } } } $this->_resolved = [ 'route' => rtrim($route, '/'), 'values' => $keys, ]; } return $this->_resolved; }
php
protected function getInternalResolverArray() { if ($this->_resolved === null) { $requestPathInfo = $this->trailingPathInfo(); $newRegex = $this->buildRegexPattern(); preg_match_all(static::VAR_MATCH_REGEX, $this->composition->pattern, $patternDefinitions, PREG_SET_ORDER); foreach ($patternDefinitions as $definition) { $newRegex = str_replace($definition[0], '('.rtrim(ltrim($definition[2], '('), ')').')', $newRegex); } preg_match_all($newRegex, $requestPathInfo, $matches, PREG_SET_ORDER); if (isset($matches[0]) && !empty($matches[0])) { $keys = []; $matches = $matches[0]; $compositionPrefix = $matches[0]; unset($matches[0]); $matches = array_values($matches); foreach ($matches as $k => $v) { $keys[$patternDefinitions[$k][1]] = $v; } $route = StringHelper::replaceFirst($compositionPrefix, '', $requestPathInfo); } else { $matches = []; $keys = $this->composition->default; $route = $requestPathInfo; } if ($this->composition->expectedValues) { foreach ($keys as $k => $v) { $possibleValues = $this->composition->expectedValues[$k]; if (!in_array($v, $possibleValues)) { throw new NotFoundHttpException("The requested composition key \"{$k}\" with value \"{$v}\" is not in the possible values list."); } } } $this->_resolved = [ 'route' => rtrim($route, '/'), 'values' => $keys, ]; } return $this->_resolved; }
[ "protected", "function", "getInternalResolverArray", "(", ")", "{", "if", "(", "$", "this", "->", "_resolved", "===", "null", ")", "{", "$", "requestPathInfo", "=", "$", "this", "->", "trailingPathInfo", "(", ")", ";", "$", "newRegex", "=", "$", "this", "->", "buildRegexPattern", "(", ")", ";", "// extract the rules from the regex pattern, this means you get array with keys for every rule inside the pattern string", "// example pattern: <langShortCode:[a-z]{2}>-<countryShortCode:[a-z]{2}>", "/* [0]=>\n array(3) {\n [0]=> string(24) \"<langShortCode:[a-z]{2}>\"\n [1]=> string(13) \"langShortCode\"\n [2]=> string(8) \"[a-z]{2}\"\n }\n [1]=>\n array(3) {\n [0]=> string(27) \"<countryShortCode:[a-z]{2}>\"\n [1]=> string(16) \"countryShortCode\"\n [2]=> string(8) \"[a-z]{2}\"\n }\n */", "preg_match_all", "(", "static", "::", "VAR_MATCH_REGEX", ",", "$", "this", "->", "composition", "->", "pattern", ",", "$", "patternDefinitions", ",", "PREG_SET_ORDER", ")", ";", "foreach", "(", "$", "patternDefinitions", "as", "$", "definition", ")", "{", "$", "newRegex", "=", "str_replace", "(", "$", "definition", "[", "0", "]", ",", "'('", ".", "rtrim", "(", "ltrim", "(", "$", "definition", "[", "2", "]", ",", "'('", ")", ",", "')'", ")", ".", "')'", ",", "$", "newRegex", ")", ";", "}", "preg_match_all", "(", "$", "newRegex", ",", "$", "requestPathInfo", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ";", "if", "(", "isset", "(", "$", "matches", "[", "0", "]", ")", "&&", "!", "empty", "(", "$", "matches", "[", "0", "]", ")", ")", "{", "$", "keys", "=", "[", "]", ";", "$", "matches", "=", "$", "matches", "[", "0", "]", ";", "$", "compositionPrefix", "=", "$", "matches", "[", "0", "]", ";", "unset", "(", "$", "matches", "[", "0", "]", ")", ";", "$", "matches", "=", "array_values", "(", "$", "matches", ")", ";", "foreach", "(", "$", "matches", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "keys", "[", "$", "patternDefinitions", "[", "$", "k", "]", "[", "1", "]", "]", "=", "$", "v", ";", "}", "$", "route", "=", "StringHelper", "::", "replaceFirst", "(", "$", "compositionPrefix", ",", "''", ",", "$", "requestPathInfo", ")", ";", "}", "else", "{", "$", "matches", "=", "[", "]", ";", "$", "keys", "=", "$", "this", "->", "composition", "->", "default", ";", "$", "route", "=", "$", "requestPathInfo", ";", "}", "// the validation check for validates composition values is enabled", "if", "(", "$", "this", "->", "composition", "->", "expectedValues", ")", "{", "foreach", "(", "$", "keys", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "possibleValues", "=", "$", "this", "->", "composition", "->", "expectedValues", "[", "$", "k", "]", ";", "if", "(", "!", "in_array", "(", "$", "v", ",", "$", "possibleValues", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", "\"The requested composition key \\\"{$k}\\\" with value \\\"{$v}\\\" is not in the possible values list.\"", ")", ";", "}", "}", "}", "$", "this", "->", "_resolved", "=", "[", "'route'", "=>", "rtrim", "(", "$", "route", ",", "'/'", ")", ",", "'values'", "=>", "$", "keys", ",", "]", ";", "}", "return", "$", "this", "->", "_resolved", ";", "}" ]
Resolve the current data. @return array
[ "Resolve", "the", "current", "data", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/CompositionResolver.php#L121-L187
luyadev/luya
core/helpers/Inflector.php
Inflector.slug
public static function slug($string, $replacement = '-', $lowercase = true, $transliterate = true) { if ($transliterate) { return parent::slug($string, $replacement, $lowercase); } $string = preg_replace('/[`%\+=\{\}\|\\\.<>\/\_]+/u', '', $string); // replace those chars with nothing $string = preg_replace('/[=\s—–-]+/u', $replacement, $string); // replace single and double spaces by $replacement char. $string = trim($string, $replacement); return $lowercase ? mb_strtolower($string) : $string; }
php
public static function slug($string, $replacement = '-', $lowercase = true, $transliterate = true) { if ($transliterate) { return parent::slug($string, $replacement, $lowercase); } $string = preg_replace('/[`%\+=\{\}\|\\\.<>\/\_]+/u', '', $string); $string = preg_replace('/[=\s—–-]+/u', $replacement, $string); $string = trim($string, $replacement); return $lowercase ? mb_strtolower($string) : $string; }
[ "public", "static", "function", "slug", "(", "$", "string", ",", "$", "replacement", "=", "'-'", ",", "$", "lowercase", "=", "true", ",", "$", "transliterate", "=", "true", ")", "{", "if", "(", "$", "transliterate", ")", "{", "return", "parent", "::", "slug", "(", "$", "string", ",", "$", "replacement", ",", "$", "lowercase", ")", ";", "}", "$", "string", "=", "preg_replace", "(", "'/[`%\\+=\\{\\}\\|\\\\\\.<>\\/\\_]+/u'", ",", "''", ",", "$", "string", ")", ";", "// replace those chars with nothing", "$", "string", "=", "preg_replace", "(", "'/[=\\s—–-]+/u', $r", "e", "l", "acement, $s", "t", "i", "ng); /", "/", " ", "eplace single and double spaces by $replacement char.", "$", "string", "=", "trim", "(", "$", "string", ",", "$", "replacement", ")", ";", "return", "$", "lowercase", "?", "mb_strtolower", "(", "$", "string", ")", ":", "$", "string", ";", "}" ]
From yii/helpers/BaseInflector: Returns a string with all spaces converted to given replacement, non word characters removed and the rest of characters transliterated. If intl extension isn't available uses fallback that converts latin characters only and removes the rest. You may customize characters map via $transliteration property of the helper. @param string $string An arbitrary string to convert @param string $replacement The replacement to use for spaces @param bool $lowercase whether to return the string in lowercase or not. Defaults to `true`. @param bool $transliterate whether to use a transliteration transformation or not. Defaults to `true` (=BaseInflector implementation) @return string The converted string.
[ "From", "yii", "/", "helpers", "/", "BaseInflector", ":" ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/helpers/Inflector.php#L35-L46
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setAuthor
public function setAuthor($author) { ObjectHelper::isInstanceOf($author, [Organization::class, PersonInterface::class]); $this->_author = $author; return $this; }
php
public function setAuthor($author) { ObjectHelper::isInstanceOf($author, [Organization::class, PersonInterface::class]); $this->_author = $author; return $this; }
[ "public", "function", "setAuthor", "(", "$", "author", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "author", ",", "[", "Organization", "::", "class", ",", "PersonInterface", "::", "class", "]", ")", ";", "$", "this", "->", "_author", "=", "$", "author", ";", "return", "$", "this", ";", "}" ]
The author of this content or rating. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangeably. @param Organization|Person $author @return static
[ "The", "author", "of", "this", "content", "or", "rating", ".", "Please", "note", "that", "author", "is", "special", "in", "that", "HTML", "5", "provides", "a", "special", "mechanism", "for", "indicating", "authorship", "via", "the", "rel", "tag", ".", "That", "is", "equivalent", "to", "this", "and", "may", "be", "used", "interchangeably", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L292-L298
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setCopyrightHolder
public function setCopyrightHolder($copyrightHolder) { ObjectHelper::isInstanceOf($copyrightHolder, [Organization::class, PersonInterface::class]); $this->_copyrightHolder = $copyrightHolder; return $this; }
php
public function setCopyrightHolder($copyrightHolder) { ObjectHelper::isInstanceOf($copyrightHolder, [Organization::class, PersonInterface::class]); $this->_copyrightHolder = $copyrightHolder; return $this; }
[ "public", "function", "setCopyrightHolder", "(", "$", "copyrightHolder", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "copyrightHolder", ",", "[", "Organization", "::", "class", ",", "PersonInterface", "::", "class", "]", ")", ";", "$", "this", "->", "_copyrightHolder", "=", "$", "copyrightHolder", ";", "return", "$", "this", ";", "}" ]
The party holding the legal copyright to the CreativeWork. @param Organization|Person $copyrightHolder @return static
[ "The", "party", "holding", "the", "legal", "copyright", "to", "the", "CreativeWork", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L519-L525
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setCreator
public function setCreator($creator) { ObjectHelper::isInstanceOf($creator, [Organization::class, PersonInterface::class]); $this->_creator = $creator; return $this; }
php
public function setCreator($creator) { ObjectHelper::isInstanceOf($creator, [Organization::class, PersonInterface::class]); $this->_creator = $creator; return $this; }
[ "public", "function", "setCreator", "(", "$", "creator", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "creator", ",", "[", "Organization", "::", "class", ",", "PersonInterface", "::", "class", "]", ")", ";", "$", "this", "->", "_creator", "=", "$", "creator", ";", "return", "$", "this", ";", "}" ]
The creator/author of this CreativeWork. This is the same as the Author property for CreativeWork. @param Organization|Person $creator @return static
[ "The", "creator", "/", "author", "of", "this", "CreativeWork", ".", "This", "is", "the", "same", "as", "the", "Author", "property", "for", "CreativeWork", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L565-L571
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setProducer
public function setProducer($producer) { ObjectHelper::isInstanceOf($producer, [Organization::class, PersonInterface::class]); $this->_producer = $producer; return $this; }
php
public function setProducer($producer) { ObjectHelper::isInstanceOf($producer, [Organization::class, PersonInterface::class]); $this->_producer = $producer; return $this; }
[ "public", "function", "setProducer", "(", "$", "producer", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "producer", ",", "[", "Organization", "::", "class", ",", "PersonInterface", "::", "class", "]", ")", ";", "$", "this", "->", "_producer", "=", "$", "producer", ";", "return", "$", "this", ";", "}" ]
The person or organization who produced the work (e.g. music album, movie, tv/radio series etc.). @param Organization|Person $producer @return static
[ "The", "person", "or", "organization", "who", "produced", "the", "work", "(", "e", ".", "g", ".", "music", "album", "movie", "tv", "/", "radio", "series", "etc", ".", ")", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L1133-L1139
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setProvider
public function setProvider($provider) { ObjectHelper::isInstanceOf($provider, [Organization::class, PersonInterface::class]); $this->_provider = $provider; return $this; }
php
public function setProvider($provider) { ObjectHelper::isInstanceOf($provider, [Organization::class, PersonInterface::class]); $this->_provider = $provider; return $this; }
[ "public", "function", "setProvider", "(", "$", "provider", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "provider", ",", "[", "Organization", "::", "class", ",", "PersonInterface", "::", "class", "]", ")", ";", "$", "this", "->", "_provider", "=", "$", "provider", ";", "return", "$", "this", ";", "}" ]
The service provider, service operator, or service performer; the goods producer. Another party (a seller) may offer those services or goods on behalf of the provider. A provider may also serve as the seller. Supersedes carrier. @param Organization|Person $provider @return static
[ "The", "service", "provider", "service", "operator", "or", "service", "performer", ";", "the", "goods", "producer", ".", "Another", "party", "(", "a", "seller", ")", "may", "offer", "those", "services", "or", "goods", "on", "behalf", "of", "the", "provider", ".", "A", "provider", "may", "also", "serve", "as", "the", "seller", ".", "Supersedes", "carrier", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L1159-L1165
luyadev/luya
core/web/jsonld/CreativeWorkTrait.php
CreativeWorkTrait.setPublisher
public function setPublisher($publisher) { ObjectHelper::isInstanceOf($publisher, [Organization::class, Person::class]); $this->_publisher = $publisher; return $this; }
php
public function setPublisher($publisher) { ObjectHelper::isInstanceOf($publisher, [Organization::class, Person::class]); $this->_publisher = $publisher; return $this; }
[ "public", "function", "setPublisher", "(", "$", "publisher", ")", "{", "ObjectHelper", "::", "isInstanceOf", "(", "$", "publisher", ",", "[", "Organization", "::", "class", ",", "Person", "::", "class", "]", ")", ";", "$", "this", "->", "_publisher", "=", "$", "publisher", ";", "return", "$", "this", ";", "}" ]
The publisher of the creative work. @param Organization|Person $publisher @return static
[ "The", "publisher", "of", "the", "creative", "work", "." ]
train
https://github.com/luyadev/luya/blob/5b1779ecc68d0374477f2dd7605de4a7d9dd5b5e/core/web/jsonld/CreativeWorkTrait.php#L1183-L1189
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Event/PreUpdateEventArgs.php
PreUpdateEventArgs.setNewValue
public function setNewValue(string $field, $value) : void { $this->assertValidField($field); $this->documentChangeSet[$field][1] = $value; $this->getDocumentManager()->getUnitOfWork()->setDocumentChangeSet($this->getDocument(), $this->documentChangeSet); }
php
public function setNewValue(string $field, $value) : void { $this->assertValidField($field); $this->documentChangeSet[$field][1] = $value; $this->getDocumentManager()->getUnitOfWork()->setDocumentChangeSet($this->getDocument(), $this->documentChangeSet); }
[ "public", "function", "setNewValue", "(", "string", "$", "field", ",", "$", "value", ")", ":", "void", "{", "$", "this", "->", "assertValidField", "(", "$", "field", ")", ";", "$", "this", "->", "documentChangeSet", "[", "$", "field", "]", "[", "1", "]", "=", "$", "value", ";", "$", "this", "->", "getDocumentManager", "(", ")", "->", "getUnitOfWork", "(", ")", "->", "setDocumentChangeSet", "(", "$", "this", "->", "getDocument", "(", ")", ",", "$", "this", "->", "documentChangeSet", ")", ";", "}" ]
Sets the new value of this field. @param mixed $value
[ "Sets", "the", "new", "value", "of", "this", "field", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Event/PreUpdateEventArgs.php#L65-L71
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Configuration.php
Configuration.getDocumentNamespace
public function getDocumentNamespace(string $documentNamespaceAlias) : string { if (! isset($this->attributes['documentNamespaces'][$documentNamespaceAlias])) { throw MongoDBException::unknownDocumentNamespace($documentNamespaceAlias); } return trim($this->attributes['documentNamespaces'][$documentNamespaceAlias], '\\'); }
php
public function getDocumentNamespace(string $documentNamespaceAlias) : string { if (! isset($this->attributes['documentNamespaces'][$documentNamespaceAlias])) { throw MongoDBException::unknownDocumentNamespace($documentNamespaceAlias); } return trim($this->attributes['documentNamespaces'][$documentNamespaceAlias], '\\'); }
[ "public", "function", "getDocumentNamespace", "(", "string", "$", "documentNamespaceAlias", ")", ":", "string", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "attributes", "[", "'documentNamespaces'", "]", "[", "$", "documentNamespaceAlias", "]", ")", ")", "{", "throw", "MongoDBException", "::", "unknownDocumentNamespace", "(", "$", "documentNamespaceAlias", ")", ";", "}", "return", "trim", "(", "$", "this", "->", "attributes", "[", "'documentNamespaces'", "]", "[", "$", "documentNamespaceAlias", "]", ",", "'\\\\'", ")", ";", "}" ]
Resolves a registered namespace alias to the full namespace. @throws MongoDBException
[ "Resolves", "a", "registered", "namespace", "alias", "to", "the", "full", "namespace", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Configuration.php#L106-L113
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Configuration.php
Configuration.setProxyDir
public function setProxyDir(string $dir) : void { $this->getProxyManagerConfiguration()->setProxiesTargetDir($dir); // Recreate proxy generator to ensure its path was updated if ($this->autoGenerateProxyClasses !== self::AUTOGENERATE_FILE_NOT_EXISTS) { return; } $this->setAutoGenerateProxyClasses($this->autoGenerateProxyClasses); }
php
public function setProxyDir(string $dir) : void { $this->getProxyManagerConfiguration()->setProxiesTargetDir($dir); if ($this->autoGenerateProxyClasses !== self::AUTOGENERATE_FILE_NOT_EXISTS) { return; } $this->setAutoGenerateProxyClasses($this->autoGenerateProxyClasses); }
[ "public", "function", "setProxyDir", "(", "string", "$", "dir", ")", ":", "void", "{", "$", "this", "->", "getProxyManagerConfiguration", "(", ")", "->", "setProxiesTargetDir", "(", "$", "dir", ")", ";", "// Recreate proxy generator to ensure its path was updated", "if", "(", "$", "this", "->", "autoGenerateProxyClasses", "!==", "self", "::", "AUTOGENERATE_FILE_NOT_EXISTS", ")", "{", "return", ";", "}", "$", "this", "->", "setAutoGenerateProxyClasses", "(", "$", "this", "->", "autoGenerateProxyClasses", ")", ";", "}" ]
Sets the directory where Doctrine generates any necessary proxy class files.
[ "Sets", "the", "directory", "where", "Doctrine", "generates", "any", "necessary", "proxy", "class", "files", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Configuration.php#L173-L183
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Configuration.php
Configuration.setAutoGenerateProxyClasses
public function setAutoGenerateProxyClasses(int $mode) : void { $this->autoGenerateProxyClasses = $mode; $proxyManagerConfig = $this->getProxyManagerConfiguration(); switch ($mode) { case self::AUTOGENERATE_FILE_NOT_EXISTS: $proxyManagerConfig->setGeneratorStrategy(new FileWriterGeneratorStrategy( new FileLocator($proxyManagerConfig->getProxiesTargetDir()) )); break; case self::AUTOGENERATE_EVAL: $proxyManagerConfig->setGeneratorStrategy(new EvaluatingGeneratorStrategy()); break; default: throw new InvalidArgumentException('Invalid proxy generation strategy given - only AUTOGENERATE_FILE_NOT_EXISTS and AUTOGENERATE_EVAL are supported.'); } }
php
public function setAutoGenerateProxyClasses(int $mode) : void { $this->autoGenerateProxyClasses = $mode; $proxyManagerConfig = $this->getProxyManagerConfiguration(); switch ($mode) { case self::AUTOGENERATE_FILE_NOT_EXISTS: $proxyManagerConfig->setGeneratorStrategy(new FileWriterGeneratorStrategy( new FileLocator($proxyManagerConfig->getProxiesTargetDir()) )); break; case self::AUTOGENERATE_EVAL: $proxyManagerConfig->setGeneratorStrategy(new EvaluatingGeneratorStrategy()); break; default: throw new InvalidArgumentException('Invalid proxy generation strategy given - only AUTOGENERATE_FILE_NOT_EXISTS and AUTOGENERATE_EVAL are supported.'); } }
[ "public", "function", "setAutoGenerateProxyClasses", "(", "int", "$", "mode", ")", ":", "void", "{", "$", "this", "->", "autoGenerateProxyClasses", "=", "$", "mode", ";", "$", "proxyManagerConfig", "=", "$", "this", "->", "getProxyManagerConfiguration", "(", ")", ";", "switch", "(", "$", "mode", ")", "{", "case", "self", "::", "AUTOGENERATE_FILE_NOT_EXISTS", ":", "$", "proxyManagerConfig", "->", "setGeneratorStrategy", "(", "new", "FileWriterGeneratorStrategy", "(", "new", "FileLocator", "(", "$", "proxyManagerConfig", "->", "getProxiesTargetDir", "(", ")", ")", ")", ")", ";", "break", ";", "case", "self", "::", "AUTOGENERATE_EVAL", ":", "$", "proxyManagerConfig", "->", "setGeneratorStrategy", "(", "new", "EvaluatingGeneratorStrategy", "(", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "InvalidArgumentException", "(", "'Invalid proxy generation strategy given - only AUTOGENERATE_FILE_NOT_EXISTS and AUTOGENERATE_EVAL are supported.'", ")", ";", "}", "}" ]
Sets an int flag that indicates whether proxy classes should always be regenerated during each script execution. @throws InvalidArgumentException If an invalid mode was given.
[ "Sets", "an", "int", "flag", "that", "indicates", "whether", "proxy", "classes", "should", "always", "be", "regenerated", "during", "each", "script", "execution", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Configuration.php#L208-L227
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Configuration.php
Configuration.addFilter
public function addFilter(string $name, string $className, array $parameters = []) : void { $this->attributes['filters'][$name] = [ 'class' => $className, 'parameters' => $parameters, ]; }
php
public function addFilter(string $name, string $className, array $parameters = []) : void { $this->attributes['filters'][$name] = [ 'class' => $className, 'parameters' => $parameters, ]; }
[ "public", "function", "addFilter", "(", "string", "$", "name", ",", "string", "$", "className", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "void", "{", "$", "this", "->", "attributes", "[", "'filters'", "]", "[", "$", "name", "]", "=", "[", "'class'", "=>", "$", "className", ",", "'parameters'", "=>", "$", "parameters", ",", "]", ";", "}" ]
Add a filter to the list of possible filters.
[ "Add", "a", "filter", "to", "the", "list", "of", "possible", "filters", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Configuration.php#L358-L364
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php
Stage.geoNear
public function geoNear($x, $y = null) : Stage\GeoNear { return $this->builder->geoNear($x, $y); }
php
public function geoNear($x, $y = null) : Stage\GeoNear { return $this->builder->geoNear($x, $y); }
[ "public", "function", "geoNear", "(", "$", "x", ",", "$", "y", "=", "null", ")", ":", "Stage", "\\", "GeoNear", "{", "return", "$", "this", "->", "builder", "->", "geoNear", "(", "$", "x", ",", "$", "y", ")", ";", "}" ]
Outputs documents in order of nearest to farthest from a specified point. You can only use this as the first stage of a pipeline. @see http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/ @param float|array|Point $x @param float $y
[ "Outputs", "documents", "in", "order", "of", "nearest", "to", "farthest", "from", "a", "specified", "point", ".", "You", "can", "only", "use", "this", "as", "the", "first", "stage", "of", "a", "pipeline", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php#L134-L137
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php
Stage.sort
public function sort($fieldName, $order = null) : Stage\Sort { return $this->builder->sort($fieldName, $order); }
php
public function sort($fieldName, $order = null) : Stage\Sort { return $this->builder->sort($fieldName, $order); }
[ "public", "function", "sort", "(", "$", "fieldName", ",", "$", "order", "=", "null", ")", ":", "Stage", "\\", "Sort", "{", "return", "$", "this", "->", "builder", "->", "sort", "(", "$", "fieldName", ",", "$", "order", ")", ";", "}" ]
Sorts all input documents and returns them to the pipeline in sorted order. If sorting by multiple fields, the first argument should be an array of field name (key) and order (value) pairs. @see http://docs.mongodb.org/manual/reference/operator/aggregation/sort/ @param array|string $fieldName Field name or array of field/order pairs @param int|string $order Field order (if one field is specified)
[ "Sorts", "all", "input", "documents", "and", "returns", "them", "to", "the", "pipeline", "in", "sorted", "order", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Aggregation/Stage.php#L310-L313
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php
HydratorFactory.getHydratorFor
public function getHydratorFor(string $className) : HydratorInterface { if (isset($this->hydrators[$className])) { return $this->hydrators[$className]; } $hydratorClassName = str_replace('\\', '', $className) . 'Hydrator'; $fqn = $this->hydratorNamespace . '\\' . $hydratorClassName; $class = $this->dm->getClassMetadata($className); if (! class_exists($fqn, false)) { $fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php'; switch ($this->autoGenerate) { case Configuration::AUTOGENERATE_NEVER: require $fileName; break; case Configuration::AUTOGENERATE_ALWAYS: $this->generateHydratorClass($class, $hydratorClassName, $fileName); require $fileName; break; case Configuration::AUTOGENERATE_FILE_NOT_EXISTS: if (! file_exists($fileName)) { $this->generateHydratorClass($class, $hydratorClassName, $fileName); } require $fileName; break; case Configuration::AUTOGENERATE_EVAL: $this->generateHydratorClass($class, $hydratorClassName, null); break; } } $this->hydrators[$className] = new $fqn($this->dm, $this->unitOfWork, $class); return $this->hydrators[$className]; }
php
public function getHydratorFor(string $className) : HydratorInterface { if (isset($this->hydrators[$className])) { return $this->hydrators[$className]; } $hydratorClassName = str_replace('\\', '', $className) . 'Hydrator'; $fqn = $this->hydratorNamespace . '\\' . $hydratorClassName; $class = $this->dm->getClassMetadata($className); if (! class_exists($fqn, false)) { $fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php'; switch ($this->autoGenerate) { case Configuration::AUTOGENERATE_NEVER: require $fileName; break; case Configuration::AUTOGENERATE_ALWAYS: $this->generateHydratorClass($class, $hydratorClassName, $fileName); require $fileName; break; case Configuration::AUTOGENERATE_FILE_NOT_EXISTS: if (! file_exists($fileName)) { $this->generateHydratorClass($class, $hydratorClassName, $fileName); } require $fileName; break; case Configuration::AUTOGENERATE_EVAL: $this->generateHydratorClass($class, $hydratorClassName, null); break; } } $this->hydrators[$className] = new $fqn($this->dm, $this->unitOfWork, $class); return $this->hydrators[$className]; }
[ "public", "function", "getHydratorFor", "(", "string", "$", "className", ")", ":", "HydratorInterface", "{", "if", "(", "isset", "(", "$", "this", "->", "hydrators", "[", "$", "className", "]", ")", ")", "{", "return", "$", "this", "->", "hydrators", "[", "$", "className", "]", ";", "}", "$", "hydratorClassName", "=", "str_replace", "(", "'\\\\'", ",", "''", ",", "$", "className", ")", ".", "'Hydrator'", ";", "$", "fqn", "=", "$", "this", "->", "hydratorNamespace", ".", "'\\\\'", ".", "$", "hydratorClassName", ";", "$", "class", "=", "$", "this", "->", "dm", "->", "getClassMetadata", "(", "$", "className", ")", ";", "if", "(", "!", "class_exists", "(", "$", "fqn", ",", "false", ")", ")", "{", "$", "fileName", "=", "$", "this", "->", "hydratorDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "hydratorClassName", ".", "'.php'", ";", "switch", "(", "$", "this", "->", "autoGenerate", ")", "{", "case", "Configuration", "::", "AUTOGENERATE_NEVER", ":", "require", "$", "fileName", ";", "break", ";", "case", "Configuration", "::", "AUTOGENERATE_ALWAYS", ":", "$", "this", "->", "generateHydratorClass", "(", "$", "class", ",", "$", "hydratorClassName", ",", "$", "fileName", ")", ";", "require", "$", "fileName", ";", "break", ";", "case", "Configuration", "::", "AUTOGENERATE_FILE_NOT_EXISTS", ":", "if", "(", "!", "file_exists", "(", "$", "fileName", ")", ")", "{", "$", "this", "->", "generateHydratorClass", "(", "$", "class", ",", "$", "hydratorClassName", ",", "$", "fileName", ")", ";", "}", "require", "$", "fileName", ";", "break", ";", "case", "Configuration", "::", "AUTOGENERATE_EVAL", ":", "$", "this", "->", "generateHydratorClass", "(", "$", "class", ",", "$", "hydratorClassName", ",", "null", ")", ";", "break", ";", "}", "}", "$", "this", "->", "hydrators", "[", "$", "className", "]", "=", "new", "$", "fqn", "(", "$", "this", "->", "dm", ",", "$", "this", "->", "unitOfWork", ",", "$", "class", ")", ";", "return", "$", "this", "->", "hydrators", "[", "$", "className", "]", ";", "}" ]
Gets the hydrator object for the given document class.
[ "Gets", "the", "hydrator", "object", "for", "the", "given", "document", "class", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php#L121-L156
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php
HydratorFactory.generateHydratorClasses
public function generateHydratorClasses(array $classes, ?string $toDir = null) : void { $hydratorDir = $toDir ?: $this->hydratorDir; $hydratorDir = rtrim($hydratorDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; foreach ($classes as $class) { $hydratorClassName = str_replace('\\', '', $class->name) . 'Hydrator'; $hydratorFileName = $hydratorDir . $hydratorClassName . '.php'; $this->generateHydratorClass($class, $hydratorClassName, $hydratorFileName); } }
php
public function generateHydratorClasses(array $classes, ?string $toDir = null) : void { $hydratorDir = $toDir ?: $this->hydratorDir; $hydratorDir = rtrim($hydratorDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; foreach ($classes as $class) { $hydratorClassName = str_replace('\\', '', $class->name) . 'Hydrator'; $hydratorFileName = $hydratorDir . $hydratorClassName . '.php'; $this->generateHydratorClass($class, $hydratorClassName, $hydratorFileName); } }
[ "public", "function", "generateHydratorClasses", "(", "array", "$", "classes", ",", "?", "string", "$", "toDir", "=", "null", ")", ":", "void", "{", "$", "hydratorDir", "=", "$", "toDir", "?", ":", "$", "this", "->", "hydratorDir", ";", "$", "hydratorDir", "=", "rtrim", "(", "$", "hydratorDir", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ";", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "$", "hydratorClassName", "=", "str_replace", "(", "'\\\\'", ",", "''", ",", "$", "class", "->", "name", ")", ".", "'Hydrator'", ";", "$", "hydratorFileName", "=", "$", "hydratorDir", ".", "$", "hydratorClassName", ".", "'.php'", ";", "$", "this", "->", "generateHydratorClass", "(", "$", "class", ",", "$", "hydratorClassName", ",", "$", "hydratorFileName", ")", ";", "}", "}" ]
Generates hydrator classes for all given classes. @param array $classes The classes (ClassMetadata instances) for which to generate hydrators. @param string $toDir The target directory of the hydrator classes. If not specified, the directory configured on the Configuration of the DocumentManager used by this factory is used.
[ "Generates", "hydrator", "classes", "for", "all", "given", "classes", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php#L166-L175
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php
CollectionHelper.isAtomic
public static function isAtomic(string $strategy) : bool { return $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET || $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY; }
php
public static function isAtomic(string $strategy) : bool { return $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET || $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY; }
[ "public", "static", "function", "isAtomic", "(", "string", "$", "strategy", ")", ":", "bool", "{", "return", "$", "strategy", "===", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET", "||", "$", "strategy", "===", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET_ARRAY", ";", "}" ]
Returns whether update query must be included in query updating owning document.
[ "Returns", "whether", "update", "query", "must", "be", "included", "in", "query", "updating", "owning", "document", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php#L22-L25
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php
CollectionHelper.isHash
public static function isHash(string $strategy) : bool { return $strategy === ClassMetadata::STORAGE_STRATEGY_SET || $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET; }
php
public static function isHash(string $strategy) : bool { return $strategy === ClassMetadata::STORAGE_STRATEGY_SET || $strategy === ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET; }
[ "public", "static", "function", "isHash", "(", "string", "$", "strategy", ")", ":", "bool", "{", "return", "$", "strategy", "===", "ClassMetadata", "::", "STORAGE_STRATEGY_SET", "||", "$", "strategy", "===", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET", ";", "}" ]
Returns whether Collection hold associative array.
[ "Returns", "whether", "Collection", "hold", "associative", "array", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php#L30-L33
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php
CollectionHelper.isList
public static function isList(?string $strategy) : bool { return $strategy !== ClassMetadata::STORAGE_STRATEGY_SET && $strategy !== ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET; }
php
public static function isList(?string $strategy) : bool { return $strategy !== ClassMetadata::STORAGE_STRATEGY_SET && $strategy !== ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET; }
[ "public", "static", "function", "isList", "(", "?", "string", "$", "strategy", ")", ":", "bool", "{", "return", "$", "strategy", "!==", "ClassMetadata", "::", "STORAGE_STRATEGY_SET", "&&", "$", "strategy", "!==", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET", ";", "}" ]
Returns whether Collection hold array indexed by consecutive numbers.
[ "Returns", "whether", "Collection", "hold", "array", "indexed", "by", "consecutive", "numbers", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php#L38-L41
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php
CollectionHelper.usesSet
public static function usesSet(string $strategy) : bool { return in_array( $strategy, [ ClassMetadata::STORAGE_STRATEGY_SET, ClassMetadata::STORAGE_STRATEGY_SET_ARRAY, ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET, ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY, ] ); }
php
public static function usesSet(string $strategy) : bool { return in_array( $strategy, [ ClassMetadata::STORAGE_STRATEGY_SET, ClassMetadata::STORAGE_STRATEGY_SET_ARRAY, ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET, ClassMetadata::STORAGE_STRATEGY_ATOMIC_SET_ARRAY, ] ); }
[ "public", "static", "function", "usesSet", "(", "string", "$", "strategy", ")", ":", "bool", "{", "return", "in_array", "(", "$", "strategy", ",", "[", "ClassMetadata", "::", "STORAGE_STRATEGY_SET", ",", "ClassMetadata", "::", "STORAGE_STRATEGY_SET_ARRAY", ",", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET", ",", "ClassMetadata", "::", "STORAGE_STRATEGY_ATOMIC_SET_ARRAY", ",", "]", ")", ";", "}" ]
Returns whether strategy uses $set to update its data.
[ "Returns", "whether", "strategy", "uses", "$set", "to", "update", "its", "data", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Utility/CollectionHelper.php#L46-L57
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php
Out.out
public function out(string $collection) : Stage\Out { try { $class = $this->dm->getClassMetadata($collection); } catch (BaseMappingException $e) { $this->collection = $collection; return $this; } $this->fromDocument($class); return $this; }
php
public function out(string $collection) : Stage\Out { try { $class = $this->dm->getClassMetadata($collection); } catch (BaseMappingException $e) { $this->collection = $collection; return $this; } $this->fromDocument($class); return $this; }
[ "public", "function", "out", "(", "string", "$", "collection", ")", ":", "Stage", "\\", "Out", "{", "try", "{", "$", "class", "=", "$", "this", "->", "dm", "->", "getClassMetadata", "(", "$", "collection", ")", ";", "}", "catch", "(", "BaseMappingException", "$", "e", ")", "{", "$", "this", "->", "collection", "=", "$", "collection", ";", "return", "$", "this", ";", "}", "$", "this", "->", "fromDocument", "(", "$", "class", ")", ";", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/Out.php#L43-L54
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Proxy/Factory/StaticProxyFactory.php
StaticProxyFactory.generateProxyClasses
public function generateProxyClasses(array $classes) : int { $concreteClasses = array_filter($classes, static function (ClassMetadata $metadata) : bool { return ! ($metadata->isMappedSuperclass || $metadata->isQueryResultDocument || $metadata->getReflectionClass()->isAbstract()); }); foreach ($concreteClasses as $metadata) { $this ->proxyFactory ->createProxy( $metadata->getName(), static function () { // empty closure, serves its purpose, for now }, [ 'skippedProperties' => $this->skippedFieldsFqns($metadata), ] ); } return count($concreteClasses); }
php
public function generateProxyClasses(array $classes) : int { $concreteClasses = array_filter($classes, static function (ClassMetadata $metadata) : bool { return ! ($metadata->isMappedSuperclass || $metadata->isQueryResultDocument || $metadata->getReflectionClass()->isAbstract()); }); foreach ($concreteClasses as $metadata) { $this ->proxyFactory ->createProxy( $metadata->getName(), static function () { }, [ 'skippedProperties' => $this->skippedFieldsFqns($metadata), ] ); } return count($concreteClasses); }
[ "public", "function", "generateProxyClasses", "(", "array", "$", "classes", ")", ":", "int", "{", "$", "concreteClasses", "=", "array_filter", "(", "$", "classes", ",", "static", "function", "(", "ClassMetadata", "$", "metadata", ")", ":", "bool", "{", "return", "!", "(", "$", "metadata", "->", "isMappedSuperclass", "||", "$", "metadata", "->", "isQueryResultDocument", "||", "$", "metadata", "->", "getReflectionClass", "(", ")", "->", "isAbstract", "(", ")", ")", ";", "}", ")", ";", "foreach", "(", "$", "concreteClasses", "as", "$", "metadata", ")", "{", "$", "this", "->", "proxyFactory", "->", "createProxy", "(", "$", "metadata", "->", "getName", "(", ")", ",", "static", "function", "(", ")", "{", "// empty closure, serves its purpose, for now", "}", ",", "[", "'skippedProperties'", "=>", "$", "this", "->", "skippedFieldsFqns", "(", "$", "metadata", ")", ",", "]", ")", ";", "}", "return", "count", "(", "$", "concreteClasses", ")", ";", "}" ]
{@inheritdoc} @param ClassMetadata[] $classes
[ "{", "@inheritdoc", "}" ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Proxy/Factory/StaticProxyFactory.php#L66-L87
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Aggregation/Stage/CollStats.php
CollStats.showLatencyStats
public function showLatencyStats(bool $histograms = false) : self { $this->latencyStats = $histograms ? self::LATENCY_STATS_HISTOGRAMS : self::LATENCY_STATS_SIMPLE; return $this; }
php
public function showLatencyStats(bool $histograms = false) : self { $this->latencyStats = $histograms ? self::LATENCY_STATS_HISTOGRAMS : self::LATENCY_STATS_SIMPLE; return $this; }
[ "public", "function", "showLatencyStats", "(", "bool", "$", "histograms", "=", "false", ")", ":", "self", "{", "$", "this", "->", "latencyStats", "=", "$", "histograms", "?", "self", "::", "LATENCY_STATS_HISTOGRAMS", ":", "self", "::", "LATENCY_STATS_SIMPLE", ";", "return", "$", "this", ";", "}" ]
Adds latency statistics to the return document.
[ "Adds", "latency", "statistics", "to", "the", "return", "document", "." ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/CollStats.php#L33-L38
doctrine/mongodb-odm
lib/Doctrine/ODM/MongoDB/Aggregation/Stage/CollStats.php
CollStats.getExpression
public function getExpression() : array { $collStats = []; if ($this->latencyStats !== self::LATENCY_STATS_NONE) { $collStats['latencyStats'] = ['histograms' => $this->latencyStats === self::LATENCY_STATS_HISTOGRAMS]; } if ($this->storageStats) { $collStats['storageStats'] = []; } return ['$collStats' => $collStats]; }
php
public function getExpression() : array { $collStats = []; if ($this->latencyStats !== self::LATENCY_STATS_NONE) { $collStats['latencyStats'] = ['histograms' => $this->latencyStats === self::LATENCY_STATS_HISTOGRAMS]; } if ($this->storageStats) { $collStats['storageStats'] = []; } return ['$collStats' => $collStats]; }
[ "public", "function", "getExpression", "(", ")", ":", "array", "{", "$", "collStats", "=", "[", "]", ";", "if", "(", "$", "this", "->", "latencyStats", "!==", "self", "::", "LATENCY_STATS_NONE", ")", "{", "$", "collStats", "[", "'latencyStats'", "]", "=", "[", "'histograms'", "=>", "$", "this", "->", "latencyStats", "===", "self", "::", "LATENCY_STATS_HISTOGRAMS", "]", ";", "}", "if", "(", "$", "this", "->", "storageStats", ")", "{", "$", "collStats", "[", "'storageStats'", "]", "=", "[", "]", ";", "}", "return", "[", "'$collStats'", "=>", "$", "collStats", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/doctrine/mongodb-odm/blob/e4971557a8200456d87e2f1def8bde7fb07bbb3f/lib/Doctrine/ODM/MongoDB/Aggregation/Stage/CollStats.php#L53-L65