repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
slickframework/mvc
src/Console/MetaDataGenerator/Composer.php
Composer.requestAuthor
protected function requestAuthor() { if (!empty($this->getComposerData()->authors)) { return $this->selectAuthors(); } $nameQuestion = new Question('Please enter your name: '); $emailQuestion = new Question('Please enter your e-mail address: '); $this->getOutput()->writeln(''); $this->getOutput()->writeln( '<info>Cannot determine the developer name ' . 'from project\'s composer.json file.</info>' ); $this->getOutput()->writeln( "<comment>To automatically set the developer's " . "name and e-mail and avoid entering it on every generate:* " . "commands set the authors entry on your project's " . "composer.json file.</comment>" ); $authorName = $this->getQuestionHelper()->ask( $this->getInput(), $this->getOutput(), $nameQuestion ); $authorEmail = $this->getQuestionHelper()->ask( $this->getInput(), $this->getOutput(), $emailQuestion ); return compact('authorName', 'authorEmail'); }
php
protected function requestAuthor() { if (!empty($this->getComposerData()->authors)) { return $this->selectAuthors(); } $nameQuestion = new Question('Please enter your name: '); $emailQuestion = new Question('Please enter your e-mail address: '); $this->getOutput()->writeln(''); $this->getOutput()->writeln( '<info>Cannot determine the developer name ' . 'from project\'s composer.json file.</info>' ); $this->getOutput()->writeln( "<comment>To automatically set the developer's " . "name and e-mail and avoid entering it on every generate:* " . "commands set the authors entry on your project's " . "composer.json file.</comment>" ); $authorName = $this->getQuestionHelper()->ask( $this->getInput(), $this->getOutput(), $nameQuestion ); $authorEmail = $this->getQuestionHelper()->ask( $this->getInput(), $this->getOutput(), $emailQuestion ); return compact('authorName', 'authorEmail'); }
[ "protected", "function", "requestAuthor", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "getComposerData", "(", ")", "->", "authors", ")", ")", "{", "return", "$", "this", "->", "selectAuthors", "(", ")", ";", "}", "$", "nameQuestion"...
Asks the author name and e-mail and returns them @return array
[ "Asks", "the", "author", "name", "and", "e", "-", "mail", "and", "returns", "them" ]
91a6c512f8aaa5a7fb9c1a96f8012d2274dc30ab
https://github.com/slickframework/mvc/blob/91a6c512f8aaa5a7fb9c1a96f8012d2274dc30ab/src/Console/MetaDataGenerator/Composer.php#L161-L191
train
slickframework/mvc
src/Console/MetaDataGenerator/Composer.php
Composer.selectAuthors
protected function selectAuthors() { $options = $this->getAuthorsAsOptions(); $this->getOutput()->writeln(''); $this->getOutput()->writeln( '<info>Multiple authors found on ' . 'project\'s composer.json file.</info>' ); $question = new ChoiceQuestion( 'Please select the author from the list above:', $options, 0 ); $question->setErrorMessage('The choice %s is invalid.'); $selected = $this->getQuestionHelper() ->ask($this->input, $this->output, $question); $parts = explode('<', $selected); return [ 'authorName' => trim($parts[0]), 'authorEmail' => trim($parts[1], '>'), ]; }
php
protected function selectAuthors() { $options = $this->getAuthorsAsOptions(); $this->getOutput()->writeln(''); $this->getOutput()->writeln( '<info>Multiple authors found on ' . 'project\'s composer.json file.</info>' ); $question = new ChoiceQuestion( 'Please select the author from the list above:', $options, 0 ); $question->setErrorMessage('The choice %s is invalid.'); $selected = $this->getQuestionHelper() ->ask($this->input, $this->output, $question); $parts = explode('<', $selected); return [ 'authorName' => trim($parts[0]), 'authorEmail' => trim($parts[1], '>'), ]; }
[ "protected", "function", "selectAuthors", "(", ")", "{", "$", "options", "=", "$", "this", "->", "getAuthorsAsOptions", "(", ")", ";", "$", "this", "->", "getOutput", "(", ")", "->", "writeln", "(", "''", ")", ";", "$", "this", "->", "getOutput", "(", ...
Requests user to select author form a list of composer authors and returns them. @return array
[ "Requests", "user", "to", "select", "author", "form", "a", "list", "of", "composer", "authors", "and", "returns", "them", "." ]
91a6c512f8aaa5a7fb9c1a96f8012d2274dc30ab
https://github.com/slickframework/mvc/blob/91a6c512f8aaa5a7fb9c1a96f8012d2274dc30ab/src/Console/MetaDataGenerator/Composer.php#L199-L220
train
treffynnon/command-wrap
src/Runners/Passthru.php
Passthru.run
public function run(RunnableInterface $command, callable $func = null) { if ($func) { throw new \Exception('You cannot process passthru with a callable. Use another Runner instead.'); } $command = (string) $command->getCommandAssembler(); passthru($command, $status); return $this->getResponseClass($command, $status, ''); }
php
public function run(RunnableInterface $command, callable $func = null) { if ($func) { throw new \Exception('You cannot process passthru with a callable. Use another Runner instead.'); } $command = (string) $command->getCommandAssembler(); passthru($command, $status); return $this->getResponseClass($command, $status, ''); }
[ "public", "function", "run", "(", "RunnableInterface", "$", "command", ",", "callable", "$", "func", "=", "null", ")", "{", "if", "(", "$", "func", ")", "{", "throw", "new", "\\", "Exception", "(", "'You cannot process passthru with a callable. Use another Runner ...
Passes through result of the command so no output is set @link http://php.net/passthru @param RunnableInterface $command
[ "Passes", "through", "result", "of", "the", "command", "so", "no", "output", "is", "set" ]
381f1a7d1bd76e2b7d0898f51e3dd5caffbf5e4b
https://github.com/treffynnon/command-wrap/blob/381f1a7d1bd76e2b7d0898f51e3dd5caffbf5e4b/src/Runners/Passthru.php#L15-L24
train
InnoGr/FivePercent-Api
src/Server/JsonRpc/JsonRpcServer.php
JsonRpcServer.processApiMethod
private function processApiMethod(SfRequest $request) { // Try parse JSON $content = $request->getContent(); if (!$content) { throw new MissingHttpContentException('Missing HTTP content.'); } $query = @json_decode($content, true); if (false === $query) { throw JsonParseException::create(json_last_error()); } return $this->processApiQuery($query); }
php
private function processApiMethod(SfRequest $request) { // Try parse JSON $content = $request->getContent(); if (!$content) { throw new MissingHttpContentException('Missing HTTP content.'); } $query = @json_decode($content, true); if (false === $query) { throw JsonParseException::create(json_last_error()); } return $this->processApiQuery($query); }
[ "private", "function", "processApiMethod", "(", "SfRequest", "$", "request", ")", "{", "// Try parse JSON", "$", "content", "=", "$", "request", "->", "getContent", "(", ")", ";", "if", "(", "!", "$", "content", ")", "{", "throw", "new", "MissingHttpContentE...
Process API method @param SfRequest $request @return JsonResponse @throws \Exception
[ "Process", "API", "method" ]
57b78ddc3c9d91a7139c276711e5792824ceab9c
https://github.com/InnoGr/FivePercent-Api/blob/57b78ddc3c9d91a7139c276711e5792824ceab9c/src/Server/JsonRpc/JsonRpcServer.php#L200-L216
train
InnoGr/FivePercent-Api
src/Server/JsonRpc/JsonRpcServer.php
JsonRpcServer.processApiQuery
private function processApiQuery(array $query) { $query += array( 'params' => array(), 'id' => null ); if (empty($query['method'])) { throw new MissingMethodException('Missing "method" parameter in query.'); } if ($query['id'] !== null && !is_scalar($query['id'])) { throw new InvalidIdException('The "id" parameter must be a scalar.'); } if (!is_scalar($query['method'])) { throw new InvalidMethodException('The "method" parameter must be a scalar.'); } if (!is_array($query['params'])) { throw new InvalidParametersException('Input parameters must be a array.'); } $this->requestId = $query['id']; $apiResponse = $this->handler->handle($query['method'], $query['params']); if ($apiResponse instanceof EmptyResponseInterface) { if ($apiResponse instanceof ResponseInterface) { return new SfResponse('', $apiResponse->getHttpStatusCode(), $apiResponse->getHeaders()->all()); } else { return new SfResponse(''); } } $data = array( 'jsonrpc' => self::JSON_RPC_VERSION, 'result' => $apiResponse->getData(), 'id' => $query['id'] ); return new JsonResponse($data, $apiResponse->getHttpStatusCode(), $apiResponse->getHeaders()->all()); }
php
private function processApiQuery(array $query) { $query += array( 'params' => array(), 'id' => null ); if (empty($query['method'])) { throw new MissingMethodException('Missing "method" parameter in query.'); } if ($query['id'] !== null && !is_scalar($query['id'])) { throw new InvalidIdException('The "id" parameter must be a scalar.'); } if (!is_scalar($query['method'])) { throw new InvalidMethodException('The "method" parameter must be a scalar.'); } if (!is_array($query['params'])) { throw new InvalidParametersException('Input parameters must be a array.'); } $this->requestId = $query['id']; $apiResponse = $this->handler->handle($query['method'], $query['params']); if ($apiResponse instanceof EmptyResponseInterface) { if ($apiResponse instanceof ResponseInterface) { return new SfResponse('', $apiResponse->getHttpStatusCode(), $apiResponse->getHeaders()->all()); } else { return new SfResponse(''); } } $data = array( 'jsonrpc' => self::JSON_RPC_VERSION, 'result' => $apiResponse->getData(), 'id' => $query['id'] ); return new JsonResponse($data, $apiResponse->getHttpStatusCode(), $apiResponse->getHeaders()->all()); }
[ "private", "function", "processApiQuery", "(", "array", "$", "query", ")", "{", "$", "query", "+=", "array", "(", "'params'", "=>", "array", "(", ")", ",", "'id'", "=>", "null", ")", ";", "if", "(", "empty", "(", "$", "query", "[", "'method'", "]", ...
Process api query @param array $query @return JsonResponse @throws \Exception
[ "Process", "api", "query" ]
57b78ddc3c9d91a7139c276711e5792824ceab9c
https://github.com/InnoGr/FivePercent-Api/blob/57b78ddc3c9d91a7139c276711e5792824ceab9c/src/Server/JsonRpc/JsonRpcServer.php#L227-L269
train
InnoGr/FivePercent-Api
src/Server/JsonRpc/JsonRpcServer.php
JsonRpcServer.createErrorResponse
private function createErrorResponse($code, $message = null, array $data = []) { if (!$message) { $messages = $this->handler->getErrors()->getErrors(); $message = isset($messages[$code]) ? $messages[$code] : 'Error'; } $json = [ 'jsonrpc' => self::JSON_RPC_VERSION, 'error' => [ 'code' => $code, 'message' => $message ], 'id' => $this->requestId ]; if ($data) { $json['error']['data'] = $data; } return new JsonResponse($json, 200); }
php
private function createErrorResponse($code, $message = null, array $data = []) { if (!$message) { $messages = $this->handler->getErrors()->getErrors(); $message = isset($messages[$code]) ? $messages[$code] : 'Error'; } $json = [ 'jsonrpc' => self::JSON_RPC_VERSION, 'error' => [ 'code' => $code, 'message' => $message ], 'id' => $this->requestId ]; if ($data) { $json['error']['data'] = $data; } return new JsonResponse($json, 200); }
[ "private", "function", "createErrorResponse", "(", "$", "code", ",", "$", "message", "=", "null", ",", "array", "$", "data", "=", "[", "]", ")", "{", "if", "(", "!", "$", "message", ")", "{", "$", "messages", "=", "$", "this", "->", "handler", "->"...
Create error response @param integer $code @param string $message @param array $data @return JsonResponse
[ "Create", "error", "response" ]
57b78ddc3c9d91a7139c276711e5792824ceab9c
https://github.com/InnoGr/FivePercent-Api/blob/57b78ddc3c9d91a7139c276711e5792824ceab9c/src/Server/JsonRpc/JsonRpcServer.php#L280-L301
train
InnoGr/FivePercent-Api
src/Server/JsonRpc/JsonRpcServer.php
JsonRpcServer.createViolationErrorResponse
public function createViolationErrorResponse(ViolationListException $exception) { $errorData = []; /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */ foreach ($exception->getViolationList() as $violation) { $errorData[$violation->getPropertyPath()] = $violation->getMessage(); } // Try get code from errors storage via exception $errors = $this->handler->getErrors(); $code = $errors->hasException($exception) ? $errors->getExceptionCode($exception) : 0; return $this->createErrorResponse($code, null, $errorData); }
php
public function createViolationErrorResponse(ViolationListException $exception) { $errorData = []; /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */ foreach ($exception->getViolationList() as $violation) { $errorData[$violation->getPropertyPath()] = $violation->getMessage(); } // Try get code from errors storage via exception $errors = $this->handler->getErrors(); $code = $errors->hasException($exception) ? $errors->getExceptionCode($exception) : 0; return $this->createErrorResponse($code, null, $errorData); }
[ "public", "function", "createViolationErrorResponse", "(", "ViolationListException", "$", "exception", ")", "{", "$", "errorData", "=", "[", "]", ";", "/** @var \\Symfony\\Component\\Validator\\ConstraintViolationInterface $violation */", "foreach", "(", "$", "exception", "->...
Create violation error response @param ViolationListException $exception @return JsonResponse
[ "Create", "violation", "error", "response" ]
57b78ddc3c9d91a7139c276711e5792824ceab9c
https://github.com/InnoGr/FivePercent-Api/blob/57b78ddc3c9d91a7139c276711e5792824ceab9c/src/Server/JsonRpc/JsonRpcServer.php#L310-L324
train
mpoiriert/draw-test-helper-bundle
Helper/RequestHelper.php
RequestHelper.head
public function head($uri = null, $expectedStatus = null) { $this->setMethod('HEAD'); $this->setUri($uri); if (!is_null($expectedStatus)) { $this->expectingStatusCode($expectedStatus); } return $this; }
php
public function head($uri = null, $expectedStatus = null) { $this->setMethod('HEAD'); $this->setUri($uri); if (!is_null($expectedStatus)) { $this->expectingStatusCode($expectedStatus); } return $this; }
[ "public", "function", "head", "(", "$", "uri", "=", "null", ",", "$", "expectedStatus", "=", "null", ")", "{", "$", "this", "->", "setMethod", "(", "'HEAD'", ")", ";", "$", "this", "->", "setUri", "(", "$", "uri", ")", ";", "if", "(", "!", "is_nu...
Set the HTTP method to HEAD and the uri if any. Return $this for a fluent interface. @param string|null $uri @param integer|null $expectedStatus @return $this
[ "Set", "the", "HTTP", "method", "to", "HEAD", "and", "the", "uri", "if", "any", "." ]
cd8bb9cb38f2ee0b333ba1a68152fb20d7d70889
https://github.com/mpoiriert/draw-test-helper-bundle/blob/cd8bb9cb38f2ee0b333ba1a68152fb20d7d70889/Helper/RequestHelper.php#L180-L189
train
agentmedia/phine-news
src/News/Modules/Backend/ArticleList.php
ArticleList.InitCategoryArticles
private function InitCategoryArticles() { $tblArticle = Article::Schema()->Table(); $sql = Access::SqlBuilder(); $orderBy = $sql->OrderList($sql->OrderDesc($tblArticle->Field('Created'))); $this->articles = Article::Schema()->FetchByCategory(false, $this->category, $orderBy, null, $this->ArticleOffset(), $this->perPage); $this->articlesTotal = Article::Schema()->CountByCategory(false, $this->category); }
php
private function InitCategoryArticles() { $tblArticle = Article::Schema()->Table(); $sql = Access::SqlBuilder(); $orderBy = $sql->OrderList($sql->OrderDesc($tblArticle->Field('Created'))); $this->articles = Article::Schema()->FetchByCategory(false, $this->category, $orderBy, null, $this->ArticleOffset(), $this->perPage); $this->articlesTotal = Article::Schema()->CountByCategory(false, $this->category); }
[ "private", "function", "InitCategoryArticles", "(", ")", "{", "$", "tblArticle", "=", "Article", "::", "Schema", "(", ")", "->", "Table", "(", ")", ";", "$", "sql", "=", "Access", "::", "SqlBuilder", "(", ")", ";", "$", "orderBy", "=", "$", "sql", "-...
Initializes the article array by category
[ "Initializes", "the", "article", "array", "by", "category" ]
51abc830fecd1325f0b7d28391ecd924cdc7c945
https://github.com/agentmedia/phine-news/blob/51abc830fecd1325f0b7d28391ecd924cdc7c945/src/News/Modules/Backend/ArticleList.php#L101-L108
train
agentmedia/phine-news
src/News/Modules/Backend/ArticleList.php
ArticleList.RemovalObject
protected function RemovalObject() { $id = Request::PostData('delete'); return $id ? Article::Schema()->ByID($id) : null; }
php
protected function RemovalObject() { $id = Request::PostData('delete'); return $id ? Article::Schema()->ByID($id) : null; }
[ "protected", "function", "RemovalObject", "(", ")", "{", "$", "id", "=", "Request", "::", "PostData", "(", "'delete'", ")", ";", "return", "$", "id", "?", "Article", "::", "Schema", "(", ")", "->", "ByID", "(", "$", "id", ")", ":", "null", ";", "}"...
Gets the object to remove in case there is any @return Article Returns the article to remove or null if none is requested
[ "Gets", "the", "object", "to", "remove", "in", "case", "there", "is", "any" ]
51abc830fecd1325f0b7d28391ecd924cdc7c945
https://github.com/agentmedia/phine-news/blob/51abc830fecd1325f0b7d28391ecd924cdc7c945/src/News/Modules/Backend/ArticleList.php#L124-L128
train
agentmedia/phine-news
src/News/Modules/Backend/ArticleList.php
ArticleList.BackLink
protected function BackLink() { if ($this->category) { return BackendRouter::ModuleUrl(new CategoryList(), array('archive'=>$this->archive->GetID())); } else { return BackendRouter::ModuleUrl(new ArchiveList()); } }
php
protected function BackLink() { if ($this->category) { return BackendRouter::ModuleUrl(new CategoryList(), array('archive'=>$this->archive->GetID())); } else { return BackendRouter::ModuleUrl(new ArchiveList()); } }
[ "protected", "function", "BackLink", "(", ")", "{", "if", "(", "$", "this", "->", "category", ")", "{", "return", "BackendRouter", "::", "ModuleUrl", "(", "new", "CategoryList", "(", ")", ",", "array", "(", "'archive'", "=>", "$", "this", "->", "archive"...
The backlink; either links to the category list or the archive list @return string Returns the link for the back button
[ "The", "backlink", ";", "either", "links", "to", "the", "category", "list", "or", "the", "archive", "list" ]
51abc830fecd1325f0b7d28391ecd924cdc7c945
https://github.com/agentmedia/phine-news/blob/51abc830fecd1325f0b7d28391ecd924cdc7c945/src/News/Modules/Backend/ArticleList.php#L134-L142
train
mszewcz/php-light-framework
src/Filesystem/AbstractFilesystem.php
AbstractFilesystem.setNewDirectoryMode
public static function setNewDirectoryMode(string $mode = '740'): void { static::init(); static::$newDirectoryMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
php
public static function setNewDirectoryMode(string $mode = '740'): void { static::init(); static::$newDirectoryMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
[ "public", "static", "function", "setNewDirectoryMode", "(", "string", "$", "mode", "=", "'740'", ")", ":", "void", "{", "static", "::", "init", "(", ")", ";", "static", "::", "$", "newDirectoryMode", "=", "\\", "preg_match", "(", "'/^[0-7]{3}$/'", ",", "$"...
Sets default mode for newly created directories @param string $mode
[ "Sets", "default", "mode", "for", "newly", "created", "directories" ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Filesystem/AbstractFilesystem.php#L91-L95
train
mszewcz/php-light-framework
src/Filesystem/AbstractFilesystem.php
AbstractFilesystem.setNewFileMode
public static function setNewFileMode(string $mode = '740'): void { static::init(); static::$newFileMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
php
public static function setNewFileMode(string $mode = '740'): void { static::init(); static::$newFileMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
[ "public", "static", "function", "setNewFileMode", "(", "string", "$", "mode", "=", "'740'", ")", ":", "void", "{", "static", "::", "init", "(", ")", ";", "static", "::", "$", "newFileMode", "=", "\\", "preg_match", "(", "'/^[0-7]{3}$/'", ",", "$", "mode"...
Sets default mode for newly created files @param string $mode
[ "Sets", "default", "mode", "for", "newly", "created", "files" ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Filesystem/AbstractFilesystem.php#L113-L117
train
mszewcz/php-light-framework
src/Filesystem/AbstractFilesystem.php
AbstractFilesystem.setNewSymbolicLinkMode
public static function setNewSymbolicLinkMode(string $mode = '740'): void { static::init(); static::$newSymlinkMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
php
public static function setNewSymbolicLinkMode(string $mode = '740'): void { static::init(); static::$newSymlinkMode = \preg_match('/^[0-7]{3}$/', $mode) ? \intval($mode, 8) : 0740; }
[ "public", "static", "function", "setNewSymbolicLinkMode", "(", "string", "$", "mode", "=", "'740'", ")", ":", "void", "{", "static", "::", "init", "(", ")", ";", "static", "::", "$", "newSymlinkMode", "=", "\\", "preg_match", "(", "'/^[0-7]{3}$/'", ",", "$...
Sets default mode for newly created symbolic links @param string $mode
[ "Sets", "default", "mode", "for", "newly", "created", "symbolic", "links" ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Filesystem/AbstractFilesystem.php#L135-L139
train
unyx/console
output/formatting/Formatter.php
Formatter.createDefaultStyles
protected function createDefaultStyles() : styles\Map { return new styles\Map([ 'error' => new Style('white', 'red'), 'info' => new Style('green'), 'comment' => new Style('cyan'), 'important' => new Style('red'), 'header' => new Style('black', 'cyan') ]); }
php
protected function createDefaultStyles() : styles\Map { return new styles\Map([ 'error' => new Style('white', 'red'), 'info' => new Style('green'), 'comment' => new Style('cyan'), 'important' => new Style('red'), 'header' => new Style('black', 'cyan') ]); }
[ "protected", "function", "createDefaultStyles", "(", ")", ":", "styles", "\\", "Map", "{", "return", "new", "styles", "\\", "Map", "(", "[", "'error'", "=>", "new", "Style", "(", "'white'", ",", "'red'", ")", ",", "'info'", "=>", "new", "Style", "(", "...
Creates a default Map of Styles to be used by this Formatter. @return styles\Map
[ "Creates", "a", "default", "Map", "of", "Styles", "to", "be", "used", "by", "this", "Formatter", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/output/formatting/Formatter.php#L129-L138
train
unyx/console
output/formatting/Formatter.php
Formatter.apply
protected function apply(string $text, bool $decorated) : string { return $decorated && !empty($text) ? $this->stack->current()->apply($text) : $text; }
php
protected function apply(string $text, bool $decorated) : string { return $decorated && !empty($text) ? $this->stack->current()->apply($text) : $text; }
[ "protected", "function", "apply", "(", "string", "$", "text", ",", "bool", "$", "decorated", ")", ":", "string", "{", "return", "$", "decorated", "&&", "!", "empty", "(", "$", "text", ")", "?", "$", "this", "->", "stack", "->", "current", "(", ")", ...
Applies formatting to the given text. @param string $text The text that should be formatted. @param bool $decorated Whether decorations, like colors, should be applied to the text. @return string The resulting text.
[ "Applies", "formatting", "to", "the", "given", "text", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/output/formatting/Formatter.php#L172-L175
train
crip-laravel/core
src/Data/Model.php
Model.scopeOrder
public function scopeOrder($query) { $order = Input::get('order', isset($this->order) ? $this->order : 'id') ?: 'id'; $direction = Input::get('direction', isset($this->direction) ? $this->direction : 'desc') ?: 'desc'; return $query->orderBy($order, $direction); }
php
public function scopeOrder($query) { $order = Input::get('order', isset($this->order) ? $this->order : 'id') ?: 'id'; $direction = Input::get('direction', isset($this->direction) ? $this->direction : 'desc') ?: 'desc'; return $query->orderBy($order, $direction); }
[ "public", "function", "scopeOrder", "(", "$", "query", ")", "{", "$", "order", "=", "Input", "::", "get", "(", "'order'", ",", "isset", "(", "$", "this", "->", "order", ")", "?", "$", "this", "->", "order", ":", "'id'", ")", "?", ":", "'id'", ";"...
Scope a query to order by query properties @param $query @return Builder
[ "Scope", "a", "query", "to", "order", "by", "query", "properties" ]
d58cef97d97fba8b01bec33801452ecbd7c992de
https://github.com/crip-laravel/core/blob/d58cef97d97fba8b01bec33801452ecbd7c992de/src/Data/Model.php#L21-L27
train
eloquent/schemer
src/Eloquent/Schemer/Uri/HttpUri.php
HttpUri.parseUserInfo
protected function parseUserInfo() { // No user information? we're done if (null === $this->userInfo) { return; } // If no ':' separator, we only have a username if (false === strpos($this->userInfo, ':')) { $this->setUser($this->userInfo); return; } // Split on the ':', and set both user and password list($user, $password) = explode(':', $this->userInfo, 2); $this->setUser($user); $this->setPassword($password); }
php
protected function parseUserInfo() { // No user information? we're done if (null === $this->userInfo) { return; } // If no ':' separator, we only have a username if (false === strpos($this->userInfo, ':')) { $this->setUser($this->userInfo); return; } // Split on the ':', and set both user and password list($user, $password) = explode(':', $this->userInfo, 2); $this->setUser($user); $this->setPassword($password); }
[ "protected", "function", "parseUserInfo", "(", ")", "{", "// No user information? we're done", "if", "(", "null", "===", "$", "this", "->", "userInfo", ")", "{", "return", ";", "}", "// If no ':' separator, we only have a username", "if", "(", "false", "===", "strpo...
Parse the user info into username and password segments Parses the user information into username and password segments, and then sets the appropriate values. @return void
[ "Parse", "the", "user", "info", "into", "username", "and", "password", "segments" ]
951fb321d1f50f5d2e905620fbe3b4a6f816b4b3
https://github.com/eloquent/schemer/blob/951fb321d1f50f5d2e905620fbe3b4a6f816b4b3/src/Eloquent/Schemer/Uri/HttpUri.php#L144-L162
train
eloquent/schemer
src/Eloquent/Schemer/Uri/HttpUri.php
HttpUri.getPort
public function getPort() { if (empty($this->port)) { if (array_key_exists($this->scheme, static::$defaultPorts)) { return static::$defaultPorts[$this->scheme]; } } return $this->port; }
php
public function getPort() { if (empty($this->port)) { if (array_key_exists($this->scheme, static::$defaultPorts)) { return static::$defaultPorts[$this->scheme]; } } return $this->port; }
[ "public", "function", "getPort", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "port", ")", ")", "{", "if", "(", "array_key_exists", "(", "$", "this", "->", "scheme", ",", "static", "::", "$", "defaultPorts", ")", ")", "{", "return", "...
Return the URI port If no port is set, will return the default port according to the scheme @return integer
[ "Return", "the", "URI", "port" ]
951fb321d1f50f5d2e905620fbe3b4a6f816b4b3
https://github.com/eloquent/schemer/blob/951fb321d1f50f5d2e905620fbe3b4a6f816b4b3/src/Eloquent/Schemer/Uri/HttpUri.php#L171-L180
train
eloquent/schemer
src/Eloquent/Schemer/Uri/HttpUri.php
HttpUri.parse
public function parse($uri) { parent::parse($uri); if (empty($this->path)) { $this->path = '/'; } return $this; }
php
public function parse($uri) { parent::parse($uri); if (empty($this->path)) { $this->path = '/'; } return $this; }
[ "public", "function", "parse", "(", "$", "uri", ")", "{", "parent", "::", "parse", "(", "$", "uri", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "path", ")", ")", "{", "$", "this", "->", "path", "=", "'/'", ";", "}", "return", "$", "...
Parse a URI string @param string $uri @return Http
[ "Parse", "a", "URI", "string" ]
951fb321d1f50f5d2e905620fbe3b4a6f816b4b3
https://github.com/eloquent/schemer/blob/951fb321d1f50f5d2e905620fbe3b4a6f816b4b3/src/Eloquent/Schemer/Uri/HttpUri.php#L188-L197
train
asbsoft/yii2-common_2_170212
helpers/EditorContentHelper.php
EditorContentHelper.beforeSaveBody
public static function beforeSaveBody($text) { static::correctParams(); $webfilesSubdir = static::$webfilesSubdir; $webfilesSubdirOld = static::$webfilesSubdirOld; $baseUrl = Yii::$app->urlManager->getBaseUrl(); $trTable = [ "src=\"{$baseUrl}/{$webfilesSubdirOld}" => "src=\"@{$webfilesSubdir}", //!! old -> new "src=\"{$baseUrl}/{$webfilesSubdir}" => "src=\"@{$webfilesSubdir}", //...todo add useful here... ]; $text = strtr($text, $trTable); return $text; }
php
public static function beforeSaveBody($text) { static::correctParams(); $webfilesSubdir = static::$webfilesSubdir; $webfilesSubdirOld = static::$webfilesSubdirOld; $baseUrl = Yii::$app->urlManager->getBaseUrl(); $trTable = [ "src=\"{$baseUrl}/{$webfilesSubdirOld}" => "src=\"@{$webfilesSubdir}", //!! old -> new "src=\"{$baseUrl}/{$webfilesSubdir}" => "src=\"@{$webfilesSubdir}", //...todo add useful here... ]; $text = strtr($text, $trTable); return $text; }
[ "public", "static", "function", "beforeSaveBody", "(", "$", "text", ")", "{", "static", "::", "correctParams", "(", ")", ";", "$", "webfilesSubdir", "=", "static", "::", "$", "webfilesSubdir", ";", "$", "webfilesSubdirOld", "=", "static", "::", "$", "webfile...
Prepare text to save after visual editor. @param string $text @return string
[ "Prepare", "text", "to", "save", "after", "visual", "editor", "." ]
6c58012ff89225d7d4e42b200cf39e009e9d9dac
https://github.com/asbsoft/yii2-common_2_170212/blob/6c58012ff89225d7d4e42b200cf39e009e9d9dac/helpers/EditorContentHelper.php#L35-L51
train
asbsoft/yii2-common_2_170212
helpers/EditorContentHelper.php
EditorContentHelper.uploadUrl
public static function uploadUrl($path = '', $uploadsAlias = '@uploads', $webfilesurlAlias = 'uploads') { $path = str_replace('\\', '/', $path); $webroot = str_replace('\\', '/', Yii::getAlias('@webroot')); $uploads = str_replace('\\', '/', Yii::getAlias($uploadsAlias)); //$subdir = str_replace($webroot, '', $uploads); // work correct only if uploads path is insite web root $subdir = str_replace($uploads, '', $path); $web = Yii::getAlias('@web'); $files = Yii::getAlias($webfilesurlAlias); $result = $web . (empty($web) ? '' : '/' ) . $files . $subdir; return $result; }
php
public static function uploadUrl($path = '', $uploadsAlias = '@uploads', $webfilesurlAlias = 'uploads') { $path = str_replace('\\', '/', $path); $webroot = str_replace('\\', '/', Yii::getAlias('@webroot')); $uploads = str_replace('\\', '/', Yii::getAlias($uploadsAlias)); //$subdir = str_replace($webroot, '', $uploads); // work correct only if uploads path is insite web root $subdir = str_replace($uploads, '', $path); $web = Yii::getAlias('@web'); $files = Yii::getAlias($webfilesurlAlias); $result = $web . (empty($web) ? '' : '/' ) . $files . $subdir; return $result; }
[ "public", "static", "function", "uploadUrl", "(", "$", "path", "=", "''", ",", "$", "uploadsAlias", "=", "'@uploads'", ",", "$", "webfilesurlAlias", "=", "'uploads'", ")", "{", "$", "path", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "path",...
Convert upload path to web URL. Work only if alias @uploads is subdir of alias @webroot. @param string $path @param string $uploadsAlias alias for uploads path in filesystem (non-standard for Yii2) @param string $webfilesurlAlias alias/subdir - path from webroot to uploads directory @return string
[ "Convert", "upload", "path", "to", "web", "URL", ".", "Work", "only", "if", "alias" ]
6c58012ff89225d7d4e42b200cf39e009e9d9dac
https://github.com/asbsoft/yii2-common_2_170212/blob/6c58012ff89225d7d4e42b200cf39e009e9d9dac/helpers/EditorContentHelper.php#L84-L98
train
kambo-1st/HttpMessage
src/Factories/Environment/Superglobal/UriFactory.php
UriFactory.create
public function create(Environment $environment) { $scheme = $environment->getRequestScheme(); $host = $environment->getHost(); $port = $environment->getPort(); $query = $environment->getQueryString(); $user = $environment->getAuthUser(); $pass = $environment->getAuthPassword(); // parse_url() requires a full URL - but only URL path is need it here. $path = parse_url('http://example.com' . $environment->getRequestUri(), PHP_URL_PATH); if ($path === false) { throw new InvalidArgumentException('Uri path must be a string'); } return new Uri($scheme, $host, $port, $path, $query, '', $user, $pass); }
php
public function create(Environment $environment) { $scheme = $environment->getRequestScheme(); $host = $environment->getHost(); $port = $environment->getPort(); $query = $environment->getQueryString(); $user = $environment->getAuthUser(); $pass = $environment->getAuthPassword(); // parse_url() requires a full URL - but only URL path is need it here. $path = parse_url('http://example.com' . $environment->getRequestUri(), PHP_URL_PATH); if ($path === false) { throw new InvalidArgumentException('Uri path must be a string'); } return new Uri($scheme, $host, $port, $path, $query, '', $user, $pass); }
[ "public", "function", "create", "(", "Environment", "$", "environment", ")", "{", "$", "scheme", "=", "$", "environment", "->", "getRequestScheme", "(", ")", ";", "$", "host", "=", "$", "environment", "->", "getHost", "(", ")", ";", "$", "port", "=", "...
Create instances of Uri object from instance of Environment object @param Environment $environment environment data @return Uri Instance of Uri object created from environment
[ "Create", "instances", "of", "Uri", "object", "from", "instance", "of", "Environment", "object" ]
38877b9d895f279fdd5bdf957d8f23f9808a940a
https://github.com/kambo-1st/HttpMessage/blob/38877b9d895f279fdd5bdf957d8f23f9808a940a/src/Factories/Environment/Superglobal/UriFactory.php#L28-L44
train
fabsgc/framework
Core/Orm/Entity/Entity.php
Entity._tableDefinition
final protected function _tableDefinition() { $annotation = Annotation::getClass($this); /** @var \ReflectionClass $fieldClass */ $fieldClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Entity\\Field'); /** @var \ReflectionClass $foreignKeyClass */ $foreignKeyClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Entity\\ForeignKey'); /** @var \ReflectionClass $builderClass */ $builderClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Builder'); foreach ($annotation['class'] as $annotationClass) { $instance = $annotationClass[0]['instance']; switch ($annotationClass[0]['annotation']) { case 'Table': $this->name($instance->name); break; case 'Form': $this->form($instance->name); break; } } foreach ($annotation['properties'] as $name => $annotationProperties) { foreach ($annotationProperties as $annotationProperty) { $instance = $annotationProperty['instance']; if ($annotationProperty['annotation'] == 'Column') { $this->field($name)->type($fieldClass->getConstant($instance->type))->size($instance->size)->beNull($instance->null == 'true' ? true : false)->primary($instance->primary == 'true' ? true : false)->unique($instance->unique == 'true' ? true : false)->precision($instance->precision)->defaultValue($instance->default)->enum($instance->enum != '' ? explode(',', $instance->enum) : []); $fieldType = $fieldClass->getConstant($instance->type); if (in_array($fieldType, [Field::DATETIME, Field::DATE, Field::TIMESTAMP])) { $this->set($name, new \DateTime()); } } else { $this->field($name)->foreign(['type' => $foreignKeyClass->getConstant($instance->type), 'reference' => explode('.', $instance->to), 'current' => explode('.', $instance->from), 'belong' => $foreignKeyClass->getConstant($instance->belong), 'join' => $builderClass->getConstant($instance->join),]); $foreignType = $foreignKeyClass->getConstant($instance->type); if (in_array($foreignType, [ForeignKey::MANY_TO_MANY, ForeignKey::ONE_TO_MANY])) { $this->set($name, new Collection()); } } } } }
php
final protected function _tableDefinition() { $annotation = Annotation::getClass($this); /** @var \ReflectionClass $fieldClass */ $fieldClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Entity\\Field'); /** @var \ReflectionClass $foreignKeyClass */ $foreignKeyClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Entity\\ForeignKey'); /** @var \ReflectionClass $builderClass */ $builderClass = new \ReflectionClass('\\Gcs\Framework\Core\\Orm\\Builder'); foreach ($annotation['class'] as $annotationClass) { $instance = $annotationClass[0]['instance']; switch ($annotationClass[0]['annotation']) { case 'Table': $this->name($instance->name); break; case 'Form': $this->form($instance->name); break; } } foreach ($annotation['properties'] as $name => $annotationProperties) { foreach ($annotationProperties as $annotationProperty) { $instance = $annotationProperty['instance']; if ($annotationProperty['annotation'] == 'Column') { $this->field($name)->type($fieldClass->getConstant($instance->type))->size($instance->size)->beNull($instance->null == 'true' ? true : false)->primary($instance->primary == 'true' ? true : false)->unique($instance->unique == 'true' ? true : false)->precision($instance->precision)->defaultValue($instance->default)->enum($instance->enum != '' ? explode(',', $instance->enum) : []); $fieldType = $fieldClass->getConstant($instance->type); if (in_array($fieldType, [Field::DATETIME, Field::DATE, Field::TIMESTAMP])) { $this->set($name, new \DateTime()); } } else { $this->field($name)->foreign(['type' => $foreignKeyClass->getConstant($instance->type), 'reference' => explode('.', $instance->to), 'current' => explode('.', $instance->from), 'belong' => $foreignKeyClass->getConstant($instance->belong), 'join' => $builderClass->getConstant($instance->join),]); $foreignType = $foreignKeyClass->getConstant($instance->type); if (in_array($foreignType, [ForeignKey::MANY_TO_MANY, ForeignKey::ONE_TO_MANY])) { $this->set($name, new Collection()); } } } } }
[ "final", "protected", "function", "_tableDefinition", "(", ")", "{", "$", "annotation", "=", "Annotation", "::", "getClass", "(", "$", "this", ")", ";", "/** @var \\ReflectionClass $fieldClass */", "$", "fieldClass", "=", "new", "\\", "ReflectionClass", "(", "'\\\...
Creation of the table @access public @return void @since 3.0 @package Gcs\Framework\Core\Orm\Entity
[ "Creation", "of", "the", "table" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Orm/Entity/Entity.php#L137-L185
train
fabsgc/framework
Core/Orm/Entity/Entity.php
Entity.field
public function field($name) { $this->_fields['' . $name . ''] = new Field($name, $this->_name); return $this->_fields['' . $name . '']; }
php
public function field($name) { $this->_fields['' . $name . ''] = new Field($name, $this->_name); return $this->_fields['' . $name . '']; }
[ "public", "function", "field", "(", "$", "name", ")", "{", "$", "this", "->", "_fields", "[", "''", ".", "$", "name", ".", "''", "]", "=", "new", "Field", "(", "$", "name", ",", "$", "this", "->", "_name", ")", ";", "return", "$", "this", "->",...
add a field @access public @param $name string @return \Gcs\Framework\Core\Orm\Entity\Field @since 3.0 @package Gcs\Framework\Core\Orm\Entity
[ "add", "a", "field" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Orm/Entity/Entity.php#L229-L233
train
fabsgc/framework
Core/Orm/Entity/Entity.php
Entity.getPrimary
public function getPrimary() { foreach ($this->_fields as $key => $field) { if ($field->primary == true) { $this->_primary = $key; break; } } }
php
public function getPrimary() { foreach ($this->_fields as $key => $field) { if ($field->primary == true) { $this->_primary = $key; break; } } }
[ "public", "function", "getPrimary", "(", ")", "{", "foreach", "(", "$", "this", "->", "_fields", "as", "$", "key", "=>", "$", "field", ")", "{", "if", "(", "$", "field", "->", "primary", "==", "true", ")", "{", "$", "this", "->", "_primary", "=", ...
Get primary key name @access public @return void @since 3.0 @package Gcs\Framework\Core\Orm\Entity
[ "Get", "primary", "key", "name" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Orm/Entity/Entity.php#L270-L277
train
fabsgc/framework
Core/Orm/Entity/Entity.php
Entity.get
public function get($key) { if (array_key_exists($key, $this->_fields)) { if (gettype($this->_fields['' . $key . '']) == 'object') { return $this->_fields['' . $key . '']->value; } else { return $this->_fields['' . $key . '']; } } else { throw new MissingEntityException('The field "' . $key . '" doesn\'t exist in ' . $this->_name); } }
php
public function get($key) { if (array_key_exists($key, $this->_fields)) { if (gettype($this->_fields['' . $key . '']) == 'object') { return $this->_fields['' . $key . '']->value; } else { return $this->_fields['' . $key . '']; } } else { throw new MissingEntityException('The field "' . $key . '" doesn\'t exist in ' . $this->_name); } }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_fields", ")", ")", "{", "if", "(", "gettype", "(", "$", "this", "->", "_fields", "[", "''", ".", "$", "key", ".", ...
return a field value @access public @param $key string @throws MissingEntityException @return mixed integer,boolean,string,\Gcs\Framework\Core\Orm\Entity\Type\Type @since 3.0 @package Gcs\Framework\Core\Orm\Entity
[ "return", "a", "field", "value" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Orm/Entity/Entity.php#L378-L390
train
Opifer/ContentBundle
Controller/Backend/ContentController.php
ContentController.createAction
public function createAction(Request $request, $type = 0) { /** @var ContentManager $manager */ $manager = $this->get('opifer.content.content_manager'); if ($type) { $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type); $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema()); $content->setContentType($contentType); } else { $content = $manager->initialize(); } $form = $this->createForm(ContentType::class, $content); $form->handleRequest($request); if ($form->isValid()) { // Create a new document $blockManager = $this->get('opifer.content.block_manager'); $document = new DocumentBlock(); $document->setPublish(true); $blockManager->save($document); $content->setBlock($document); $manager->save($content); return $this->redirectToRoute('opifer_content_contenteditor_design', [ 'type' => 'content', 'id' => $content->getId(), 'rootVersion' => 0, ]); } return $this->render($this->getParameter('opifer_content.content_new_view'), [ 'form' => $form->createView(), ]); }
php
public function createAction(Request $request, $type = 0) { /** @var ContentManager $manager */ $manager = $this->get('opifer.content.content_manager'); if ($type) { $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type); $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema()); $content->setContentType($contentType); } else { $content = $manager->initialize(); } $form = $this->createForm(ContentType::class, $content); $form->handleRequest($request); if ($form->isValid()) { // Create a new document $blockManager = $this->get('opifer.content.block_manager'); $document = new DocumentBlock(); $document->setPublish(true); $blockManager->save($document); $content->setBlock($document); $manager->save($content); return $this->redirectToRoute('opifer_content_contenteditor_design', [ 'type' => 'content', 'id' => $content->getId(), 'rootVersion' => 0, ]); } return $this->render($this->getParameter('opifer_content.content_new_view'), [ 'form' => $form->createView(), ]); }
[ "public", "function", "createAction", "(", "Request", "$", "request", ",", "$", "type", "=", "0", ")", "{", "/** @var ContentManager $manager */", "$", "manager", "=", "$", "this", "->", "get", "(", "'opifer.content.content_manager'", ")", ";", "if", "(", "$",...
Select the type of content, the site and the language before actually creating a new content item. @param Request $request @param integer $type @return Response
[ "Select", "the", "type", "of", "content", "the", "site", "and", "the", "language", "before", "actually", "creating", "a", "new", "content", "item", "." ]
df44ef36b81a839ce87ea9a92f7728618111541f
https://github.com/Opifer/ContentBundle/blob/df44ef36b81a839ce87ea9a92f7728618111541f/Controller/Backend/ContentController.php#L52-L88
train
Opifer/ContentBundle
Controller/Backend/ContentController.php
ContentController.detailsAction
public function detailsAction(Request $request, $id) { $manager = $this->get('opifer.content.content_manager'); $content = $manager->getRepository()->find($id); $form = $this->createForm(ContentType::class, $content); $form->handleRequest($request); if ($form->isValid()) { $manager->save($content); } return $this->render($this->getParameter('opifer_content.content_details_view'), [ 'content' => $content, 'form' => $form->createView() ]); }
php
public function detailsAction(Request $request, $id) { $manager = $this->get('opifer.content.content_manager'); $content = $manager->getRepository()->find($id); $form = $this->createForm(ContentType::class, $content); $form->handleRequest($request); if ($form->isValid()) { $manager->save($content); } return $this->render($this->getParameter('opifer_content.content_details_view'), [ 'content' => $content, 'form' => $form->createView() ]); }
[ "public", "function", "detailsAction", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "manager", "=", "$", "this", "->", "get", "(", "'opifer.content.content_manager'", ")", ";", "$", "content", "=", "$", "manager", "->", "getRepository", "...
Details action. @param Request $request @param integer $directoryId @return \Symfony\Component\HttpFoundation\Response
[ "Details", "action", "." ]
df44ef36b81a839ce87ea9a92f7728618111541f
https://github.com/Opifer/ContentBundle/blob/df44ef36b81a839ce87ea9a92f7728618111541f/Controller/Backend/ContentController.php#L98-L114
train
staccatocode/listable
src/Repository/RepositoryFactory.php
RepositoryFactory.add
public function add(string $name, RepositoryFactoryInterface $factory): void { $this->factories[$name] = $factory; }
php
public function add(string $name, RepositoryFactoryInterface $factory): void { $this->factories[$name] = $factory; }
[ "public", "function", "add", "(", "string", "$", "name", ",", "RepositoryFactoryInterface", "$", "factory", ")", ":", "void", "{", "$", "this", "->", "factories", "[", "$", "name", "]", "=", "$", "factory", ";", "}" ]
Add repository factory. @param string $name factory name @param RepositoryFactoryInterface $factory
[ "Add", "repository", "factory", "." ]
9e97ff44e7d2af59f5a46c8e0faa29880545a40b
https://github.com/staccatocode/listable/blob/9e97ff44e7d2af59f5a46c8e0faa29880545a40b/src/Repository/RepositoryFactory.php#L48-L51
train
staccatocode/listable
src/Repository/RepositoryFactory.php
RepositoryFactory.remove
public function remove(string $name): void { if ($this->has($name)) { unset($this->factories[$name]); } }
php
public function remove(string $name): void { if ($this->has($name)) { unset($this->factories[$name]); } }
[ "public", "function", "remove", "(", "string", "$", "name", ")", ":", "void", "{", "if", "(", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "unset", "(", "$", "this", "->", "factories", "[", "$", "name", "]", ")", ";", "}", "}" ]
Remove repository factory. @param string $name factory name
[ "Remove", "repository", "factory", "." ]
9e97ff44e7d2af59f5a46c8e0faa29880545a40b
https://github.com/staccatocode/listable/blob/9e97ff44e7d2af59f5a46c8e0faa29880545a40b/src/Repository/RepositoryFactory.php#L70-L75
train
parfumix/laravel-translator
src/TranslatorServiceProvider.php
TranslatorServiceProvider.publishDatabaseDriver
protected function publishDatabaseDriver() { $this->publishes([ __DIR__.'/DriverAssets/Database/migrations' => database_path('migrations'), ]); $this->publishes([ __DIR__.'/DriverAssets/Database/seeds' => database_path('seeds'), ]); return $this; }
php
protected function publishDatabaseDriver() { $this->publishes([ __DIR__.'/DriverAssets/Database/migrations' => database_path('migrations'), ]); $this->publishes([ __DIR__.'/DriverAssets/Database/seeds' => database_path('seeds'), ]); return $this; }
[ "protected", "function", "publishDatabaseDriver", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/DriverAssets/Database/migrations'", "=>", "database_path", "(", "'migrations'", ")", ",", "]", ")", ";", "$", "this", "->", "publishes",...
Publish database driver assets . @return $this
[ "Publish", "database", "driver", "assets", "." ]
b85f17cbfebd4f35d1bfb817fbf13bff2c3f487e
https://github.com/parfumix/laravel-translator/blob/b85f17cbfebd4f35d1bfb817fbf13bff2c3f487e/src/TranslatorServiceProvider.php#L65-L75
train
digitalicagroup/slack-hook-framework
lib/SlackHookFramework/CmdHello.php
CmdHello.executeImpl
protected function executeImpl($params) { /** * Get a reference to the log. */ $log = $this->log; /** * Output some debug info to log file. */ $log->debug ( "CmdHello: Parameters received: " . implode ( ",", $params ) ); /** * Preparing the result text and validating parameters. */ $resultText = "[requested by " . $this->post ["user_name"] . "]"; if (empty ( $params )) { $resultText .= " You must specify at least one parameter!"; } else { $resultText .= " CmdHello Result: "; } /** * Preparing attachments. */ $attachments = array (); /** * Cycling through parameters, just for fun. */ foreach ( $params as $param ) { $log->debug ( "CmdHello: processing parameter $param" ); /** * Preparing one result attachment for processing this parameter. */ $attachment = new SlackResultAttachment (); $attachment->setTitle ( "Processing $param" ); $attachment->setText ( "Hello $param !!" ); $attachment->setFallback ( "fallback text." ); $attachment->setPretext ( "pretext here." ); $attachment->setColor ( "#00ff00" ); /** * Adding some fields to the attachment. */ $fields = array (); $fields [] = SlackResultAttachmentField::withAttributes ( "Short Field", "Short Field Value" ); $fields [] = SlackResultAttachmentField::withAttributes ( "This is a long field", "this is a long Value", FALSE ); $attachment->setFieldsArray ( $fields ); /** * Adding the attachment to the attachments array. */ $attachments [] = $attachment; } $this->setResultText ( $resultText ); $this->setSlackResultAttachments ( $attachments ); /** * If you want more control, you can create your own instance of * SlackResult and override $this->result with your own object. */ }
php
protected function executeImpl($params) { /** * Get a reference to the log. */ $log = $this->log; /** * Output some debug info to log file. */ $log->debug ( "CmdHello: Parameters received: " . implode ( ",", $params ) ); /** * Preparing the result text and validating parameters. */ $resultText = "[requested by " . $this->post ["user_name"] . "]"; if (empty ( $params )) { $resultText .= " You must specify at least one parameter!"; } else { $resultText .= " CmdHello Result: "; } /** * Preparing attachments. */ $attachments = array (); /** * Cycling through parameters, just for fun. */ foreach ( $params as $param ) { $log->debug ( "CmdHello: processing parameter $param" ); /** * Preparing one result attachment for processing this parameter. */ $attachment = new SlackResultAttachment (); $attachment->setTitle ( "Processing $param" ); $attachment->setText ( "Hello $param !!" ); $attachment->setFallback ( "fallback text." ); $attachment->setPretext ( "pretext here." ); $attachment->setColor ( "#00ff00" ); /** * Adding some fields to the attachment. */ $fields = array (); $fields [] = SlackResultAttachmentField::withAttributes ( "Short Field", "Short Field Value" ); $fields [] = SlackResultAttachmentField::withAttributes ( "This is a long field", "this is a long Value", FALSE ); $attachment->setFieldsArray ( $fields ); /** * Adding the attachment to the attachments array. */ $attachments [] = $attachment; } $this->setResultText ( $resultText ); $this->setSlackResultAttachments ( $attachments ); /** * If you want more control, you can create your own instance of * SlackResult and override $this->result with your own object. */ }
[ "protected", "function", "executeImpl", "(", "$", "params", ")", "{", "/**\n\t\t * Get a reference to the log.\n\t\t */", "$", "log", "=", "$", "this", "->", "log", ";", "/**\n\t\t * Output some debug info to log file.\n\t\t */", "$", "log", "->", "debug", "(", "\"CmdHe...
Factory method to be implemented from \SlackHookFramework\AbstractCommand. This method should execute your command's logic. There are several ways to return information to Slack: 1) Simply use $this->setResultText("string here"); to return a single line to slack. 2) Create an array with one or more instances of SlackResultAttachment with relevant information and formatting options. Add this array using $this->setSlackResultAttachments(myArray); . 3) Add an array with one or more instances of SlackResultAttachmentField to each one of your attachments to include even more detailed information. 4) Complete override the internal reference $this->result with your own SlackResult instance if you want more control over your result. @param String[] $params An array of strings with the parameters already parsed for your command (without the command trigger). If you didn't defined a split_regexp field in your custom_cmds.json, the paramters are parsed by one or consecutive space characters after detecting your command trigger. @see \SlackHookFramework\AbstractCommand::executeImpl() @return \SlackHookFramework\SlackResult
[ "Factory", "method", "to", "be", "implemented", "from", "\\", "SlackHookFramework", "\\", "AbstractCommand", "." ]
b2357275d6042e49cb082e375716effd4c001ee0
https://github.com/digitalicagroup/slack-hook-framework/blob/b2357275d6042e49cb082e375716effd4c001ee0/lib/SlackHookFramework/CmdHello.php#L43-L106
train
jurchiks/commons
src/collections/ArrayMap.php
ArrayMap.toList
public function toList(bool $mutable): ArrayList { if ($mutable) { return new MutableList(array_values($this->data)); } else { return new ImmutableList(array_values($this->data)); } }
php
public function toList(bool $mutable): ArrayList { if ($mutable) { return new MutableList(array_values($this->data)); } else { return new ImmutableList(array_values($this->data)); } }
[ "public", "function", "toList", "(", "bool", "$", "mutable", ")", ":", "ArrayList", "{", "if", "(", "$", "mutable", ")", "{", "return", "new", "MutableList", "(", "array_values", "(", "$", "this", "->", "data", ")", ")", ";", "}", "else", "{", "retur...
Copy the values of this collection into a list. Keys are not preserved. @param bool $mutable : if true, will return a MutableList, otherwise an ImmutableList @return ArrayList
[ "Copy", "the", "values", "of", "this", "collection", "into", "a", "list", ".", "Keys", "are", "not", "preserved", "." ]
be9e1eca6a94380647160a882b8476bee3e4d8f8
https://github.com/jurchiks/commons/blob/be9e1eca6a94380647160a882b8476bee3e4d8f8/src/collections/ArrayMap.php#L44-L54
train
mtils/beetree
src/BeeTree/Eloquent/Relation/HasChildren.php
HasChildren.append
public function append(Node $node) { if (!is_array($this->_children)) { $this->_children = []; } $this->_children[] = $node; return $this; }
php
public function append(Node $node) { if (!is_array($this->_children)) { $this->_children = []; } $this->_children[] = $node; return $this; }
[ "public", "function", "append", "(", "Node", "$", "node", ")", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "_children", ")", ")", "{", "$", "this", "->", "_children", "=", "[", "]", ";", "}", "$", "this", "->", "_children", "[", "]",...
Append a node to the list @param \BeeTree\Contracts\Node $node @return self
[ "Append", "a", "node", "to", "the", "list" ]
4a68fc94ec14d5faef773b1628c9060db7bf1ce2
https://github.com/mtils/beetree/blob/4a68fc94ec14d5faef773b1628c9060db7bf1ce2/src/BeeTree/Eloquent/Relation/HasChildren.php#L154-L163
train
phPoirot/Http
Header/FactoryHttpHeader.php
FactoryHttpHeader.plugins
static function plugins() { if (! self::isEnabledPlugins() ) throw new \Exception('Using Plugins depends on Poirot/Ioc; that not exists currently.'); if (! self::$pluginManager ) self::$pluginManager = new PluginsHttpHeader; return self::$pluginManager; }
php
static function plugins() { if (! self::isEnabledPlugins() ) throw new \Exception('Using Plugins depends on Poirot/Ioc; that not exists currently.'); if (! self::$pluginManager ) self::$pluginManager = new PluginsHttpHeader; return self::$pluginManager; }
[ "static", "function", "plugins", "(", ")", "{", "if", "(", "!", "self", "::", "isEnabledPlugins", "(", ")", ")", "throw", "new", "\\", "Exception", "(", "'Using Plugins depends on Poirot/Ioc; that not exists currently.'", ")", ";", "if", "(", "!", "self", "::", ...
Headers Plugin Manager @return PluginsHttpHeader @throws \Exception
[ "Headers", "Plugin", "Manager" ]
3230b3555abf0e74c3d593fc49c8978758969736
https://github.com/phPoirot/Http/blob/3230b3555abf0e74c3d593fc49c8978758969736/Header/FactoryHttpHeader.php#L116-L126
train
phPoirot/Http
Header/FactoryHttpHeader.php
FactoryHttpHeader.givePluginManager
static function givePluginManager(PluginsHttpHeader $pluginsManager) { if ( self::$pluginManager !== null ) throw new exImmutable('Header Factory Has Plugin Manager, and can`t be changed.'); self::$pluginManager = $pluginsManager; }
php
static function givePluginManager(PluginsHttpHeader $pluginsManager) { if ( self::$pluginManager !== null ) throw new exImmutable('Header Factory Has Plugin Manager, and can`t be changed.'); self::$pluginManager = $pluginsManager; }
[ "static", "function", "givePluginManager", "(", "PluginsHttpHeader", "$", "pluginsManager", ")", "{", "if", "(", "self", "::", "$", "pluginManager", "!==", "null", ")", "throw", "new", "exImmutable", "(", "'Header Factory Has Plugin Manager, and can`t be changed.'", ")"...
Set Headers Plugin Manager @param PluginsHttpHeader $pluginsManager
[ "Set", "Headers", "Plugin", "Manager" ]
3230b3555abf0e74c3d593fc49c8978758969736
https://github.com/phPoirot/Http/blob/3230b3555abf0e74c3d593fc49c8978758969736/Header/FactoryHttpHeader.php#L133-L139
train
Cheezykins/RestAPICore
lib/Cache/LocalCache.php
LocalCache.forget
public function forget(string $key): bool { $key = $this->hashKey($key); if (\array_key_exists($key, $this->cache)) { unset($this->cache[$key]); return true; } return false; }
php
public function forget(string $key): bool { $key = $this->hashKey($key); if (\array_key_exists($key, $this->cache)) { unset($this->cache[$key]); return true; } return false; }
[ "public", "function", "forget", "(", "string", "$", "key", ")", ":", "bool", "{", "$", "key", "=", "$", "this", "->", "hashKey", "(", "$", "key", ")", ";", "if", "(", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cache", ")"...
Clear the cache for the given key Returns true on success or false on failure. @param string $key @return bool @internal param string $url
[ "Clear", "the", "cache", "for", "the", "given", "key", "Returns", "true", "on", "success", "or", "false", "on", "failure", "." ]
35c0b40b9b71db93da1ff8ecd1849f18b616705a
https://github.com/Cheezykins/RestAPICore/blob/35c0b40b9b71db93da1ff8ecd1849f18b616705a/lib/Cache/LocalCache.php#L44-L52
train
Cheezykins/RestAPICore
lib/Cache/LocalCache.php
LocalCache.remember
public function remember(string $key, callable $callBack) { $existing = $this->get($key); if ($existing !== null) { return $existing; } $result = $callBack(); return $this->put($key, $result); }
php
public function remember(string $key, callable $callBack) { $existing = $this->get($key); if ($existing !== null) { return $existing; } $result = $callBack(); return $this->put($key, $result); }
[ "public", "function", "remember", "(", "string", "$", "key", ",", "callable", "$", "callBack", ")", "{", "$", "existing", "=", "$", "this", "->", "get", "(", "$", "key", ")", ";", "if", "(", "$", "existing", "!==", "null", ")", "{", "return", "$", ...
Remembers the return value of the callback and returns that if available on next call. @param $key string @param callable $callBack @return mixed
[ "Remembers", "the", "return", "value", "of", "the", "callback", "and", "returns", "that", "if", "available", "on", "next", "call", "." ]
35c0b40b9b71db93da1ff8ecd1849f18b616705a
https://github.com/Cheezykins/RestAPICore/blob/35c0b40b9b71db93da1ff8ecd1849f18b616705a/lib/Cache/LocalCache.php#L71-L80
train
Cheezykins/RestAPICore
lib/Cache/LocalCache.php
LocalCache.get
public function get(string $key) { $key = $this->hashKey($key); if (\array_key_exists($key, $this->cache)) { $this->hits++; return $this->cache[$key]; } $this->misses++; return null; }
php
public function get(string $key) { $key = $this->hashKey($key); if (\array_key_exists($key, $this->cache)) { $this->hits++; return $this->cache[$key]; } $this->misses++; return null; }
[ "public", "function", "get", "(", "string", "$", "key", ")", "{", "$", "key", "=", "$", "this", "->", "hashKey", "(", "$", "key", ")", ";", "if", "(", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cache", ")", ")", "{", "$...
Retrieve an item from the cache. @param $key string @return mixed
[ "Retrieve", "an", "item", "from", "the", "cache", "." ]
35c0b40b9b71db93da1ff8ecd1849f18b616705a
https://github.com/Cheezykins/RestAPICore/blob/35c0b40b9b71db93da1ff8ecd1849f18b616705a/lib/Cache/LocalCache.php#L87-L96
train
Cheezykins/RestAPICore
lib/Cache/LocalCache.php
LocalCache.put
public function put(string $key, $value) { $this->cache[$this->hashKey($key)] = $value; return $value; }
php
public function put(string $key, $value) { $this->cache[$this->hashKey($key)] = $value; return $value; }
[ "public", "function", "put", "(", "string", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "cache", "[", "$", "this", "->", "hashKey", "(", "$", "key", ")", "]", "=", "$", "value", ";", "return", "$", "value", ";", "}" ]
Push an item into the cache for a given URL Returns true on success or false on fail @param $key string @param $value mixed @return mixed
[ "Push", "an", "item", "into", "the", "cache", "for", "a", "given", "URL", "Returns", "true", "on", "success", "or", "false", "on", "fail" ]
35c0b40b9b71db93da1ff8ecd1849f18b616705a
https://github.com/Cheezykins/RestAPICore/blob/35c0b40b9b71db93da1ff8ecd1849f18b616705a/lib/Cache/LocalCache.php#L105-L109
train
weew/http-app-request-handler
src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php
RequestHandlerProvider.handleHandleHttpRequestEvent
public function handleHandleHttpRequestEvent(HandleHttpRequestEvent $event) { $event->setResponse( $this->requestHandler->handle($event->getRequest()) ); }
php
public function handleHandleHttpRequestEvent(HandleHttpRequestEvent $event) { $event->setResponse( $this->requestHandler->handle($event->getRequest()) ); }
[ "public", "function", "handleHandleHttpRequestEvent", "(", "HandleHttpRequestEvent", "$", "event", ")", "{", "$", "event", "->", "setResponse", "(", "$", "this", "->", "requestHandler", "->", "handle", "(", "$", "event", "->", "getRequest", "(", ")", ")", ")",...
Handle HandleHttpRequestEvent and create a response. @param HandleHttpRequestEvent $event
[ "Handle", "HandleHttpRequestEvent", "and", "create", "a", "response", "." ]
d3227c52518dfb8c434d2db02583c05ae94fec4a
https://github.com/weew/http-app-request-handler/blob/d3227c52518dfb8c434d2db02583c05ae94fec4a/src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php#L87-L91
train
weew/http-app-request-handler
src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php
RequestHandlerProvider.shareInstancesInContainer
protected function shareInstancesInContainer() { $this->container->set([Router::class, IRouter::class], $this->router); $this->container->set( [RequestHandler::class, IRequestHandler::class], $this->requestHandler ); }
php
protected function shareInstancesInContainer() { $this->container->set([Router::class, IRouter::class], $this->router); $this->container->set( [RequestHandler::class, IRequestHandler::class], $this->requestHandler ); }
[ "protected", "function", "shareInstancesInContainer", "(", ")", "{", "$", "this", "->", "container", "->", "set", "(", "[", "Router", "::", "class", ",", "IRouter", "::", "class", "]", ",", "$", "this", "->", "router", ")", ";", "$", "this", "->", "con...
Share instances in the container.
[ "Share", "instances", "in", "the", "container", "." ]
d3227c52518dfb8c434d2db02583c05ae94fec4a
https://github.com/weew/http-app-request-handler/blob/d3227c52518dfb8c434d2db02583c05ae94fec4a/src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php#L96-L101
train
weew/http-app-request-handler
src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php
RequestHandlerProvider.loadRoutesFromConfig
protected function loadRoutesFromConfig() { $config = $this->config->getRaw('routing', []); $this->routerConfigurator->processConfig($this->router, $config); }
php
protected function loadRoutesFromConfig() { $config = $this->config->getRaw('routing', []); $this->routerConfigurator->processConfig($this->router, $config); }
[ "protected", "function", "loadRoutesFromConfig", "(", ")", "{", "$", "config", "=", "$", "this", "->", "config", "->", "getRaw", "(", "'routing'", ",", "[", "]", ")", ";", "$", "this", "->", "routerConfigurator", "->", "processConfig", "(", "$", "this", ...
Load routes from config.
[ "Load", "routes", "from", "config", "." ]
d3227c52518dfb8c434d2db02583c05ae94fec4a
https://github.com/weew/http-app-request-handler/blob/d3227c52518dfb8c434d2db02583c05ae94fec4a/src/Weew/HttpApp/RequestHandler/RequestHandlerProvider.php#L106-L109
train
rocketphp/template
src/Template.php
Template.output
public function output() { if (!file_exists($this->_file)) throw new RuntimeException( "Error loading template file: $this->_file.", 1 ); $output = file_get_contents($this->_file); foreach ($this->_vars as $key => $value) { $tagToReplace = "[@$key]"; $output = str_replace($tagToReplace, $value, $output); } return $output; }
php
public function output() { if (!file_exists($this->_file)) throw new RuntimeException( "Error loading template file: $this->_file.", 1 ); $output = file_get_contents($this->_file); foreach ($this->_vars as $key => $value) { $tagToReplace = "[@$key]"; $output = str_replace($tagToReplace, $value, $output); } return $output; }
[ "public", "function", "output", "(", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "_file", ")", ")", "throw", "new", "RuntimeException", "(", "\"Error loading template file: $this->_file.\"", ",", "1", ")", ";", "$", "output", "=", "file_...
Outputs interpreted template content @return string
[ "Outputs", "interpreted", "template", "content" ]
cc870b5572df830cd6b3a83e5fbec59943deb2df
https://github.com/rocketphp/template/blob/cc870b5572df830cd6b3a83e5fbec59943deb2df/src/Template.php#L99-L115
train
AnonymPHP/Anonym-Library
src/Anonym/Security/Validation.php
Validation.make
public function make(array $data = [],array $validationRules = [],array $filterRules = []) { $data = $this->sanitize($data); $this->validation_rules($validationRules); $this->filter_rules($filterRules); return $this->run($data); }
php
public function make(array $data = [],array $validationRules = [],array $filterRules = []) { $data = $this->sanitize($data); $this->validation_rules($validationRules); $this->filter_rules($filterRules); return $this->run($data); }
[ "public", "function", "make", "(", "array", "$", "data", "=", "[", "]", ",", "array", "$", "validationRules", "=", "[", "]", ",", "array", "$", "filterRules", "=", "[", "]", ")", "{", "$", "data", "=", "$", "this", "->", "sanitize", "(", "$", "da...
validate datas with validation rules and filter rules @param array $data @param array $validationRules @param array $filterRules @return bool|array
[ "validate", "datas", "with", "validation", "rules", "and", "filter", "rules" ]
c967ad804f84e8fb204593a0959cda2fed5ae075
https://github.com/AnonymPHP/Anonym-Library/blob/c967ad804f84e8fb204593a0959cda2fed5ae075/src/Anonym/Security/Validation.php#L29-L36
train
LordMonoxide/phi
src/Phi.php
Phi.make
public function make($alias, array $arguments = []) { // Iterate over each resolver and see if they have a binding override foreach($this->_resolvers as $resolver) { // Ask the resolver for the alias' binding $binding = $resolver->make($alias, $arguments); // If it's not null, we got a binding if($binding !== null) { return $binding; } } // Check to see if we have something bound to this alias if(array_key_exists($alias, $this->_map)) { $binding = $this->_map[$alias]; if(is_callable($binding)) { // If it's callable, we call it and pass on our arguments return call_user_func_array($binding, $arguments); } elseif(is_object($binding)) { // If it's an object, simply return it return $binding; } } else { // If we don't have a binding, we'll just be `new`ing up the alias $binding = $alias; } // This will be used to `new` up the binding $reflector = new ReflectionClass($binding); // Make sure it's instantiable (ie. not abstract/interface) if(!$reflector->isInstantiable()) { throw new InvalidArgumentException("$binding is not an instantiable class"); } // Grab the constructor $constructor = $reflector->getConstructor(); // If there's no constructor, it's easy. Just make a new instance. if(empty($constructor)) { return $reflector->newInstance(); } // Grab all of the constructor's parameters $parameters = $constructor->getParameters(); $values = []; // Size array for($i = 0; $i < count($parameters); $i++) { $values[] = null; } /* * The following is a three-step process to fill out the parameters. For example: * * ``` * parameters = [A $p1, B $p2, string $p3, B $p4, string $p5] * arguments = [new B, new B, 'p5' => 'asdf', 'fdsa'] * values = [, , , , ] * * Iterate over arguments -> * Does argument have key? -> * Iterate over parameters -> * Is argument key == parameter name? -> * values[parameter index] = argument * unset argument[argument key] * break * * parameters = [A $p1, B $p2, string $p3, B $p4, string $p5] * arguments = [new B, new B, 'fdsa'] * values = [, , , , 'asdf'] * * Iterate over parameters -> * Does parameter have a class? -> * Iterate over arguments -> * Is argument instance of parameter? -> * values[parameter index] = argument * unset argument[argument index] * break * * parameters = [A $p1, B $p2, string $p3 B $p4, string $p5] * arguments = ['fdsa'] * values = [, new B, , new B, 'asdf'] * * Iterate over parameters -> * Is values missing index [parameter index]? * Does parameter have a class? * values[parameter index] = Ioc::make(parameter) * Otherwise, * values[parameter index] = the first argument left in arguments * pop the first element from arguments * * parameters = [A, B, string, B, string] * arguments = [] * values = [new A (from Ioc), new B, 'fdsa', new B, 'asdf'] * ``` */ // Step 1... foreach($arguments as $argIndex => $argument) { if(is_string($argIndex)) { foreach($parameters as $paramIndex => $parameter) { if($argIndex == $parameter->getName()) { $values[$paramIndex] = $argument; unset($arguments[$argIndex]); break; } } } } // Step 2... foreach($parameters as $paramIndex => $parameter) { if($parameter->getClass()) { foreach($arguments as $argIndex => $argument) { if(is_object($argument)) { if($parameter->getClass()->isInstance($argument)) { $values[$paramIndex] = $argument; unset($arguments[$argIndex]); break; } } } } } // Step 3... foreach($parameters as $paramIndex => $parameter) { if(!isset($values[$paramIndex])) { if($parameter->getClass()) { $values[$paramIndex] = $this->make($parameter->getClass()->getName()); } else { $values[$paramIndex] = array_shift($arguments); } } } // Done! Create a new instance using the values array return $reflector->newInstanceArgs($values); }
php
public function make($alias, array $arguments = []) { // Iterate over each resolver and see if they have a binding override foreach($this->_resolvers as $resolver) { // Ask the resolver for the alias' binding $binding = $resolver->make($alias, $arguments); // If it's not null, we got a binding if($binding !== null) { return $binding; } } // Check to see if we have something bound to this alias if(array_key_exists($alias, $this->_map)) { $binding = $this->_map[$alias]; if(is_callable($binding)) { // If it's callable, we call it and pass on our arguments return call_user_func_array($binding, $arguments); } elseif(is_object($binding)) { // If it's an object, simply return it return $binding; } } else { // If we don't have a binding, we'll just be `new`ing up the alias $binding = $alias; } // This will be used to `new` up the binding $reflector = new ReflectionClass($binding); // Make sure it's instantiable (ie. not abstract/interface) if(!$reflector->isInstantiable()) { throw new InvalidArgumentException("$binding is not an instantiable class"); } // Grab the constructor $constructor = $reflector->getConstructor(); // If there's no constructor, it's easy. Just make a new instance. if(empty($constructor)) { return $reflector->newInstance(); } // Grab all of the constructor's parameters $parameters = $constructor->getParameters(); $values = []; // Size array for($i = 0; $i < count($parameters); $i++) { $values[] = null; } /* * The following is a three-step process to fill out the parameters. For example: * * ``` * parameters = [A $p1, B $p2, string $p3, B $p4, string $p5] * arguments = [new B, new B, 'p5' => 'asdf', 'fdsa'] * values = [, , , , ] * * Iterate over arguments -> * Does argument have key? -> * Iterate over parameters -> * Is argument key == parameter name? -> * values[parameter index] = argument * unset argument[argument key] * break * * parameters = [A $p1, B $p2, string $p3, B $p4, string $p5] * arguments = [new B, new B, 'fdsa'] * values = [, , , , 'asdf'] * * Iterate over parameters -> * Does parameter have a class? -> * Iterate over arguments -> * Is argument instance of parameter? -> * values[parameter index] = argument * unset argument[argument index] * break * * parameters = [A $p1, B $p2, string $p3 B $p4, string $p5] * arguments = ['fdsa'] * values = [, new B, , new B, 'asdf'] * * Iterate over parameters -> * Is values missing index [parameter index]? * Does parameter have a class? * values[parameter index] = Ioc::make(parameter) * Otherwise, * values[parameter index] = the first argument left in arguments * pop the first element from arguments * * parameters = [A, B, string, B, string] * arguments = [] * values = [new A (from Ioc), new B, 'fdsa', new B, 'asdf'] * ``` */ // Step 1... foreach($arguments as $argIndex => $argument) { if(is_string($argIndex)) { foreach($parameters as $paramIndex => $parameter) { if($argIndex == $parameter->getName()) { $values[$paramIndex] = $argument; unset($arguments[$argIndex]); break; } } } } // Step 2... foreach($parameters as $paramIndex => $parameter) { if($parameter->getClass()) { foreach($arguments as $argIndex => $argument) { if(is_object($argument)) { if($parameter->getClass()->isInstance($argument)) { $values[$paramIndex] = $argument; unset($arguments[$argIndex]); break; } } } } } // Step 3... foreach($parameters as $paramIndex => $parameter) { if(!isset($values[$paramIndex])) { if($parameter->getClass()) { $values[$paramIndex] = $this->make($parameter->getClass()->getName()); } else { $values[$paramIndex] = array_shift($arguments); } } } // Done! Create a new instance using the values array return $reflector->newInstanceArgs($values); }
[ "public", "function", "make", "(", "$", "alias", ",", "array", "$", "arguments", "=", "[", "]", ")", "{", "// Iterate over each resolver and see if they have a binding override", "foreach", "(", "$", "this", "->", "_resolvers", "as", "$", "resolver", ")", "{", "...
Gets or creates an instance of an alias @param string $alias An alias (eg. `db.helper`), or a real class or interface name @param array $arguments The arguments to pass to the binding @returns object A new instance of `$alias`'s binding, or a shared instance in the case of singletons
[ "Gets", "or", "creates", "an", "instance", "of", "an", "alias" ]
c542804d621c81b40de9b648fa6e2eb3ec3cbc50
https://github.com/LordMonoxide/phi/blob/c542804d621c81b40de9b648fa6e2eb3ec3cbc50/src/Phi.php#L59-L199
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.start
public function start() { $this->_starttime = microtime(true); if (extension_loaded('xdebug') === false) { return false; } if (is_null($this->_traceFile) === true) { $this->_traceFile = tempnam(sys_get_temp_dir(), 'PHPConsistent_'); } ini_set('xdebug.auto_trace', 1); ini_set('xdebug.trace_format', 1); ini_set('xdebug.collect_return', 1); ini_set('xdebug.collect_params', 1); ini_set('xdebug.trace_options', 0); xdebug_start_trace($this->_traceFile); if ($this->_log === self::LOG_TO_FIREPHP) { ob_start(); break; } if ($this->_log !== self::LOG_TO_PHPUNIT) { register_shutdown_function(array($this, 'stop')); register_shutdown_function(array($this, 'analyze')); } return true; }
php
public function start() { $this->_starttime = microtime(true); if (extension_loaded('xdebug') === false) { return false; } if (is_null($this->_traceFile) === true) { $this->_traceFile = tempnam(sys_get_temp_dir(), 'PHPConsistent_'); } ini_set('xdebug.auto_trace', 1); ini_set('xdebug.trace_format', 1); ini_set('xdebug.collect_return', 1); ini_set('xdebug.collect_params', 1); ini_set('xdebug.trace_options', 0); xdebug_start_trace($this->_traceFile); if ($this->_log === self::LOG_TO_FIREPHP) { ob_start(); break; } if ($this->_log !== self::LOG_TO_PHPUNIT) { register_shutdown_function(array($this, 'stop')); register_shutdown_function(array($this, 'analyze')); } return true; }
[ "public", "function", "start", "(", ")", "{", "$", "this", "->", "_starttime", "=", "microtime", "(", "true", ")", ";", "if", "(", "extension_loaded", "(", "'xdebug'", ")", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "is_null", ...
Start PHPConsistent run
[ "Start", "PHPConsistent", "run" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L105-L134
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.analyze
public function analyze() { if (!file_exists($this->_traceFile)) { return false; } $this->processFunctionCalls(); unlink($this->_traceFile); if (file_exists($this->_traceFile . '.xt')) { unlink($this->_traceFile . '.xt'); } if (count($this->_failures) > 0) { return $this->_failures; } else { return array(); } }
php
public function analyze() { if (!file_exists($this->_traceFile)) { return false; } $this->processFunctionCalls(); unlink($this->_traceFile); if (file_exists($this->_traceFile . '.xt')) { unlink($this->_traceFile . '.xt'); } if (count($this->_failures) > 0) { return $this->_failures; } else { return array(); } }
[ "public", "function", "analyze", "(", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "_traceFile", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "processFunctionCalls", "(", ")", ";", "unlink", "(", "$", "this", "->...
Analyze PHPConsistent data from trace file
[ "Analyze", "PHPConsistent", "data", "from", "trace", "file" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L152-L168
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.addParamTypeFailure
protected function addParamTypeFailure($fileName, $fileLine, $calledFunction, $parameterNumber, $parameterName, $expectedType, $calledType) { $data = 'Invalid type calling ' . $calledFunction . ' : parameter ' . $parameterNumber . ' (' . $parameterName . ') should be of type ' . $expectedType . ' but got ' . $calledType . ' instead'; $this->reportFailure($fileName, $fileLine, $data); }
php
protected function addParamTypeFailure($fileName, $fileLine, $calledFunction, $parameterNumber, $parameterName, $expectedType, $calledType) { $data = 'Invalid type calling ' . $calledFunction . ' : parameter ' . $parameterNumber . ' (' . $parameterName . ') should be of type ' . $expectedType . ' but got ' . $calledType . ' instead'; $this->reportFailure($fileName, $fileLine, $data); }
[ "protected", "function", "addParamTypeFailure", "(", "$", "fileName", ",", "$", "fileLine", ",", "$", "calledFunction", ",", "$", "parameterNumber", ",", "$", "parameterName", ",", "$", "expectedType", ",", "$", "calledType", ")", "{", "$", "data", "=", "'In...
Add a failure about incorrect parameter type @param string $fileName @param int $fileLine @param string $calledFunction @param int $parameterNumber @param string $parameterName @param string $expectedType @param string $calledType
[ "Add", "a", "failure", "about", "incorrect", "parameter", "type" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L483-L487
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.addParamNameMismatchFailure
protected function addParamNameMismatchFailure($fileName, $fileLine, $calledFunction, $parameterNumber, $expectedName, $calledName) { $data = 'Parameter names in function definition and docblock don\'t match when calling ' . $calledFunction . ' : parameter ' . $parameterNumber . ' (' . $calledName . ') should be called ' . $expectedName . ' according to docblock'; $this->reportFailure($fileName, $fileLine, $data); }
php
protected function addParamNameMismatchFailure($fileName, $fileLine, $calledFunction, $parameterNumber, $expectedName, $calledName) { $data = 'Parameter names in function definition and docblock don\'t match when calling ' . $calledFunction . ' : parameter ' . $parameterNumber . ' (' . $calledName . ') should be called ' . $expectedName . ' according to docblock'; $this->reportFailure($fileName, $fileLine, $data); }
[ "protected", "function", "addParamNameMismatchFailure", "(", "$", "fileName", ",", "$", "fileLine", ",", "$", "calledFunction", ",", "$", "parameterNumber", ",", "$", "expectedName", ",", "$", "calledName", ")", "{", "$", "data", "=", "'Parameter names in function...
Add a failure about mismatching parameter names @param string $fileName @param int $fileLine @param stirng $calledFunction @param int $parameterNumber @param string $expectedName @param string $calledName
[ "Add", "a", "failure", "about", "mismatching", "parameter", "names" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L512-L516
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.addParamCountMismatchFailure
protected function addParamCountMismatchFailure($fileName, $fileLine, $calledFunction, $expectedCount, $actualCount) { $data = 'Parameter count in function definition and docblock don\'t match when calling ' . $calledFunction . ' : function has ' . $actualCount . ' but should be ' . $expectedCount . ' according to docblock'; $this->reportFailure($fileName, $fileLine, $data); }
php
protected function addParamCountMismatchFailure($fileName, $fileLine, $calledFunction, $expectedCount, $actualCount) { $data = 'Parameter count in function definition and docblock don\'t match when calling ' . $calledFunction . ' : function has ' . $actualCount . ' but should be ' . $expectedCount . ' according to docblock'; $this->reportFailure($fileName, $fileLine, $data); }
[ "protected", "function", "addParamCountMismatchFailure", "(", "$", "fileName", ",", "$", "fileLine", ",", "$", "calledFunction", ",", "$", "expectedCount", ",", "$", "actualCount", ")", "{", "$", "data", "=", "'Parameter count in function definition and docblock don\\'t...
Add a failure about mismatching parameter count @param string $fileName @param int $fileLine @param string $calledFunction @param int $expectedCount @param int $actualCount
[ "Add", "a", "failure", "about", "mismatching", "parameter", "count" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L526-L530
train
Cube-Solutions/PHPConsistent
Main.php
PHPConsistent_Main.reportFailure
protected function reportFailure($fileName, $fileLine, $data) { switch ($this->_log) { case self::LOG_TO_FILE: file_put_contents( $this->_logLocation, $data . ' - in ' . $fileName . ' (line ' . $fileLine . ')', FILE_APPEND ); break; case self::LOG_TO_FIREPHP: require_once 'FirePHPCore/FirePHP.class.php'; $firephp = FirePHP::getInstance(true); $firephp->warn($fileName . ' (line ' . $fileLine . ')', $data); break; case self::LOG_TO_PHPUNIT; $this->_failures[] = array( 'fileName' => $fileName, 'fileLine' => $fileLine, 'data' => $data ); break; } }
php
protected function reportFailure($fileName, $fileLine, $data) { switch ($this->_log) { case self::LOG_TO_FILE: file_put_contents( $this->_logLocation, $data . ' - in ' . $fileName . ' (line ' . $fileLine . ')', FILE_APPEND ); break; case self::LOG_TO_FIREPHP: require_once 'FirePHPCore/FirePHP.class.php'; $firephp = FirePHP::getInstance(true); $firephp->warn($fileName . ' (line ' . $fileLine . ')', $data); break; case self::LOG_TO_PHPUNIT; $this->_failures[] = array( 'fileName' => $fileName, 'fileLine' => $fileLine, 'data' => $data ); break; } }
[ "protected", "function", "reportFailure", "(", "$", "fileName", ",", "$", "fileLine", ",", "$", "data", ")", "{", "switch", "(", "$", "this", "->", "_log", ")", "{", "case", "self", "::", "LOG_TO_FILE", ":", "file_put_contents", "(", "$", "this", "->", ...
Output to the chosen reporting system @param string $fileName @param int $fileLine @param string $data
[ "Output", "to", "the", "chosen", "reporting", "system" ]
3b294d05a3c781735b51358e97bf27c799973641
https://github.com/Cube-Solutions/PHPConsistent/blob/3b294d05a3c781735b51358e97bf27c799973641/Main.php#L538-L561
train
aberdnikov/meerkat-core
classes/Meerkat/Html/Kohana/Table/Row.php
Kohana_Table_Row.&
function &add_cell($name = null) { if (!$name) { $name = uniqid(microtime(true), true); } $this->cells[$name] = new KHtml_Table_Cell(); return $this->cells[$name]; }
php
function &add_cell($name = null) { if (!$name) { $name = uniqid(microtime(true), true); } $this->cells[$name] = new KHtml_Table_Cell(); return $this->cells[$name]; }
[ "function", "&", "add_cell", "(", "$", "name", "=", "null", ")", "{", "if", "(", "!", "$", "name", ")", "{", "$", "name", "=", "uniqid", "(", "microtime", "(", "true", ")", ",", "true", ")", ";", "}", "$", "this", "->", "cells", "[", "$", "na...
Add named cell to row of table @param string $name @return KHtml_Table_Cell
[ "Add", "named", "cell", "to", "row", "of", "table" ]
9aab1555919d76f1920198c64e21fd3faf9b5f5d
https://github.com/aberdnikov/meerkat-core/blob/9aab1555919d76f1920198c64e21fd3faf9b5f5d/classes/Meerkat/Html/Kohana/Table/Row.php#L18-L24
train
silinternational/ssp-utilities
src/DiscoUtils.php
DiscoUtils.getIdpsForSp
public static function getIdpsForSp( $spEntityId, $metadataPath ) { $idpEntries = Metadata::getIdpMetadataEntries($metadataPath); return self::getReducedIdpList( $idpEntries, $metadataPath, $spEntityId); }
php
public static function getIdpsForSp( $spEntityId, $metadataPath ) { $idpEntries = Metadata::getIdpMetadataEntries($metadataPath); return self::getReducedIdpList( $idpEntries, $metadataPath, $spEntityId); }
[ "public", "static", "function", "getIdpsForSp", "(", "$", "spEntityId", ",", "$", "metadataPath", ")", "{", "$", "idpEntries", "=", "Metadata", "::", "getIdpMetadataEntries", "(", "$", "metadataPath", ")", ";", "return", "self", "::", "getReducedIdpList", "(", ...
Takes the original idp entries and reduces them down to the ones the current SP is meant to see. @param string $spEntityId @param string $metadataPath, the path to the simplesamlphp/metadata folder @returns array of strings of entity id's of IDP's that this SP is allowed to use for authentication.
[ "Takes", "the", "original", "idp", "entries", "and", "reduces", "them", "down", "to", "the", "ones", "the", "current", "SP", "is", "meant", "to", "see", "." ]
e8c05bd8e4688aea2960bca74b7d6aa5f9f34286
https://github.com/silinternational/ssp-utilities/blob/e8c05bd8e4688aea2960bca74b7d6aa5f9f34286/src/DiscoUtils.php#L76-L86
train
llwebsol/EasyDB
src/Core/DB.php
DB.prepareStatement
private function prepareStatement($query, $parameters) { $stmt = $this->db_connection->prepare($query); if (!empty($parameters)) { foreach ($parameters as $key => $val) { $stmt->bindValue($key, $val); } } return $stmt; }
php
private function prepareStatement($query, $parameters) { $stmt = $this->db_connection->prepare($query); if (!empty($parameters)) { foreach ($parameters as $key => $val) { $stmt->bindValue($key, $val); } } return $stmt; }
[ "private", "function", "prepareStatement", "(", "$", "query", ",", "$", "parameters", ")", "{", "$", "stmt", "=", "$", "this", "->", "db_connection", "->", "prepare", "(", "$", "query", ")", ";", "if", "(", "!", "empty", "(", "$", "parameters", ")", ...
Convert a string query and parameters to a PDO Statement @param $query @param $parameters @return PDOStatement
[ "Convert", "a", "string", "query", "and", "parameters", "to", "a", "PDO", "Statement" ]
7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0
https://github.com/llwebsol/EasyDB/blob/7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0/src/Core/DB.php#L130-L140
train
llwebsol/EasyDB
src/Core/DB.php
DB.deleteWhere
function deleteWhere($table_name, $where_with_placeholders, $named_parameters) { if (empty($where_with_placeholders) || !$table_name) { return false; } $sql_query = 'DELETE FROM ' . $table_name . ' WHERE ' . $where_with_placeholders; Event::dispatch(EventData::forBefore(Event::BEFORE_DELETE, $table_name, $named_parameters, $sql_query)); try { //Run Delete query, collect stats $stmt = $this->db_connection->prepare($sql_query); if (!empty($named_parameters)) { foreach ($named_parameters as $k => $v) { $stmt->bindValue($k, $v); } } $stmt->execute(); } catch (Exception $ex) { Event::dispatch(EventData::forException($ex, $sql_query, $named_parameters)); throw new QueryException($ex->getMessage(), $ex->getCode(), $ex); } $rows_affected = $stmt->rowCount(); Event::dispatch(EventData::forAfter(Event::AFTER_DELETE, $table_name, $named_parameters, $sql_query, $rows_affected)); return $rows_affected; }
php
function deleteWhere($table_name, $where_with_placeholders, $named_parameters) { if (empty($where_with_placeholders) || !$table_name) { return false; } $sql_query = 'DELETE FROM ' . $table_name . ' WHERE ' . $where_with_placeholders; Event::dispatch(EventData::forBefore(Event::BEFORE_DELETE, $table_name, $named_parameters, $sql_query)); try { //Run Delete query, collect stats $stmt = $this->db_connection->prepare($sql_query); if (!empty($named_parameters)) { foreach ($named_parameters as $k => $v) { $stmt->bindValue($k, $v); } } $stmt->execute(); } catch (Exception $ex) { Event::dispatch(EventData::forException($ex, $sql_query, $named_parameters)); throw new QueryException($ex->getMessage(), $ex->getCode(), $ex); } $rows_affected = $stmt->rowCount(); Event::dispatch(EventData::forAfter(Event::AFTER_DELETE, $table_name, $named_parameters, $sql_query, $rows_affected)); return $rows_affected; }
[ "function", "deleteWhere", "(", "$", "table_name", ",", "$", "where_with_placeholders", ",", "$", "named_parameters", ")", "{", "if", "(", "empty", "(", "$", "where_with_placeholders", ")", "||", "!", "$", "table_name", ")", "{", "return", "false", ";", "}",...
Performs an SQL delete with a 'WHERE' clause @param string $table_name @param string $where_with_placeholders @param array $named_parameters @return bool|int rows_affected @throws QueryException
[ "Performs", "an", "SQL", "delete", "with", "a", "WHERE", "clause" ]
7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0
https://github.com/llwebsol/EasyDB/blob/7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0/src/Core/DB.php#L324-L354
train
llwebsol/EasyDB
src/Core/DB.php
DB.getEnumeratedParameterList
private function getEnumeratedParameterList($parameter_name, $param_array) { $result = []; if ($param_array) { foreach ($param_array as $k => $v) { $result[ ':' . $parameter_name . '_' . $k ] = $v; } } return $result; }
php
private function getEnumeratedParameterList($parameter_name, $param_array) { $result = []; if ($param_array) { foreach ($param_array as $k => $v) { $result[ ':' . $parameter_name . '_' . $k ] = $v; } } return $result; }
[ "private", "function", "getEnumeratedParameterList", "(", "$", "parameter_name", ",", "$", "param_array", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "$", "param_array", ")", "{", "foreach", "(", "$", "param_array", "as", "$", "k", "=>", "$",...
Returns an array of named parameters @param string $parameter_name @param array $param_array @return array * ex. for $parameter_name = 'user', $param_array = [123,345,456] returns: [':user_0' => 123, ':user_1' => 345, ':user_2' => 456]
[ "Returns", "an", "array", "of", "named", "parameters" ]
7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0
https://github.com/llwebsol/EasyDB/blob/7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0/src/Core/DB.php#L386-L395
train
llwebsol/EasyDB
src/Core/DB.php
DB.updateWhere
public function updateWhere($table_name, $update_values, $where_with_placeholders, $named_parameters = null) { $all_params = empty($named_parameters) ? $update_values : array_merge($update_values, $named_parameters); Event::dispatch(EventData::forBefore(Event::BEFORE_UPDATE, $table_name, $all_params, $where_with_placeholders), $update_values); $q = $this->config->getSystemIdentifierQuote(); $sql_query = 'UPDATE ' . $q . $table_name . $q . ' SET '; $statement_params = []; $null_params = []; foreach ($update_values as $field_name => $value) { if ($field_name != 'id') { if (strtolower($value) == 'null' || is_null($value)) { $sql_query .= "\n$q" . $field_name . "$q = NULL,"; $null_params[ $field_name ] = 'NULL'; } else { $sql_query .= "\n$q" . $field_name . "$q = :" . $field_name . ","; $statement_params[ ':' . $field_name ] = $value; } } } $full_param_list = array_merge($null_params, $statement_params); // remove trailing comma $sql_query = substr($sql_query, 0, -1); $sql_query .= ' WHERE ' . $where_with_placeholders; // add extra named parameters for where clause if ($named_parameters) { foreach ($named_parameters as $param => $val) { $statement_params[ $param ] = $val; } } try { // prepare the query and bind parameters $stmt = $this->db_connection->prepare($sql_query); if ($statement_params) { foreach ($statement_params as $k => $v) { $stmt->bindValue($k, $v); } } $stmt->execute(); } catch (Exception $ex) { Event::dispatch(EventData::forException($ex, $sql_query, $full_param_list)); return false; } $rows_affected = $stmt->rowCount(); Event::dispatch(EventData::forAfter(Event::AFTER_UPDATE, $table_name, $full_param_list, $sql_query, $rows_affected)); return $rows_affected; }
php
public function updateWhere($table_name, $update_values, $where_with_placeholders, $named_parameters = null) { $all_params = empty($named_parameters) ? $update_values : array_merge($update_values, $named_parameters); Event::dispatch(EventData::forBefore(Event::BEFORE_UPDATE, $table_name, $all_params, $where_with_placeholders), $update_values); $q = $this->config->getSystemIdentifierQuote(); $sql_query = 'UPDATE ' . $q . $table_name . $q . ' SET '; $statement_params = []; $null_params = []; foreach ($update_values as $field_name => $value) { if ($field_name != 'id') { if (strtolower($value) == 'null' || is_null($value)) { $sql_query .= "\n$q" . $field_name . "$q = NULL,"; $null_params[ $field_name ] = 'NULL'; } else { $sql_query .= "\n$q" . $field_name . "$q = :" . $field_name . ","; $statement_params[ ':' . $field_name ] = $value; } } } $full_param_list = array_merge($null_params, $statement_params); // remove trailing comma $sql_query = substr($sql_query, 0, -1); $sql_query .= ' WHERE ' . $where_with_placeholders; // add extra named parameters for where clause if ($named_parameters) { foreach ($named_parameters as $param => $val) { $statement_params[ $param ] = $val; } } try { // prepare the query and bind parameters $stmt = $this->db_connection->prepare($sql_query); if ($statement_params) { foreach ($statement_params as $k => $v) { $stmt->bindValue($k, $v); } } $stmt->execute(); } catch (Exception $ex) { Event::dispatch(EventData::forException($ex, $sql_query, $full_param_list)); return false; } $rows_affected = $stmt->rowCount(); Event::dispatch(EventData::forAfter(Event::AFTER_UPDATE, $table_name, $full_param_list, $sql_query, $rows_affected)); return $rows_affected; }
[ "public", "function", "updateWhere", "(", "$", "table_name", ",", "$", "update_values", ",", "$", "where_with_placeholders", ",", "$", "named_parameters", "=", "null", ")", "{", "$", "all_params", "=", "empty", "(", "$", "named_parameters", ")", "?", "$", "u...
Performs an SQL update with a 'WHERE' clause @param string $table_name @param array $update_values array( $column_name => $new_value ) @param string $where_with_placeholders @param null|array $named_parameters @return bool|int $rows_affected
[ "Performs", "an", "SQL", "update", "with", "a", "WHERE", "clause" ]
7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0
https://github.com/llwebsol/EasyDB/blob/7a37e926da4b6b62c3dc58c83b8addd1ab04c2d0/src/Core/DB.php#L422-L479
train
gintonicweb/menus
src/Menu/MenuWrapper.php
MenuWrapper.render
public function render($data) { if (isset($data['content'])) { $this->config(['content' => $data['content']]); $content = new MenuContent($this->config(), $this->_here); $group = isset($data['group'])? $data['group'] : null; $contents = $content->render($group); $this->_active = $this->_active || $content->active(); $this->config('wrapper.wrapper', $contents); } if ($this->_active) { $class = $this->config('wrapper.class') . ' active'; $this->config('wrapper.class', $class); } return $this->formatTemplate('wrapper', $this->config('wrapper')); }
php
public function render($data) { if (isset($data['content'])) { $this->config(['content' => $data['content']]); $content = new MenuContent($this->config(), $this->_here); $group = isset($data['group'])? $data['group'] : null; $contents = $content->render($group); $this->_active = $this->_active || $content->active(); $this->config('wrapper.wrapper', $contents); } if ($this->_active) { $class = $this->config('wrapper.class') . ' active'; $this->config('wrapper.class', $class); } return $this->formatTemplate('wrapper', $this->config('wrapper')); }
[ "public", "function", "render", "(", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'content'", "]", ")", ")", "{", "$", "this", "->", "config", "(", "[", "'content'", "=>", "$", "data", "[", "'content'", "]", "]", ")", ";", ...
Renders the menu wrapper and it's content. @param array $data options and content of the wrapper @return string rendered wrapper
[ "Renders", "the", "menu", "wrapper", "and", "it", "s", "content", "." ]
79ccbef8a014339a7bed9c1886d1837a5ef084b8
https://github.com/gintonicweb/menus/blob/79ccbef8a014339a7bed9c1886d1837a5ef084b8/src/Menu/MenuWrapper.php#L48-L65
train
Archi-Strasbourg/archi-wiki
includes/framework/frameworkClasses/googleMap.class.php
GoogleMap.addAdresse
function addAdresse($params=array()) { $index = count($this->coordonnees); if (isset($params['adresse']) && $params['adresse']!='') { $this->coordonnees[$index]['adresse'] = $params['adresse']; } else { $this->coordonnees[$index]['adresse'] = ''; } if (isset($params['link']) && $params['link']!='') { $this->coordonnees[$index]['link'] = $params['link']; } else { $this->coordonnees[$index]['link']=''; } if (isset($params['imageFlag']) && $params['imageFlag']!='') { $this->coordonnees[$index]['imageFlag']=$params['imageFlag']; } else { $this->coordonnees[$index]['imageFlag']=''; } if (isset($params['longitude']) && $params['longitude']!='' && isset($params['latitude']) && $params['latitude']!='') { $this->coordonnees[$index]['longitude'] = $params['longitude']; $this->coordonnees[$index]['latitude'] = $params['latitude']; } if (isset($params['setImageWidth'])) { $this->coordonnees[$index]['imageWidth'] = $params['setImageWidth']; } if (isset($params['setImageHeight'])) { $this->coordonnees[$index]['imageHeight'] = $params['setImageHeight']; } if (isset($params['pathToImageFlag']) && $params['pathToImageFlag']!='') { $this->coordonnees[$index]['pathToImageFlag']=$params['pathToImageFlag']; } else { $this->coordonnees[$index]['pathToImageFlag']=''; } }
php
function addAdresse($params=array()) { $index = count($this->coordonnees); if (isset($params['adresse']) && $params['adresse']!='') { $this->coordonnees[$index]['adresse'] = $params['adresse']; } else { $this->coordonnees[$index]['adresse'] = ''; } if (isset($params['link']) && $params['link']!='') { $this->coordonnees[$index]['link'] = $params['link']; } else { $this->coordonnees[$index]['link']=''; } if (isset($params['imageFlag']) && $params['imageFlag']!='') { $this->coordonnees[$index]['imageFlag']=$params['imageFlag']; } else { $this->coordonnees[$index]['imageFlag']=''; } if (isset($params['longitude']) && $params['longitude']!='' && isset($params['latitude']) && $params['latitude']!='') { $this->coordonnees[$index]['longitude'] = $params['longitude']; $this->coordonnees[$index]['latitude'] = $params['latitude']; } if (isset($params['setImageWidth'])) { $this->coordonnees[$index]['imageWidth'] = $params['setImageWidth']; } if (isset($params['setImageHeight'])) { $this->coordonnees[$index]['imageHeight'] = $params['setImageHeight']; } if (isset($params['pathToImageFlag']) && $params['pathToImageFlag']!='') { $this->coordonnees[$index]['pathToImageFlag']=$params['pathToImageFlag']; } else { $this->coordonnees[$index]['pathToImageFlag']=''; } }
[ "function", "addAdresse", "(", "$", "params", "=", "array", "(", ")", ")", "{", "$", "index", "=", "count", "(", "$", "this", "->", "coordonnees", ")", ";", "if", "(", "isset", "(", "$", "params", "[", "'adresse'", "]", ")", "&&", "$", "params", ...
Ajouter une adresse ? @param array $params Paramètres @return void
[ "Ajouter", "une", "adresse", "?" ]
b9fb39f43a78409890a7de96426c1f6c49d5c323
https://github.com/Archi-Strasbourg/archi-wiki/blob/b9fb39f43a78409890a7de96426c1f6c49d5c323/includes/framework/frameworkClasses/googleMap.class.php#L165-L205
train
Archi-Strasbourg/archi-wiki
includes/framework/frameworkClasses/googleMap.class.php
GoogleMap.getHTML
public function getHTML() { $html="<div id='".$this->googleMapNameId."' style='width: ".$this->googleMapWidth."px; height: ".$this->googleMapHeight."px; ".$this->divStyle."'>Veuilliez patienter pendant le chargement de la carte...</div>"; //$html.="<script >"; /* if (count($this->coordonnees)>0) { foreach ($this->coordonnees as $indice => $value) { if (isset($value['link'])) { $html.="tabAdresses[".$indice."]=\"".$value['link']."\";\n"; } } } $html.="</script>"; $html.="<div id='".$this->googleMapNameId."' style='width: ".$this->googleMapWidth."px; height: ".$this->googleMapHeight."px;'>Veuilliez patienter pendant le chargement de la carte...</div>"; if ($this->debugMode) $displayDebug='block'; else $displayDebug='none'; $html.="<div style='width:500px; height:300px;overflow:scroll;display:".$displayDebug.";' id='debugGoogleMap'></div>"; $html.="<script >load();</script>"; // fonction appelant les affichages de coordonnées , appels regroupées dans une fonction qui groupe les coordonnées par paquet , afin de ne pas trop en envoyer a la fois if (count($this->coordonnees)>0) { $html.="<script >"; $html.="var numPaquet=0;\n"; $html.="var timer;\n"; $html.="startTimerPaquets();\n"; $html.="function startTimerPaquets()\n"; $html.="{"; $html.="afficheCoordonneesParPaquets();\n"; $html.="timer = setInterval(\"afficheCoordonneesParPaquets()\", ".$this->setTimeOutPaquets.");\n"; $html.="}\n"; $html.="function afficheCoordonneesParPaquets(){\n"; $i=0; $numPaquet = 0; foreach ($this->coordonnees as $indice => $value) { $image = ", \"http://www.google.com/mapfiles/marker.png\"";// if (isset($value['imageFlag']) && $value['imageFlag']!='') { $image = ", \"".$value['imageFlag']."\""; } if ($i%10==0) { $html.="if (numPaquet==".$numPaquet.")\n"; $html.="{\n"; $iDebut = $i; } $html.=" getCoordonnees(\"".$value['adresse']."\", ".$indice." ".$image.");\n"; if ($i==$iDebut+9 || $i==count($this->coordonnees)-1 ) { $html.="}\n"; $numPaquet++; } $i++; } $html.="if (numPaquet>".$numPaquet.")\n"; $html.="{\n"; $html.="clearInterval(timer);\n"; $html.="}\n"; $html.="numPaquet++;\n"; $html.="}\n"; $html.="</script>"; } */ /* if ($this->debugMode) $displayDebug='block'; else $displayDebug='none'; */ //$html.="<div style='width:500px; height:300px;overflow:scroll;display:".$displayDebug.";' id='debugGoogleMap'></div>"; $html.="<script >load();</script>"; $html.="<script >"; if (isset($params['urlImageIcon']) && isset($params['pathImageIcon'])) { $urlImage = $params['urlImageIcon']; list($imageSizeX, $imageSizeY, $typeImage, $attrImage) = getimagesize($params['pathImageIcon']); $html.=" var icon = new GIcon(); //icon.image = image; icon.image = \"$urlImage\"; //icon.shadow = \"https://labs.google.com/ridefinder/images/mm_20_shadow.png\"; icon.iconSize = new GSize($imageSizeX, $imageSizeY); icon.shadowSize = new GSize(22, 20); icon.iconAnchor = new GPoint(2, 24); icon.infoWindowAnchor = new GPoint(5, 1); var iconMarker = new GIcon(icon); "; } else { $html.=" var icon = new GIcon(); //icon.image = image; var iconMarker = new GIcon(icon); icon.image = \"https://labs.google.com/ridefinder/images/mm_20_red.png\"; //icon.shadow = \"https://labs.google.com/ridefinder/images/mm_20_shadow.png\"; icon.iconSize = new GSize(30, 24); icon.shadowSize = new GSize(22, 20); icon.iconAnchor = new GPoint(2, 24); icon.infoWindowAnchor = new GPoint(5, 1); "; } $html.="</script>"; if (isset($params['listeCoordonnees'])) { $html.="<script >"; foreach ($params['listeCoordonnees'] as $indice => $values) { $html.=" point$indice = new GLatLng(".$values['latitude'].", ".$values['longitude']."); marker$indice = new GMarker(point$indice, iconMarker); overlay$indice = map.addOverlay(marker$indice); //marker$indice.openInfoWindowHtml(\"".$values['libelle']."\"); "; if (isset($values['jsCodeOnClickMarker'])) { $html.=" function onClickFunction$indice(overlay, point){".$values['jsCodeOnClickMarker']."}"; $html.="GEvent.addListener(marker$indice, 'click', onClickFunction$indice);"; } if (isset($values['jsCodeOnMouseOverMarker'])) { $html.="function onMouseOverFunction$indice(overlay, point){".$values['jsOnMouseOverMarker']."}"; $html.="GEvent.addListener(marker$indice, 'mouseover', onMouseOverFunction$indice);"; } if (isset($values['jsCodeOnMouseOutMarker'])) { $html.="function onMouseOutFunction$indice(overlay, point){".$values['jsCodeOnMouseOutMarker']."}"; $html.="GEvent.addListener(marker$indice, 'mouseout', onMouseOutFunction$indice);"; } } $html.="</script>"; } return $html; }
php
public function getHTML() { $html="<div id='".$this->googleMapNameId."' style='width: ".$this->googleMapWidth."px; height: ".$this->googleMapHeight."px; ".$this->divStyle."'>Veuilliez patienter pendant le chargement de la carte...</div>"; //$html.="<script >"; /* if (count($this->coordonnees)>0) { foreach ($this->coordonnees as $indice => $value) { if (isset($value['link'])) { $html.="tabAdresses[".$indice."]=\"".$value['link']."\";\n"; } } } $html.="</script>"; $html.="<div id='".$this->googleMapNameId."' style='width: ".$this->googleMapWidth."px; height: ".$this->googleMapHeight."px;'>Veuilliez patienter pendant le chargement de la carte...</div>"; if ($this->debugMode) $displayDebug='block'; else $displayDebug='none'; $html.="<div style='width:500px; height:300px;overflow:scroll;display:".$displayDebug.";' id='debugGoogleMap'></div>"; $html.="<script >load();</script>"; // fonction appelant les affichages de coordonnées , appels regroupées dans une fonction qui groupe les coordonnées par paquet , afin de ne pas trop en envoyer a la fois if (count($this->coordonnees)>0) { $html.="<script >"; $html.="var numPaquet=0;\n"; $html.="var timer;\n"; $html.="startTimerPaquets();\n"; $html.="function startTimerPaquets()\n"; $html.="{"; $html.="afficheCoordonneesParPaquets();\n"; $html.="timer = setInterval(\"afficheCoordonneesParPaquets()\", ".$this->setTimeOutPaquets.");\n"; $html.="}\n"; $html.="function afficheCoordonneesParPaquets(){\n"; $i=0; $numPaquet = 0; foreach ($this->coordonnees as $indice => $value) { $image = ", \"http://www.google.com/mapfiles/marker.png\"";// if (isset($value['imageFlag']) && $value['imageFlag']!='') { $image = ", \"".$value['imageFlag']."\""; } if ($i%10==0) { $html.="if (numPaquet==".$numPaquet.")\n"; $html.="{\n"; $iDebut = $i; } $html.=" getCoordonnees(\"".$value['adresse']."\", ".$indice." ".$image.");\n"; if ($i==$iDebut+9 || $i==count($this->coordonnees)-1 ) { $html.="}\n"; $numPaquet++; } $i++; } $html.="if (numPaquet>".$numPaquet.")\n"; $html.="{\n"; $html.="clearInterval(timer);\n"; $html.="}\n"; $html.="numPaquet++;\n"; $html.="}\n"; $html.="</script>"; } */ /* if ($this->debugMode) $displayDebug='block'; else $displayDebug='none'; */ //$html.="<div style='width:500px; height:300px;overflow:scroll;display:".$displayDebug.";' id='debugGoogleMap'></div>"; $html.="<script >load();</script>"; $html.="<script >"; if (isset($params['urlImageIcon']) && isset($params['pathImageIcon'])) { $urlImage = $params['urlImageIcon']; list($imageSizeX, $imageSizeY, $typeImage, $attrImage) = getimagesize($params['pathImageIcon']); $html.=" var icon = new GIcon(); //icon.image = image; icon.image = \"$urlImage\"; //icon.shadow = \"https://labs.google.com/ridefinder/images/mm_20_shadow.png\"; icon.iconSize = new GSize($imageSizeX, $imageSizeY); icon.shadowSize = new GSize(22, 20); icon.iconAnchor = new GPoint(2, 24); icon.infoWindowAnchor = new GPoint(5, 1); var iconMarker = new GIcon(icon); "; } else { $html.=" var icon = new GIcon(); //icon.image = image; var iconMarker = new GIcon(icon); icon.image = \"https://labs.google.com/ridefinder/images/mm_20_red.png\"; //icon.shadow = \"https://labs.google.com/ridefinder/images/mm_20_shadow.png\"; icon.iconSize = new GSize(30, 24); icon.shadowSize = new GSize(22, 20); icon.iconAnchor = new GPoint(2, 24); icon.infoWindowAnchor = new GPoint(5, 1); "; } $html.="</script>"; if (isset($params['listeCoordonnees'])) { $html.="<script >"; foreach ($params['listeCoordonnees'] as $indice => $values) { $html.=" point$indice = new GLatLng(".$values['latitude'].", ".$values['longitude']."); marker$indice = new GMarker(point$indice, iconMarker); overlay$indice = map.addOverlay(marker$indice); //marker$indice.openInfoWindowHtml(\"".$values['libelle']."\"); "; if (isset($values['jsCodeOnClickMarker'])) { $html.=" function onClickFunction$indice(overlay, point){".$values['jsCodeOnClickMarker']."}"; $html.="GEvent.addListener(marker$indice, 'click', onClickFunction$indice);"; } if (isset($values['jsCodeOnMouseOverMarker'])) { $html.="function onMouseOverFunction$indice(overlay, point){".$values['jsOnMouseOverMarker']."}"; $html.="GEvent.addListener(marker$indice, 'mouseover', onMouseOverFunction$indice);"; } if (isset($values['jsCodeOnMouseOutMarker'])) { $html.="function onMouseOutFunction$indice(overlay, point){".$values['jsCodeOnMouseOutMarker']."}"; $html.="GEvent.addListener(marker$indice, 'mouseout', onMouseOutFunction$indice);"; } } $html.="</script>"; } return $html; }
[ "public", "function", "getHTML", "(", ")", "{", "$", "html", "=", "\"<div id='\"", ".", "$", "this", "->", "googleMapNameId", ".", "\"' style='width: \"", ".", "$", "this", "->", "googleMapWidth", ".", "\"px; height: \"", ".", "$", "this", "->", "googleMapHeig...
Affiche la carte Si l'on veut rajouter des evenements a cette carte , il faut ajouter le code des evenements apres l'appel a cette fonction, car c'est ici que l'on cree "map" @return string HTML
[ "Affiche", "la", "carte", "Si", "l", "on", "veut", "rajouter", "des", "evenements", "a", "cette", "carte", "il", "faut", "ajouter", "le", "code", "des", "evenements", "apres", "l", "appel", "a", "cette", "fonction", "car", "c", "est", "ici", "que", "l", ...
b9fb39f43a78409890a7de96426c1f6c49d5c323
https://github.com/Archi-Strasbourg/archi-wiki/blob/b9fb39f43a78409890a7de96426c1f6c49d5c323/includes/framework/frameworkClasses/googleMap.class.php#L439-L593
train
Archi-Strasbourg/archi-wiki
includes/framework/frameworkClasses/googleMap.class.php
GoogleMap.distance
public function distance($lat1=0, $lon1=0, $lat2=0, $lon2=0) { $theta = $lon1 - $lon2; $dist = sin(_deg2rad($lat1)) * sin(_deg2rad($lat2)) + cos(_deg2rad($lat1)) * cos(_deg2rad($lat2)) * cos(_deg2rad($theta)); $dist = acos($dist); $dist = _rad2deg($dist); $dist = $dist * 60 * 1.1515; $dist = $dist * 1.609344; return $dist; }
php
public function distance($lat1=0, $lon1=0, $lat2=0, $lon2=0) { $theta = $lon1 - $lon2; $dist = sin(_deg2rad($lat1)) * sin(_deg2rad($lat2)) + cos(_deg2rad($lat1)) * cos(_deg2rad($lat2)) * cos(_deg2rad($theta)); $dist = acos($dist); $dist = _rad2deg($dist); $dist = $dist * 60 * 1.1515; $dist = $dist * 1.609344; return $dist; }
[ "public", "function", "distance", "(", "$", "lat1", "=", "0", ",", "$", "lon1", "=", "0", ",", "$", "lat2", "=", "0", ",", "$", "lon2", "=", "0", ")", "{", "$", "theta", "=", "$", "lon1", "-", "$", "lon2", ";", "$", "dist", "=", "sin", "(",...
Calcul de distance @param int $lat1 Latitude 1 @param int $lon1 Longitude 1 @param int $lat2 Latitude 2 @param int $lon2 Longitude 2 @return int Distance
[ "Calcul", "de", "distance" ]
b9fb39f43a78409890a7de96426c1f6c49d5c323
https://github.com/Archi-Strasbourg/archi-wiki/blob/b9fb39f43a78409890a7de96426c1f6c49d5c323/includes/framework/frameworkClasses/googleMap.class.php#L1984-L1994
train
oroinc/OroChainProcessorComponent
Debug/ActionProcessorDataCollector.php
ActionProcessorDataCollector.getActions
public function getActions() { $actions = []; foreach ($this->data['actions'] as $action) { $name = $action['name']; $time = isset($action['time']) ? $action['time'] : 0; if (isset($actions[$name])) { $actions[$name]['count'] += 1; $actions[$name]['time'] += $time; } else { $actions[$name] = ['name' => $name, 'count' => 1, 'time' => $time]; } } return array_values($actions); }
php
public function getActions() { $actions = []; foreach ($this->data['actions'] as $action) { $name = $action['name']; $time = isset($action['time']) ? $action['time'] : 0; if (isset($actions[$name])) { $actions[$name]['count'] += 1; $actions[$name]['time'] += $time; } else { $actions[$name] = ['name' => $name, 'count' => 1, 'time' => $time]; } } return array_values($actions); }
[ "public", "function", "getActions", "(", ")", "{", "$", "actions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "data", "[", "'actions'", "]", "as", "$", "action", ")", "{", "$", "name", "=", "$", "action", "[", "'name'", "]", ";", "$",...
Gets executed actions. @return array
[ "Gets", "executed", "actions", "." ]
89c9bc60140292c9367a0c3178f760ecbcec6bd2
https://github.com/oroinc/OroChainProcessorComponent/blob/89c9bc60140292c9367a0c3178f760ecbcec6bd2/Debug/ActionProcessorDataCollector.php#L60-L77
train
oroinc/OroChainProcessorComponent
Debug/ActionProcessorDataCollector.php
ActionProcessorDataCollector.getProcessors
public function getProcessors() { $processors = []; foreach ($this->data['actions'] as $action) { if (isset($action['processors'])) { foreach ($action['processors'] as $processor) { $id = $processor['id']; $time = isset($processor['time']) ? $processor['time'] : 0; if (isset($processors[$id])) { $processors[$id]['count'] += 1; $processors[$id]['time'] += $time; } else { $processors[$id] = ['id' => $id, 'count' => 1, 'time' => $time]; } } } } return array_values($processors); }
php
public function getProcessors() { $processors = []; foreach ($this->data['actions'] as $action) { if (isset($action['processors'])) { foreach ($action['processors'] as $processor) { $id = $processor['id']; $time = isset($processor['time']) ? $processor['time'] : 0; if (isset($processors[$id])) { $processors[$id]['count'] += 1; $processors[$id]['time'] += $time; } else { $processors[$id] = ['id' => $id, 'count' => 1, 'time' => $time]; } } } } return array_values($processors); }
[ "public", "function", "getProcessors", "(", ")", "{", "$", "processors", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "data", "[", "'actions'", "]", "as", "$", "action", ")", "{", "if", "(", "isset", "(", "$", "action", "[", "'processors'",...
Gets executed processors. @return array
[ "Gets", "executed", "processors", "." ]
89c9bc60140292c9367a0c3178f760ecbcec6bd2
https://github.com/oroinc/OroChainProcessorComponent/blob/89c9bc60140292c9367a0c3178f760ecbcec6bd2/Debug/ActionProcessorDataCollector.php#L94-L115
train
oroinc/OroChainProcessorComponent
Debug/ActionProcessorDataCollector.php
ActionProcessorDataCollector.getProcessorCount
public function getProcessorCount() { $count = 0; foreach ($this->data['actions'] as $action) { if (isset($action['processors'])) { $count += count($action['processors']); } } return $count; }
php
public function getProcessorCount() { $count = 0; foreach ($this->data['actions'] as $action) { if (isset($action['processors'])) { $count += count($action['processors']); } } return $count; }
[ "public", "function", "getProcessorCount", "(", ")", "{", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "data", "[", "'actions'", "]", "as", "$", "action", ")", "{", "if", "(", "isset", "(", "$", "action", "[", "'processors'", "]", ...
Gets the number of executed processors. @return int
[ "Gets", "the", "number", "of", "executed", "processors", "." ]
89c9bc60140292c9367a0c3178f760ecbcec6bd2
https://github.com/oroinc/OroChainProcessorComponent/blob/89c9bc60140292c9367a0c3178f760ecbcec6bd2/Debug/ActionProcessorDataCollector.php#L122-L132
train
oroinc/OroChainProcessorComponent
Debug/ActionProcessorDataCollector.php
ActionProcessorDataCollector.getTotalTime
public function getTotalTime() { if (null === $this->totalTime) { $this->totalTime = 0; foreach ($this->data['actions'] as $action) { if (isset($action['time'])) { $this->totalTime += $action['time']; } } foreach ($this->data['applicableCheckers'] as $applicableChecker) { if (isset($applicableChecker['time'])) { $this->totalTime += $applicableChecker['time']; } } } return $this->totalTime; }
php
public function getTotalTime() { if (null === $this->totalTime) { $this->totalTime = 0; foreach ($this->data['actions'] as $action) { if (isset($action['time'])) { $this->totalTime += $action['time']; } } foreach ($this->data['applicableCheckers'] as $applicableChecker) { if (isset($applicableChecker['time'])) { $this->totalTime += $applicableChecker['time']; } } } return $this->totalTime; }
[ "public", "function", "getTotalTime", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "totalTime", ")", "{", "$", "this", "->", "totalTime", "=", "0", ";", "foreach", "(", "$", "this", "->", "data", "[", "'actions'", "]", "as", "$", "ac...
Gets the total time of all executed actions. @return float
[ "Gets", "the", "total", "time", "of", "all", "executed", "actions", "." ]
89c9bc60140292c9367a0c3178f760ecbcec6bd2
https://github.com/oroinc/OroChainProcessorComponent/blob/89c9bc60140292c9367a0c3178f760ecbcec6bd2/Debug/ActionProcessorDataCollector.php#L149-L166
train
agentmedia/phine-forms
src/Forms/Modules/Backend/FormForm.php
FormForm.SaveElement
protected function SaveElement() { $this->form->SetMethod($this->Value('Method')); $this->form->SetSaveTo($this->Value('SaveTo')); $this->form->SetSendFrom($this->Value('SendFrom')); $this->form->SetSendTo($this->Value('SendTo')); $this->form->SetRedirectUrl($this->selector->Save($this->form->GetRedirectUrl())); return $this->form; }
php
protected function SaveElement() { $this->form->SetMethod($this->Value('Method')); $this->form->SetSaveTo($this->Value('SaveTo')); $this->form->SetSendFrom($this->Value('SendFrom')); $this->form->SetSendTo($this->Value('SendTo')); $this->form->SetRedirectUrl($this->selector->Save($this->form->GetRedirectUrl())); return $this->form; }
[ "protected", "function", "SaveElement", "(", ")", "{", "$", "this", "->", "form", "->", "SetMethod", "(", "$", "this", "->", "Value", "(", "'Method'", ")", ")", ";", "$", "this", "->", "form", "->", "SetSaveTo", "(", "$", "this", "->", "Value", "(", ...
Attaches properties and returns the form content @return ContentForm
[ "Attaches", "properties", "and", "returns", "the", "form", "content" ]
cd7a92ea443756bef5885a9e8f59ad6b8d2771fc
https://github.com/agentmedia/phine-forms/blob/cd7a92ea443756bef5885a9e8f59ad6b8d2771fc/src/Forms/Modules/Backend/FormForm.php#L120-L128
train
sios13/simox
src/Cache.php
Cache.exists
public function exists( $key, $lifetime ) { if ( !$this->cache_dir ) { $this->initializeCacheDir(); } if ( !file_exists($this->cache_dir . $key . ".html") ) { return false; } $file_lifetime = time() - filectime( $this->cache_dir . $key . ".html" ); if ( $file_lifetime > $lifetime ) { $this->delete( $key ); return false; } return true; }
php
public function exists( $key, $lifetime ) { if ( !$this->cache_dir ) { $this->initializeCacheDir(); } if ( !file_exists($this->cache_dir . $key . ".html") ) { return false; } $file_lifetime = time() - filectime( $this->cache_dir . $key . ".html" ); if ( $file_lifetime > $lifetime ) { $this->delete( $key ); return false; } return true; }
[ "public", "function", "exists", "(", "$", "key", ",", "$", "lifetime", ")", "{", "if", "(", "!", "$", "this", "->", "cache_dir", ")", "{", "$", "this", "->", "initializeCacheDir", "(", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "this",...
Returns true if cache with given key exists, otherwise false If the cache has lived for longer than its life time, destroy the cache
[ "Returns", "true", "if", "cache", "with", "given", "key", "exists", "otherwise", "false", "If", "the", "cache", "has", "lived", "for", "longer", "than", "its", "life", "time", "destroy", "the", "cache" ]
8be964949ef179aba7eceb3fc6439815a1af2ad2
https://github.com/sios13/simox/blob/8be964949ef179aba7eceb3fc6439815a1af2ad2/src/Cache.php#L40-L61
train
anonymous-php/containers
src/RedisContainer.php
RedisContainer.prefill
protected function prefill() { if (!$this->prefill || $this->prefilled) { return; } try { $this->definitions = $this->getReadConnection()->hGetAll($this->hashName); $this->prefilled = true; } catch (\Exception $exception) { throw new RedisException($exception->getMessage(), $exception->getCode(), $exception); } }
php
protected function prefill() { if (!$this->prefill || $this->prefilled) { return; } try { $this->definitions = $this->getReadConnection()->hGetAll($this->hashName); $this->prefilled = true; } catch (\Exception $exception) { throw new RedisException($exception->getMessage(), $exception->getCode(), $exception); } }
[ "protected", "function", "prefill", "(", ")", "{", "if", "(", "!", "$", "this", "->", "prefill", "||", "$", "this", "->", "prefilled", ")", "{", "return", ";", "}", "try", "{", "$", "this", "->", "definitions", "=", "$", "this", "->", "getReadConnect...
Loads all container data from Redis @throws RedisException
[ "Loads", "all", "container", "data", "from", "Redis" ]
c16275f05f14d188cf4d3043e7f037aea40aa7ba
https://github.com/anonymous-php/containers/blob/c16275f05f14d188cf4d3043e7f037aea40aa7ba/src/RedisContainer.php#L133-L145
train
ddehart/dilmun
src/Nabu/LoggerHandler/System.php
System.write
public function write($message) { $written = false; if ($this->output_allowed) { $written = error_log($message); } return $written; }
php
public function write($message) { $written = false; if ($this->output_allowed) { $written = error_log($message); } return $written; }
[ "public", "function", "write", "(", "$", "message", ")", "{", "$", "written", "=", "false", ";", "if", "(", "$", "this", "->", "output_allowed", ")", "{", "$", "written", "=", "error_log", "(", "$", "message", ")", ";", "}", "return", "$", "written",...
Writes to the configured PHP error logger. @see error_log() @param string $message Message to be written to PHP's system log @return bool Returns the status from the error_log function
[ "Writes", "to", "the", "configured", "PHP", "error", "logger", "." ]
e2a294dbcd4c6754063c247be64930c5ee91378f
https://github.com/ddehart/dilmun/blob/e2a294dbcd4c6754063c247be64930c5ee91378f/src/Nabu/LoggerHandler/System.php#L34-L43
train
slickframework/configuration
src/Configuration.php
Configuration.get
public static function get($fileName, $driverClass = null) { $configuration = new Configuration($fileName, $driverClass); return $configuration->initialize(); }
php
public static function get($fileName, $driverClass = null) { $configuration = new Configuration($fileName, $driverClass); return $configuration->initialize(); }
[ "public", "static", "function", "get", "(", "$", "fileName", ",", "$", "driverClass", "=", "null", ")", "{", "$", "configuration", "=", "new", "Configuration", "(", "$", "fileName", ",", "$", "driverClass", ")", ";", "return", "$", "configuration", "->", ...
Creates a ConfigurationInterface with passed arguments @param string|array $fileName @param null $driverClass @return ConfigurationInterface|PriorityConfigurationChain
[ "Creates", "a", "ConfigurationInterface", "with", "passed", "arguments" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L72-L76
train
slickframework/configuration
src/Configuration.php
Configuration.driverClass
private function driverClass() { if (null == $this->driverClass) { $this->driverClass = $this->determineDriver($this->file); } return $this->driverClass; }
php
private function driverClass() { if (null == $this->driverClass) { $this->driverClass = $this->determineDriver($this->file); } return $this->driverClass; }
[ "private", "function", "driverClass", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "driverClass", ")", "{", "$", "this", "->", "driverClass", "=", "$", "this", "->", "determineDriver", "(", "$", "this", "->", "file", ")", ";", "}", "ret...
Returns the driver class to be initialized @return mixed|null|string
[ "Returns", "the", "driver", "class", "to", "be", "initialized" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L112-L118
train
slickframework/configuration
src/Configuration.php
Configuration.determineDriver
private function determineDriver($file) { $exception = new InvalidArgumentException( "Cannot initialize the configuration driver. I could not determine ". "the correct driver class." ); if (is_null($file) || !is_string($file)) { throw $exception; } $nameDivision = explode('.', $file); $extension = strtolower(end($nameDivision)); if (!array_key_exists($extension, $this->extensionToDriver)) { throw $exception; } return $this->extensionToDriver[$extension]; }
php
private function determineDriver($file) { $exception = new InvalidArgumentException( "Cannot initialize the configuration driver. I could not determine ". "the correct driver class." ); if (is_null($file) || !is_string($file)) { throw $exception; } $nameDivision = explode('.', $file); $extension = strtolower(end($nameDivision)); if (!array_key_exists($extension, $this->extensionToDriver)) { throw $exception; } return $this->extensionToDriver[$extension]; }
[ "private", "function", "determineDriver", "(", "$", "file", ")", "{", "$", "exception", "=", "new", "InvalidArgumentException", "(", "\"Cannot initialize the configuration driver. I could not determine \"", ".", "\"the correct driver class.\"", ")", ";", "if", "(", "is_null...
Tries to determine the driver class based on given file @param string $file @return mixed
[ "Tries", "to", "determine", "the", "driver", "class", "based", "on", "given", "file" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L126-L145
train
slickframework/configuration
src/Configuration.php
Configuration.composeFileName
private function composeFileName($name) { if (is_null($name)) { return $name; } $ext = $this->determineExtension(); $withExtension = $this->createName($name, $ext); list($found, $fileName) = $this->searchFor($name, $withExtension); return $found ? $fileName : $name; }
php
private function composeFileName($name) { if (is_null($name)) { return $name; } $ext = $this->determineExtension(); $withExtension = $this->createName($name, $ext); list($found, $fileName) = $this->searchFor($name, $withExtension); return $found ? $fileName : $name; }
[ "private", "function", "composeFileName", "(", "$", "name", ")", "{", "if", "(", "is_null", "(", "$", "name", ")", ")", "{", "return", "$", "name", ";", "}", "$", "ext", "=", "$", "this", "->", "determineExtension", "(", ")", ";", "$", "withExtension...
Compose the filename with existing paths and return when match If no match is found the $name is returned as is; If no extension is given it will add it from driver class map; By default it will try to find <$name>.php file @param string $name @return string
[ "Compose", "the", "filename", "with", "existing", "paths", "and", "return", "when", "match" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L158-L170
train
slickframework/configuration
src/Configuration.php
Configuration.determineExtension
private function determineExtension() { $ext = 'php'; if (in_array($this->driverClass, $this->extensionToDriver)) { $map = array_flip($this->extensionToDriver); $ext = $map[$this->driverClass]; } return $ext; }
php
private function determineExtension() { $ext = 'php'; if (in_array($this->driverClass, $this->extensionToDriver)) { $map = array_flip($this->extensionToDriver); $ext = $map[$this->driverClass]; } return $ext; }
[ "private", "function", "determineExtension", "(", ")", "{", "$", "ext", "=", "'php'", ";", "if", "(", "in_array", "(", "$", "this", "->", "driverClass", ",", "$", "this", "->", "extensionToDriver", ")", ")", "{", "$", "map", "=", "array_flip", "(", "$"...
Determine the extension based on the driver class If there is no driver class given it will default to .php @return string
[ "Determine", "the", "extension", "based", "on", "the", "driver", "class" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L179-L187
train
slickframework/configuration
src/Configuration.php
Configuration.searchFor
private function searchFor($name, $withExtension) { $found = false; $fileName = $name; foreach (self::$paths as $path) { $fileName = "{$path}/$withExtension"; if (is_file($fileName)) { $found = true; break; } } return [$found, $fileName]; }
php
private function searchFor($name, $withExtension) { $found = false; $fileName = $name; foreach (self::$paths as $path) { $fileName = "{$path}/$withExtension"; if (is_file($fileName)) { $found = true; break; } } return [$found, $fileName]; }
[ "private", "function", "searchFor", "(", "$", "name", ",", "$", "withExtension", ")", "{", "$", "found", "=", "false", ";", "$", "fileName", "=", "$", "name", ";", "foreach", "(", "self", "::", "$", "paths", "as", "$", "path", ")", "{", "$", "fileN...
Search for name in the list of paths @param string $name @param string $withExtension @return array
[ "Search", "for", "name", "in", "the", "list", "of", "paths" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L214-L228
train
slickframework/configuration
src/Configuration.php
Configuration.createConfigurationDriver
private function createConfigurationDriver() { $reflection = new \ReflectionClass($this->driverClass()); /** @var ConfigurationInterface $config */ $config = $reflection->hasMethod('__construct') ? $reflection->newInstanceArgs([$this->file]) : $reflection->newInstance(); return $config; }
php
private function createConfigurationDriver() { $reflection = new \ReflectionClass($this->driverClass()); /** @var ConfigurationInterface $config */ $config = $reflection->hasMethod('__construct') ? $reflection->newInstanceArgs([$this->file]) : $reflection->newInstance(); return $config; }
[ "private", "function", "createConfigurationDriver", "(", ")", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "this", "->", "driverClass", "(", ")", ")", ";", "/** @var ConfigurationInterface $config */", "$", "config", "=", "$", "reflection...
Creates the configuration driver from current properties @return ConfigurationInterface
[ "Creates", "the", "configuration", "driver", "from", "current", "properties" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L235-L244
train
slickframework/configuration
src/Configuration.php
Configuration.setProperties
private function setProperties($option) { $priority = isset($option[2]) ? $option[2] : 0; $this->driverClass = isset($option[1]) ? $option[1] : null; $this->file = isset($option[0]) ? $this->composeFileName($option[0]) : null; return $priority; }
php
private function setProperties($option) { $priority = isset($option[2]) ? $option[2] : 0; $this->driverClass = isset($option[1]) ? $option[1] : null; $this->file = isset($option[0]) ? $this->composeFileName($option[0]) : null; return $priority; }
[ "private", "function", "setProperties", "(", "$", "option", ")", "{", "$", "priority", "=", "isset", "(", "$", "option", "[", "2", "]", ")", "?", "$", "option", "[", "2", "]", ":", "0", ";", "$", "this", "->", "driverClass", "=", "isset", "(", "$...
Sets the file and driver class @param array $option @return int
[ "Sets", "the", "file", "and", "driver", "class" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L253-L259
train
slickframework/configuration
src/Configuration.php
Configuration.fixOptions
private function fixOptions() { $options = (is_array($this->file)) ? $this->file : [[$this->file]]; return $options; }
php
private function fixOptions() { $options = (is_array($this->file)) ? $this->file : [[$this->file]]; return $options; }
[ "private", "function", "fixOptions", "(", ")", "{", "$", "options", "=", "(", "is_array", "(", "$", "this", "->", "file", ")", ")", "?", "$", "this", "->", "file", ":", "[", "[", "$", "this", "->", "file", "]", "]", ";", "return", "$", "options",...
Fixes the file for initialization @return array
[ "Fixes", "the", "file", "for", "initialization" ]
9aa1edbddd007b4af4032a2b383c39f4db47d87e
https://github.com/slickframework/configuration/blob/9aa1edbddd007b4af4032a2b383c39f4db47d87e/src/Configuration.php#L266-L272
train
webriq/core
module/User/src/Grid/User/Controller/PasswordChangeRequestController.php
PasswordChangeRequestController.createAction
public function createAction() { $success = null; $this->paragraphLayout(); /* @var $form \Zend\Form\Form */ $request = $this->getRequest(); $data = $request->getPost(); $service = $this->getServiceLocator(); $model = $service->get( 'Grid\User\Model\User\Model' ); $form = $service->get( 'Form' ) ->get( 'Grid\User\PasswordChangeRequest\Create' ); if ( $request->isPost() ) { $form->setData( $data ); if ( $form->isValid() ) { $data = $form->getData( 'email' ); $user = $model->findByEmail( $data['email'] ); if ( ! empty( $user ) && $user->state != UserStructure::STATE_BANNED ) { $change = $this->url() ->fromRoute( 'Grid\User\PasswordChangeRequest\Resolve', array( 'locale' => (string) $this->locale(), 'hash' => $this->getServiceLocator() ->get( 'Grid\User\Model\ConfirmHash' ) ->create( $user->email ), ) ); $this->getServiceLocator() ->get( 'Grid\Mail\Model\Template\Sender' ) ->prepare( array( 'template' => 'user.forgotten-password', 'locale' => $user->locale, ) ) ->send( array( 'email' => $user->email, 'display_name' => $user->displayName, 'change_url' => $change, ), array( $user->email => $user->displayName, ) ); $success = true; } else { $success = false; } } else { $success = false; } } /* Says success even if email does not exists */ if ( $success === true || $success === false ) { $this->messenger() ->add( 'user.form.passwordRequest.success', 'user', Message::LEVEL_INFO ); } return new MetaContent( 'user.passwordChangeRequest', array( 'form' => $form, ) ); }
php
public function createAction() { $success = null; $this->paragraphLayout(); /* @var $form \Zend\Form\Form */ $request = $this->getRequest(); $data = $request->getPost(); $service = $this->getServiceLocator(); $model = $service->get( 'Grid\User\Model\User\Model' ); $form = $service->get( 'Form' ) ->get( 'Grid\User\PasswordChangeRequest\Create' ); if ( $request->isPost() ) { $form->setData( $data ); if ( $form->isValid() ) { $data = $form->getData( 'email' ); $user = $model->findByEmail( $data['email'] ); if ( ! empty( $user ) && $user->state != UserStructure::STATE_BANNED ) { $change = $this->url() ->fromRoute( 'Grid\User\PasswordChangeRequest\Resolve', array( 'locale' => (string) $this->locale(), 'hash' => $this->getServiceLocator() ->get( 'Grid\User\Model\ConfirmHash' ) ->create( $user->email ), ) ); $this->getServiceLocator() ->get( 'Grid\Mail\Model\Template\Sender' ) ->prepare( array( 'template' => 'user.forgotten-password', 'locale' => $user->locale, ) ) ->send( array( 'email' => $user->email, 'display_name' => $user->displayName, 'change_url' => $change, ), array( $user->email => $user->displayName, ) ); $success = true; } else { $success = false; } } else { $success = false; } } /* Says success even if email does not exists */ if ( $success === true || $success === false ) { $this->messenger() ->add( 'user.form.passwordRequest.success', 'user', Message::LEVEL_INFO ); } return new MetaContent( 'user.passwordChangeRequest', array( 'form' => $form, ) ); }
[ "public", "function", "createAction", "(", ")", "{", "$", "success", "=", "null", ";", "$", "this", "->", "paragraphLayout", "(", ")", ";", "/* @var $form \\Zend\\Form\\Form */", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "da...
Create a password-request
[ "Create", "a", "password", "-", "request" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/User/src/Grid/User/Controller/PasswordChangeRequestController.php#L21-L92
train
webriq/core
module/User/src/Grid/User/Controller/PasswordChangeRequestController.php
PasswordChangeRequestController.resolveAction
public function resolveAction() { $success = null; $failed = null; $service = $this->getServiceLocator(); $userModel = $service->get( 'Grid\User\Model\User\Model' ); $confirm = $service->get( 'Grid\User\Model\ConfirmHash' ); $hash = $this->params() ->fromRoute( 'hash' ); if ( $confirm->has( $hash ) && ( $email = $confirm->find( $hash ) ) ) { $user = $userModel->findByEmail( $email ); if ( ! empty( $user ) && $user->state != UserStructure::STATE_BANNED ) { $request = $this->getRequest(); $data = $request->getPost(); $form = $service->get( 'Form' ) ->get( 'Grid\User\PasswordChangeRequest\Resolve' ); if ( $request->isPost() ) { $form->setData( $data ); if ( $form->isValid() ) { $data = $form->getData(); $user->state = UserStructure::STATE_ACTIVE; $user->confirmed = true; $user->password = $data['password']; if ( $user->save() ) { $confirm->delete( $hash ); $success = true; } } else { $success = false; } } } else { $failed = true; } } else { $failed = true; } if ( $failed === true ) { $this->messenger() ->add( 'user.form.passwordChange.failed', 'user', Message::LEVEL_ERROR ); return $this->redirect() ->toRoute( 'Grid\User\PasswordChangeRequest\Create', array( 'locale' => (string) $this->locale(), 'returnUri' => '/', ) ); } if ( $success === true ) { $this->messenger() ->add( 'user.form.passwordChange.success', 'user', Message::LEVEL_INFO ); return $this->redirect() ->toRoute( 'Grid\User\Authentication\Login', array( 'locale' => (string) $this->locale(), 'returnUri' => '/', ) ); } if ( $success === false ) { $this->messenger() ->add( 'user.form.passwordChange.resolve.failed', 'user', Message::LEVEL_ERROR ); } $this->paragraphLayout(); return new MetaContent( 'user.passwordChangeRequest', array( 'success' => $success, 'form' => $form, ) ); }
php
public function resolveAction() { $success = null; $failed = null; $service = $this->getServiceLocator(); $userModel = $service->get( 'Grid\User\Model\User\Model' ); $confirm = $service->get( 'Grid\User\Model\ConfirmHash' ); $hash = $this->params() ->fromRoute( 'hash' ); if ( $confirm->has( $hash ) && ( $email = $confirm->find( $hash ) ) ) { $user = $userModel->findByEmail( $email ); if ( ! empty( $user ) && $user->state != UserStructure::STATE_BANNED ) { $request = $this->getRequest(); $data = $request->getPost(); $form = $service->get( 'Form' ) ->get( 'Grid\User\PasswordChangeRequest\Resolve' ); if ( $request->isPost() ) { $form->setData( $data ); if ( $form->isValid() ) { $data = $form->getData(); $user->state = UserStructure::STATE_ACTIVE; $user->confirmed = true; $user->password = $data['password']; if ( $user->save() ) { $confirm->delete( $hash ); $success = true; } } else { $success = false; } } } else { $failed = true; } } else { $failed = true; } if ( $failed === true ) { $this->messenger() ->add( 'user.form.passwordChange.failed', 'user', Message::LEVEL_ERROR ); return $this->redirect() ->toRoute( 'Grid\User\PasswordChangeRequest\Create', array( 'locale' => (string) $this->locale(), 'returnUri' => '/', ) ); } if ( $success === true ) { $this->messenger() ->add( 'user.form.passwordChange.success', 'user', Message::LEVEL_INFO ); return $this->redirect() ->toRoute( 'Grid\User\Authentication\Login', array( 'locale' => (string) $this->locale(), 'returnUri' => '/', ) ); } if ( $success === false ) { $this->messenger() ->add( 'user.form.passwordChange.resolve.failed', 'user', Message::LEVEL_ERROR ); } $this->paragraphLayout(); return new MetaContent( 'user.passwordChangeRequest', array( 'success' => $success, 'form' => $form, ) ); }
[ "public", "function", "resolveAction", "(", ")", "{", "$", "success", "=", "null", ";", "$", "failed", "=", "null", ";", "$", "service", "=", "$", "this", "->", "getServiceLocator", "(", ")", ";", "$", "userModel", "=", "$", "service", "->", "get", "...
Resolve a password-request
[ "Resolve", "a", "password", "-", "request" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/User/src/Grid/User/Controller/PasswordChangeRequestController.php#L97-L192
train
asbsoft/yii2-common_2_170212
web/UrlManagerInModule.php
UrlManagerInModule.getSitetreeManager
public function getSitetreeManager() { if (empty(static::$_sitetreeManager)) { $module = Yii::$app->getModule($this->sitetreeModuleUniqueId); if (!empty($module) && $module instanceof UniModule) { $mgr = $module->getDataModel($this->sitetreeManagerAlias); if (empty($mgr->rules)) $mgr->rules = Yii::$app->urlManager->rules; static::$_sitetreeManager = $mgr; } } return static::$_sitetreeManager; }
php
public function getSitetreeManager() { if (empty(static::$_sitetreeManager)) { $module = Yii::$app->getModule($this->sitetreeModuleUniqueId); if (!empty($module) && $module instanceof UniModule) { $mgr = $module->getDataModel($this->sitetreeManagerAlias); if (empty($mgr->rules)) $mgr->rules = Yii::$app->urlManager->rules; static::$_sitetreeManager = $mgr; } } return static::$_sitetreeManager; }
[ "public", "function", "getSitetreeManager", "(", ")", "{", "if", "(", "empty", "(", "static", "::", "$", "_sitetreeManager", ")", ")", "{", "$", "module", "=", "Yii", "::", "$", "app", "->", "getModule", "(", "$", "this", "->", "sitetreeModuleUniqueId", ...
Find Sitetree module from system loaded modules
[ "Find", "Sitetree", "module", "from", "system", "loaded", "modules" ]
6c58012ff89225d7d4e42b200cf39e009e9d9dac
https://github.com/asbsoft/yii2-common_2_170212/blob/6c58012ff89225d7d4e42b200cf39e009e9d9dac/web/UrlManagerInModule.php#L37-L48
train
uthando-cms/uthando-common
src/UthandoCommon/Form/Settings/AkismetFieldSet.php
AkismetFieldSet.getInputFilterSpecification
public function getInputFilterSpecification(): array { return [ 'api_key' => [ 'required' => false, 'filters' => [ ['name' => StripTags::class], ['name' => StringTrim::class], ], 'validators' => [ ['name' => StringLength::class, 'options' => [ 'encoding' => 'UTF-8', 'min' => 10, 'max' => 20, ]], ['name' => Alnum::class], ], ], 'blog' => [ 'required' => false, 'filters' => [ ['name' => StripTags::class], ['name' => StringTrim::class], ], 'validators' => [ ['name' => StringLength::class, 'options' => [ 'encoding' => 'UTF-8', 'min' => 10, 'max' => 255, ]], ['name' => Uri::class, 'options' => [ 'uriHandler' => Http::class, 'allowRelative' => false, ]], ], ], ]; }
php
public function getInputFilterSpecification(): array { return [ 'api_key' => [ 'required' => false, 'filters' => [ ['name' => StripTags::class], ['name' => StringTrim::class], ], 'validators' => [ ['name' => StringLength::class, 'options' => [ 'encoding' => 'UTF-8', 'min' => 10, 'max' => 20, ]], ['name' => Alnum::class], ], ], 'blog' => [ 'required' => false, 'filters' => [ ['name' => StripTags::class], ['name' => StringTrim::class], ], 'validators' => [ ['name' => StringLength::class, 'options' => [ 'encoding' => 'UTF-8', 'min' => 10, 'max' => 255, ]], ['name' => Uri::class, 'options' => [ 'uriHandler' => Http::class, 'allowRelative' => false, ]], ], ], ]; }
[ "public", "function", "getInputFilterSpecification", "(", ")", ":", "array", "{", "return", "[", "'api_key'", "=>", "[", "'required'", "=>", "false", ",", "'filters'", "=>", "[", "[", "'name'", "=>", "StripTags", "::", "class", "]", ",", "[", "'name'", "=>...
Get input filter for elements. @return array
[ "Get", "input", "filter", "for", "elements", "." ]
feb915da5d26b60f536282e1bc3ad5c22e53f485
https://github.com/uthando-cms/uthando-common/blob/feb915da5d26b60f536282e1bc3ad5c22e53f485/src/UthandoCommon/Form/Settings/AkismetFieldSet.php#L85-L122
train
KonstantinKuklin/doctrine-compressed-fields
src/KonstantinKuklin/DoctrineCompressedFields/EventListener/LoadClassMetadataListener.php
LoadClassMetadataListener.initDefaultAnnotationReader
private function initDefaultAnnotationReader() { if (null !== self::$defaultAnnotationReader) { return; } $docParser = new DocParser(); $docParser->setImports([ 'Bits' => 'KonstantinKuklin\\DoctrineCompressedFields\\Annotation', ]); $docParser->setIgnoreNotImportedAnnotations(true); $reader = new AnnotationReader($docParser); AnnotationRegistry::registerFile(__DIR__ . '/../Annotation/Hub.php'); AnnotationRegistry::registerFile(__DIR__ . '/../Annotation/Mask.php'); $reader = new CachedReader($reader, new VoidCache()); self::$defaultAnnotationReader = $reader; }
php
private function initDefaultAnnotationReader() { if (null !== self::$defaultAnnotationReader) { return; } $docParser = new DocParser(); $docParser->setImports([ 'Bits' => 'KonstantinKuklin\\DoctrineCompressedFields\\Annotation', ]); $docParser->setIgnoreNotImportedAnnotations(true); $reader = new AnnotationReader($docParser); AnnotationRegistry::registerFile(__DIR__ . '/../Annotation/Hub.php'); AnnotationRegistry::registerFile(__DIR__ . '/../Annotation/Mask.php'); $reader = new CachedReader($reader, new VoidCache()); self::$defaultAnnotationReader = $reader; }
[ "private", "function", "initDefaultAnnotationReader", "(", ")", "{", "if", "(", "null", "!==", "self", "::", "$", "defaultAnnotationReader", ")", "{", "return", ";", "}", "$", "docParser", "=", "new", "DocParser", "(", ")", ";", "$", "docParser", "->", "se...
Create default annotation reader for extension @throws \RuntimeException
[ "Create", "default", "annotation", "reader", "for", "extension" ]
277a62748806359d6e3ad6cc88f04a8d02ed68bd
https://github.com/KonstantinKuklin/doctrine-compressed-fields/blob/277a62748806359d6e3ad6cc88f04a8d02ed68bd/src/KonstantinKuklin/DoctrineCompressedFields/EventListener/LoadClassMetadataListener.php#L39-L58
train
phlexible/phlexible
src/Phlexible/Bundle/MediaTemplateBundle/Controller/TemplatesController.php
TemplatesController.listAction
public function listAction() { $repository = $this->get('phlexible_media_template.template_manager'); $allTemplates = $repository->findAll(); $templates = []; foreach ($allTemplates as $template) { if (substr($template->getKey(), 0, 4) === '_mm_') { continue; } $templates[] = [ 'key' => $template->getKey(), 'type' => $template->getType(), ]; } return new JsonResponse(['templates' => $templates]); }
php
public function listAction() { $repository = $this->get('phlexible_media_template.template_manager'); $allTemplates = $repository->findAll(); $templates = []; foreach ($allTemplates as $template) { if (substr($template->getKey(), 0, 4) === '_mm_') { continue; } $templates[] = [ 'key' => $template->getKey(), 'type' => $template->getType(), ]; } return new JsonResponse(['templates' => $templates]); }
[ "public", "function", "listAction", "(", ")", "{", "$", "repository", "=", "$", "this", "->", "get", "(", "'phlexible_media_template.template_manager'", ")", ";", "$", "allTemplates", "=", "$", "repository", "->", "findAll", "(", ")", ";", "$", "templates", ...
List mediatemplates. @return JsonResponse @Route("/list", name="mediatemplates_templates_list")
[ "List", "mediatemplates", "." ]
132f24924c9bb0dbb6c1ea84db0a463f97fa3893
https://github.com/phlexible/phlexible/blob/132f24924c9bb0dbb6c1ea84db0a463f97fa3893/src/Phlexible/Bundle/MediaTemplateBundle/Controller/TemplatesController.php#L40-L59
train
phlexible/phlexible
src/Phlexible/Bundle/MediaTemplateBundle/Controller/TemplatesController.php
TemplatesController.createAction
public function createAction(Request $request) { $templateRepository = $this->get('phlexible_media_template.template_manager'); $type = $request->get('type'); $key = $request->get('key'); switch ($type) { case 'image': $template = new ImageTemplate(); $template->setCache(false); break; case 'video': $template = new VideoTemplate(); $template->setCache(true); break; case 'audio': $template = new AudioTemplate(); $template->setCache(true); break; default: throw new InvalidArgumentException("Unknown template type $type"); } $template->setKey($key); $templateRepository->updateTemplate($template); return new ResultResponse(true, 'New "'.$type.'" template "'.$key.'" created.'); }
php
public function createAction(Request $request) { $templateRepository = $this->get('phlexible_media_template.template_manager'); $type = $request->get('type'); $key = $request->get('key'); switch ($type) { case 'image': $template = new ImageTemplate(); $template->setCache(false); break; case 'video': $template = new VideoTemplate(); $template->setCache(true); break; case 'audio': $template = new AudioTemplate(); $template->setCache(true); break; default: throw new InvalidArgumentException("Unknown template type $type"); } $template->setKey($key); $templateRepository->updateTemplate($template); return new ResultResponse(true, 'New "'.$type.'" template "'.$key.'" created.'); }
[ "public", "function", "createAction", "(", "Request", "$", "request", ")", "{", "$", "templateRepository", "=", "$", "this", "->", "get", "(", "'phlexible_media_template.template_manager'", ")", ";", "$", "type", "=", "$", "request", "->", "get", "(", "'type'"...
Create mediatemplate. @param Request $request @throws \InvalidArgumentException @return ResultResponse @Route("/create", name="mediatemplates_templates_create")
[ "Create", "mediatemplate", "." ]
132f24924c9bb0dbb6c1ea84db0a463f97fa3893
https://github.com/phlexible/phlexible/blob/132f24924c9bb0dbb6c1ea84db0a463f97fa3893/src/Phlexible/Bundle/MediaTemplateBundle/Controller/TemplatesController.php#L71-L100
train
Opifer/ContentBundle
Repository/BlockLogEntryRepository.php
BlockLogEntryRepository.findDistinctByRootId
public function findDistinctByRootId($rootId) { $qb = $this->createQueryBuilder('l') ->andWhere('l.rootId = :rootId') ->groupBy('l.rootVersion') ->setParameter('rootId', $rootId); return $qb->getQuery()->getResult(); }
php
public function findDistinctByRootId($rootId) { $qb = $this->createQueryBuilder('l') ->andWhere('l.rootId = :rootId') ->groupBy('l.rootVersion') ->setParameter('rootId', $rootId); return $qb->getQuery()->getResult(); }
[ "public", "function", "findDistinctByRootId", "(", "$", "rootId", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "'l'", ")", "->", "andWhere", "(", "'l.rootId = :rootId'", ")", "->", "groupBy", "(", "'l.rootVersion'", ")", "->", "set...
Returns a list of BlockLogEntries distinct by rootId @param integer $rootId @return ArrayCollection
[ "Returns", "a", "list", "of", "BlockLogEntries", "distinct", "by", "rootId" ]
df44ef36b81a839ce87ea9a92f7728618111541f
https://github.com/Opifer/ContentBundle/blob/df44ef36b81a839ce87ea9a92f7728618111541f/Repository/BlockLogEntryRepository.php#L39-L47
train
Opifer/ContentBundle
Repository/BlockLogEntryRepository.php
BlockLogEntryRepository.getLogEntriesRoot
public function getLogEntriesRoot($entity, $rootVersion = null) { $q = $this->getLogEntriesQueryRoot($entity, $rootVersion); return $q->getResult(); }
php
public function getLogEntriesRoot($entity, $rootVersion = null) { $q = $this->getLogEntriesQueryRoot($entity, $rootVersion); return $q->getResult(); }
[ "public", "function", "getLogEntriesRoot", "(", "$", "entity", ",", "$", "rootVersion", "=", "null", ")", "{", "$", "q", "=", "$", "this", "->", "getLogEntriesQueryRoot", "(", "$", "entity", ",", "$", "rootVersion", ")", ";", "return", "$", "q", "->", ...
Loads all log entries for the given entity @param object $entity @param integer $rootVersion @return array
[ "Loads", "all", "log", "entries", "for", "the", "given", "entity" ]
df44ef36b81a839ce87ea9a92f7728618111541f
https://github.com/Opifer/ContentBundle/blob/df44ef36b81a839ce87ea9a92f7728618111541f/Repository/BlockLogEntryRepository.php#L57-L62
train
Opifer/ContentBundle
Repository/BlockLogEntryRepository.php
BlockLogEntryRepository.getLogEntriesQueryRoot
public function getLogEntriesQueryRoot($entity, $rootVersion = null) { $wrapped = new EntityWrapper($entity, $this->_em); $objectClass = $wrapped->getMetadata()->name; $meta = $this->getClassMetadata(); $dql = "SELECT log FROM {$meta->name} log"; $dql .= " WHERE log.objectId = :objectId"; $dql .= " AND log.objectClass = :objectClass"; $dql .= " AND log.rootVersion <= :rootVersion"; $dql .= " ORDER BY log.version DESC"; $objectId = $wrapped->getIdentifier(); $q = $this->_em->createQuery($dql); $q->setParameters(compact('objectId', 'objectClass', 'rootVersion')); return $q; }
php
public function getLogEntriesQueryRoot($entity, $rootVersion = null) { $wrapped = new EntityWrapper($entity, $this->_em); $objectClass = $wrapped->getMetadata()->name; $meta = $this->getClassMetadata(); $dql = "SELECT log FROM {$meta->name} log"; $dql .= " WHERE log.objectId = :objectId"; $dql .= " AND log.objectClass = :objectClass"; $dql .= " AND log.rootVersion <= :rootVersion"; $dql .= " ORDER BY log.version DESC"; $objectId = $wrapped->getIdentifier(); $q = $this->_em->createQuery($dql); $q->setParameters(compact('objectId', 'objectClass', 'rootVersion')); return $q; }
[ "public", "function", "getLogEntriesQueryRoot", "(", "$", "entity", ",", "$", "rootVersion", "=", "null", ")", "{", "$", "wrapped", "=", "new", "EntityWrapper", "(", "$", "entity", ",", "$", "this", "->", "_em", ")", ";", "$", "objectClass", "=", "$", ...
Get the query for loading of log entries @param object $entity @param integer $rootVersion @return Query
[ "Get", "the", "query", "for", "loading", "of", "log", "entries" ]
df44ef36b81a839ce87ea9a92f7728618111541f
https://github.com/Opifer/ContentBundle/blob/df44ef36b81a839ce87ea9a92f7728618111541f/Repository/BlockLogEntryRepository.php#L72-L88
train
ytubes/videos
controllers/ViewController.php
ViewController.actionIndex
public function actionIndex($slug) { $this->trigger(self::EVENT_BEFORE_VIEW_SHOW); $data['slug'] = $slug; $data['route'] = '/' . $this->getRoute(); $videoFinder = new VideoFinder(); $data['video'] = $videoFinder->findBySlug($slug); if (empty($data['video'])) { throw new NotFoundHttpException('The requested page does not exist.'); } $settings = Yii::$app->settings->getAll(); $settings['videos'] = Module::getInstance()->settings->getAll(); if ($data['video']['template'] !== '') { $template = $data['video']['template']; } else { $template = 'view'; } Event::on(self::class, self::EVENT_AFTER_VIEW_SHOW, [\ytubes\videos\events\UpdateCountersEvent::class, 'onClickVideo'], $data); $this->trigger(self::EVENT_AFTER_VIEW_SHOW); return $this->render($template, [ 'data' => $data, 'settings' => $settings ]); }
php
public function actionIndex($slug) { $this->trigger(self::EVENT_BEFORE_VIEW_SHOW); $data['slug'] = $slug; $data['route'] = '/' . $this->getRoute(); $videoFinder = new VideoFinder(); $data['video'] = $videoFinder->findBySlug($slug); if (empty($data['video'])) { throw new NotFoundHttpException('The requested page does not exist.'); } $settings = Yii::$app->settings->getAll(); $settings['videos'] = Module::getInstance()->settings->getAll(); if ($data['video']['template'] !== '') { $template = $data['video']['template']; } else { $template = 'view'; } Event::on(self::class, self::EVENT_AFTER_VIEW_SHOW, [\ytubes\videos\events\UpdateCountersEvent::class, 'onClickVideo'], $data); $this->trigger(self::EVENT_AFTER_VIEW_SHOW); return $this->render($template, [ 'data' => $data, 'settings' => $settings ]); }
[ "public", "function", "actionIndex", "(", "$", "slug", ")", "{", "$", "this", "->", "trigger", "(", "self", "::", "EVENT_BEFORE_VIEW_SHOW", ")", ";", "$", "data", "[", "'slug'", "]", "=", "$", "slug", ";", "$", "data", "[", "'route'", "]", "=", "'/'"...
Displays a single Videos model. @param integer $id @return mixed
[ "Displays", "a", "single", "Videos", "model", "." ]
a35ecb1f8e38381063fbd757683a13df3a8cbc48
https://github.com/ytubes/videos/blob/a35ecb1f8e38381063fbd757683a13df3a8cbc48/controllers/ViewController.php#L51-L82
train
mszewcz/php-light-framework
src/Variables/Specific/Cookie.php
Cookie.getExpireTime
private function getExpireTime(array $expires = ['m' => 1]): int { $expireTime = \time(); if (\is_array($expires)) { if (isset($expires['y'])) { $expireTime += \intval(0 + $expires['y']) * 60 * 60 * 24 * 365; } if (isset($expires['m'])) { $expireTime += \intval(0 + $expires['m']) * 60 * 60 * 24 * 30; } if (isset($expires['d'])) { $expireTime += \intval(0 + $expires['d']) * 60 * 60 * 24; } if (isset($expires['h'])) { $expireTime += \intval(0 + $expires['h']) * 60 * 60; } if (isset($expires['i'])) { $expireTime += \intval(0 + $expires['i']) * 60; } if (isset($expires['s'])) { $expireTime += \intval(0 + $expires['s']); } } return $expireTime; }
php
private function getExpireTime(array $expires = ['m' => 1]): int { $expireTime = \time(); if (\is_array($expires)) { if (isset($expires['y'])) { $expireTime += \intval(0 + $expires['y']) * 60 * 60 * 24 * 365; } if (isset($expires['m'])) { $expireTime += \intval(0 + $expires['m']) * 60 * 60 * 24 * 30; } if (isset($expires['d'])) { $expireTime += \intval(0 + $expires['d']) * 60 * 60 * 24; } if (isset($expires['h'])) { $expireTime += \intval(0 + $expires['h']) * 60 * 60; } if (isset($expires['i'])) { $expireTime += \intval(0 + $expires['i']) * 60; } if (isset($expires['s'])) { $expireTime += \intval(0 + $expires['s']); } } return $expireTime; }
[ "private", "function", "getExpireTime", "(", "array", "$", "expires", "=", "[", "'m'", "=>", "1", "]", ")", ":", "int", "{", "$", "expireTime", "=", "\\", "time", "(", ")", ";", "if", "(", "\\", "is_array", "(", "$", "expires", ")", ")", "{", "if...
Calculates cookie expire time @param array $expires @return int
[ "Calculates", "cookie", "expire", "time" ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Variables/Specific/Cookie.php#L78-L102
train
mszewcz/php-light-framework
src/Variables/Specific/Cookie.php
Cookie.get
public function get(string $variableName = null, int $type = Variables::TYPE_STRING) { if ($variableName === null) { throw new BadMethodCallException('Variable name must be specified'); } if (isset($this->variables[$variableName])) { return $this->cast($this->variables[$variableName], $type); } return $this->cast(null, $type); }
php
public function get(string $variableName = null, int $type = Variables::TYPE_STRING) { if ($variableName === null) { throw new BadMethodCallException('Variable name must be specified'); } if (isset($this->variables[$variableName])) { return $this->cast($this->variables[$variableName], $type); } return $this->cast(null, $type); }
[ "public", "function", "get", "(", "string", "$", "variableName", "=", "null", ",", "int", "$", "type", "=", "Variables", "::", "TYPE_STRING", ")", "{", "if", "(", "$", "variableName", "===", "null", ")", "{", "throw", "new", "BadMethodCallException", "(", ...
Returns COOKIE variable's value. If variable doesn't exist method returns default value for specified type. @param string|null $variableName @param int $type @return array|float|int|mixed|null|string
[ "Returns", "COOKIE", "variable", "s", "value", ".", "If", "variable", "doesn", "t", "exist", "method", "returns", "default", "value", "for", "specified", "type", "." ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Variables/Specific/Cookie.php#L111-L120
train
mszewcz/php-light-framework
src/Variables/Specific/Cookie.php
Cookie.set
public function set(string $variableName = null, $variableValue = null, array $expires = ['m' => 1], bool $encrypted = true): Cookie { if ($variableName === null) { throw new BadMethodCallException('Variable name must be specified'); } \setcookie( $variableName, $encrypted === true ? $variableValue : $variableValue, $this->getExpireTime($expires), $this->getPath(), $this->getDomain(), $this->isSecure(), $this->isHttpOnly() ); $this->variables[$variableName] = $variableValue; return static::$instance; }
php
public function set(string $variableName = null, $variableValue = null, array $expires = ['m' => 1], bool $encrypted = true): Cookie { if ($variableName === null) { throw new BadMethodCallException('Variable name must be specified'); } \setcookie( $variableName, $encrypted === true ? $variableValue : $variableValue, $this->getExpireTime($expires), $this->getPath(), $this->getDomain(), $this->isSecure(), $this->isHttpOnly() ); $this->variables[$variableName] = $variableValue; return static::$instance; }
[ "public", "function", "set", "(", "string", "$", "variableName", "=", "null", ",", "$", "variableValue", "=", "null", ",", "array", "$", "expires", "=", "[", "'m'", "=>", "1", "]", ",", "bool", "$", "encrypted", "=", "true", ")", ":", "Cookie", "{", ...
Sets COOKIE variable. @param string|null $variableName @param null $variableValue @param array $expires @param bool $encrypted @return Cookie
[ "Sets", "COOKIE", "variable", "." ]
4d3b46781c387202c2dfbdb8760151b3ae8ef49c
https://github.com/mszewcz/php-light-framework/blob/4d3b46781c387202c2dfbdb8760151b3ae8ef49c/src/Variables/Specific/Cookie.php#L131-L150
train
ironedgesoftware/common-utils
src/System/SystemService.php
SystemService.executeCommand
public function executeCommand(string $cmd, array $arguments = [], array $options = []) { $options = array_replace( [ 'overrideExitCode' => null, 'exceptionMessage' => 'There was an error while executing the command.', 'returnString' => false, 'implodeSeparator' => PHP_EOL, 'postCommand' => '' ], $options ); foreach ($arguments as $arg) { $cmd .= ' '.escapeshellarg($arg); } $cmd .= $options['postCommand']; exec($cmd, $output, $status); $status = $status && $options['overrideExitCode'] ? $options['overrideExitCode'] : $status; $this->_lastExecutedCommand['cmd'] = $cmd; $this->_lastExecutedCommand['arguments'] = $arguments; $this->_lastExecutedCommand['options'] = $options; $this->_lastExecutedCommand['output'] = $output; $this->_lastExecutedCommand['exitCode'] = $status; if ($status) { throw CommandException::create( $options['exceptionMessage'], $options['overrideExitCode'] ? $options['overrideExitCode'] : $status, $output, $cmd, $arguments ); } return $options['returnString'] ? implode($options['implodeSeparator'], $output) : $output; }
php
public function executeCommand(string $cmd, array $arguments = [], array $options = []) { $options = array_replace( [ 'overrideExitCode' => null, 'exceptionMessage' => 'There was an error while executing the command.', 'returnString' => false, 'implodeSeparator' => PHP_EOL, 'postCommand' => '' ], $options ); foreach ($arguments as $arg) { $cmd .= ' '.escapeshellarg($arg); } $cmd .= $options['postCommand']; exec($cmd, $output, $status); $status = $status && $options['overrideExitCode'] ? $options['overrideExitCode'] : $status; $this->_lastExecutedCommand['cmd'] = $cmd; $this->_lastExecutedCommand['arguments'] = $arguments; $this->_lastExecutedCommand['options'] = $options; $this->_lastExecutedCommand['output'] = $output; $this->_lastExecutedCommand['exitCode'] = $status; if ($status) { throw CommandException::create( $options['exceptionMessage'], $options['overrideExitCode'] ? $options['overrideExitCode'] : $status, $output, $cmd, $arguments ); } return $options['returnString'] ? implode($options['implodeSeparator'], $output) : $output; }
[ "public", "function", "executeCommand", "(", "string", "$", "cmd", ",", "array", "$", "arguments", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_replace", "(", "[", "'overrideExitCode'", "=>", "null", ...
Executes a Command. @param string $cmd - Command. @param array $arguments - Arguments. @param array $options - Options. @throws CommandException @return array|string
[ "Executes", "a", "Command", "." ]
1cbe4c77a4abeb17a45250b9b86353457ce6c2b4
https://github.com/ironedgesoftware/common-utils/blob/1cbe4c77a4abeb17a45250b9b86353457ce6c2b4/src/System/SystemService.php#L101-L145
train
ironedgesoftware/common-utils
src/System/SystemService.php
SystemService.mkdir
public function mkdir(string $dir, array $options = []): SystemService { $options = array_replace( [ 'mode' => 0777, 'recursive' => true, 'context' => null ], $options ); if (file_exists($dir)) { if (!is_dir($dir)) { throw NotADirectoryException::create( 'Can\'t create directory "'.$dir.'" because it exists and it\'s not a directory.' ); } return $this; } $args = [ $dir, $options['mode'], $options['recursive'] ]; if ($options['context'] !== null) { $args[] = $options['context']; } if (!@mkdir(...$args)) { $lastError = $this->getLastPhpError(); throw IOException::create( 'Couldn\'t create directory "'.$dir.'". PHP Error: '.print_r($lastError, true) ); } return $this; }
php
public function mkdir(string $dir, array $options = []): SystemService { $options = array_replace( [ 'mode' => 0777, 'recursive' => true, 'context' => null ], $options ); if (file_exists($dir)) { if (!is_dir($dir)) { throw NotADirectoryException::create( 'Can\'t create directory "'.$dir.'" because it exists and it\'s not a directory.' ); } return $this; } $args = [ $dir, $options['mode'], $options['recursive'] ]; if ($options['context'] !== null) { $args[] = $options['context']; } if (!@mkdir(...$args)) { $lastError = $this->getLastPhpError(); throw IOException::create( 'Couldn\'t create directory "'.$dir.'". PHP Error: '.print_r($lastError, true) ); } return $this; }
[ "public", "function", "mkdir", "(", "string", "$", "dir", ",", "array", "$", "options", "=", "[", "]", ")", ":", "SystemService", "{", "$", "options", "=", "array_replace", "(", "[", "'mode'", "=>", "0777", ",", "'recursive'", "=>", "true", ",", "'cont...
Creates a directory. If it already exists, it doesn't throw an exception. Options: - mode: Default 0777 - recursive: Create missing directories recursively. - context: Stream context. @param string $dir - Directory. @param array $options - Options. @throws IOException @return SystemService
[ "Creates", "a", "directory", ".", "If", "it", "already", "exists", "it", "doesn", "t", "throw", "an", "exception", "." ]
1cbe4c77a4abeb17a45250b9b86353457ce6c2b4
https://github.com/ironedgesoftware/common-utils/blob/1cbe4c77a4abeb17a45250b9b86353457ce6c2b4/src/System/SystemService.php#L163-L203
train
ironedgesoftware/common-utils
src/System/SystemService.php
SystemService.rm
public function rm(string $fileOrDirectory, array $options = []): SystemService { $options = array_replace( [ 'force' => false, 'recursive' => false, 'context' => null, 'skipIfAlreadyRemoved' => true ], $options ); if (!file_exists($fileOrDirectory) && $options['skipIfAlreadyRemoved']) { return $this; } $args = [ $fileOrDirectory ]; if ($options['context'] !== null) { $args[] = $options['context']; } if (is_dir($fileOrDirectory) && !is_link($fileOrDirectory)) { if (!$options['force']) { throw CantRemoveDirectoryException::create( '"' . $fileOrDirectory . '" is a directory. If you really want to remove it, ' . 'set the "force" option to "true".' ); } if ($options['recursive']) { $elements = $this->scandir( $fileOrDirectory, [ 'recursive' => true, 'context' => $options['context'], 'skipDots' => true, 'skipSymlinks' => true ] ); foreach ($elements as $e) { $this->rm($e, $options); } } if (!@rmdir(...$args)) { throw IOException::create( 'Couldn\'t remove directory "'.$fileOrDirectory.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } } else if (!@unlink(...$args)) { throw IOException::create( 'Couldn\'t remove file or symlink "'.$fileOrDirectory.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } return $this; }
php
public function rm(string $fileOrDirectory, array $options = []): SystemService { $options = array_replace( [ 'force' => false, 'recursive' => false, 'context' => null, 'skipIfAlreadyRemoved' => true ], $options ); if (!file_exists($fileOrDirectory) && $options['skipIfAlreadyRemoved']) { return $this; } $args = [ $fileOrDirectory ]; if ($options['context'] !== null) { $args[] = $options['context']; } if (is_dir($fileOrDirectory) && !is_link($fileOrDirectory)) { if (!$options['force']) { throw CantRemoveDirectoryException::create( '"' . $fileOrDirectory . '" is a directory. If you really want to remove it, ' . 'set the "force" option to "true".' ); } if ($options['recursive']) { $elements = $this->scandir( $fileOrDirectory, [ 'recursive' => true, 'context' => $options['context'], 'skipDots' => true, 'skipSymlinks' => true ] ); foreach ($elements as $e) { $this->rm($e, $options); } } if (!@rmdir(...$args)) { throw IOException::create( 'Couldn\'t remove directory "'.$fileOrDirectory.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } } else if (!@unlink(...$args)) { throw IOException::create( 'Couldn\'t remove file or symlink "'.$fileOrDirectory.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } return $this; }
[ "public", "function", "rm", "(", "string", "$", "fileOrDirectory", ",", "array", "$", "options", "=", "[", "]", ")", ":", "SystemService", "{", "$", "options", "=", "array_replace", "(", "[", "'force'", "=>", "false", ",", "'recursive'", "=>", "false", "...
Removes a file, symlink or directory. It removes directories, if option "force" is true. If it's a directory and option "force" is false, it throws an exception. Also, it removes directories recursively. If file, symlink or directory already does not exist, it does NOT throw an exception. Options: - force: If $fileOrDirectory is a directory, you need to set this option to "true" to be able to remove it. By default, it's set to "false". - recursive: If this option is "true" and $fileOrDirectory is a directory, then we'll traverse it and remove every file and directory found on it as well. By default, it's set to "false". @param string $fileOrDirectory - File, symlink or directory. @param array $options - Options. @throws IOException @return SystemService
[ "Removes", "a", "file", "symlink", "or", "directory", ".", "It", "removes", "directories", "if", "option", "force", "is", "true", ".", "If", "it", "s", "a", "directory", "and", "option", "force", "is", "false", "it", "throws", "an", "exception", ".", "Al...
1cbe4c77a4abeb17a45250b9b86353457ce6c2b4
https://github.com/ironedgesoftware/common-utils/blob/1cbe4c77a4abeb17a45250b9b86353457ce6c2b4/src/System/SystemService.php#L226-L288
train
ironedgesoftware/common-utils
src/System/SystemService.php
SystemService.scandir
public function scandir(string $dir, array $options = []) { $options = array_replace( [ 'sort' => SCANDIR_SORT_NONE, 'context' => null, 'recursive' => false, 'skipDots' => true, 'skipSymlinks' => false ], $options ); if (!$options['skipSymlinks'] && is_link($dir)) { $dir = @readlink($dir); } $args = [ $dir, $options['sort'] ]; if ($options['context']) { $args[] = $options['context']; } if (($tmp = @scandir(...$args)) === false) { throw IOException::create( 'Couldn\'t scan directory "'.$dir.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } if ($options['skipDots']) { $tmp = array_diff($tmp, array('.', '..')); } $result = []; foreach ($tmp as $f) { $f = $dir.'/'.$f; if ($options['skipSymlinks'] && is_link($f)) { continue; } $result[] = $f; if ($options['recursive'] && is_dir($f)) { $result = array_merge( $result, $this->scandir($f, $options) ); } } $tmp = null; return array_unique($result); }
php
public function scandir(string $dir, array $options = []) { $options = array_replace( [ 'sort' => SCANDIR_SORT_NONE, 'context' => null, 'recursive' => false, 'skipDots' => true, 'skipSymlinks' => false ], $options ); if (!$options['skipSymlinks'] && is_link($dir)) { $dir = @readlink($dir); } $args = [ $dir, $options['sort'] ]; if ($options['context']) { $args[] = $options['context']; } if (($tmp = @scandir(...$args)) === false) { throw IOException::create( 'Couldn\'t scan directory "'.$dir.'". Last PHP Error: '. print_r($this->getLastPhpError(), true) ); } if ($options['skipDots']) { $tmp = array_diff($tmp, array('.', '..')); } $result = []; foreach ($tmp as $f) { $f = $dir.'/'.$f; if ($options['skipSymlinks'] && is_link($f)) { continue; } $result[] = $f; if ($options['recursive'] && is_dir($f)) { $result = array_merge( $result, $this->scandir($f, $options) ); } } $tmp = null; return array_unique($result); }
[ "public", "function", "scandir", "(", "string", "$", "dir", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_replace", "(", "[", "'sort'", "=>", "SCANDIR_SORT_NONE", ",", "'context'", "=>", "null", ",", "'recursive'", "=...
Scans a directory and returns an array of files, symlinks and directories. Options: - sort: One of the SCANDIR_SORT_* constants. Defaults to SCANDIR_SORT_NONE. - context: Context to use for the scandir function. Defaults to "null". - recursive: If this option is "true", we'll call this method for every directory found. Defaults to "false". - skipDots: If "true", then "." and ".." won't be returned. Defaults to "true". - skipSymlinks: If "true", then symlinks will be skipped. Defaults to "true". Please note that this option also applies if the $dir argument is a symlink. If this option is false then we will call "readlink" to determine where the symlink points to. @param string $dir - Directory to scan. @param array $options - Options. @throws IOException @return array
[ "Scans", "a", "directory", "and", "returns", "an", "array", "of", "files", "symlinks", "and", "directories", "." ]
1cbe4c77a4abeb17a45250b9b86353457ce6c2b4
https://github.com/ironedgesoftware/common-utils/blob/1cbe4c77a4abeb17a45250b9b86353457ce6c2b4/src/System/SystemService.php#L312-L371
train
toadsuck/toadsuck-core
src/Dispatcher.php
Dispatcher.getRoutes
public function getRoutes() { $router_factory = new RouterFactory; $router = $router_factory->newInstance(); $routes_file = $this->getAppResourcePath('config/routes.php'); if (file_exists($routes_file)) { // Let the app specify it's own routes. include_once($routes_file); } else { // Fall back on some sensible defaults. $router->add(null, '/'); $router->add(null, '/{controller}'); $router->add(null, '/{controller}/{action}'); $router->add(null, '/{controller}/{action}/{id}'); } $this->router = $router; }
php
public function getRoutes() { $router_factory = new RouterFactory; $router = $router_factory->newInstance(); $routes_file = $this->getAppResourcePath('config/routes.php'); if (file_exists($routes_file)) { // Let the app specify it's own routes. include_once($routes_file); } else { // Fall back on some sensible defaults. $router->add(null, '/'); $router->add(null, '/{controller}'); $router->add(null, '/{controller}/{action}'); $router->add(null, '/{controller}/{action}/{id}'); } $this->router = $router; }
[ "public", "function", "getRoutes", "(", ")", "{", "$", "router_factory", "=", "new", "RouterFactory", ";", "$", "router", "=", "$", "router_factory", "->", "newInstance", "(", ")", ";", "$", "routes_file", "=", "$", "this", "->", "getAppResourcePath", "(", ...
What routes have been configured for this app?
[ "What", "routes", "have", "been", "configured", "for", "this", "app?" ]
1c307b8410d43dcee42e215403ed905a70fc55de
https://github.com/toadsuck/toadsuck-core/blob/1c307b8410d43dcee42e215403ed905a70fc55de/src/Dispatcher.php#L99-L118
train
vivait/symfony-console-promptable-options
src/Command/PromptableOptionsTrait.php
PromptableOptionsTrait.addPrompts
protected function addPrompts(array $options = []) { $resolver = $this->getConfigResolver(); $optionNames = []; foreach ($options as $key => $value) { if (is_string($value)) { $optionNames[] = $value; $this->promptConfig[$key] = $resolver->resolve([]); continue; } if (is_array($value)) { $optionNames[] = $key; $this->promptConfig[$key] = $resolver->resolve($value); continue; } throw new \InvalidArgumentException("Invalid value passed into `addPrompts`."); } $this->consolePrompts = array_unique(array_merge($this->consolePrompts, $optionNames)); foreach ($optionNames as $option) { if ($this->getDefinition()->hasOption($option)) { continue; } $this->addOption( $option, null, InputOption::VALUE_OPTIONAL, $this->promptConfig[$option]['description'] ); } return $this; }
php
protected function addPrompts(array $options = []) { $resolver = $this->getConfigResolver(); $optionNames = []; foreach ($options as $key => $value) { if (is_string($value)) { $optionNames[] = $value; $this->promptConfig[$key] = $resolver->resolve([]); continue; } if (is_array($value)) { $optionNames[] = $key; $this->promptConfig[$key] = $resolver->resolve($value); continue; } throw new \InvalidArgumentException("Invalid value passed into `addPrompts`."); } $this->consolePrompts = array_unique(array_merge($this->consolePrompts, $optionNames)); foreach ($optionNames as $option) { if ($this->getDefinition()->hasOption($option)) { continue; } $this->addOption( $option, null, InputOption::VALUE_OPTIONAL, $this->promptConfig[$option]['description'] ); } return $this; }
[ "protected", "function", "addPrompts", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "resolver", "=", "$", "this", "->", "getConfigResolver", "(", ")", ";", "$", "optionNames", "=", "[", "]", ";", "foreach", "(", "$", "options", "as", "...
Add prompts through a key value array of option names => their configuration. The configuration is optional. e.g. [ 'myOption' => ['type' => 'int'], 'myDefaultOption', 'myOtherOption' => ['description' => 'Hello!'] ] @param array $options @return static
[ "Add", "prompts", "through", "a", "key", "value", "array", "of", "option", "names", "=", ">", "their", "configuration", ".", "The", "configuration", "is", "optional", "." ]
79fbaa835efcc5a0d28f3ede1e92d9f9ac7a2ba4
https://github.com/vivait/symfony-console-promptable-options/blob/79fbaa835efcc5a0d28f3ede1e92d9f9ac7a2ba4/src/Command/PromptableOptionsTrait.php#L203-L241
train