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
Linkvalue-Interne/MajoraFrameworkExtraBundle
src/Majora/Framework/Validation/Listener/ValidationExceptionListener.php
ValidationExceptionListener.onKernelException
public function onKernelException(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); $exception = $event->getException(); if (!$this->supports($request)) { return; } $statusCode = $exception instanceof HttpException ? $exception->getStatusCode() : 500; $errors = array(); switch(true) { // validation exception case $exception instanceof ValidationException : $errors = $this->parseValidationException($exception); $statusCode = 400; break; // other http exceptions default: $errors = array($exception->getMessage()); } $data = array( 'code' => $statusCode, 'message' => $exception->getMessage(), 'errors' => $errors ); if ($this->debug) { $data['trace'] = explode("\n", $exception->getTraceAsString()); } $event->setResponse(new JsonResponse($data, $statusCode)); }
php
public function onKernelException(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); $exception = $event->getException(); if (!$this->supports($request)) { return; } $statusCode = $exception instanceof HttpException ? $exception->getStatusCode() : 500; $errors = array(); switch(true) { // validation exception case $exception instanceof ValidationException : $errors = $this->parseValidationException($exception); $statusCode = 400; break; // other http exceptions default: $errors = array($exception->getMessage()); } $data = array( 'code' => $statusCode, 'message' => $exception->getMessage(), 'errors' => $errors ); if ($this->debug) { $data['trace'] = explode("\n", $exception->getTraceAsString()); } $event->setResponse(new JsonResponse($data, $statusCode)); }
[ "public", "function", "onKernelException", "(", "GetResponseForExceptionEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "$", "exception", "=", "$", "event", "->", "getException", "(", ")", ";", "if", "(", "!", "$", "this", "->", "supports", "(", "$", "request", ")", ")", "{", "return", ";", "}", "$", "statusCode", "=", "$", "exception", "instanceof", "HttpException", "?", "$", "exception", "->", "getStatusCode", "(", ")", ":", "500", ";", "$", "errors", "=", "array", "(", ")", ";", "switch", "(", "true", ")", "{", "// validation exception", "case", "$", "exception", "instanceof", "ValidationException", ":", "$", "errors", "=", "$", "this", "->", "parseValidationException", "(", "$", "exception", ")", ";", "$", "statusCode", "=", "400", ";", "break", ";", "// other http exceptions", "default", ":", "$", "errors", "=", "array", "(", "$", "exception", "->", "getMessage", "(", ")", ")", ";", "}", "$", "data", "=", "array", "(", "'code'", "=>", "$", "statusCode", ",", "'message'", "=>", "$", "exception", "->", "getMessage", "(", ")", ",", "'errors'", "=>", "$", "errors", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "$", "data", "[", "'trace'", "]", "=", "explode", "(", "\"\\n\"", ",", "$", "exception", "->", "getTraceAsString", "(", ")", ")", ";", "}", "$", "event", "->", "setResponse", "(", "new", "JsonResponse", "(", "$", "data", ",", "$", "statusCode", ")", ")", ";", "}" ]
Exception event handler @param GetResponseForExceptionEvent $event
[ "Exception", "event", "handler" ]
6f368380cfc39d27fafb0844e9a53b4d86d7c034
https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Framework/Validation/Listener/ValidationExceptionListener.php#L53-L88
train
Facebook-Anonymous-Publisher/wordfilter
src/Match/Chinese.php
Chinese.transformWords
protected function transformWords(array $words) { $text = implode(" {$this->determine} ", $words); $text = $this->pinyin->sentence($text); return explode(" {$this->determine} ", $text); }
php
protected function transformWords(array $words) { $text = implode(" {$this->determine} ", $words); $text = $this->pinyin->sentence($text); return explode(" {$this->determine} ", $text); }
[ "protected", "function", "transformWords", "(", "array", "$", "words", ")", "{", "$", "text", "=", "implode", "(", "\" {$this->determine} \"", ",", "$", "words", ")", ";", "$", "text", "=", "$", "this", "->", "pinyin", "->", "sentence", "(", "$", "text", ")", ";", "return", "explode", "(", "\" {$this->determine} \"", ",", "$", "text", ")", ";", "}" ]
Transform words to pinyin. @param array $words @return array
[ "Transform", "words", "to", "pinyin", "." ]
0a2ce766a509650ac622eeaa809391ebf304885e
https://github.com/Facebook-Anonymous-Publisher/wordfilter/blob/0a2ce766a509650ac622eeaa809391ebf304885e/src/Match/Chinese.php#L61-L68
train
ARCANESOFT/Blog
src/ViewComposers/Admin/Dashboard/TagsRatiosComposer.php
TagsRatiosComposer.prepareRatios
protected function prepareRatios(Collection $tags) { $ratios = $tags->filter(function (Tag $tag) { return $tag->hasPosts(); }) ->transform(function (Tag $tag) { return [ 'label' => $tag->name, 'posts' => $tag->posts->count(), ]; }) ->sortByDesc('posts'); $chunk = $ratios->splice(5); $ratios = $this->colorizeRatios($ratios); return $chunk->isEmpty() ? $ratios : $ratios->push([ 'label' => 'Other Tags', 'posts' => $chunk->sum('posts'), 'color' => '#D2D6DE', ]); }
php
protected function prepareRatios(Collection $tags) { $ratios = $tags->filter(function (Tag $tag) { return $tag->hasPosts(); }) ->transform(function (Tag $tag) { return [ 'label' => $tag->name, 'posts' => $tag->posts->count(), ]; }) ->sortByDesc('posts'); $chunk = $ratios->splice(5); $ratios = $this->colorizeRatios($ratios); return $chunk->isEmpty() ? $ratios : $ratios->push([ 'label' => 'Other Tags', 'posts' => $chunk->sum('posts'), 'color' => '#D2D6DE', ]); }
[ "protected", "function", "prepareRatios", "(", "Collection", "$", "tags", ")", "{", "$", "ratios", "=", "$", "tags", "->", "filter", "(", "function", "(", "Tag", "$", "tag", ")", "{", "return", "$", "tag", "->", "hasPosts", "(", ")", ";", "}", ")", "->", "transform", "(", "function", "(", "Tag", "$", "tag", ")", "{", "return", "[", "'label'", "=>", "$", "tag", "->", "name", ",", "'posts'", "=>", "$", "tag", "->", "posts", "->", "count", "(", ")", ",", "]", ";", "}", ")", "->", "sortByDesc", "(", "'posts'", ")", ";", "$", "chunk", "=", "$", "ratios", "->", "splice", "(", "5", ")", ";", "$", "ratios", "=", "$", "this", "->", "colorizeRatios", "(", "$", "ratios", ")", ";", "return", "$", "chunk", "->", "isEmpty", "(", ")", "?", "$", "ratios", ":", "$", "ratios", "->", "push", "(", "[", "'label'", "=>", "'Other Tags'", ",", "'posts'", "=>", "$", "chunk", "->", "sum", "(", "'posts'", ")", ",", "'color'", "=>", "'#D2D6DE'", ",", "]", ")", ";", "}" ]
Prepare the tags ratios. @param \Illuminate\Database\Eloquent\Collection $tags @return \Illuminate\Database\Eloquent\Collection
[ "Prepare", "the", "tags", "ratios", "." ]
2078fdfdcbccda161c02899b9e1f344f011b2859
https://github.com/ARCANESOFT/Blog/blob/2078fdfdcbccda161c02899b9e1f344f011b2859/src/ViewComposers/Admin/Dashboard/TagsRatiosComposer.php#L52-L73
train
ARCANESOFT/Blog
src/ViewComposers/Admin/Dashboard/TagsRatiosComposer.php
TagsRatiosComposer.colorizeRatios
private function colorizeRatios(Collection $ratios) { $colors = ['#F56954', '#00A65A', '#F39C12', '#00C0EF', '#3C8DBC']; return $ratios->values()->transform(function (array $values, $key) use ($colors) { return $values + ['color' => $colors[$key]]; }); }
php
private function colorizeRatios(Collection $ratios) { $colors = ['#F56954', '#00A65A', '#F39C12', '#00C0EF', '#3C8DBC']; return $ratios->values()->transform(function (array $values, $key) use ($colors) { return $values + ['color' => $colors[$key]]; }); }
[ "private", "function", "colorizeRatios", "(", "Collection", "$", "ratios", ")", "{", "$", "colors", "=", "[", "'#F56954'", ",", "'#00A65A'", ",", "'#F39C12'", ",", "'#00C0EF'", ",", "'#3C8DBC'", "]", ";", "return", "$", "ratios", "->", "values", "(", ")", "->", "transform", "(", "function", "(", "array", "$", "values", ",", "$", "key", ")", "use", "(", "$", "colors", ")", "{", "return", "$", "values", "+", "[", "'color'", "=>", "$", "colors", "[", "$", "key", "]", "]", ";", "}", ")", ";", "}" ]
Colorize the ratios. @param \Illuminate\Database\Eloquent\Collection $ratios @return \Illuminate\Database\Eloquent\Collection
[ "Colorize", "the", "ratios", "." ]
2078fdfdcbccda161c02899b9e1f344f011b2859
https://github.com/ARCANESOFT/Blog/blob/2078fdfdcbccda161c02899b9e1f344f011b2859/src/ViewComposers/Admin/Dashboard/TagsRatiosComposer.php#L82-L89
train
ptlis/grep-db
src/GrepDb.php
GrepDb.searchTable
public function searchTable( string $databaseName, string $tableName, string $searchTerm ): \Generator { return $this->search->searchTable($this->connection, $databaseName, $tableName, $searchTerm); }
php
public function searchTable( string $databaseName, string $tableName, string $searchTerm ): \Generator { return $this->search->searchTable($this->connection, $databaseName, $tableName, $searchTerm); }
[ "public", "function", "searchTable", "(", "string", "$", "databaseName", ",", "string", "$", "tableName", ",", "string", "$", "searchTerm", ")", ":", "\\", "Generator", "{", "return", "$", "this", "->", "search", "->", "searchTable", "(", "$", "this", "->", "connection", ",", "$", "databaseName", ",", "$", "tableName", ",", "$", "searchTerm", ")", ";", "}" ]
Performs search on the specified database and table. @param string $databaseName @param string $tableName @param string $searchTerm @return \Generator|RowSearchResult[]
[ "Performs", "search", "on", "the", "specified", "database", "and", "table", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/GrepDb.php#L58-L64
train
ptlis/grep-db
src/GrepDb.php
GrepDb.searchDatabase
public function searchDatabase( string $databaseName, string $searchTerm ): \Generator { return $this->search->searchDatabase($this->connection, $databaseName, $searchTerm); }
php
public function searchDatabase( string $databaseName, string $searchTerm ): \Generator { return $this->search->searchDatabase($this->connection, $databaseName, $searchTerm); }
[ "public", "function", "searchDatabase", "(", "string", "$", "databaseName", ",", "string", "$", "searchTerm", ")", ":", "\\", "Generator", "{", "return", "$", "this", "->", "search", "->", "searchDatabase", "(", "$", "this", "->", "connection", ",", "$", "databaseName", ",", "$", "searchTerm", ")", ";", "}" ]
Performs search on all tables in the specified database. @param string $databaseName @param string $searchTerm @return \Generator|RowSearchResult[]
[ "Performs", "search", "on", "all", "tables", "in", "the", "specified", "database", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/GrepDb.php#L73-L78
train
ptlis/grep-db
src/GrepDb.php
GrepDb.searchServer
public function searchServer( string $searchTerm ): \Generator { return $this->search->searchServer($this->connection, $searchTerm); }
php
public function searchServer( string $searchTerm ): \Generator { return $this->search->searchServer($this->connection, $searchTerm); }
[ "public", "function", "searchServer", "(", "string", "$", "searchTerm", ")", ":", "\\", "Generator", "{", "return", "$", "this", "->", "search", "->", "searchServer", "(", "$", "this", "->", "connection", ",", "$", "searchTerm", ")", ";", "}" ]
Performs search on all available databases. @param string $searchTerm @return \Generator|RowSearchResult[]
[ "Performs", "search", "on", "all", "available", "databases", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/GrepDb.php#L86-L90
train
ptlis/grep-db
src/GrepDb.php
GrepDb.replaceTable
public function replaceTable( string $databaseName, string $tableName, string $searchTerm, string $replaceTerm ): \Generator { return $this->replace->replaceTable( $this->connection, $databaseName, $tableName, $searchTerm, $replaceTerm ); }
php
public function replaceTable( string $databaseName, string $tableName, string $searchTerm, string $replaceTerm ): \Generator { return $this->replace->replaceTable( $this->connection, $databaseName, $tableName, $searchTerm, $replaceTerm ); }
[ "public", "function", "replaceTable", "(", "string", "$", "databaseName", ",", "string", "$", "tableName", ",", "string", "$", "searchTerm", ",", "string", "$", "replaceTerm", ")", ":", "\\", "Generator", "{", "return", "$", "this", "->", "replace", "->", "replaceTable", "(", "$", "this", "->", "connection", ",", "$", "databaseName", ",", "$", "tableName", ",", "$", "searchTerm", ",", "$", "replaceTerm", ")", ";", "}" ]
Performs search and replacement on the specified database and table. @param string $databaseName @param string $tableName @param string $searchTerm @param string $replaceTerm @return \Generator|RowReplaceResult[]
[ "Performs", "search", "and", "replacement", "on", "the", "specified", "database", "and", "table", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/GrepDb.php#L101-L114
train
ptlis/grep-db
src/GrepDb.php
GrepDb.replaceDatabase
public function replaceDatabase( string $databaseName, string $searchTerm, string $replaceTerm ): \Generator { return $this->replace->replaceDatabase($this->connection, $databaseName, $searchTerm, $replaceTerm); }
php
public function replaceDatabase( string $databaseName, string $searchTerm, string $replaceTerm ): \Generator { return $this->replace->replaceDatabase($this->connection, $databaseName, $searchTerm, $replaceTerm); }
[ "public", "function", "replaceDatabase", "(", "string", "$", "databaseName", ",", "string", "$", "searchTerm", ",", "string", "$", "replaceTerm", ")", ":", "\\", "Generator", "{", "return", "$", "this", "->", "replace", "->", "replaceDatabase", "(", "$", "this", "->", "connection", ",", "$", "databaseName", ",", "$", "searchTerm", ",", "$", "replaceTerm", ")", ";", "}" ]
Performs search and replacement on all tables in the specified database. @param string $databaseName @param string $searchTerm @param string $replaceTerm @return \Generator|RowReplaceResult[]
[ "Performs", "search", "and", "replacement", "on", "all", "tables", "in", "the", "specified", "database", "." ]
7abff68982d426690d0515ccd7adc7a2e3d72a3f
https://github.com/ptlis/grep-db/blob/7abff68982d426690d0515ccd7adc7a2e3d72a3f/src/GrepDb.php#L124-L130
train
ZFury/framework
library/Model/Traits/Memcached.php
Memcached.getCacheService
public function getCacheService() { $memcached = $this->memcached; if (empty($memcached)) { /** * @var \Zend\Cache\Storage\Adapter\Memcached $memcached */ $memcached = $this->getServiceLocator()->get('memcached'); } return $memcached; }
php
public function getCacheService() { $memcached = $this->memcached; if (empty($memcached)) { /** * @var \Zend\Cache\Storage\Adapter\Memcached $memcached */ $memcached = $this->getServiceLocator()->get('memcached'); } return $memcached; }
[ "public", "function", "getCacheService", "(", ")", "{", "$", "memcached", "=", "$", "this", "->", "memcached", ";", "if", "(", "empty", "(", "$", "memcached", ")", ")", "{", "/**\n * @var \\Zend\\Cache\\Storage\\Adapter\\Memcached $memcached\n */", "$", "memcached", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "'memcached'", ")", ";", "}", "return", "$", "memcached", ";", "}" ]
Get memcached service @return \Zend\Cache\Storage\Adapter\Memcached
[ "Get", "memcached", "service" ]
eee4ca2a64d2d65490777b08be56c4c9b67bc892
https://github.com/ZFury/framework/blob/eee4ca2a64d2d65490777b08be56c4c9b67bc892/library/Model/Traits/Memcached.php#L26-L37
train
agentmedia/phine-core
src/Core/Logic/Installation/InstallUtil/Page.php
Page.NextStep
static function NextStep($step) { $keys = array_keys(self::Steps()); $index = array_search($step, $keys); if ($index !== false && $index < count($keys) - 1) { return $keys[$index + 1]; } return null; }
php
static function NextStep($step) { $keys = array_keys(self::Steps()); $index = array_search($step, $keys); if ($index !== false && $index < count($keys) - 1) { return $keys[$index + 1]; } return null; }
[ "static", "function", "NextStep", "(", "$", "step", ")", "{", "$", "keys", "=", "array_keys", "(", "self", "::", "Steps", "(", ")", ")", ";", "$", "index", "=", "array_search", "(", "$", "step", ",", "$", "keys", ")", ";", "if", "(", "$", "index", "!==", "false", "&&", "$", "index", "<", "count", "(", "$", "keys", ")", "-", "1", ")", "{", "return", "$", "keys", "[", "$", "index", "+", "1", "]", ";", "}", "return", "null", ";", "}" ]
Gets the next step name @param string $step The current step key name @return string Returns the next step name or null if
[ "Gets", "the", "next", "step", "name" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Installation/InstallUtil/Page.php#L42-L51
train
Wedeto/Util
src/Encoding.php
Encoding.fixUTF8
public static function fixUTF8($text, $option = self::WITHOUT_ICONV) { if (is_array($text)) { foreach($text as $k => $v) $text[$k] = self::fixUTF8($v, $option); return $text; } $last = ""; while ($last <> $text) { $last = $text; $text = self::toUTF8(static::utf8_decode($text, $option)); } $text = self::toUTF8(static::utf8_decode($text, $option)); return $text; }
php
public static function fixUTF8($text, $option = self::WITHOUT_ICONV) { if (is_array($text)) { foreach($text as $k => $v) $text[$k] = self::fixUTF8($v, $option); return $text; } $last = ""; while ($last <> $text) { $last = $text; $text = self::toUTF8(static::utf8_decode($text, $option)); } $text = self::toUTF8(static::utf8_decode($text, $option)); return $text; }
[ "public", "static", "function", "fixUTF8", "(", "$", "text", ",", "$", "option", "=", "self", "::", "WITHOUT_ICONV", ")", "{", "if", "(", "is_array", "(", "$", "text", ")", ")", "{", "foreach", "(", "$", "text", "as", "$", "k", "=>", "$", "v", ")", "$", "text", "[", "$", "k", "]", "=", "self", "::", "fixUTF8", "(", "$", "v", ",", "$", "option", ")", ";", "return", "$", "text", ";", "}", "$", "last", "=", "\"\"", ";", "while", "(", "$", "last", "<>", "$", "text", ")", "{", "$", "last", "=", "$", "text", ";", "$", "text", "=", "self", "::", "toUTF8", "(", "static", "::", "utf8_decode", "(", "$", "text", ",", "$", "option", ")", ")", ";", "}", "$", "text", "=", "self", "::", "toUTF8", "(", "static", "::", "utf8_decode", "(", "$", "text", ",", "$", "option", ")", ")", ";", "return", "$", "text", ";", "}" ]
Fix broken UTF-8 text. @param $text string The text of whic valid UTF-8 should be created @param $option Can be WITHOUT_ICONV to disable usage of ICONV extension, or ICONV_TRANSLIT or ICONV_IGNORE to determine what to do with invalid characters. @return The fixed UTF-8 text
[ "Fix", "broken", "UTF", "-", "8", "text", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Encoding.php#L310-L327
train
Wedeto/Util
src/Encoding.php
Encoding.encode
public static function encode($encodingLabel, $text) { $encodingLabel = self::normalizeEncoding($encodingLabel); if ($encodingLabel == 'ISO-8859-1') return self::toWin1252($text); return self::toUTF8($text); }
php
public static function encode($encodingLabel, $text) { $encodingLabel = self::normalizeEncoding($encodingLabel); if ($encodingLabel == 'ISO-8859-1') return self::toWin1252($text); return self::toUTF8($text); }
[ "public", "static", "function", "encode", "(", "$", "encodingLabel", ",", "$", "text", ")", "{", "$", "encodingLabel", "=", "self", "::", "normalizeEncoding", "(", "$", "encodingLabel", ")", ";", "if", "(", "$", "encodingLabel", "==", "'ISO-8859-1'", ")", "return", "self", "::", "toWin1252", "(", "$", "text", ")", ";", "return", "self", "::", "toUTF8", "(", "$", "text", ")", ";", "}" ]
Convert the text to either UTF-8 or ISO-85591-1. @param $encodingLabel Can be UTF-8 or ISO-8859-1 @return string The encoded text
[ "Convert", "the", "text", "to", "either", "UTF", "-", "8", "or", "ISO", "-", "85591", "-", "1", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Encoding.php#L399-L405
train
Wedeto/Util
src/Encoding.php
Encoding.getBOM
public static function getBOM(string $which) { $cname = self::class . '::' . strtoupper($which) . '_BOM'; if (!defined($cname)) return null; $bytes = constant($cname); $bom = ''; foreach ($bytes as $ord) $bom .= chr($ord); return $bom; }
php
public static function getBOM(string $which) { $cname = self::class . '::' . strtoupper($which) . '_BOM'; if (!defined($cname)) return null; $bytes = constant($cname); $bom = ''; foreach ($bytes as $ord) $bom .= chr($ord); return $bom; }
[ "public", "static", "function", "getBOM", "(", "string", "$", "which", ")", "{", "$", "cname", "=", "self", "::", "class", ".", "'::'", ".", "strtoupper", "(", "$", "which", ")", ".", "'_BOM'", ";", "if", "(", "!", "defined", "(", "$", "cname", ")", ")", "return", "null", ";", "$", "bytes", "=", "constant", "(", "$", "cname", ")", ";", "$", "bom", "=", "''", ";", "foreach", "(", "$", "bytes", "as", "$", "ord", ")", "$", "bom", ".=", "chr", "(", "$", "ord", ")", ";", "return", "$", "bom", ";", "}" ]
Get a BOM for a supported encoding @param string $which One of UTF8, UTF16LE, UTF16BE, UTF32LE or UTF32BE @return string The correct BOM
[ "Get", "a", "BOM", "for", "a", "supported", "encoding" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Encoding.php#L436-L447
train
Finesse/QueryScribe
src/QueryBricks/OrderTrait.php
OrderTrait.orderBy
public function orderBy($column, string $direction = 'asc'): self { $column = $this->checkStringValue('Argument $column', $column); $this->order[] = new Order($column, strtolower($direction) === 'desc'); return $this; }
php
public function orderBy($column, string $direction = 'asc'): self { $column = $this->checkStringValue('Argument $column', $column); $this->order[] = new Order($column, strtolower($direction) === 'desc'); return $this; }
[ "public", "function", "orderBy", "(", "$", "column", ",", "string", "$", "direction", "=", "'asc'", ")", ":", "self", "{", "$", "column", "=", "$", "this", "->", "checkStringValue", "(", "'Argument $column'", ",", "$", "column", ")", ";", "$", "this", "->", "order", "[", "]", "=", "new", "Order", "(", "$", "column", ",", "strtolower", "(", "$", "direction", ")", "===", "'desc'", ")", ";", "return", "$", "this", ";", "}" ]
Adds a simple order to the orders list. @param string|\Closure|self|StatementInterface $column Column to order by @param string $direction Order direction: `asc` - ascending, `desc` - descending @return $this @throws InvalidArgumentException @throws InvalidReturnValueException
[ "Adds", "a", "simple", "order", "to", "the", "orders", "list", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/QueryBricks/OrderTrait.php#L35-L40
train
Finesse/QueryScribe
src/QueryBricks/OrderTrait.php
OrderTrait.orderByNullLast
public function orderByNullLast($column, bool $doReverse = false): self { $column = $this->checkStringValue('Argument $column', $column); $this->order[] = new OrderByIsNull($column, $doReverse); return $this; }
php
public function orderByNullLast($column, bool $doReverse = false): self { $column = $this->checkStringValue('Argument $column', $column); $this->order[] = new OrderByIsNull($column, $doReverse); return $this; }
[ "public", "function", "orderByNullLast", "(", "$", "column", ",", "bool", "$", "doReverse", "=", "false", ")", ":", "self", "{", "$", "column", "=", "$", "this", "->", "checkStringValue", "(", "'Argument $column'", ",", "$", "column", ")", ";", "$", "this", "->", "order", "[", "]", "=", "new", "OrderByIsNull", "(", "$", "column", ",", "$", "doReverse", ")", ";", "return", "$", "this", ";", "}" ]
Adds such order that the null column values go last. @param string|\Closure|self|StatementInterface $column The column @param boolean $doReverse Do reverse the order (the null values go first) @return $this @throws InvalidArgumentException @throws InvalidReturnValueException
[ "Adds", "such", "order", "that", "the", "null", "column", "values", "go", "last", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/QueryBricks/OrderTrait.php#L51-L56
train
Finesse/QueryScribe
src/QueryBricks/OrderTrait.php
OrderTrait.inExplicitOrder
public function inExplicitOrder($column, array $order, bool $areOtherFirst = false): self { $column = $this->checkStringValue('Argument $column', $column); foreach ($order as $index => &$value) { $value = $this->checkScalarOrNullValue('Argument $order['.$index.']', $value); } $this->order[] = new ExplicitOrder($column, $order, $areOtherFirst); return $this; }
php
public function inExplicitOrder($column, array $order, bool $areOtherFirst = false): self { $column = $this->checkStringValue('Argument $column', $column); foreach ($order as $index => &$value) { $value = $this->checkScalarOrNullValue('Argument $order['.$index.']', $value); } $this->order[] = new ExplicitOrder($column, $order, $areOtherFirst); return $this; }
[ "public", "function", "inExplicitOrder", "(", "$", "column", ",", "array", "$", "order", ",", "bool", "$", "areOtherFirst", "=", "false", ")", ":", "self", "{", "$", "column", "=", "$", "this", "->", "checkStringValue", "(", "'Argument $column'", ",", "$", "column", ")", ";", "foreach", "(", "$", "order", "as", "$", "index", "=>", "&", "$", "value", ")", "{", "$", "value", "=", "$", "this", "->", "checkScalarOrNullValue", "(", "'Argument $order['", ".", "$", "index", ".", "']'", ",", "$", "value", ")", ";", "}", "$", "this", "->", "order", "[", "]", "=", "new", "ExplicitOrder", "(", "$", "column", ",", "$", "order", ",", "$", "areOtherFirst", ")", ";", "return", "$", "this", ";", "}" ]
Adds such order that makes a column values follow the explicitly given order. @param string|\Closure|self|StatementInterface $column The column @param mixed[]|\Closure[]|Query[]|StatementInterface[] $order The values in the required order @param bool $areOtherFirst Must the values not in the list go first; otherwise they will go last @return $this @throws InvalidArgumentException @throws InvalidReturnValueException
[ "Adds", "such", "order", "that", "makes", "a", "column", "values", "follow", "the", "explicitly", "given", "order", "." ]
4edba721e37693780d142229b3ecb0cd4004c7a5
https://github.com/Finesse/QueryScribe/blob/4edba721e37693780d142229b3ecb0cd4004c7a5/src/QueryBricks/OrderTrait.php#L81-L90
train
maddoger/yii2-cms-user
common/models/Role.php
Role.delete
public function delete() { if (!$this->isNewRecord) { $item = Yii::$app->authManager->getRole($this->name); if ($item) { Yii::$app->authManager->remove($item); } } }
php
public function delete() { if (!$this->isNewRecord) { $item = Yii::$app->authManager->getRole($this->name); if ($item) { Yii::$app->authManager->remove($item); } } }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isNewRecord", ")", "{", "$", "item", "=", "Yii", "::", "$", "app", "->", "authManager", "->", "getRole", "(", "$", "this", "->", "name", ")", ";", "if", "(", "$", "item", ")", "{", "Yii", "::", "$", "app", "->", "authManager", "->", "remove", "(", "$", "item", ")", ";", "}", "}", "}" ]
Delete current item
[ "Delete", "current", "item" ]
6792d1d0d2c0bf01fe87729985b5659de4c1aac1
https://github.com/maddoger/yii2-cms-user/blob/6792d1d0d2c0bf01fe87729985b5659de4c1aac1/common/models/Role.php#L109-L117
train
maddoger/yii2-cms-user
common/models/Role.php
Role.getRolesList
static public function getRolesList($except=null) { $res = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description'); if ($except !== null) { unset($res[$except]); } asort($res); return $res; }
php
static public function getRolesList($except=null) { $res = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description'); if ($except !== null) { unset($res[$except]); } asort($res); return $res; }
[ "static", "public", "function", "getRolesList", "(", "$", "except", "=", "null", ")", "{", "$", "res", "=", "ArrayHelper", "::", "map", "(", "Yii", "::", "$", "app", "->", "authManager", "->", "getRoles", "(", ")", ",", "'name'", ",", "'description'", ")", ";", "if", "(", "$", "except", "!==", "null", ")", "{", "unset", "(", "$", "res", "[", "$", "except", "]", ")", ";", "}", "asort", "(", "$", "res", ")", ";", "return", "$", "res", ";", "}" ]
Returns roles list description by name as key @param $except string name @return array
[ "Returns", "roles", "list", "description", "by", "name", "as", "key" ]
6792d1d0d2c0bf01fe87729985b5659de4c1aac1
https://github.com/maddoger/yii2-cms-user/blob/6792d1d0d2c0bf01fe87729985b5659de4c1aac1/common/models/Role.php#L197-L205
train
maddoger/yii2-cms-user
common/models/Role.php
Role.getPermissionsList
static public function getPermissionsList($except=null) { $res = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); if ($except !== null) { unset($res[$except]); } ksort($res); return $res; }
php
static public function getPermissionsList($except=null) { $res = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); if ($except !== null) { unset($res[$except]); } ksort($res); return $res; }
[ "static", "public", "function", "getPermissionsList", "(", "$", "except", "=", "null", ")", "{", "$", "res", "=", "ArrayHelper", "::", "map", "(", "Yii", "::", "$", "app", "->", "authManager", "->", "getPermissions", "(", ")", ",", "'name'", ",", "'description'", ")", ";", "if", "(", "$", "except", "!==", "null", ")", "{", "unset", "(", "$", "res", "[", "$", "except", "]", ")", ";", "}", "ksort", "(", "$", "res", ")", ";", "return", "$", "res", ";", "}" ]
Returns permissions list description by name as key @param $except string name @return array
[ "Returns", "permissions", "list", "description", "by", "name", "as", "key" ]
6792d1d0d2c0bf01fe87729985b5659de4c1aac1
https://github.com/maddoger/yii2-cms-user/blob/6792d1d0d2c0bf01fe87729985b5659de4c1aac1/common/models/Role.php#L212-L220
train
tonis-io-legacy/tonis
src/Router/Router.php
Router.query
public function query($param, $handler) { $param = new QueryParam($param, $handler); $this->middleware[] = $param; }
php
public function query($param, $handler) { $param = new QueryParam($param, $handler); $this->middleware[] = $param; }
[ "public", "function", "query", "(", "$", "param", ",", "$", "handler", ")", "{", "$", "param", "=", "new", "QueryParam", "(", "$", "param", ",", "$", "handler", ")", ";", "$", "this", "->", "middleware", "[", "]", "=", "$", "param", ";", "}" ]
Adds query handlers to a queue. The queue is processed at invocation by RelayPHP. @param string $param @param callable $handler
[ "Adds", "query", "handlers", "to", "a", "queue", ".", "The", "queue", "is", "processed", "at", "invocation", "by", "RelayPHP", "." ]
8371a277a94232433d882aaf37a85cd469daf501
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Router/Router.php#L96-L100
train
tonis-io-legacy/tonis
src/Router/Router.php
Router.param
public function param($param, $handler) { $param = new RouteParam($param, $handler); $this->middleware[] = $param; }
php
public function param($param, $handler) { $param = new RouteParam($param, $handler); $this->middleware[] = $param; }
[ "public", "function", "param", "(", "$", "param", ",", "$", "handler", ")", "{", "$", "param", "=", "new", "RouteParam", "(", "$", "param", ",", "$", "handler", ")", ";", "$", "this", "->", "middleware", "[", "]", "=", "$", "param", ";", "}" ]
Adds param handlers to a queue. The queue is processed at invocation by RelayPHP. @param string $param @param callable $handler
[ "Adds", "param", "handlers", "to", "a", "queue", ".", "The", "queue", "is", "processed", "at", "invocation", "by", "RelayPHP", "." ]
8371a277a94232433d882aaf37a85cd469daf501
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Router/Router.php#L108-L112
train
mvccore/ext-router-media
src/MvcCore/Ext/Routers/Media/PreRouting.php
PreRouting.manageMediaDetectionAndStoreInSession
protected function manageMediaDetectionAndStoreInSession() { $detect = new \Mobile_Detect(); if ( array_key_exists(Routers\IMedia::MEDIA_VERSION_MOBILE, $this->allowedMediaVersionsAndUrlValues) && $detect->isMobile() ) { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_MOBILE; } else if ( array_key_exists(Routers\IMedia::MEDIA_VERSION_TABLET, $this->allowedMediaVersionsAndUrlValues) && $detect->isTablet() ) { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_TABLET; } else { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_FULL; } $mediaVersionUrlParam = static::URL_PARAM_MEDIA_VERSION; $this->session->{$mediaVersionUrlParam} = $this->mediaSiteVersion; $this->firstRequestMediaDetection = $this->mediaSiteVersion === $this->requestMediaSiteVersion; }
php
protected function manageMediaDetectionAndStoreInSession() { $detect = new \Mobile_Detect(); if ( array_key_exists(Routers\IMedia::MEDIA_VERSION_MOBILE, $this->allowedMediaVersionsAndUrlValues) && $detect->isMobile() ) { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_MOBILE; } else if ( array_key_exists(Routers\IMedia::MEDIA_VERSION_TABLET, $this->allowedMediaVersionsAndUrlValues) && $detect->isTablet() ) { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_TABLET; } else { $this->mediaSiteVersion = Routers\IMedia::MEDIA_VERSION_FULL; } $mediaVersionUrlParam = static::URL_PARAM_MEDIA_VERSION; $this->session->{$mediaVersionUrlParam} = $this->mediaSiteVersion; $this->firstRequestMediaDetection = $this->mediaSiteVersion === $this->requestMediaSiteVersion; }
[ "protected", "function", "manageMediaDetectionAndStoreInSession", "(", ")", "{", "$", "detect", "=", "new", "\\", "Mobile_Detect", "(", ")", ";", "if", "(", "array_key_exists", "(", "Routers", "\\", "IMedia", "::", "MEDIA_VERSION_MOBILE", ",", "$", "this", "->", "allowedMediaVersionsAndUrlValues", ")", "&&", "$", "detect", "->", "isMobile", "(", ")", ")", "{", "$", "this", "->", "mediaSiteVersion", "=", "Routers", "\\", "IMedia", "::", "MEDIA_VERSION_MOBILE", ";", "}", "else", "if", "(", "array_key_exists", "(", "Routers", "\\", "IMedia", "::", "MEDIA_VERSION_TABLET", ",", "$", "this", "->", "allowedMediaVersionsAndUrlValues", ")", "&&", "$", "detect", "->", "isTablet", "(", ")", ")", "{", "$", "this", "->", "mediaSiteVersion", "=", "Routers", "\\", "IMedia", "::", "MEDIA_VERSION_TABLET", ";", "}", "else", "{", "$", "this", "->", "mediaSiteVersion", "=", "Routers", "\\", "IMedia", "::", "MEDIA_VERSION_FULL", ";", "}", "$", "mediaVersionUrlParam", "=", "static", "::", "URL_PARAM_MEDIA_VERSION", ";", "$", "this", "->", "session", "->", "{", "$", "mediaVersionUrlParam", "}", "=", "$", "this", "->", "mediaSiteVersion", ";", "$", "this", "->", "firstRequestMediaDetection", "=", "$", "this", "->", "mediaSiteVersion", "===", "$", "this", "->", "requestMediaSiteVersion", ";", "}" ]
Detect media site version by sent user agent string by third party `\Mobile_Detect` library and store detected result in session namespace for next requests. @return void
[ "Detect", "media", "site", "version", "by", "sent", "user", "agent", "string", "by", "third", "party", "\\", "Mobile_Detect", "library", "and", "store", "detected", "result", "in", "session", "namespace", "for", "next", "requests", "." ]
976e83290cf25ad6bc32e4824790b5e0d5d4c08b
https://github.com/mvccore/ext-router-media/blob/976e83290cf25ad6bc32e4824790b5e0d5d4c08b/src/MvcCore/Ext/Routers/Media/PreRouting.php#L98-L116
train
mvccore/ext-router-media
src/MvcCore/Ext/Routers/Media/PreRouting.php
PreRouting.setUpMediaSiteVersionToContextAndSession
protected function setUpMediaSiteVersionToContextAndSession ($targetMediaSiteVersion) { $this->session->{static::URL_PARAM_MEDIA_VERSION} = $targetMediaSiteVersion; $this->mediaSiteVersion = $targetMediaSiteVersion; return [\MvcCore\Ext\Routers\IMedia::URL_PARAM_MEDIA_VERSION => $targetMediaSiteVersion]; }
php
protected function setUpMediaSiteVersionToContextAndSession ($targetMediaSiteVersion) { $this->session->{static::URL_PARAM_MEDIA_VERSION} = $targetMediaSiteVersion; $this->mediaSiteVersion = $targetMediaSiteVersion; return [\MvcCore\Ext\Routers\IMedia::URL_PARAM_MEDIA_VERSION => $targetMediaSiteVersion]; }
[ "protected", "function", "setUpMediaSiteVersionToContextAndSession", "(", "$", "targetMediaSiteVersion", ")", "{", "$", "this", "->", "session", "->", "{", "static", "::", "URL_PARAM_MEDIA_VERSION", "}", "=", "$", "targetMediaSiteVersion", ";", "$", "this", "->", "mediaSiteVersion", "=", "$", "targetMediaSiteVersion", ";", "return", "[", "\\", "MvcCore", "\\", "Ext", "\\", "Routers", "\\", "IMedia", "::", "URL_PARAM_MEDIA_VERSION", "=>", "$", "targetMediaSiteVersion", "]", ";", "}" ]
Set up media site version string into current context and into session and return it. @param string $targetMediaSiteVersion @return array
[ "Set", "up", "media", "site", "version", "string", "into", "current", "context", "and", "into", "session", "and", "return", "it", "." ]
976e83290cf25ad6bc32e4824790b5e0d5d4c08b
https://github.com/mvccore/ext-router-media/blob/976e83290cf25ad6bc32e4824790b5e0d5d4c08b/src/MvcCore/Ext/Routers/Media/PreRouting.php#L168-L172
train
LpFactory/NestedSetRoutingBundle
Twig/RoutingExtension.php
RoutingExtension.getLpPath
public function getLpPath(NestedSetRoutingPageInterface $page, $action, $parameters = array(), $relative = false) { $configuration = $this->routeConfiguration->get($action); return $this->opGenerator->generate( $configuration->getPageRouteName($page), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH ); }
php
public function getLpPath(NestedSetRoutingPageInterface $page, $action, $parameters = array(), $relative = false) { $configuration = $this->routeConfiguration->get($action); return $this->opGenerator->generate( $configuration->getPageRouteName($page), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH ); }
[ "public", "function", "getLpPath", "(", "NestedSetRoutingPageInterface", "$", "page", ",", "$", "action", ",", "$", "parameters", "=", "array", "(", ")", ",", "$", "relative", "=", "false", ")", "{", "$", "configuration", "=", "$", "this", "->", "routeConfiguration", "->", "get", "(", "$", "action", ")", ";", "return", "$", "this", "->", "opGenerator", "->", "generate", "(", "$", "configuration", "->", "getPageRouteName", "(", "$", "page", ")", ",", "$", "parameters", ",", "$", "relative", "?", "UrlGeneratorInterface", "::", "RELATIVE_PATH", ":", "UrlGeneratorInterface", "::", "ABSOLUTE_PATH", ")", ";", "}" ]
Build nested set page route @param NestedSetRoutingPageInterface $page @param string $action @param array $parameters @param bool $relative @return string
[ "Build", "nested", "set", "page", "route" ]
dc07227a6764e657b7b321827a18127ec18ba214
https://github.com/LpFactory/NestedSetRoutingBundle/blob/dc07227a6764e657b7b321827a18127ec18ba214/Twig/RoutingExtension.php#L77-L86
train
Lillfilly/duploflash
src/Flash/FlashInSession.php
FlashInSession.saveMessage
public function saveMessage($msg) { $messages = $this->session->get("FlashInSession", []); $messages[] = $msg; $this->session->set("FlashInSession", $messages); }
php
public function saveMessage($msg) { $messages = $this->session->get("FlashInSession", []); $messages[] = $msg; $this->session->set("FlashInSession", $messages); }
[ "public", "function", "saveMessage", "(", "$", "msg", ")", "{", "$", "messages", "=", "$", "this", "->", "session", "->", "get", "(", "\"FlashInSession\"", ",", "[", "]", ")", ";", "$", "messages", "[", "]", "=", "$", "msg", ";", "$", "this", "->", "session", "->", "set", "(", "\"FlashInSession\"", ",", "$", "messages", ")", ";", "}" ]
Save a message to the session @param $msg The message to store @return void
[ "Save", "a", "message", "to", "the", "session" ]
900144b36636b9010e22359345b5ad5897ba32c0
https://github.com/Lillfilly/duploflash/blob/900144b36636b9010e22359345b5ad5897ba32c0/src/Flash/FlashInSession.php#L18-L23
train
Lillfilly/duploflash
src/Flash/FlashInSession.php
FlashInSession.getMessages
public function getMessages($removeOnGet = false){ $messages = $this->session->get("FlashInSession", []); if($removeOnGet){ $this->clear(); } return $messages; }
php
public function getMessages($removeOnGet = false){ $messages = $this->session->get("FlashInSession", []); if($removeOnGet){ $this->clear(); } return $messages; }
[ "public", "function", "getMessages", "(", "$", "removeOnGet", "=", "false", ")", "{", "$", "messages", "=", "$", "this", "->", "session", "->", "get", "(", "\"FlashInSession\"", ",", "[", "]", ")", ";", "if", "(", "$", "removeOnGet", ")", "{", "$", "this", "->", "clear", "(", ")", ";", "}", "return", "$", "messages", ";", "}" ]
Retrievs all stored messages. @param $removeOnGet boolean If the messages should be removed. @return array with all the stored messages
[ "Retrievs", "all", "stored", "messages", "." ]
900144b36636b9010e22359345b5ad5897ba32c0
https://github.com/Lillfilly/duploflash/blob/900144b36636b9010e22359345b5ad5897ba32c0/src/Flash/FlashInSession.php#L29-L35
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/email/EmailWithPHPMailer.php
EmailWithPHPMailer._setParams
private function _setParams($params, $keys, $required = true) { foreach ( $keys as $key ) { if (!array_key_exists($key, $params)) { if ($required == true) { throw new EmailException("Required configuration key '{$key}' was not found."); } else { continue; } } switch ( strtolower($key) ) { case 'charset': $this->mailer->CharSet = $params['charset']; break; case 'content-type': $this->mailer->ContentType = $params['content-type']; break; case 'encoding': $this->mailer->Encoding = $params['encoding']; break; case 'helo': $this->mailer->Helo = $params['helo']; break; case 'host': $this->mailer->Host = $params['host']; break; case 'hostname': $this->mailer->Hostname = $params['hostname']; break; case 'message-id': $this->mailer->MessageId = $params['message-id']; break; case 'password': $this->mailer->Password = $params['password']; break; case 'port': $this->mailer->Port = $params['port']; break; case 'priority': $this->mailer->Priority = $params['priority']; break; case 'smtp-debug': // $this->_check_key($params, 'smtp-debug'); $this->mailer->SMTPDebug = json_decode($params['smtp-debug']); break; case 'smtp-keepalive': // $this->_check_key($params, 'smtp-keepalive'); $this->mailer->SMTPKeepAlive = json_decode($params['smtp-keepalive']); break; case 'smtp-secure': $this->mailer->SMTPSecure = $params['smtp-secure']; break; case 'sendmail': $this->mailer->Sendmail = $params['sendmail']; break; case 'timeout': $this->mailer->Timeout = $params['timeout']; break; case 'username': $this->mailer->Username = $params['username']; break; default: throw new EmailException("Parameter '{$key}' not supported."); } } }
php
private function _setParams($params, $keys, $required = true) { foreach ( $keys as $key ) { if (!array_key_exists($key, $params)) { if ($required == true) { throw new EmailException("Required configuration key '{$key}' was not found."); } else { continue; } } switch ( strtolower($key) ) { case 'charset': $this->mailer->CharSet = $params['charset']; break; case 'content-type': $this->mailer->ContentType = $params['content-type']; break; case 'encoding': $this->mailer->Encoding = $params['encoding']; break; case 'helo': $this->mailer->Helo = $params['helo']; break; case 'host': $this->mailer->Host = $params['host']; break; case 'hostname': $this->mailer->Hostname = $params['hostname']; break; case 'message-id': $this->mailer->MessageId = $params['message-id']; break; case 'password': $this->mailer->Password = $params['password']; break; case 'port': $this->mailer->Port = $params['port']; break; case 'priority': $this->mailer->Priority = $params['priority']; break; case 'smtp-debug': // $this->_check_key($params, 'smtp-debug'); $this->mailer->SMTPDebug = json_decode($params['smtp-debug']); break; case 'smtp-keepalive': // $this->_check_key($params, 'smtp-keepalive'); $this->mailer->SMTPKeepAlive = json_decode($params['smtp-keepalive']); break; case 'smtp-secure': $this->mailer->SMTPSecure = $params['smtp-secure']; break; case 'sendmail': $this->mailer->Sendmail = $params['sendmail']; break; case 'timeout': $this->mailer->Timeout = $params['timeout']; break; case 'username': $this->mailer->Username = $params['username']; break; default: throw new EmailException("Parameter '{$key}' not supported."); } } }
[ "private", "function", "_setParams", "(", "$", "params", ",", "$", "keys", ",", "$", "required", "=", "true", ")", "{", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "params", ")", ")", "{", "if", "(", "$", "required", "==", "true", ")", "{", "throw", "new", "EmailException", "(", "\"Required configuration key '{$key}' was not found.\"", ")", ";", "}", "else", "{", "continue", ";", "}", "}", "switch", "(", "strtolower", "(", "$", "key", ")", ")", "{", "case", "'charset'", ":", "$", "this", "->", "mailer", "->", "CharSet", "=", "$", "params", "[", "'charset'", "]", ";", "break", ";", "case", "'content-type'", ":", "$", "this", "->", "mailer", "->", "ContentType", "=", "$", "params", "[", "'content-type'", "]", ";", "break", ";", "case", "'encoding'", ":", "$", "this", "->", "mailer", "->", "Encoding", "=", "$", "params", "[", "'encoding'", "]", ";", "break", ";", "case", "'helo'", ":", "$", "this", "->", "mailer", "->", "Helo", "=", "$", "params", "[", "'helo'", "]", ";", "break", ";", "case", "'host'", ":", "$", "this", "->", "mailer", "->", "Host", "=", "$", "params", "[", "'host'", "]", ";", "break", ";", "case", "'hostname'", ":", "$", "this", "->", "mailer", "->", "Hostname", "=", "$", "params", "[", "'hostname'", "]", ";", "break", ";", "case", "'message-id'", ":", "$", "this", "->", "mailer", "->", "MessageId", "=", "$", "params", "[", "'message-id'", "]", ";", "break", ";", "case", "'password'", ":", "$", "this", "->", "mailer", "->", "Password", "=", "$", "params", "[", "'password'", "]", ";", "break", ";", "case", "'port'", ":", "$", "this", "->", "mailer", "->", "Port", "=", "$", "params", "[", "'port'", "]", ";", "break", ";", "case", "'priority'", ":", "$", "this", "->", "mailer", "->", "Priority", "=", "$", "params", "[", "'priority'", "]", ";", "break", ";", "case", "'smtp-debug'", ":", "// $this->_check_key($params, 'smtp-debug');", "$", "this", "->", "mailer", "->", "SMTPDebug", "=", "json_decode", "(", "$", "params", "[", "'smtp-debug'", "]", ")", ";", "break", ";", "case", "'smtp-keepalive'", ":", "// $this->_check_key($params, 'smtp-keepalive');", "$", "this", "->", "mailer", "->", "SMTPKeepAlive", "=", "json_decode", "(", "$", "params", "[", "'smtp-keepalive'", "]", ")", ";", "break", ";", "case", "'smtp-secure'", ":", "$", "this", "->", "mailer", "->", "SMTPSecure", "=", "$", "params", "[", "'smtp-secure'", "]", ";", "break", ";", "case", "'sendmail'", ":", "$", "this", "->", "mailer", "->", "Sendmail", "=", "$", "params", "[", "'sendmail'", "]", ";", "break", ";", "case", "'timeout'", ":", "$", "this", "->", "mailer", "->", "Timeout", "=", "$", "params", "[", "'timeout'", "]", ";", "break", ";", "case", "'username'", ":", "$", "this", "->", "mailer", "->", "Username", "=", "$", "params", "[", "'username'", "]", ";", "break", ";", "default", ":", "throw", "new", "EmailException", "(", "\"Parameter '{$key}' not supported.\"", ")", ";", "}", "}", "}" ]
Sets various parameters on our mailer object. Example: <code> $this->_setParams(array('username', 'host'), $params); </code> @param array $params A key-value array containing configuration values. For example: array('port' => 25, 'host' => 'localhost', ...) @param array $keys A list of keys to extract from the {@link $params} and set on our mailer object @param boolean $required If set to true an exception will be thrown if the specified key doesn't exist in the params @return void
[ "Sets", "various", "parameters", "on", "our", "mailer", "object", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/email/EmailWithPHPMailer.php#L49-L132
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/email/EmailWithPHPMailer.php
EmailWithPHPMailer.subject
public function subject($subject) { try { $this->mailer->Subject = $subject; } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
php
public function subject($subject) { try { $this->mailer->Subject = $subject; } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
[ "public", "function", "subject", "(", "$", "subject", ")", "{", "try", "{", "$", "this", "->", "mailer", "->", "Subject", "=", "$", "subject", ";", "}", "catch", "(", "phpmailerException", "$", "e", ")", "{", "throw", "new", "EmailException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the subject for your email. @param string $subject The subject for the email. @return $this
[ "Sets", "the", "subject", "for", "your", "email", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/email/EmailWithPHPMailer.php#L348-L357
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/email/EmailWithPHPMailer.php
EmailWithPHPMailer.body
public function body($text) { try { $this->mailer->MsgHTML($text); } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
php
public function body($text) { try { $this->mailer->MsgHTML($text); } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
[ "public", "function", "body", "(", "$", "text", ")", "{", "try", "{", "$", "this", "->", "mailer", "->", "MsgHTML", "(", "$", "text", ")", ";", "}", "catch", "(", "phpmailerException", "$", "e", ")", "{", "throw", "new", "EmailException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the email message body @param string $text The text to use as the message body @return $this
[ "Sets", "the", "email", "message", "body" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/email/EmailWithPHPMailer.php#L366-L375
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/email/EmailWithPHPMailer.php
EmailWithPHPMailer.altMessage
public function altMessage($altMessage) { try { $this->mailer->IsHTML(); $this->mailer->AltBody = $altMessage; } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
php
public function altMessage($altMessage) { try { $this->mailer->IsHTML(); $this->mailer->AltBody = $altMessage; } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
[ "public", "function", "altMessage", "(", "$", "altMessage", ")", "{", "try", "{", "$", "this", "->", "mailer", "->", "IsHTML", "(", ")", ";", "$", "this", "->", "mailer", "->", "AltBody", "=", "$", "altMessage", ";", "}", "catch", "(", "phpmailerException", "$", "e", ")", "{", "throw", "new", "EmailException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the alternative email message body. This is an optional message string which can be used if you send HTML formatted email. It lets you specify an alternative message with no HTML formatting which is added to the header string for people who do not accept HTML email. @param string $altMessage The alternative message to use @return $this
[ "Sets", "the", "alternative", "email", "message", "body", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/email/EmailWithPHPMailer.php#L389-L399
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/email/EmailWithPHPMailer.php
EmailWithPHPMailer.attach
public function attach($filename) { try { $this->mailer->AddAttachment($filename); } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
php
public function attach($filename) { try { $this->mailer->AddAttachment($filename); } catch (phpmailerException $e) { throw new EmailException($e->getMessage(), $e->getCode()); } return $this; }
[ "public", "function", "attach", "(", "$", "filename", ")", "{", "try", "{", "$", "this", "->", "mailer", "->", "AddAttachment", "(", "$", "filename", ")", ";", "}", "catch", "(", "phpmailerException", "$", "e", ")", "{", "throw", "new", "EmailException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Attaches the file specified to the email. @param string $filename The absolute filename of the file to attach @return void
[ "Attaches", "the", "file", "specified", "to", "the", "email", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/email/EmailWithPHPMailer.php#L408-L417
train
FlexModel/FlexModelBundle
Model/UploadTrait.php
UploadTrait.getFileUpload
public function getFileUpload() { $propertyName = $this->getFileUploadPropertyName(__FUNCTION__); if (isset($this->fileUploads[$propertyName])) { return $this->fileUploads[$propertyName]; } }
php
public function getFileUpload() { $propertyName = $this->getFileUploadPropertyName(__FUNCTION__); if (isset($this->fileUploads[$propertyName])) { return $this->fileUploads[$propertyName]; } }
[ "public", "function", "getFileUpload", "(", ")", "{", "$", "propertyName", "=", "$", "this", "->", "getFileUploadPropertyName", "(", "__FUNCTION__", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "fileUploads", "[", "$", "propertyName", "]", ")", ")", "{", "return", "$", "this", "->", "fileUploads", "[", "$", "propertyName", "]", ";", "}", "}" ]
Returns the uploaded file. @return UploadedFile|null
[ "Returns", "the", "uploaded", "file", "." ]
7b4720d25b0dc6baf29b1da8ad7c67dfb2686460
https://github.com/FlexModel/FlexModelBundle/blob/7b4720d25b0dc6baf29b1da8ad7c67dfb2686460/Model/UploadTrait.php#L28-L35
train
FlexModel/FlexModelBundle
Model/UploadTrait.php
UploadTrait.setFileUpload
public function setFileUpload(UploadedFile $file = null) { $propertyName = $this->getFileUploadPropertyName(__FUNCTION__); unset($this->fileUploads[$propertyName]); if ($file instanceof UploadedFile) { $this->fileUploads[$propertyName] = $file; } }
php
public function setFileUpload(UploadedFile $file = null) { $propertyName = $this->getFileUploadPropertyName(__FUNCTION__); unset($this->fileUploads[$propertyName]); if ($file instanceof UploadedFile) { $this->fileUploads[$propertyName] = $file; } }
[ "public", "function", "setFileUpload", "(", "UploadedFile", "$", "file", "=", "null", ")", "{", "$", "propertyName", "=", "$", "this", "->", "getFileUploadPropertyName", "(", "__FUNCTION__", ")", ";", "unset", "(", "$", "this", "->", "fileUploads", "[", "$", "propertyName", "]", ")", ";", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "this", "->", "fileUploads", "[", "$", "propertyName", "]", "=", "$", "file", ";", "}", "}" ]
Sets the uploaded file. @param UploadedFile|null $file
[ "Sets", "the", "uploaded", "file", "." ]
7b4720d25b0dc6baf29b1da8ad7c67dfb2686460
https://github.com/FlexModel/FlexModelBundle/blob/7b4720d25b0dc6baf29b1da8ad7c67dfb2686460/Model/UploadTrait.php#L52-L60
train
FlexModel/FlexModelBundle
Model/UploadTrait.php
UploadTrait.getFileUploadPropertyName
private function getFileUploadPropertyName($realCallerMethod) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); $callerMethodName = $backtrace[1]['function']; if ($callerMethodName === $realCallerMethod) { $callerMethodName = $backtrace[2]['function']; } return lcfirst(substr($callerMethodName, 3, -6)); }
php
private function getFileUploadPropertyName($realCallerMethod) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); $callerMethodName = $backtrace[1]['function']; if ($callerMethodName === $realCallerMethod) { $callerMethodName = $backtrace[2]['function']; } return lcfirst(substr($callerMethodName, 3, -6)); }
[ "private", "function", "getFileUploadPropertyName", "(", "$", "realCallerMethod", ")", "{", "$", "backtrace", "=", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "3", ")", ";", "$", "callerMethodName", "=", "$", "backtrace", "[", "1", "]", "[", "'function'", "]", ";", "if", "(", "$", "callerMethodName", "===", "$", "realCallerMethod", ")", "{", "$", "callerMethodName", "=", "$", "backtrace", "[", "2", "]", "[", "'function'", "]", ";", "}", "return", "lcfirst", "(", "substr", "(", "$", "callerMethodName", ",", "3", ",", "-", "6", ")", ")", ";", "}" ]
Returns file upload name based on the called method name. @return string
[ "Returns", "file", "upload", "name", "based", "on", "the", "called", "method", "name", "." ]
7b4720d25b0dc6baf29b1da8ad7c67dfb2686460
https://github.com/FlexModel/FlexModelBundle/blob/7b4720d25b0dc6baf29b1da8ad7c67dfb2686460/Model/UploadTrait.php#L77-L86
train
prolic/HumusMvc
src/HumusMvc/Service/ViewFactory.php
ViewFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { // handle configuration $config = $serviceLocator->get('Config'); $viewConfig = isset($config['view']) ? $config['view'] : array(); $className = isset($viewConfig['classname']) ? $viewConfig['classname'] : 'HumusMvc\View\View'; $view = new $className($viewConfig); if (!$view instanceof View) { throw new InvalidArgumentException('View object must extend HumusMvc\View\View'); } $view->setHelperPluginManager($serviceLocator->get('ViewHelperManager')); if (isset($viewConfig['doctype'])) { $view->doctype()->setDoctype(strtoupper($viewConfig['doctype'])); if (isset($viewConfig['charset']) && $view->doctype()->isHtml5()) { $view->headMeta()->setCharset($viewConfig['charset']); } } if (isset($viewConfig['contentType'])) { $view->headMeta()->appendHttpEquiv('Content-Type', $viewConfig['contentType']); } if (isset($viewConfig['assign']) && is_array($viewConfig['assign'])) { $view->assign($viewConfig['assign']); } if (isset($viewConfig['useViewRenderer']) && true === (bool) $viewConfig['useViewRenderer']) { $viewRenderer = ControllerActionHelper::getStaticHelper('viewRenderer'); $viewRenderer->setView($view); } return $view; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { // handle configuration $config = $serviceLocator->get('Config'); $viewConfig = isset($config['view']) ? $config['view'] : array(); $className = isset($viewConfig['classname']) ? $viewConfig['classname'] : 'HumusMvc\View\View'; $view = new $className($viewConfig); if (!$view instanceof View) { throw new InvalidArgumentException('View object must extend HumusMvc\View\View'); } $view->setHelperPluginManager($serviceLocator->get('ViewHelperManager')); if (isset($viewConfig['doctype'])) { $view->doctype()->setDoctype(strtoupper($viewConfig['doctype'])); if (isset($viewConfig['charset']) && $view->doctype()->isHtml5()) { $view->headMeta()->setCharset($viewConfig['charset']); } } if (isset($viewConfig['contentType'])) { $view->headMeta()->appendHttpEquiv('Content-Type', $viewConfig['contentType']); } if (isset($viewConfig['assign']) && is_array($viewConfig['assign'])) { $view->assign($viewConfig['assign']); } if (isset($viewConfig['useViewRenderer']) && true === (bool) $viewConfig['useViewRenderer']) { $viewRenderer = ControllerActionHelper::getStaticHelper('viewRenderer'); $viewRenderer->setView($view); } return $view; }
[ "public", "function", "createService", "(", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "// handle configuration", "$", "config", "=", "$", "serviceLocator", "->", "get", "(", "'Config'", ")", ";", "$", "viewConfig", "=", "isset", "(", "$", "config", "[", "'view'", "]", ")", "?", "$", "config", "[", "'view'", "]", ":", "array", "(", ")", ";", "$", "className", "=", "isset", "(", "$", "viewConfig", "[", "'classname'", "]", ")", "?", "$", "viewConfig", "[", "'classname'", "]", ":", "'HumusMvc\\View\\View'", ";", "$", "view", "=", "new", "$", "className", "(", "$", "viewConfig", ")", ";", "if", "(", "!", "$", "view", "instanceof", "View", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'View object must extend HumusMvc\\View\\View'", ")", ";", "}", "$", "view", "->", "setHelperPluginManager", "(", "$", "serviceLocator", "->", "get", "(", "'ViewHelperManager'", ")", ")", ";", "if", "(", "isset", "(", "$", "viewConfig", "[", "'doctype'", "]", ")", ")", "{", "$", "view", "->", "doctype", "(", ")", "->", "setDoctype", "(", "strtoupper", "(", "$", "viewConfig", "[", "'doctype'", "]", ")", ")", ";", "if", "(", "isset", "(", "$", "viewConfig", "[", "'charset'", "]", ")", "&&", "$", "view", "->", "doctype", "(", ")", "->", "isHtml5", "(", ")", ")", "{", "$", "view", "->", "headMeta", "(", ")", "->", "setCharset", "(", "$", "viewConfig", "[", "'charset'", "]", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "viewConfig", "[", "'contentType'", "]", ")", ")", "{", "$", "view", "->", "headMeta", "(", ")", "->", "appendHttpEquiv", "(", "'Content-Type'", ",", "$", "viewConfig", "[", "'contentType'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "viewConfig", "[", "'assign'", "]", ")", "&&", "is_array", "(", "$", "viewConfig", "[", "'assign'", "]", ")", ")", "{", "$", "view", "->", "assign", "(", "$", "viewConfig", "[", "'assign'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "viewConfig", "[", "'useViewRenderer'", "]", ")", "&&", "true", "===", "(", "bool", ")", "$", "viewConfig", "[", "'useViewRenderer'", "]", ")", "{", "$", "viewRenderer", "=", "ControllerActionHelper", "::", "getStaticHelper", "(", "'viewRenderer'", ")", ";", "$", "viewRenderer", "->", "setView", "(", "$", "view", ")", ";", "}", "return", "$", "view", ";", "}" ]
Create view service @param ServiceLocatorInterface $serviceLocator @return View @throws InvalidArgumentException
[ "Create", "view", "service" ]
09e8c6422d84b57745cc643047e10761be2a21a7
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/Service/ViewFactory.php#L43-L76
train
bkstg/resource-bundle
Controller/ResourceController.php
ResourceController.archiveAction
public function archiveAction( string $production_slug, PaginatorInterface $paginator, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Ensure the user is a member of the production. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get inactive resources. $resource_repo = $this->em->getRepository(Resource::class); $query = $resource_repo->findAllByGroupQuery($production, false); // Paginate and render result. $resources = $paginator->paginate($query, $request->query->getInt('page', 1)); return new Response($this->templating->render( '@BkstgResource/Resource/archive.html.twig', [ 'resources' => $resources, 'production' => $production, ] )); }
php
public function archiveAction( string $production_slug, PaginatorInterface $paginator, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Ensure the user is a member of the production. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get inactive resources. $resource_repo = $this->em->getRepository(Resource::class); $query = $resource_repo->findAllByGroupQuery($production, false); // Paginate and render result. $resources = $paginator->paginate($query, $request->query->getInt('page', 1)); return new Response($this->templating->render( '@BkstgResource/Resource/archive.html.twig', [ 'resources' => $resources, 'production' => $production, ] )); }
[ "public", "function", "archiveAction", "(", "string", "$", "production_slug", ",", "PaginatorInterface", "$", "paginator", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Lookup the production.", "$", "production_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Production", "::", "class", ")", ";", "if", "(", "null", "===", "$", "production", "=", "$", "production_repo", "->", "findOneBy", "(", "[", "'slug'", "=>", "$", "production_slug", "]", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "// Ensure the user is a member of the production.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'GROUP_ROLE_EDITOR'", ",", "$", "production", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Get inactive resources.", "$", "resource_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Resource", "::", "class", ")", ";", "$", "query", "=", "$", "resource_repo", "->", "findAllByGroupQuery", "(", "$", "production", ",", "false", ")", ";", "// Paginate and render result.", "$", "resources", "=", "$", "paginator", "->", "paginate", "(", "$", "query", ",", "$", "request", "->", "query", "->", "getInt", "(", "'page'", ",", "1", ")", ")", ";", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgResource/Resource/archive.html.twig'", ",", "[", "'resources'", "=>", "$", "resources", ",", "'production'", "=>", "$", "production", ",", "]", ")", ")", ";", "}" ]
Show a list of archived resources for a production. @param string $production_slug The production slug. @param PaginatorInterface $paginator The paginator service. @param AuthorizationCheckerInterface $auth The authorization checker service. @param Request $request The incoming request. @throws NotFoundHttpException When the production is not found. @throws AccessDeniedException When the user is not a member of the production. @return Response
[ "Show", "a", "list", "of", "archived", "resources", "for", "a", "production", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Controller/ResourceController.php#L88-L119
train
bkstg/resource-bundle
Controller/ResourceController.php
ResourceController.createAction
public function createAction( string $production_slug, TokenStorageInterface $token, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Ensure the user is a member of the production. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get some information about the user. $user = $token->getToken()->getUser(); // Create a new active resource. $resource = new Resource(); $resource->setAuthor($user->getUsername()); $resource->setActive(true); $resource->setPinned(false); $resource->addGroup($production); // Create and handle the form. $form = $this->form->create(ResourceType::class, $resource); $form->handleRequest($request); // Form is valid, persist and flush. if ($form->isSubmitted() && $form->isValid()) { // Cascade active property to media. if (null !== $media = $resource->getMedia()) { $media->setActive($resource->isActive()); } $this->em->persist($resource); $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('resource.created', [], 'BkstgResourceBundle') ); return new RedirectResponse($this->url_generator->generate( 'bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the form. return new Response($this->templating->render( '@BkstgResource/Resource/create.html.twig', [ 'form' => $form->createView(), 'production' => $production, ] )); }
php
public function createAction( string $production_slug, TokenStorageInterface $token, AuthorizationCheckerInterface $auth, Request $request ): Response { // Lookup the production. $production_repo = $this->em->getRepository(Production::class); if (null === $production = $production_repo->findOneBy(['slug' => $production_slug])) { throw new NotFoundHttpException(); } // Ensure the user is a member of the production. if (!$auth->isGranted('GROUP_ROLE_EDITOR', $production)) { throw new AccessDeniedException(); } // Get some information about the user. $user = $token->getToken()->getUser(); // Create a new active resource. $resource = new Resource(); $resource->setAuthor($user->getUsername()); $resource->setActive(true); $resource->setPinned(false); $resource->addGroup($production); // Create and handle the form. $form = $this->form->create(ResourceType::class, $resource); $form->handleRequest($request); // Form is valid, persist and flush. if ($form->isSubmitted() && $form->isValid()) { // Cascade active property to media. if (null !== $media = $resource->getMedia()) { $media->setActive($resource->isActive()); } $this->em->persist($resource); $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('resource.created', [], 'BkstgResourceBundle') ); return new RedirectResponse($this->url_generator->generate( 'bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the form. return new Response($this->templating->render( '@BkstgResource/Resource/create.html.twig', [ 'form' => $form->createView(), 'production' => $production, ] )); }
[ "public", "function", "createAction", "(", "string", "$", "production_slug", ",", "TokenStorageInterface", "$", "token", ",", "AuthorizationCheckerInterface", "$", "auth", ",", "Request", "$", "request", ")", ":", "Response", "{", "// Lookup the production.", "$", "production_repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "Production", "::", "class", ")", ";", "if", "(", "null", "===", "$", "production", "=", "$", "production_repo", "->", "findOneBy", "(", "[", "'slug'", "=>", "$", "production_slug", "]", ")", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "// Ensure the user is a member of the production.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'GROUP_ROLE_EDITOR'", ",", "$", "production", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Get some information about the user.", "$", "user", "=", "$", "token", "->", "getToken", "(", ")", "->", "getUser", "(", ")", ";", "// Create a new active resource.", "$", "resource", "=", "new", "Resource", "(", ")", ";", "$", "resource", "->", "setAuthor", "(", "$", "user", "->", "getUsername", "(", ")", ")", ";", "$", "resource", "->", "setActive", "(", "true", ")", ";", "$", "resource", "->", "setPinned", "(", "false", ")", ";", "$", "resource", "->", "addGroup", "(", "$", "production", ")", ";", "// Create and handle the form.", "$", "form", "=", "$", "this", "->", "form", "->", "create", "(", "ResourceType", "::", "class", ",", "$", "resource", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "// Form is valid, persist and flush.", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", "&&", "$", "form", "->", "isValid", "(", ")", ")", "{", "// Cascade active property to media.", "if", "(", "null", "!==", "$", "media", "=", "$", "resource", "->", "getMedia", "(", ")", ")", "{", "$", "media", "->", "setActive", "(", "$", "resource", "->", "isActive", "(", ")", ")", ";", "}", "$", "this", "->", "em", "->", "persist", "(", "$", "resource", ")", ";", "$", "this", "->", "em", "->", "flush", "(", ")", ";", "// Set success message and redirect.", "$", "this", "->", "session", "->", "getFlashBag", "(", ")", "->", "add", "(", "'success'", ",", "$", "this", "->", "translator", "->", "trans", "(", "'resource.created'", ",", "[", "]", ",", "'BkstgResourceBundle'", ")", ")", ";", "return", "new", "RedirectResponse", "(", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_resource_read'", ",", "[", "'id'", "=>", "$", "resource", "->", "getId", "(", ")", ",", "'production_slug'", "=>", "$", "production", "->", "getSlug", "(", ")", ",", "]", ")", ")", ";", "}", "// Render the form.", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgResource/Resource/create.html.twig'", ",", "[", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "'production'", "=>", "$", "production", ",", "]", ")", ")", ";", "}" ]
Create a new resource in a production. @param string $production_slug The production slug. @param TokenStorageInterface $token The token storage service. @param AuthorizationCheckerInterface $auth The authorization checker service. @param Request $request The incoming request. @throws NotFoundHttpException When the production is not found. @throws AccessDeniedException When the user is not a member of the production. @return Response
[ "Create", "a", "new", "resource", "in", "a", "production", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Controller/ResourceController.php#L134-L198
train
bkstg/resource-bundle
Controller/ResourceController.php
ResourceController.readAction
public function readAction( int $id, string $production_slug, AuthorizationCheckerInterface $auth ): Response { list($resource, $production) = $this->lookupEntity(Resource::class, $id, $production_slug); if (!$auth->isGranted('view', $resource)) { throw new AccessDeniedException(); } return new Response($this->templating->render( '@BkstgResource/Resource/read.html.twig', [ 'production' => $production, 'resource' => $resource, ] )); }
php
public function readAction( int $id, string $production_slug, AuthorizationCheckerInterface $auth ): Response { list($resource, $production) = $this->lookupEntity(Resource::class, $id, $production_slug); if (!$auth->isGranted('view', $resource)) { throw new AccessDeniedException(); } return new Response($this->templating->render( '@BkstgResource/Resource/read.html.twig', [ 'production' => $production, 'resource' => $resource, ] )); }
[ "public", "function", "readAction", "(", "int", "$", "id", ",", "string", "$", "production_slug", ",", "AuthorizationCheckerInterface", "$", "auth", ")", ":", "Response", "{", "list", "(", "$", "resource", ",", "$", "production", ")", "=", "$", "this", "->", "lookupEntity", "(", "Resource", "::", "class", ",", "$", "id", ",", "$", "production_slug", ")", ";", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'view'", ",", "$", "resource", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgResource/Resource/read.html.twig'", ",", "[", "'production'", "=>", "$", "production", ",", "'resource'", "=>", "$", "resource", ",", "]", ")", ")", ";", "}" ]
Read a resource from this production. @param int $id The resource id. @param string $production_slug The production slug. @param AuthorizationCheckerInterface $auth The authorization checker service. @throws AccessDeniedException When the user does not have access to view the resource. @return Response
[ "Read", "a", "resource", "from", "this", "production", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Controller/ResourceController.php#L211-L229
train
bkstg/resource-bundle
Controller/ResourceController.php
ResourceController.updateAction
public function updateAction( int $id, string $production_slug, Request $request, AuthorizationCheckerInterface $auth ): Response { // Lookup the resource and production. list($resource, $production) = $this->lookupEntity(Resource::class, $id, $production_slug); // Check access to the resource. if (!$auth->isGranted('edit', $resource)) { throw new AccessDeniedException(); } // Create and handle the form. $form = $this->form->create(ResourceType::class, $resource); $form->handleRequest($request); // Form is submitted, flush changes. if ($form->isSubmitted() && $form->isValid()) { // Cascade active property to media. if (null !== $media = $resource->getMedia()) { $media->setActive($resource->isActive()); } $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('resource.updated', ['%name%' => $resource->getName()], 'BkstgResourceBundle') ); return new RedirectResponse($this->url_generator->generate( 'bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the response. return new Response($this->templating->render( '@BkstgResource/Resource/update.html.twig', [ 'resource' => $resource, 'form' => $form->createView(), 'production' => $production, ] )); }
php
public function updateAction( int $id, string $production_slug, Request $request, AuthorizationCheckerInterface $auth ): Response { // Lookup the resource and production. list($resource, $production) = $this->lookupEntity(Resource::class, $id, $production_slug); // Check access to the resource. if (!$auth->isGranted('edit', $resource)) { throw new AccessDeniedException(); } // Create and handle the form. $form = $this->form->create(ResourceType::class, $resource); $form->handleRequest($request); // Form is submitted, flush changes. if ($form->isSubmitted() && $form->isValid()) { // Cascade active property to media. if (null !== $media = $resource->getMedia()) { $media->setActive($resource->isActive()); } $this->em->flush(); // Set success message and redirect. $this->session->getFlashBag()->add( 'success', $this->translator->trans('resource.updated', ['%name%' => $resource->getName()], 'BkstgResourceBundle') ); return new RedirectResponse($this->url_generator->generate( 'bkstg_resource_read', [ 'id' => $resource->getId(), 'production_slug' => $production->getSlug(), ] )); } // Render the response. return new Response($this->templating->render( '@BkstgResource/Resource/update.html.twig', [ 'resource' => $resource, 'form' => $form->createView(), 'production' => $production, ] )); }
[ "public", "function", "updateAction", "(", "int", "$", "id", ",", "string", "$", "production_slug", ",", "Request", "$", "request", ",", "AuthorizationCheckerInterface", "$", "auth", ")", ":", "Response", "{", "// Lookup the resource and production.", "list", "(", "$", "resource", ",", "$", "production", ")", "=", "$", "this", "->", "lookupEntity", "(", "Resource", "::", "class", ",", "$", "id", ",", "$", "production_slug", ")", ";", "// Check access to the resource.", "if", "(", "!", "$", "auth", "->", "isGranted", "(", "'edit'", ",", "$", "resource", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// Create and handle the form.", "$", "form", "=", "$", "this", "->", "form", "->", "create", "(", "ResourceType", "::", "class", ",", "$", "resource", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "// Form is submitted, flush changes.", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", "&&", "$", "form", "->", "isValid", "(", ")", ")", "{", "// Cascade active property to media.", "if", "(", "null", "!==", "$", "media", "=", "$", "resource", "->", "getMedia", "(", ")", ")", "{", "$", "media", "->", "setActive", "(", "$", "resource", "->", "isActive", "(", ")", ")", ";", "}", "$", "this", "->", "em", "->", "flush", "(", ")", ";", "// Set success message and redirect.", "$", "this", "->", "session", "->", "getFlashBag", "(", ")", "->", "add", "(", "'success'", ",", "$", "this", "->", "translator", "->", "trans", "(", "'resource.updated'", ",", "[", "'%name%'", "=>", "$", "resource", "->", "getName", "(", ")", "]", ",", "'BkstgResourceBundle'", ")", ")", ";", "return", "new", "RedirectResponse", "(", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_resource_read'", ",", "[", "'id'", "=>", "$", "resource", "->", "getId", "(", ")", ",", "'production_slug'", "=>", "$", "production", "->", "getSlug", "(", ")", ",", "]", ")", ")", ";", "}", "// Render the response.", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgResource/Resource/update.html.twig'", ",", "[", "'resource'", "=>", "$", "resource", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "'production'", "=>", "$", "production", ",", "]", ")", ")", ";", "}" ]
Update a resource for this production. @param int $id The resource id. @param string $production_slug The production slug. @param Request $request The incoming request. @param AuthorizationCheckerInterface $auth The authorization checker service. @throws AccessDeniedException When the user does not have access to edit the resource. @return Response
[ "Update", "a", "resource", "for", "this", "production", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Controller/ResourceController.php#L243-L294
train
Krinkle/toollabs-base
src/LabsDB.php
LabsDB.getConnection
public static function getConnection( $hostname, $dbname ) { if ( isset( self::$dbConnections[ $hostname ] ) ) { $conn = self::$dbConnections[ $hostname ]; } else { $section = new kfLogSection( __METHOD__ ); try { $conn = new LoggedPDO( 'mysql:host=' . $hostname . ';dbname=' . $dbname . '_p;charset=utf8', kfDbUsername(), kfDbPassword() ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch ( Exception $e ) { throw new Exception( "Connection to '$hostname' failed: " . $e->getMessage() ); } self::$dbConnections[ $hostname ] = $conn; return $conn; } // Re-used connection, switch database first. self::selectDB( $conn, $dbname ); return $conn; }
php
public static function getConnection( $hostname, $dbname ) { if ( isset( self::$dbConnections[ $hostname ] ) ) { $conn = self::$dbConnections[ $hostname ]; } else { $section = new kfLogSection( __METHOD__ ); try { $conn = new LoggedPDO( 'mysql:host=' . $hostname . ';dbname=' . $dbname . '_p;charset=utf8', kfDbUsername(), kfDbPassword() ); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch ( Exception $e ) { throw new Exception( "Connection to '$hostname' failed: " . $e->getMessage() ); } self::$dbConnections[ $hostname ] = $conn; return $conn; } // Re-used connection, switch database first. self::selectDB( $conn, $dbname ); return $conn; }
[ "public", "static", "function", "getConnection", "(", "$", "hostname", ",", "$", "dbname", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "dbConnections", "[", "$", "hostname", "]", ")", ")", "{", "$", "conn", "=", "self", "::", "$", "dbConnections", "[", "$", "hostname", "]", ";", "}", "else", "{", "$", "section", "=", "new", "kfLogSection", "(", "__METHOD__", ")", ";", "try", "{", "$", "conn", "=", "new", "LoggedPDO", "(", "'mysql:host='", ".", "$", "hostname", ".", "';dbname='", ".", "$", "dbname", ".", "'_p;charset=utf8'", ",", "kfDbUsername", "(", ")", ",", "kfDbPassword", "(", ")", ")", ";", "$", "conn", "->", "setAttribute", "(", "PDO", "::", "ATTR_ERRMODE", ",", "PDO", "::", "ERRMODE_EXCEPTION", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "Exception", "(", "\"Connection to '$hostname' failed: \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "self", "::", "$", "dbConnections", "[", "$", "hostname", "]", "=", "$", "conn", ";", "return", "$", "conn", ";", "}", "// Re-used connection, switch database first.", "self", "::", "selectDB", "(", "$", "conn", ",", "$", "dbname", ")", ";", "return", "$", "conn", ";", "}" ]
Get a database connection by hostname Returns a previously established connection or initiates a new one. @return PDO @throws If connection failed
[ "Get", "a", "database", "connection", "by", "hostname" ]
784150ca58f4b48cc89534fd6142c54b4f138cd2
https://github.com/Krinkle/toollabs-base/blob/784150ca58f4b48cc89534fd6142c54b4f138cd2/src/LabsDB.php#L31-L54
train
Krinkle/toollabs-base
src/LabsDB.php
LabsDB.getDB
public static function getDB( $dbname ) { if ( $dbname === 'meta' ) { return self::getMetaDB(); } $wikiInfo = self::getDbInfo( $dbname ); if ( !$wikiInfo['slice'] ) { throw new Exception( "Incomplete database information for '$dbname'" ); } return self::getConnection( $wikiInfo['slice'], $dbname ); }
php
public static function getDB( $dbname ) { if ( $dbname === 'meta' ) { return self::getMetaDB(); } $wikiInfo = self::getDbInfo( $dbname ); if ( !$wikiInfo['slice'] ) { throw new Exception( "Incomplete database information for '$dbname'" ); } return self::getConnection( $wikiInfo['slice'], $dbname ); }
[ "public", "static", "function", "getDB", "(", "$", "dbname", ")", "{", "if", "(", "$", "dbname", "===", "'meta'", ")", "{", "return", "self", "::", "getMetaDB", "(", ")", ";", "}", "$", "wikiInfo", "=", "self", "::", "getDbInfo", "(", "$", "dbname", ")", ";", "if", "(", "!", "$", "wikiInfo", "[", "'slice'", "]", ")", "{", "throw", "new", "Exception", "(", "\"Incomplete database information for '$dbname'\"", ")", ";", "}", "return", "self", "::", "getConnection", "(", "$", "wikiInfo", "[", "'slice'", "]", ",", "$", "dbname", ")", ";", "}" ]
Get a database connection by dbname. Usage: $conn = LabsDB::getDB( 'aawiki' ); $rows = LabsDB::query( $conn, 'SELECT * WHERE name = "str"' ); $conn = LabsDB::getDB( 'aawiki' ); $rows = LabsDB::query( $conn, 'SELECT * WHERE name = :name', array( ':name' => "string" ) ); $conn = LabsDB::getDB( 'aawiki' ); $m = $conn->prepare( 'SELECT * WHERE total = :total' ); $m->bindParam( ':total', $total, PDO::PARAM_INT ); $m->execute(); $rows = $m->fetchAll( PDO::FETCH_ASSOC ); @return PDO @throws If dbname could not be found
[ "Get", "a", "database", "connection", "by", "dbname", "." ]
784150ca58f4b48cc89534fd6142c54b4f138cd2
https://github.com/Krinkle/toollabs-base/blob/784150ca58f4b48cc89534fd6142c54b4f138cd2/src/LabsDB.php#L112-L123
train
Krinkle/toollabs-base
src/LabsDB.php
LabsDB.getAllWikiInfos
public static function getAllWikiInfos() { if ( !isset( self::$wikiInfos ) ) { $wikiInfos = self::getAllDbInfos(); foreach ( $wikiInfos as $dbname => &$wikiInfo ) { if ( !$wikiInfo['url'] ) { unset( $wikiInfos[ $dbname ] ); } } self::$wikiInfos = $wikiInfos; } return self::$wikiInfos; }
php
public static function getAllWikiInfos() { if ( !isset( self::$wikiInfos ) ) { $wikiInfos = self::getAllDbInfos(); foreach ( $wikiInfos as $dbname => &$wikiInfo ) { if ( !$wikiInfo['url'] ) { unset( $wikiInfos[ $dbname ] ); } } self::$wikiInfos = $wikiInfos; } return self::$wikiInfos; }
[ "public", "static", "function", "getAllWikiInfos", "(", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "wikiInfos", ")", ")", "{", "$", "wikiInfos", "=", "self", "::", "getAllDbInfos", "(", ")", ";", "foreach", "(", "$", "wikiInfos", "as", "$", "dbname", "=>", "&", "$", "wikiInfo", ")", "{", "if", "(", "!", "$", "wikiInfo", "[", "'url'", "]", ")", "{", "unset", "(", "$", "wikiInfos", "[", "$", "dbname", "]", ")", ";", "}", "}", "self", "::", "$", "wikiInfos", "=", "$", "wikiInfos", ";", "}", "return", "self", "::", "$", "wikiInfos", ";", "}" ]
Like getAllDbInfos, but without databases that aren't wikis. Because meta_p.wiki also contains dbname='centralauth' we need to filter out non-wikis. Do so by removing rows with NULL values for url (see wmbug.com/65789). Could simply be done in SQL, but we want to cache all db infos, so do here instead. @return Array
[ "Like", "getAllDbInfos", "but", "without", "databases", "that", "aren", "t", "wikis", "." ]
784150ca58f4b48cc89534fd6142c54b4f138cd2
https://github.com/Krinkle/toollabs-base/blob/784150ca58f4b48cc89534fd6142c54b4f138cd2/src/LabsDB.php#L221-L234
train
Krinkle/toollabs-base
src/LabsDB.php
LoggedPDO.generalizeSQL
protected static function generalizeSQL( $sql ) { // This does the same as the regexp below would do, but in such a way // as to avoid crashing php on some large strings. # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql ); $sql = str_replace( "\\\\", '', $sql ); $sql = str_replace( "\\'", '', $sql ); $sql = str_replace( "\\\"", '', $sql ); $sql = preg_replace( "/'.*'/s", "'X'", $sql ); $sql = preg_replace( '/".*"/s', "'X'", $sql ); // All newlines, tabs, etc replaced by single space $sql = preg_replace( '/\s+/', ' ', $sql ); // All numbers => N $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql ); $sql = preg_replace( '/-?\d+/s', 'N', $sql ); return $sql; }
php
protected static function generalizeSQL( $sql ) { // This does the same as the regexp below would do, but in such a way // as to avoid crashing php on some large strings. # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql ); $sql = str_replace( "\\\\", '', $sql ); $sql = str_replace( "\\'", '', $sql ); $sql = str_replace( "\\\"", '', $sql ); $sql = preg_replace( "/'.*'/s", "'X'", $sql ); $sql = preg_replace( '/".*"/s', "'X'", $sql ); // All newlines, tabs, etc replaced by single space $sql = preg_replace( '/\s+/', ' ', $sql ); // All numbers => N $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql ); $sql = preg_replace( '/-?\d+/s', 'N', $sql ); return $sql; }
[ "protected", "static", "function", "generalizeSQL", "(", "$", "sql", ")", "{", "// This does the same as the regexp below would do, but in such a way", "// as to avoid crashing php on some large strings.", "# $sql = preg_replace( \"/'([^\\\\\\\\']|\\\\\\\\.)*'|\\\"([^\\\\\\\\\\\"]|\\\\\\\\.)*\\\"/\", \"'X'\", $sql );", "$", "sql", "=", "str_replace", "(", "\"\\\\\\\\\"", ",", "''", ",", "$", "sql", ")", ";", "$", "sql", "=", "str_replace", "(", "\"\\\\'\"", ",", "''", ",", "$", "sql", ")", ";", "$", "sql", "=", "str_replace", "(", "\"\\\\\\\"\"", ",", "''", ",", "$", "sql", ")", ";", "$", "sql", "=", "preg_replace", "(", "\"/'.*'/s\"", ",", "\"'X'\"", ",", "$", "sql", ")", ";", "$", "sql", "=", "preg_replace", "(", "'/\".*\"/s'", ",", "\"'X'\"", ",", "$", "sql", ")", ";", "// All newlines, tabs, etc replaced by single space", "$", "sql", "=", "preg_replace", "(", "'/\\s+/'", ",", "' '", ",", "$", "sql", ")", ";", "// All numbers => N", "$", "sql", "=", "preg_replace", "(", "'/-?\\d+(,-?\\d+)+/s'", ",", "'N,...,N'", ",", "$", "sql", ")", ";", "$", "sql", "=", "preg_replace", "(", "'/-?\\d+/s'", ",", "'N'", ",", "$", "sql", ")", ";", "return", "$", "sql", ";", "}" ]
Remove most variables from an SQL query and replace them with X or N markers. Based on Database.php of mediawik-core 1.24-alpha @param string $sql @return string
[ "Remove", "most", "variables", "from", "an", "SQL", "query", "and", "replace", "them", "with", "X", "or", "N", "markers", "." ]
784150ca58f4b48cc89534fd6142c54b4f138cd2
https://github.com/Krinkle/toollabs-base/blob/784150ca58f4b48cc89534fd6142c54b4f138cd2/src/LabsDB.php#L266-L285
train
nicodevs/laito
src/Laito/Http/Client.php
Client.setupParams
public function setupParams($params = []) { if (is_array($params)) { $this->params = array_merge($this->params, $params); } return $this; }
php
public function setupParams($params = []) { if (is_array($params)) { $this->params = array_merge($this->params, $params); } return $this; }
[ "public", "function", "setupParams", "(", "$", "params", "=", "[", "]", ")", "{", "if", "(", "is_array", "(", "$", "params", ")", ")", "{", "$", "this", "->", "params", "=", "array_merge", "(", "$", "this", "->", "params", ",", "$", "params", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets fixed parameters to be sent in all calls @param array $params Parameters @return object Http instance
[ "Sets", "fixed", "parameters", "to", "be", "sent", "in", "all", "calls" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Http/Client.php#L19-L25
train
nicodevs/laito
src/Laito/Http/Client.php
Client.call
public function call($url, $method = 'GET', $params = []) { // Set call parameters $params = array_merge($this->params, is_array($params)? $params : []); // Setup parameters $content = ''; $queryString = http_build_query($params); if ($method === 'GET') { $url = $url . '?' . $queryString; } else { $content = $queryString; } // Make call $result = @file_get_contents($url, false, stream_context_create([ 'http' => [ 'method' => $method, 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $content ] ])); // Return result return $result; }
php
public function call($url, $method = 'GET', $params = []) { // Set call parameters $params = array_merge($this->params, is_array($params)? $params : []); // Setup parameters $content = ''; $queryString = http_build_query($params); if ($method === 'GET') { $url = $url . '?' . $queryString; } else { $content = $queryString; } // Make call $result = @file_get_contents($url, false, stream_context_create([ 'http' => [ 'method' => $method, 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $content ] ])); // Return result return $result; }
[ "public", "function", "call", "(", "$", "url", ",", "$", "method", "=", "'GET'", ",", "$", "params", "=", "[", "]", ")", "{", "// Set call parameters", "$", "params", "=", "array_merge", "(", "$", "this", "->", "params", ",", "is_array", "(", "$", "params", ")", "?", "$", "params", ":", "[", "]", ")", ";", "// Setup parameters", "$", "content", "=", "''", ";", "$", "queryString", "=", "http_build_query", "(", "$", "params", ")", ";", "if", "(", "$", "method", "===", "'GET'", ")", "{", "$", "url", "=", "$", "url", ".", "'?'", ".", "$", "queryString", ";", "}", "else", "{", "$", "content", "=", "$", "queryString", ";", "}", "// Make call", "$", "result", "=", "@", "file_get_contents", "(", "$", "url", ",", "false", ",", "stream_context_create", "(", "[", "'http'", "=>", "[", "'method'", "=>", "$", "method", ",", "'header'", "=>", "'Content-type: application/x-www-form-urlencoded'", ",", "'content'", "=>", "$", "content", "]", "]", ")", ")", ";", "// Return result", "return", "$", "result", ";", "}" ]
Makes an HTTP call @param string $url URL to request @param string $method HTTP method @param array $params Parameters @return object Http instance
[ "Makes", "an", "HTTP", "call" ]
d2d28abfcbf981c4decfec28ce94f8849600e9fe
https://github.com/nicodevs/laito/blob/d2d28abfcbf981c4decfec28ce94f8849600e9fe/src/Laito/Http/Client.php#L35-L60
train
facile-it/sentry-common
src/Sender/Sender.php
Sender.send
public function send(string $priority, string $message, array $context = []) { if (! $this->contextContainsException($context)) { $data = [ 'extra' => $this->sanitizer->sanitize($context), 'level' => $priority, ]; $this->client->captureMessage( $message, [], $data, $this->stackTrace->cleanBacktrace(debug_backtrace()) ); return; } /** @var \Exception $exception */ $exception = $context['exception']; unset($context['exception']); $exceptionsStack = $this->stackTrace->getExceptions($exception); // Adding a first fake exception to log the message $stack = $this->stackTrace->cleanBacktrace(debug_backtrace()); $exceptionsStack[] = [ 'value' => $message, 'type' => get_class($exception), 'stacktrace' => [ 'frames' => $this->stackTrace->getStackTraceFrames($stack), ], ]; $data = [ 'extra' => $this->sanitizer->sanitize($context), 'level' => $priority, 'exception' => [ 'values' => $exceptionsStack, ], ]; $this->client->captureMessage($message, [], $data); }
php
public function send(string $priority, string $message, array $context = []) { if (! $this->contextContainsException($context)) { $data = [ 'extra' => $this->sanitizer->sanitize($context), 'level' => $priority, ]; $this->client->captureMessage( $message, [], $data, $this->stackTrace->cleanBacktrace(debug_backtrace()) ); return; } /** @var \Exception $exception */ $exception = $context['exception']; unset($context['exception']); $exceptionsStack = $this->stackTrace->getExceptions($exception); // Adding a first fake exception to log the message $stack = $this->stackTrace->cleanBacktrace(debug_backtrace()); $exceptionsStack[] = [ 'value' => $message, 'type' => get_class($exception), 'stacktrace' => [ 'frames' => $this->stackTrace->getStackTraceFrames($stack), ], ]; $data = [ 'extra' => $this->sanitizer->sanitize($context), 'level' => $priority, 'exception' => [ 'values' => $exceptionsStack, ], ]; $this->client->captureMessage($message, [], $data); }
[ "public", "function", "send", "(", "string", "$", "priority", ",", "string", "$", "message", ",", "array", "$", "context", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "contextContainsException", "(", "$", "context", ")", ")", "{", "$", "data", "=", "[", "'extra'", "=>", "$", "this", "->", "sanitizer", "->", "sanitize", "(", "$", "context", ")", ",", "'level'", "=>", "$", "priority", ",", "]", ";", "$", "this", "->", "client", "->", "captureMessage", "(", "$", "message", ",", "[", "]", ",", "$", "data", ",", "$", "this", "->", "stackTrace", "->", "cleanBacktrace", "(", "debug_backtrace", "(", ")", ")", ")", ";", "return", ";", "}", "/** @var \\Exception $exception */", "$", "exception", "=", "$", "context", "[", "'exception'", "]", ";", "unset", "(", "$", "context", "[", "'exception'", "]", ")", ";", "$", "exceptionsStack", "=", "$", "this", "->", "stackTrace", "->", "getExceptions", "(", "$", "exception", ")", ";", "// Adding a first fake exception to log the message", "$", "stack", "=", "$", "this", "->", "stackTrace", "->", "cleanBacktrace", "(", "debug_backtrace", "(", ")", ")", ";", "$", "exceptionsStack", "[", "]", "=", "[", "'value'", "=>", "$", "message", ",", "'type'", "=>", "get_class", "(", "$", "exception", ")", ",", "'stacktrace'", "=>", "[", "'frames'", "=>", "$", "this", "->", "stackTrace", "->", "getStackTraceFrames", "(", "$", "stack", ")", ",", "]", ",", "]", ";", "$", "data", "=", "[", "'extra'", "=>", "$", "this", "->", "sanitizer", "->", "sanitize", "(", "$", "context", ")", ",", "'level'", "=>", "$", "priority", ",", "'exception'", "=>", "[", "'values'", "=>", "$", "exceptionsStack", ",", "]", ",", "]", ";", "$", "this", "->", "client", "->", "captureMessage", "(", "$", "message", ",", "[", "]", ",", "$", "data", ")", ";", "}" ]
Send the log @param string $priority Sentry priority @param string $message Log Message @param array $context Log context
[ "Send", "the", "log" ]
63ca40700e19363e6af94c69ef8f0f889ba031bd
https://github.com/facile-it/sentry-common/blob/63ca40700e19363e6af94c69ef8f0f889ba031bd/src/Sender/Sender.php#L80-L123
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.to
public function to(string $target): Date { $modifiedHandle = clone $this->originalDate->handle(); $modifiedHandle->modify($target); return new Date($modifiedHandle); }
php
public function to(string $target): Date { $modifiedHandle = clone $this->originalDate->handle(); $modifiedHandle->modify($target); return new Date($modifiedHandle); }
[ "public", "function", "to", "(", "string", "$", "target", ")", ":", "Date", "{", "$", "modifiedHandle", "=", "clone", "$", "this", "->", "originalDate", "->", "handle", "(", ")", ";", "$", "modifiedHandle", "->", "modify", "(", "$", "target", ")", ";", "return", "new", "Date", "(", "$", "modifiedHandle", ")", ";", "}" ]
returns a new date instance which represents the changed date @api @param string $target relative format accepted by strtotime() @return \stubbles\date\Date
[ "returns", "a", "new", "date", "instance", "which", "represents", "the", "changed", "date" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L43-L48
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.timeTo
public function timeTo(string $time): Date { $times = explode(':', $time); if (count($times) != 3) { throw new \InvalidArgumentException( 'Given time "' . $time . '" does not follow required format HH:MM:SS' ); } list($hour, $minute, $second) = $times; if (!ctype_digit($hour) || 0 > $hour || 23 < $hour) { throw new \InvalidArgumentException( 'Given value ' . $hour . ' for hour not suitable for changing the time.' ); } if (!ctype_digit($minute) || 0 > $minute || 59 < $minute) { throw new \InvalidArgumentException( 'Given value ' . $minute . ' for minute not suitable for changing the time.' ); } if (!ctype_digit($second) || 0 > $second || 59 < $second) { throw new \InvalidArgumentException( 'Given value ' . $second . ' for second not suitable for changing the time.' ); } return $this->createDateWithNewTime((int) $hour, (int) $minute, (int) $second); }
php
public function timeTo(string $time): Date { $times = explode(':', $time); if (count($times) != 3) { throw new \InvalidArgumentException( 'Given time "' . $time . '" does not follow required format HH:MM:SS' ); } list($hour, $minute, $second) = $times; if (!ctype_digit($hour) || 0 > $hour || 23 < $hour) { throw new \InvalidArgumentException( 'Given value ' . $hour . ' for hour not suitable for changing the time.' ); } if (!ctype_digit($minute) || 0 > $minute || 59 < $minute) { throw new \InvalidArgumentException( 'Given value ' . $minute . ' for minute not suitable for changing the time.' ); } if (!ctype_digit($second) || 0 > $second || 59 < $second) { throw new \InvalidArgumentException( 'Given value ' . $second . ' for second not suitable for changing the time.' ); } return $this->createDateWithNewTime((int) $hour, (int) $minute, (int) $second); }
[ "public", "function", "timeTo", "(", "string", "$", "time", ")", ":", "Date", "{", "$", "times", "=", "explode", "(", "':'", ",", "$", "time", ")", ";", "if", "(", "count", "(", "$", "times", ")", "!=", "3", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given time \"'", ".", "$", "time", ".", "'\" does not follow required format HH:MM:SS'", ")", ";", "}", "list", "(", "$", "hour", ",", "$", "minute", ",", "$", "second", ")", "=", "$", "times", ";", "if", "(", "!", "ctype_digit", "(", "$", "hour", ")", "||", "0", ">", "$", "hour", "||", "23", "<", "$", "hour", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "hour", ".", "' for hour not suitable for changing the time.'", ")", ";", "}", "if", "(", "!", "ctype_digit", "(", "$", "minute", ")", "||", "0", ">", "$", "minute", "||", "59", "<", "$", "minute", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "minute", ".", "' for minute not suitable for changing the time.'", ")", ";", "}", "if", "(", "!", "ctype_digit", "(", "$", "second", ")", "||", "0", ">", "$", "second", "||", "59", "<", "$", "second", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "second", ".", "' for second not suitable for changing the time.'", ")", ";", "}", "return", "$", "this", "->", "createDateWithNewTime", "(", "(", "int", ")", "$", "hour", ",", "(", "int", ")", "$", "minute", ",", "(", "int", ")", "$", "second", ")", ";", "}" ]
returns a new date instance with same date but changed time @api @param string $time time representation in format HH:MM:SS @return \stubbles\date\Date @throws \InvalidArgumentException
[ "returns", "a", "new", "date", "instance", "with", "same", "date", "but", "changed", "time" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L58-L87
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.hourTo
public function hourTo(int $hour): Date { return $this->createDateWithNewTime( $hour, $this->originalDate->minutes(), $this->originalDate->seconds() ); }
php
public function hourTo(int $hour): Date { return $this->createDateWithNewTime( $hour, $this->originalDate->minutes(), $this->originalDate->seconds() ); }
[ "public", "function", "hourTo", "(", "int", "$", "hour", ")", ":", "Date", "{", "return", "$", "this", "->", "createDateWithNewTime", "(", "$", "hour", ",", "$", "this", "->", "originalDate", "->", "minutes", "(", ")", ",", "$", "this", "->", "originalDate", "->", "seconds", "(", ")", ")", ";", "}" ]
returns a new date instance with same date, minute and second but changed hour @api @param int $hour @return \stubbles\date\Date
[ "returns", "a", "new", "date", "instance", "with", "same", "date", "minute", "and", "second", "but", "changed", "hour" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L120-L127
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.byHours
public function byHours(int $hours): Date { return $this->hourTo($this->originalDate->hours() + $hours); }
php
public function byHours(int $hours): Date { return $this->hourTo($this->originalDate->hours() + $hours); }
[ "public", "function", "byHours", "(", "int", "$", "hours", ")", ":", "Date", "{", "return", "$", "this", "->", "hourTo", "(", "$", "this", "->", "originalDate", "->", "hours", "(", ")", "+", "$", "hours", ")", ";", "}" ]
changes date by given amount of hours @api @param int $hours @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "hours" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L136-L139
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.minuteTo
public function minuteTo(int $minute): Date { return $this->createDateWithNewTime( $this->originalDate->hours(), $minute, $this->originalDate->seconds() ); }
php
public function minuteTo(int $minute): Date { return $this->createDateWithNewTime( $this->originalDate->hours(), $minute, $this->originalDate->seconds() ); }
[ "public", "function", "minuteTo", "(", "int", "$", "minute", ")", ":", "Date", "{", "return", "$", "this", "->", "createDateWithNewTime", "(", "$", "this", "->", "originalDate", "->", "hours", "(", ")", ",", "$", "minute", ",", "$", "this", "->", "originalDate", "->", "seconds", "(", ")", ")", ";", "}" ]
returns a new date instance with same date, hour and second but changed minute @api @param int $minute @return \stubbles\date\Date
[ "returns", "a", "new", "date", "instance", "with", "same", "date", "hour", "and", "second", "but", "changed", "minute" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L148-L155
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.byMinutes
public function byMinutes(int $minutes): Date { return $this->minuteTo($this->originalDate->minutes() + $minutes); }
php
public function byMinutes(int $minutes): Date { return $this->minuteTo($this->originalDate->minutes() + $minutes); }
[ "public", "function", "byMinutes", "(", "int", "$", "minutes", ")", ":", "Date", "{", "return", "$", "this", "->", "minuteTo", "(", "$", "this", "->", "originalDate", "->", "minutes", "(", ")", "+", "$", "minutes", ")", ";", "}" ]
changes date by given amount of minutes @api @param int $minutes @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "minutes" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L164-L167
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.secondTo
public function secondTo(int $second): Date { return $this->createDateWithNewTime( $this->originalDate->hours(), $this->originalDate->minutes(), $second ); }
php
public function secondTo(int $second): Date { return $this->createDateWithNewTime( $this->originalDate->hours(), $this->originalDate->minutes(), $second ); }
[ "public", "function", "secondTo", "(", "int", "$", "second", ")", ":", "Date", "{", "return", "$", "this", "->", "createDateWithNewTime", "(", "$", "this", "->", "originalDate", "->", "hours", "(", ")", ",", "$", "this", "->", "originalDate", "->", "minutes", "(", ")", ",", "$", "second", ")", ";", "}" ]
returns a new date instance with same date, hour and minute but changed second @api @param int $second @return \stubbles\date\Date
[ "returns", "a", "new", "date", "instance", "with", "same", "date", "hour", "and", "minute", "but", "changed", "second" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L176-L183
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.bySeconds
public function bySeconds(int $seconds): Date { return $this->secondTo($this->originalDate->seconds() + $seconds); }
php
public function bySeconds(int $seconds): Date { return $this->secondTo($this->originalDate->seconds() + $seconds); }
[ "public", "function", "bySeconds", "(", "int", "$", "seconds", ")", ":", "Date", "{", "return", "$", "this", "->", "secondTo", "(", "$", "this", "->", "originalDate", "->", "seconds", "(", ")", "+", "$", "seconds", ")", ";", "}" ]
changes date by given amount of seconds @api @param int $seconds @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "seconds" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L192-L195
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.createDateWithNewTime
private function createDateWithNewTime(int $hour, int $minute, int $second): Date { return new Date($this->originalDate->handle()->setTime($hour, $minute, $second)); }
php
private function createDateWithNewTime(int $hour, int $minute, int $second): Date { return new Date($this->originalDate->handle()->setTime($hour, $minute, $second)); }
[ "private", "function", "createDateWithNewTime", "(", "int", "$", "hour", ",", "int", "$", "minute", ",", "int", "$", "second", ")", ":", "Date", "{", "return", "new", "Date", "(", "$", "this", "->", "originalDate", "->", "handle", "(", ")", "->", "setTime", "(", "$", "hour", ",", "$", "minute", ",", "$", "second", ")", ")", ";", "}" ]
creates new date instance with changed time @param int $hour @param int $minute @param int $second @return \stubbles\date\Date
[ "creates", "new", "date", "instance", "with", "changed", "time" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L205-L208
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.dateTo
public function dateTo(string $date): Date { $dates = explode('-', $date); if (count($dates) != 3) { throw new \InvalidArgumentException( 'Given date "' . $date . '" does not follow required format YYYY-MM-DD' ); } list($year, $month, $day) = $dates; if (!ctype_digit($year)) { throw new \InvalidArgumentException( 'Given value ' . $year . ' for year not suitable for changing the date.' ); } if (!ctype_digit($month) || 1 > $month || 12 < $month) { throw new \InvalidArgumentException( 'Given value ' . $month . ' for month not suitable for changing the date.' ); } if (!ctype_digit($day) || 1 > $day || 31 < $day) { throw new \InvalidArgumentException( 'Given value ' . $day . ' for day not suitable for changing the date.' ); } return $this->createNewDateWithExistingTime((int) $year, (int) $month, (int) $day); }
php
public function dateTo(string $date): Date { $dates = explode('-', $date); if (count($dates) != 3) { throw new \InvalidArgumentException( 'Given date "' . $date . '" does not follow required format YYYY-MM-DD' ); } list($year, $month, $day) = $dates; if (!ctype_digit($year)) { throw new \InvalidArgumentException( 'Given value ' . $year . ' for year not suitable for changing the date.' ); } if (!ctype_digit($month) || 1 > $month || 12 < $month) { throw new \InvalidArgumentException( 'Given value ' . $month . ' for month not suitable for changing the date.' ); } if (!ctype_digit($day) || 1 > $day || 31 < $day) { throw new \InvalidArgumentException( 'Given value ' . $day . ' for day not suitable for changing the date.' ); } return $this->createNewDateWithExistingTime((int) $year, (int) $month, (int) $day); }
[ "public", "function", "dateTo", "(", "string", "$", "date", ")", ":", "Date", "{", "$", "dates", "=", "explode", "(", "'-'", ",", "$", "date", ")", ";", "if", "(", "count", "(", "$", "dates", ")", "!=", "3", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given date \"'", ".", "$", "date", ".", "'\" does not follow required format YYYY-MM-DD'", ")", ";", "}", "list", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", "=", "$", "dates", ";", "if", "(", "!", "ctype_digit", "(", "$", "year", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "year", ".", "' for year not suitable for changing the date.'", ")", ";", "}", "if", "(", "!", "ctype_digit", "(", "$", "month", ")", "||", "1", ">", "$", "month", "||", "12", "<", "$", "month", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "month", ".", "' for month not suitable for changing the date.'", ")", ";", "}", "if", "(", "!", "ctype_digit", "(", "$", "day", ")", "||", "1", ">", "$", "day", "||", "31", "<", "$", "day", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given value '", ".", "$", "day", ".", "' for day not suitable for changing the date.'", ")", ";", "}", "return", "$", "this", "->", "createNewDateWithExistingTime", "(", "(", "int", ")", "$", "year", ",", "(", "int", ")", "$", "month", ",", "(", "int", ")", "$", "day", ")", ";", "}" ]
returns a new date instance with changed date but same time @api @param string $date date representation in format YYYY-MM-DD @return \stubbles\date\Date @throws \InvalidArgumentException
[ "returns", "a", "new", "date", "instance", "with", "changed", "date", "but", "same", "time" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L218-L247
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.byYears
public function byYears(int $years): Date { return $this->yearTo($this->originalDate->year() + $years); }
php
public function byYears(int $years): Date { return $this->yearTo($this->originalDate->year() + $years); }
[ "public", "function", "byYears", "(", "int", "$", "years", ")", ":", "Date", "{", "return", "$", "this", "->", "yearTo", "(", "$", "this", "->", "originalDate", "->", "year", "(", ")", "+", "$", "years", ")", ";", "}" ]
changes date by given amount of years @api @param int $years @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "years" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L272-L275
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.byMonths
public function byMonths(int $months): Date { return $this->monthTo($this->originalDate->month() + $months); }
php
public function byMonths(int $months): Date { return $this->monthTo($this->originalDate->month() + $months); }
[ "public", "function", "byMonths", "(", "int", "$", "months", ")", ":", "Date", "{", "return", "$", "this", "->", "monthTo", "(", "$", "this", "->", "originalDate", "->", "month", "(", ")", "+", "$", "months", ")", ";", "}" ]
changes date by given amount of months @api @param int $months @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "months" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L300-L303
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.dayTo
public function dayTo(int $day): Date { return $this->createNewDateWithExistingTime( $this->originalDate->year(), $this->originalDate->month(), $day ); }
php
public function dayTo(int $day): Date { return $this->createNewDateWithExistingTime( $this->originalDate->year(), $this->originalDate->month(), $day ); }
[ "public", "function", "dayTo", "(", "int", "$", "day", ")", ":", "Date", "{", "return", "$", "this", "->", "createNewDateWithExistingTime", "(", "$", "this", "->", "originalDate", "->", "year", "(", ")", ",", "$", "this", "->", "originalDate", "->", "month", "(", ")", ",", "$", "day", ")", ";", "}" ]
returns a new date instance with changed day but same time, year and month @api @param int $day @return \stubbles\date\Date
[ "returns", "a", "new", "date", "instance", "with", "changed", "day", "but", "same", "time", "year", "and", "month" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L312-L319
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.byDays
public function byDays(int $days): Date { return $this->dayTo($this->originalDate->day() + $days); }
php
public function byDays(int $days): Date { return $this->dayTo($this->originalDate->day() + $days); }
[ "public", "function", "byDays", "(", "int", "$", "days", ")", ":", "Date", "{", "return", "$", "this", "->", "dayTo", "(", "$", "this", "->", "originalDate", "->", "day", "(", ")", "+", "$", "days", ")", ";", "}" ]
changes date by given amount of days @api @param int $days @return \stubbles\date\Date
[ "changes", "date", "by", "given", "amount", "of", "days" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L328-L331
train
stubbles/stubbles-date
src/main/php/DateModifier.php
DateModifier.createNewDateWithExistingTime
private function createNewDateWithExistingTime(int $year, int $month, int $day): Date { return new Date($this->originalDate->handle()->setDate($year, $month, $day)); }
php
private function createNewDateWithExistingTime(int $year, int $month, int $day): Date { return new Date($this->originalDate->handle()->setDate($year, $month, $day)); }
[ "private", "function", "createNewDateWithExistingTime", "(", "int", "$", "year", ",", "int", "$", "month", ",", "int", "$", "day", ")", ":", "Date", "{", "return", "new", "Date", "(", "$", "this", "->", "originalDate", "->", "handle", "(", ")", "->", "setDate", "(", "$", "year", ",", "$", "month", ",", "$", "day", ")", ")", ";", "}" ]
creates new date instance with changed date but same time @param int $year @param int $month @param int $day @return \stubbles\date\Date
[ "creates", "new", "date", "instance", "with", "changed", "date", "but", "same", "time" ]
98553392bec03affc53a6e3eb7f88408c2720d1c
https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/DateModifier.php#L341-L344
train
Hnto/nuki
src/Handlers/Provider/ProviderHandler.php
ProviderHandler.buildProvider
public function buildProvider(string $key, array $options = []) { $provider = $this->get($key); switch($provider['Type']) { case "Database": if (!isset($options['storageHandler']) || !$options['storageHandler'] instanceof \Nuki\Skeletons\Handlers\StorageHandler) { throw new \Nuki\Exceptions\Base('No storage handler provided'); } return new $provider['Location']($options['storageHandler']); default: throw new \Nuki\Exceptions\Base('Unknown provider type given for provider ' . $provider['Location']); } }
php
public function buildProvider(string $key, array $options = []) { $provider = $this->get($key); switch($provider['Type']) { case "Database": if (!isset($options['storageHandler']) || !$options['storageHandler'] instanceof \Nuki\Skeletons\Handlers\StorageHandler) { throw new \Nuki\Exceptions\Base('No storage handler provided'); } return new $provider['Location']($options['storageHandler']); default: throw new \Nuki\Exceptions\Base('Unknown provider type given for provider ' . $provider['Location']); } }
[ "public", "function", "buildProvider", "(", "string", "$", "key", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "provider", "=", "$", "this", "->", "get", "(", "$", "key", ")", ";", "switch", "(", "$", "provider", "[", "'Type'", "]", ")", "{", "case", "\"Database\"", ":", "if", "(", "!", "isset", "(", "$", "options", "[", "'storageHandler'", "]", ")", "||", "!", "$", "options", "[", "'storageHandler'", "]", "instanceof", "\\", "Nuki", "\\", "Skeletons", "\\", "Handlers", "\\", "StorageHandler", ")", "{", "throw", "new", "\\", "Nuki", "\\", "Exceptions", "\\", "Base", "(", "'No storage handler provided'", ")", ";", "}", "return", "new", "$", "provider", "[", "'Location'", "]", "(", "$", "options", "[", "'storageHandler'", "]", ")", ";", "default", ":", "throw", "new", "\\", "Nuki", "\\", "Exceptions", "\\", "Base", "(", "'Unknown provider type given for provider '", ".", "$", "provider", "[", "'Location'", "]", ")", ";", "}", "}" ]
Build a provider by its key and additional options @param string $key @param array $options @return \Nuki\Skeletons\Providers\Storage @throws \Nuki\Exceptions\Base
[ "Build", "a", "provider", "by", "its", "key", "and", "additional", "options" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Provider/ProviderHandler.php#L44-L58
train
eureka-framework/component-yaml
src/Yaml.php
Yaml.getTranslations
private static function getTranslations(array $words) { $result = array(); foreach ($words as $i) { $result = array_merge($result, array(ucfirst($i), strtoupper($i), strtolower($i))); } return $result; }
php
private static function getTranslations(array $words) { $result = array(); foreach ($words as $i) { $result = array_merge($result, array(ucfirst($i), strtoupper($i), strtolower($i))); } return $result; }
[ "private", "static", "function", "getTranslations", "(", "array", "$", "words", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "words", "as", "$", "i", ")", "{", "$", "result", "=", "array_merge", "(", "$", "result", ",", "array", "(", "ucfirst", "(", "$", "i", ")", ",", "strtoupper", "(", "$", "i", ")", ",", "strtolower", "(", "$", "i", ")", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Given a set of words, perform the appropriate translations on them to match the YAML 1.1 specification for type coercing. @param $words The words to translate @access private
[ "Given", "a", "set", "of", "words", "perform", "the", "appropriate", "translations", "on", "them", "to", "match", "the", "YAML", "1", ".", "1", "specification", "for", "type", "coercing", "." ]
939ebf450c20d1eeec72fd43f73805b501d66472
https://github.com/eureka-framework/component-yaml/blob/939ebf450c20d1eeec72fd43f73805b501d66472/src/Yaml.php#L425-L433
train
native5/native5-sdk-client-php
src/Native5/Route/HttpResponse.php
HttpResponse.redirectTo
public function redirectTo($location) { $app = $GLOBALS['app']; $host = $_SERVER['HTTP_HOST']; if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $host = $_SERVER['HTTP_X_FORWARDED_HOST']; } $protocol = isset($_SERVER['HTTPS'])?'https://':'http://'; $redirectLocation = $protocol.$host.'/'.$app->getConfiguration()->getApplicationContext().'/'.$location; if ($app->getSubject()->isAuthenticated()) { $separator = '?'; if(strpos($redirectLocation, '?')) $separator = '&'; $redirectLocation .= $separator."rand_token=".urlencode($app->getSessionManager()->getActiveSession()->getAttribute('nonce')); } if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $this->addHeader("Content-type: application/json"); $response = array(); $response['redirect'] = $redirectLocation; echo json_encode($response); exit; } else { $this->addHeader('Location: '.$redirectLocation); } }
php
public function redirectTo($location) { $app = $GLOBALS['app']; $host = $_SERVER['HTTP_HOST']; if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $host = $_SERVER['HTTP_X_FORWARDED_HOST']; } $protocol = isset($_SERVER['HTTPS'])?'https://':'http://'; $redirectLocation = $protocol.$host.'/'.$app->getConfiguration()->getApplicationContext().'/'.$location; if ($app->getSubject()->isAuthenticated()) { $separator = '?'; if(strpos($redirectLocation, '?')) $separator = '&'; $redirectLocation .= $separator."rand_token=".urlencode($app->getSessionManager()->getActiveSession()->getAttribute('nonce')); } if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $this->addHeader("Content-type: application/json"); $response = array(); $response['redirect'] = $redirectLocation; echo json_encode($response); exit; } else { $this->addHeader('Location: '.$redirectLocation); } }
[ "public", "function", "redirectTo", "(", "$", "location", ")", "{", "$", "app", "=", "$", "GLOBALS", "[", "'app'", "]", ";", "$", "host", "=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_HOST'", "]", ")", ")", "{", "$", "host", "=", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_HOST'", "]", ";", "}", "$", "protocol", "=", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "?", "'https://'", ":", "'http://'", ";", "$", "redirectLocation", "=", "$", "protocol", ".", "$", "host", ".", "'/'", ".", "$", "app", "->", "getConfiguration", "(", ")", "->", "getApplicationContext", "(", ")", ".", "'/'", ".", "$", "location", ";", "if", "(", "$", "app", "->", "getSubject", "(", ")", "->", "isAuthenticated", "(", ")", ")", "{", "$", "separator", "=", "'?'", ";", "if", "(", "strpos", "(", "$", "redirectLocation", ",", "'?'", ")", ")", "$", "separator", "=", "'&'", ";", "$", "redirectLocation", ".=", "$", "separator", ".", "\"rand_token=\"", ".", "urlencode", "(", "$", "app", "->", "getSessionManager", "(", ")", "->", "getActiveSession", "(", ")", "->", "getAttribute", "(", "'nonce'", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_X_REQUESTED_WITH'", "]", ")", "&&", "strtolower", "(", "$", "_SERVER", "[", "'HTTP_X_REQUESTED_WITH'", "]", ")", "==", "'xmlhttprequest'", ")", "{", "$", "this", "->", "addHeader", "(", "\"Content-type: application/json\"", ")", ";", "$", "response", "=", "array", "(", ")", ";", "$", "response", "[", "'redirect'", "]", "=", "$", "redirectLocation", ";", "echo", "json_encode", "(", "$", "response", ")", ";", "exit", ";", "}", "else", "{", "$", "this", "->", "addHeader", "(", "'Location: '", ".", "$", "redirectLocation", ")", ";", "}", "}" ]
redirectTo Helper method to allow redirection to a certain url. @param mixed $location @access public @return void
[ "redirectTo", "Helper", "method", "to", "allow", "redirection", "to", "a", "certain", "url", "." ]
e1f598cf27654d81bb5facace1990b737242a2f9
https://github.com/native5/native5-sdk-client-php/blob/e1f598cf27654d81bb5facace1990b737242a2f9/src/Native5/Route/HttpResponse.php#L84-L108
train
Nicklas766/Comment
src/Comment/LoginController.php
LoginController.logout
public function logout() { $this->di->get('session')->set("user", null); $this->di->get("response")->redirect("user/login"); }
php
public function logout() { $this->di->get('session')->set("user", null); $this->di->get("response")->redirect("user/login"); }
[ "public", "function", "logout", "(", ")", "{", "$", "this", "->", "di", "->", "get", "(", "'session'", ")", "->", "set", "(", "\"user\"", ",", "null", ")", ";", "$", "this", "->", "di", "->", "get", "(", "\"response\"", ")", "->", "redirect", "(", "\"user/login\"", ")", ";", "}" ]
Logout user by setting "user" == null in session. @return void
[ "Logout", "user", "by", "setting", "user", "==", "null", "in", "session", "." ]
1483eaf1ebb120b8bd6c2a1552c084b3a288ff25
https://github.com/Nicklas766/Comment/blob/1483eaf1ebb120b8bd6c2a1552c084b3a288ff25/src/Comment/LoginController.php#L33-L37
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/logging/AbstractLogger.php
AbstractLogger.getCalleeClass
protected function getCalleeClass() { if (PHP_VERSION_ID < 50205) $backtrace = debug_backtrace(); else $backtrace = debug_backtrace(false); foreach ( $backtrace as $bt ) { // Making sure the class we're getting out of the backtrace is not a logger if (!is_a($this, $bt['class']) && strpos($bt['class'], 'Logger') === false) { return $bt['class']; } } return ''; }
php
protected function getCalleeClass() { if (PHP_VERSION_ID < 50205) $backtrace = debug_backtrace(); else $backtrace = debug_backtrace(false); foreach ( $backtrace as $bt ) { // Making sure the class we're getting out of the backtrace is not a logger if (!is_a($this, $bt['class']) && strpos($bt['class'], 'Logger') === false) { return $bt['class']; } } return ''; }
[ "protected", "function", "getCalleeClass", "(", ")", "{", "if", "(", "PHP_VERSION_ID", "<", "50205", ")", "$", "backtrace", "=", "debug_backtrace", "(", ")", ";", "else", "$", "backtrace", "=", "debug_backtrace", "(", "false", ")", ";", "foreach", "(", "$", "backtrace", "as", "$", "bt", ")", "{", "// Making sure the class we're getting out of the backtrace is not a logger", "if", "(", "!", "is_a", "(", "$", "this", ",", "$", "bt", "[", "'class'", "]", ")", "&&", "strpos", "(", "$", "bt", "[", "'class'", "]", ",", "'Logger'", ")", "===", "false", ")", "{", "return", "$", "bt", "[", "'class'", "]", ";", "}", "}", "return", "''", ";", "}" ]
Returns the name of the class that called the logger function @return void
[ "Returns", "the", "name", "of", "the", "class", "that", "called", "the", "logger", "function" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/logging/AbstractLogger.php#L155-L171
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/logging/AbstractLogger.php
AbstractLogger.getLogHistory
public function getLogHistory($klass = null) { if (empty($klass)) return $this->history; if (!isset($this->history[$klass])) return array(); return $this->history[$klass]; }
php
public function getLogHistory($klass = null) { if (empty($klass)) return $this->history; if (!isset($this->history[$klass])) return array(); return $this->history[$klass]; }
[ "public", "function", "getLogHistory", "(", "$", "klass", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "klass", ")", ")", "return", "$", "this", "->", "history", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "history", "[", "$", "klass", "]", ")", ")", "return", "array", "(", ")", ";", "return", "$", "this", "->", "history", "[", "$", "klass", "]", ";", "}" ]
This function returns the current array of log message for a particular category. @param string $klass The category of log messages. If this parameter is omitted, then all log history is returned. @return array Array of strings containing sequential log messages for the given {@link $klass}.
[ "This", "function", "returns", "the", "current", "array", "of", "log", "message", "for", "a", "particular", "category", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/logging/AbstractLogger.php#L348-L357
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/logging/AbstractLogger.php
AbstractLogger.clearLogHistory
public function clearLogHistory($klass = null) { if (empty($klass)) $this->history = array(); if (!isset($this->history[$klass])) return; $this->history[$klass] = array(); }
php
public function clearLogHistory($klass = null) { if (empty($klass)) $this->history = array(); if (!isset($this->history[$klass])) return; $this->history[$klass] = array(); }
[ "public", "function", "clearLogHistory", "(", "$", "klass", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "klass", ")", ")", "$", "this", "->", "history", "=", "array", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "history", "[", "$", "klass", "]", ")", ")", "return", ";", "$", "this", "->", "history", "[", "$", "klass", "]", "=", "array", "(", ")", ";", "}" ]
This function clears the current array of log message for a particular category. @param string $klass The category of log messages. If this parameter is ommitted, then all history is cleared. @return void
[ "This", "function", "clears", "the", "current", "array", "of", "log", "message", "for", "a", "particular", "category", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/logging/AbstractLogger.php#L366-L375
train
chalasr/RCHCapistranoBundle
Generator/GemfileGenerator.php
GemfileGenerator.write
public function write() { $gemfile = ''; foreach ($this->parameters as $gem) { $line = str_replace('<gem>', $gem, self::$template); $gemfile = sprintf('%s%s%s', $gemfile, PHP_EOL, $line); } $gemfile .= self::$sourceTemplate; fwrite($this->file, $this->addHeaders($gemfile)); }
php
public function write() { $gemfile = ''; foreach ($this->parameters as $gem) { $line = str_replace('<gem>', $gem, self::$template); $gemfile = sprintf('%s%s%s', $gemfile, PHP_EOL, $line); } $gemfile .= self::$sourceTemplate; fwrite($this->file, $this->addHeaders($gemfile)); }
[ "public", "function", "write", "(", ")", "{", "$", "gemfile", "=", "''", ";", "foreach", "(", "$", "this", "->", "parameters", "as", "$", "gem", ")", "{", "$", "line", "=", "str_replace", "(", "'<gem>'", ",", "$", "gem", ",", "self", "::", "$", "template", ")", ";", "$", "gemfile", "=", "sprintf", "(", "'%s%s%s'", ",", "$", "gemfile", ",", "PHP_EOL", ",", "$", "line", ")", ";", "}", "$", "gemfile", ".=", "self", "::", "$", "sourceTemplate", ";", "fwrite", "(", "$", "this", "->", "file", ",", "$", "this", "->", "addHeaders", "(", "$", "gemfile", ")", ")", ";", "}" ]
Writes Gemfile.
[ "Writes", "Gemfile", "." ]
c4a4cbaa2bc05f33bf431fd3afe6cac39947640e
https://github.com/chalasr/RCHCapistranoBundle/blob/c4a4cbaa2bc05f33bf431fd3afe6cac39947640e/Generator/GemfileGenerator.php#L46-L58
train
OxfordInfoLabs/kinikit-core
src/Util/Caching/SessionCache.php
SessionCache.cacheObject
public function cacheObject($key, $object, $timeoutSeconds = -1) { $cache = HttpSession::instance()->getValue("__SESSION_CACHED_ITEMS"); if (!is_array($cache)) { $cache = array(); } $cache[$key] = $object; HttpSession::instance()->setValue("__SESSION_CACHED_ITEMS", $cache); if ($timeoutSeconds > 0) { $timeouts = HttpSession::instance()->getValue("__SESSION_CACHE_TIMEOUTS"); if (!is_array($timeouts)) { $timeouts = array(); } $dateTime = new \DateTime(); $dateTime->add(new \DateInterval("PT" . $timeoutSeconds . "S")); $timeouts[$key] = $dateTime->format("d/m/Y H:i:s"); HttpSession::instance()->setValue("__SESSION_CACHE_TIMEOUTS", $timeouts); } }
php
public function cacheObject($key, $object, $timeoutSeconds = -1) { $cache = HttpSession::instance()->getValue("__SESSION_CACHED_ITEMS"); if (!is_array($cache)) { $cache = array(); } $cache[$key] = $object; HttpSession::instance()->setValue("__SESSION_CACHED_ITEMS", $cache); if ($timeoutSeconds > 0) { $timeouts = HttpSession::instance()->getValue("__SESSION_CACHE_TIMEOUTS"); if (!is_array($timeouts)) { $timeouts = array(); } $dateTime = new \DateTime(); $dateTime->add(new \DateInterval("PT" . $timeoutSeconds . "S")); $timeouts[$key] = $dateTime->format("d/m/Y H:i:s"); HttpSession::instance()->setValue("__SESSION_CACHE_TIMEOUTS", $timeouts); } }
[ "public", "function", "cacheObject", "(", "$", "key", ",", "$", "object", ",", "$", "timeoutSeconds", "=", "-", "1", ")", "{", "$", "cache", "=", "HttpSession", "::", "instance", "(", ")", "->", "getValue", "(", "\"__SESSION_CACHED_ITEMS\"", ")", ";", "if", "(", "!", "is_array", "(", "$", "cache", ")", ")", "{", "$", "cache", "=", "array", "(", ")", ";", "}", "$", "cache", "[", "$", "key", "]", "=", "$", "object", ";", "HttpSession", "::", "instance", "(", ")", "->", "setValue", "(", "\"__SESSION_CACHED_ITEMS\"", ",", "$", "cache", ")", ";", "if", "(", "$", "timeoutSeconds", ">", "0", ")", "{", "$", "timeouts", "=", "HttpSession", "::", "instance", "(", ")", "->", "getValue", "(", "\"__SESSION_CACHE_TIMEOUTS\"", ")", ";", "if", "(", "!", "is_array", "(", "$", "timeouts", ")", ")", "{", "$", "timeouts", "=", "array", "(", ")", ";", "}", "$", "dateTime", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "dateTime", "->", "add", "(", "new", "\\", "DateInterval", "(", "\"PT\"", ".", "$", "timeoutSeconds", ".", "\"S\"", ")", ")", ";", "$", "timeouts", "[", "$", "key", "]", "=", "$", "dateTime", "->", "format", "(", "\"d/m/Y H:i:s\"", ")", ";", "HttpSession", "::", "instance", "(", ")", "->", "setValue", "(", "\"__SESSION_CACHE_TIMEOUTS\"", ",", "$", "timeouts", ")", ";", "}", "}" ]
Cache an object with a key and an optional timeout in seconds. @param $key @param $object
[ "Cache", "an", "object", "with", "a", "key", "and", "an", "optional", "timeout", "in", "seconds", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/Caching/SessionCache.php#L33-L59
train
OxfordInfoLabs/kinikit-core
src/Util/Caching/SessionCache.php
SessionCache.getCachedObject
public function getCachedObject($key) { $cache = HttpSession::instance()->getValue("__SESSION_CACHED_ITEMS"); $timeouts = HttpSession::instance()->getValue("__SESSION_CACHE_TIMEOUTS"); if (is_array($timeouts) && isset($timeouts[$key])) { $now = new \DateTime(); $expiry = date_create_from_format("d/m/Y H:i:s", $timeouts[$key]); if ($now >= $expiry) { return null; } } return isset($cache[$key]) ? $cache[$key] : null; }
php
public function getCachedObject($key) { $cache = HttpSession::instance()->getValue("__SESSION_CACHED_ITEMS"); $timeouts = HttpSession::instance()->getValue("__SESSION_CACHE_TIMEOUTS"); if (is_array($timeouts) && isset($timeouts[$key])) { $now = new \DateTime(); $expiry = date_create_from_format("d/m/Y H:i:s", $timeouts[$key]); if ($now >= $expiry) { return null; } } return isset($cache[$key]) ? $cache[$key] : null; }
[ "public", "function", "getCachedObject", "(", "$", "key", ")", "{", "$", "cache", "=", "HttpSession", "::", "instance", "(", ")", "->", "getValue", "(", "\"__SESSION_CACHED_ITEMS\"", ")", ";", "$", "timeouts", "=", "HttpSession", "::", "instance", "(", ")", "->", "getValue", "(", "\"__SESSION_CACHE_TIMEOUTS\"", ")", ";", "if", "(", "is_array", "(", "$", "timeouts", ")", "&&", "isset", "(", "$", "timeouts", "[", "$", "key", "]", ")", ")", "{", "$", "now", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "expiry", "=", "date_create_from_format", "(", "\"d/m/Y H:i:s\"", ",", "$", "timeouts", "[", "$", "key", "]", ")", ";", "if", "(", "$", "now", ">=", "$", "expiry", ")", "{", "return", "null", ";", "}", "}", "return", "isset", "(", "$", "cache", "[", "$", "key", "]", ")", "?", "$", "cache", "[", "$", "key", "]", ":", "null", ";", "}" ]
Get a cached object by key @param $key
[ "Get", "a", "cached", "object", "by", "key" ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/Caching/SessionCache.php#L67-L81
train
prosoftSolutions/Pager
Twig/PagerfantaExtension.php
PagerfantaExtension.getPageUrl
public function getPageUrl(PagerfantaInterface $pagerfanta, $page, array $options = array()) { if ($page < 0 || $page > $pagerfanta->count()) { throw new \InvalidArgumentException("Page '{$page}' is out of bounds"); } $routeGenerator = $this->createRouteGenerator($options); return $routeGenerator($page); }
php
public function getPageUrl(PagerfantaInterface $pagerfanta, $page, array $options = array()) { if ($page < 0 || $page > $pagerfanta->count()) { throw new \InvalidArgumentException("Page '{$page}' is out of bounds"); } $routeGenerator = $this->createRouteGenerator($options); return $routeGenerator($page); }
[ "public", "function", "getPageUrl", "(", "PagerfantaInterface", "$", "pagerfanta", ",", "$", "page", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "$", "page", "<", "0", "||", "$", "page", ">", "$", "pagerfanta", "->", "count", "(", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Page '{$page}' is out of bounds\"", ")", ";", "}", "$", "routeGenerator", "=", "$", "this", "->", "createRouteGenerator", "(", "$", "options", ")", ";", "return", "$", "routeGenerator", "(", "$", "page", ")", ";", "}" ]
Generates the url for a given page in a pagerfanta instance. @param \Pagerfanta\PagerfantaInterface $pagerfanta @param $page @param array $options @return string The url of the given page @throws \InvalidArgumentException
[ "Generates", "the", "url", "for", "a", "given", "page", "in", "a", "pagerfanta", "instance", "." ]
96446ee22caedc0b9bb486d9ffe7a50b6c13177f
https://github.com/prosoftSolutions/Pager/blob/96446ee22caedc0b9bb486d9ffe7a50b6c13177f/Twig/PagerfantaExtension.php#L80-L89
train
prosoftSolutions/Pager
Twig/PagerfantaExtension.php
PagerfantaExtension.createRouteGenerator
private function createRouteGenerator($options = array()) { $options = array_replace(array( 'routeName' => null, 'routeParams' => array(), 'pageParameter' => '[page]', ), $options); $router = $this->container->get('router'); if (null === $options['routeName']) { $request = $this->container->get('request'); $options['routeName'] = $request->attributes->get('_route'); if ('_internal' === $options['routeName']) { throw new \Exception('PagerfantaBundle can not guess the route when used in a subrequest'); } // make sure we read the route parameters from the passed option array $defaultRouteParams = array_merge($request->query->all(), $request->attributes->get('_route_params')); if (array_key_exists('routeParams', $options)) { $options['routeParams'] = array_merge($defaultRouteParams, $options['routeParams']); } else { $options['routeParams'] = $defaultRouteParams; } } $routeName = $options['routeName']; $routeParams = $options['routeParams']; $pagePropertyPath = new PropertyPath($options['pageParameter']); return function($page) use($router, $routeName, $routeParams, $pagePropertyPath) { $propertyAccessor = PropertyAccess::getPropertyAccessor(); $propertyAccessor->setValue($routeParams, $pagePropertyPath, $page); return $router->generate($routeName, $routeParams); }; }
php
private function createRouteGenerator($options = array()) { $options = array_replace(array( 'routeName' => null, 'routeParams' => array(), 'pageParameter' => '[page]', ), $options); $router = $this->container->get('router'); if (null === $options['routeName']) { $request = $this->container->get('request'); $options['routeName'] = $request->attributes->get('_route'); if ('_internal' === $options['routeName']) { throw new \Exception('PagerfantaBundle can not guess the route when used in a subrequest'); } // make sure we read the route parameters from the passed option array $defaultRouteParams = array_merge($request->query->all(), $request->attributes->get('_route_params')); if (array_key_exists('routeParams', $options)) { $options['routeParams'] = array_merge($defaultRouteParams, $options['routeParams']); } else { $options['routeParams'] = $defaultRouteParams; } } $routeName = $options['routeName']; $routeParams = $options['routeParams']; $pagePropertyPath = new PropertyPath($options['pageParameter']); return function($page) use($router, $routeName, $routeParams, $pagePropertyPath) { $propertyAccessor = PropertyAccess::getPropertyAccessor(); $propertyAccessor->setValue($routeParams, $pagePropertyPath, $page); return $router->generate($routeName, $routeParams); }; }
[ "private", "function", "createRouteGenerator", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "=", "array_replace", "(", "array", "(", "'routeName'", "=>", "null", ",", "'routeParams'", "=>", "array", "(", ")", ",", "'pageParameter'", "=>", "'[page]'", ",", ")", ",", "$", "options", ")", ";", "$", "router", "=", "$", "this", "->", "container", "->", "get", "(", "'router'", ")", ";", "if", "(", "null", "===", "$", "options", "[", "'routeName'", "]", ")", "{", "$", "request", "=", "$", "this", "->", "container", "->", "get", "(", "'request'", ")", ";", "$", "options", "[", "'routeName'", "]", "=", "$", "request", "->", "attributes", "->", "get", "(", "'_route'", ")", ";", "if", "(", "'_internal'", "===", "$", "options", "[", "'routeName'", "]", ")", "{", "throw", "new", "\\", "Exception", "(", "'PagerfantaBundle can not guess the route when used in a subrequest'", ")", ";", "}", "// make sure we read the route parameters from the passed option array ", "$", "defaultRouteParams", "=", "array_merge", "(", "$", "request", "->", "query", "->", "all", "(", ")", ",", "$", "request", "->", "attributes", "->", "get", "(", "'_route_params'", ")", ")", ";", "if", "(", "array_key_exists", "(", "'routeParams'", ",", "$", "options", ")", ")", "{", "$", "options", "[", "'routeParams'", "]", "=", "array_merge", "(", "$", "defaultRouteParams", ",", "$", "options", "[", "'routeParams'", "]", ")", ";", "}", "else", "{", "$", "options", "[", "'routeParams'", "]", "=", "$", "defaultRouteParams", ";", "}", "}", "$", "routeName", "=", "$", "options", "[", "'routeName'", "]", ";", "$", "routeParams", "=", "$", "options", "[", "'routeParams'", "]", ";", "$", "pagePropertyPath", "=", "new", "PropertyPath", "(", "$", "options", "[", "'pageParameter'", "]", ")", ";", "return", "function", "(", "$", "page", ")", "use", "(", "$", "router", ",", "$", "routeName", ",", "$", "routeParams", ",", "$", "pagePropertyPath", ")", "{", "$", "propertyAccessor", "=", "PropertyAccess", "::", "getPropertyAccessor", "(", ")", ";", "$", "propertyAccessor", "->", "setValue", "(", "$", "routeParams", ",", "$", "pagePropertyPath", ",", "$", "page", ")", ";", "return", "$", "router", "->", "generate", "(", "$", "routeName", ",", "$", "routeParams", ")", ";", "}", ";", "}" ]
Creates an anonymous function which returns the URL for a given page. @param array $options @return callable @throws \Exception
[ "Creates", "an", "anonymous", "function", "which", "returns", "the", "URL", "for", "a", "given", "page", "." ]
96446ee22caedc0b9bb486d9ffe7a50b6c13177f
https://github.com/prosoftSolutions/Pager/blob/96446ee22caedc0b9bb486d9ffe7a50b6c13177f/Twig/PagerfantaExtension.php#L100-L138
train
brain-diminished/schema-version-control
src/Utils/SchemaBuilder.php
SchemaBuilder.build
public function build(array $schemaDesc): Schema { $this->schemaDesc = $schemaDesc; $schema = new Schema(); foreach ($schemaDesc['tables'] as $name => $tableDesc) { $table = $schema->createTable($name); $this->buildTable($tableDesc, $table); } return $schema; }
php
public function build(array $schemaDesc): Schema { $this->schemaDesc = $schemaDesc; $schema = new Schema(); foreach ($schemaDesc['tables'] as $name => $tableDesc) { $table = $schema->createTable($name); $this->buildTable($tableDesc, $table); } return $schema; }
[ "public", "function", "build", "(", "array", "$", "schemaDesc", ")", ":", "Schema", "{", "$", "this", "->", "schemaDesc", "=", "$", "schemaDesc", ";", "$", "schema", "=", "new", "Schema", "(", ")", ";", "foreach", "(", "$", "schemaDesc", "[", "'tables'", "]", "as", "$", "name", "=>", "$", "tableDesc", ")", "{", "$", "table", "=", "$", "schema", "->", "createTable", "(", "$", "name", ")", ";", "$", "this", "->", "buildTable", "(", "$", "tableDesc", ",", "$", "table", ")", ";", "}", "return", "$", "schema", ";", "}" ]
Build an array descriptor into a Schema object @param array $schemaDesc @return Schema
[ "Build", "an", "array", "descriptor", "into", "a", "Schema", "object" ]
215dd96394072720b61a682e10a55a6520470c46
https://github.com/brain-diminished/schema-version-control/blob/215dd96394072720b61a682e10a55a6520470c46/src/Utils/SchemaBuilder.php#L24-L33
train
brightnucleus/values
src/Exception/FailedToValidate.php
FailedToValidate.fromValueForClass
public static function fromValueForClass($value, string $class) { $message = sprintf( 'Failed to validate value of type %1$s to fit into Value object of type %2$s. (%3$s)', is_object($value) ? get_class($value) : gettype($value), $class, json_encode($value) ); return new static($message); }
php
public static function fromValueForClass($value, string $class) { $message = sprintf( 'Failed to validate value of type %1$s to fit into Value object of type %2$s. (%3$s)', is_object($value) ? get_class($value) : gettype($value), $class, json_encode($value) ); return new static($message); }
[ "public", "static", "function", "fromValueForClass", "(", "$", "value", ",", "string", "$", "class", ")", "{", "$", "message", "=", "sprintf", "(", "'Failed to validate value of type %1$s to fit into Value object of type %2$s. (%3$s)'", ",", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ",", "$", "class", ",", "json_encode", "(", "$", "value", ")", ")", ";", "return", "new", "static", "(", "$", "message", ")", ";", "}" ]
Create a new exception instance from a failing value. @since 0.1.1 @param mixed $value Value that failed validation. @param string $class FQCN of the class that the value was validated against. @return static
[ "Create", "a", "new", "exception", "instance", "from", "a", "failing", "value", "." ]
e9bdfbec949f6f964631aacaccaa98a0f13d916f
https://github.com/brightnucleus/values/blob/e9bdfbec949f6f964631aacaccaa98a0f13d916f/src/Exception/FailedToValidate.php#L40-L50
train
dmj/PicaRecord
src/HAB/Pica/Record/LocalRecord.php
LocalRecord.addCopyRecord
public function addCopyRecord (CopyRecord $record) { if ($this->getCopyRecordByItemNumber($record->getItemNumber())) { throw new InvalidArgumentException("Cannot add copy record: Copy record with item number {$record->getItemNumber()} already present"); } $this->addRecord($record); $record->setLocalRecord($this); }
php
public function addCopyRecord (CopyRecord $record) { if ($this->getCopyRecordByItemNumber($record->getItemNumber())) { throw new InvalidArgumentException("Cannot add copy record: Copy record with item number {$record->getItemNumber()} already present"); } $this->addRecord($record); $record->setLocalRecord($this); }
[ "public", "function", "addCopyRecord", "(", "CopyRecord", "$", "record", ")", "{", "if", "(", "$", "this", "->", "getCopyRecordByItemNumber", "(", "$", "record", "->", "getItemNumber", "(", ")", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Cannot add copy record: Copy record with item number {$record->getItemNumber()} already present\"", ")", ";", "}", "$", "this", "->", "addRecord", "(", "$", "record", ")", ";", "$", "record", "->", "setLocalRecord", "(", "$", "this", ")", ";", "}" ]
Add a copy record. @throws InvalidArgumentException Record already contains the copy record @throws InvalidArgumentException Record already contains a copy record with the same item number @param CopyRecord $record Copy record to add @return void
[ "Add", "a", "copy", "record", "." ]
bd5577b9a4333aa6156398b94cc870a9377061b8
https://github.com/dmj/PicaRecord/blob/bd5577b9a4333aa6156398b94cc870a9377061b8/src/HAB/Pica/Record/LocalRecord.php#L64-L71
train
dmj/PicaRecord
src/HAB/Pica/Record/LocalRecord.php
LocalRecord.getCopyRecordByItemNumber
public function getCopyRecordByItemNumber ($itemNumber) { foreach ($this->_records as $record) { if ($record->getItemNumber() === $itemNumber) { return $record; } } return null; }
php
public function getCopyRecordByItemNumber ($itemNumber) { foreach ($this->_records as $record) { if ($record->getItemNumber() === $itemNumber) { return $record; } } return null; }
[ "public", "function", "getCopyRecordByItemNumber", "(", "$", "itemNumber", ")", "{", "foreach", "(", "$", "this", "->", "_records", "as", "$", "record", ")", "{", "if", "(", "$", "record", "->", "getItemNumber", "(", ")", "===", "$", "itemNumber", ")", "{", "return", "$", "record", ";", "}", "}", "return", "null", ";", "}" ]
Return copy record by item number. @param integer $itemNumber Item number @return CopyRecord|null The copy record or null if none exists
[ "Return", "copy", "record", "by", "item", "number", "." ]
bd5577b9a4333aa6156398b94cc870a9377061b8
https://github.com/dmj/PicaRecord/blob/bd5577b9a4333aa6156398b94cc870a9377061b8/src/HAB/Pica/Record/LocalRecord.php#L91-L99
train
dmj/PicaRecord
src/HAB/Pica/Record/LocalRecord.php
LocalRecord.setTitleRecord
public function setTitleRecord (TitleRecord $record) { $this->unsetTitleRecord(); if (!$record->containsLocalRecord($this)) { $record->addLocalRecord($this); } $this->_parent = $record; }
php
public function setTitleRecord (TitleRecord $record) { $this->unsetTitleRecord(); if (!$record->containsLocalRecord($this)) { $record->addLocalRecord($this); } $this->_parent = $record; }
[ "public", "function", "setTitleRecord", "(", "TitleRecord", "$", "record", ")", "{", "$", "this", "->", "unsetTitleRecord", "(", ")", ";", "if", "(", "!", "$", "record", "->", "containsLocalRecord", "(", "$", "this", ")", ")", "{", "$", "record", "->", "addLocalRecord", "(", "$", "this", ")", ";", "}", "$", "this", "->", "_parent", "=", "$", "record", ";", "}" ]
Set the containing title record. @param TitleRecord $record Title record @return void
[ "Set", "the", "containing", "title", "record", "." ]
bd5577b9a4333aa6156398b94cc870a9377061b8
https://github.com/dmj/PicaRecord/blob/bd5577b9a4333aa6156398b94cc870a9377061b8/src/HAB/Pica/Record/LocalRecord.php#L145-L152
train
dmj/PicaRecord
src/HAB/Pica/Record/LocalRecord.php
LocalRecord.unsetTitleRecord
public function unsetTitleRecord () { if ($this->_parent) { if ($this->_parent->containsLocalRecord($this)) { $this->_parent->removeLocalRecord($this); } $this->_parent = null; } }
php
public function unsetTitleRecord () { if ($this->_parent) { if ($this->_parent->containsLocalRecord($this)) { $this->_parent->removeLocalRecord($this); } $this->_parent = null; } }
[ "public", "function", "unsetTitleRecord", "(", ")", "{", "if", "(", "$", "this", "->", "_parent", ")", "{", "if", "(", "$", "this", "->", "_parent", "->", "containsLocalRecord", "(", "$", "this", ")", ")", "{", "$", "this", "->", "_parent", "->", "removeLocalRecord", "(", "$", "this", ")", ";", "}", "$", "this", "->", "_parent", "=", "null", ";", "}", "}" ]
Unset the containing title record. @return void
[ "Unset", "the", "containing", "title", "record", "." ]
bd5577b9a4333aa6156398b94cc870a9377061b8
https://github.com/dmj/PicaRecord/blob/bd5577b9a4333aa6156398b94cc870a9377061b8/src/HAB/Pica/Record/LocalRecord.php#L159-L167
train
bseddon/XPath20
XPath2Expression.php
XPath2Expression.getParameterQNames
public function getParameterQNames() { $result = array(); $forQNames = array(); // Need to ignore variables that are defined for the 'for' clause $this->traverseNodes( $this->exprTree, function( $node ) use( &$result, &$forQNames ) { if ( $node instanceof ForNode ) { $forQNames[] = $node->getQNVarName(); } else if ( $node instanceof VarRefNode ) { $qname = $node->getQNVarName(); if ( ! in_array( $qname, $forQNames ) ) { $result[] = $qname; } } return true; } ); return $result; }
php
public function getParameterQNames() { $result = array(); $forQNames = array(); // Need to ignore variables that are defined for the 'for' clause $this->traverseNodes( $this->exprTree, function( $node ) use( &$result, &$forQNames ) { if ( $node instanceof ForNode ) { $forQNames[] = $node->getQNVarName(); } else if ( $node instanceof VarRefNode ) { $qname = $node->getQNVarName(); if ( ! in_array( $qname, $forQNames ) ) { $result[] = $qname; } } return true; } ); return $result; }
[ "public", "function", "getParameterQNames", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "forQNames", "=", "array", "(", ")", ";", "// Need to ignore variables that are defined for the 'for' clause\r", "$", "this", "->", "traverseNodes", "(", "$", "this", "->", "exprTree", ",", "function", "(", "$", "node", ")", "use", "(", "&", "$", "result", ",", "&", "$", "forQNames", ")", "{", "if", "(", "$", "node", "instanceof", "ForNode", ")", "{", "$", "forQNames", "[", "]", "=", "$", "node", "->", "getQNVarName", "(", ")", ";", "}", "else", "if", "(", "$", "node", "instanceof", "VarRefNode", ")", "{", "$", "qname", "=", "$", "node", "->", "getQNVarName", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "qname", ",", "$", "forQNames", ")", ")", "{", "$", "result", "[", "]", "=", "$", "qname", ";", "}", "}", "return", "true", ";", "}", ")", ";", "return", "$", "result", ";", "}" ]
Return an array of parameter names @return QName[]
[ "Return", "an", "array", "of", "parameter", "names" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/XPath2Expression.php#L306-L330
train
bseddon/XPath20
XPath2Expression.php
XPath2Expression.isFunctionUsed
public function isFunctionUsed( $functions ) { if ( is_string( $functions ) ) { $functions = array( $functions ); } $result = $this->traverseNodes( $this->exprTree, function( $node ) use( &$result, $functions ) { // TODO Test the functions in this node and return false if any are found return true; } ); return ! $result; }
php
public function isFunctionUsed( $functions ) { if ( is_string( $functions ) ) { $functions = array( $functions ); } $result = $this->traverseNodes( $this->exprTree, function( $node ) use( &$result, $functions ) { // TODO Test the functions in this node and return false if any are found return true; } ); return ! $result; }
[ "public", "function", "isFunctionUsed", "(", "$", "functions", ")", "{", "if", "(", "is_string", "(", "$", "functions", ")", ")", "{", "$", "functions", "=", "array", "(", "$", "functions", ")", ";", "}", "$", "result", "=", "$", "this", "->", "traverseNodes", "(", "$", "this", "->", "exprTree", ",", "function", "(", "$", "node", ")", "use", "(", "&", "$", "result", ",", "$", "functions", ")", "{", "// TODO Test the functions in this node and return false if any are found\r", "return", "true", ";", "}", ")", ";", "return", "!", "$", "result", ";", "}" ]
Checks to see is one or any of a collection of functions are used in an expression @param array $functions
[ "Checks", "to", "see", "is", "one", "or", "any", "of", "a", "collection", "of", "functions", "are", "used", "in", "an", "expression" ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/XPath2Expression.php#L356-L370
train
WellCommerce/ShippingBundle
Visitor/ShippingMethodOrderVisitor.php
ShippingMethodOrderVisitor.getCostCollection
private function getCostCollection(OrderInterface $order) : Collection { if ($order->hasShippingMethod()) { $costs = $this->getCurrentShippingMethodCostsCollection($order); if ($costs->count() > 0) { return $costs; } } return $this->getShippingCostCollection($order); }
php
private function getCostCollection(OrderInterface $order) : Collection { if ($order->hasShippingMethod()) { $costs = $this->getCurrentShippingMethodCostsCollection($order); if ($costs->count() > 0) { return $costs; } } return $this->getShippingCostCollection($order); }
[ "private", "function", "getCostCollection", "(", "OrderInterface", "$", "order", ")", ":", "Collection", "{", "if", "(", "$", "order", "->", "hasShippingMethod", "(", ")", ")", "{", "$", "costs", "=", "$", "this", "->", "getCurrentShippingMethodCostsCollection", "(", "$", "order", ")", ";", "if", "(", "$", "costs", "->", "count", "(", ")", ">", "0", ")", "{", "return", "$", "costs", ";", "}", "}", "return", "$", "this", "->", "getShippingCostCollection", "(", "$", "order", ")", ";", "}" ]
Returns the costs collection for existing shipping method or all shipping methods if current method is not longer available @param OrderInterface $order @return Collection
[ "Returns", "the", "costs", "collection", "for", "existing", "shipping", "method", "or", "all", "shipping", "methods", "if", "current", "method", "is", "not", "longer", "available" ]
c298c571440f3058b0efd64744df194b461198f3
https://github.com/WellCommerce/ShippingBundle/blob/c298c571440f3058b0efd64744df194b461198f3/Visitor/ShippingMethodOrderVisitor.php#L113-L123
train
WellCommerce/ShippingBundle
Visitor/ShippingMethodOrderVisitor.php
ShippingMethodOrderVisitor.getCurrentShippingMethodCostsCollection
private function getCurrentShippingMethodCostsCollection(OrderInterface $order) : Collection { return $this->methodProvider->getShippingMethodCosts($order->getShippingMethod(), new OrderContext($order)); }
php
private function getCurrentShippingMethodCostsCollection(OrderInterface $order) : Collection { return $this->methodProvider->getShippingMethodCosts($order->getShippingMethod(), new OrderContext($order)); }
[ "private", "function", "getCurrentShippingMethodCostsCollection", "(", "OrderInterface", "$", "order", ")", ":", "Collection", "{", "return", "$", "this", "->", "methodProvider", "->", "getShippingMethodCosts", "(", "$", "order", "->", "getShippingMethod", "(", ")", ",", "new", "OrderContext", "(", "$", "order", ")", ")", ";", "}" ]
Returns the collection of costs for current shipping method @param OrderInterface $order @return Collection
[ "Returns", "the", "collection", "of", "costs", "for", "current", "shipping", "method" ]
c298c571440f3058b0efd64744df194b461198f3
https://github.com/WellCommerce/ShippingBundle/blob/c298c571440f3058b0efd64744df194b461198f3/Visitor/ShippingMethodOrderVisitor.php#L144-L147
train
t-kanstantsin/fileupload
src/model/Type.php
Type.getByMimeType
public static function getByMimeType(?string $mimeType): int { switch (explode('/', (string) $mimeType)[0] ?? null) { case 'image': return static::IMAGE; case 'audio': return static::AUDIO; case 'video': return static::VIDEO; default: return static::FILE; } }
php
public static function getByMimeType(?string $mimeType): int { switch (explode('/', (string) $mimeType)[0] ?? null) { case 'image': return static::IMAGE; case 'audio': return static::AUDIO; case 'video': return static::VIDEO; default: return static::FILE; } }
[ "public", "static", "function", "getByMimeType", "(", "?", "string", "$", "mimeType", ")", ":", "int", "{", "switch", "(", "explode", "(", "'/'", ",", "(", "string", ")", "$", "mimeType", ")", "[", "0", "]", "??", "null", ")", "{", "case", "'image'", ":", "return", "static", "::", "IMAGE", ";", "case", "'audio'", ":", "return", "static", "::", "AUDIO", ";", "case", "'video'", ":", "return", "static", "::", "VIDEO", ";", "default", ":", "return", "static", "::", "FILE", ";", "}", "}" ]
Returns file type by its mime type. @param string|null $mimeType @return int
[ "Returns", "file", "type", "by", "its", "mime", "type", "." ]
d6317a9b9b36d992f09affe3900ef7d7ddfd855f
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/model/Type.php#L56-L68
train
MindyPHP/QueryBuilder
ExpressionBuilder.php
ExpressionBuilder.literal
public function literal($input, $type = null) { // TODO remove if (!is_string($input)) { return $input; } // TODO remove return $this->connection->quote($input, $type); }
php
public function literal($input, $type = null) { // TODO remove if (!is_string($input)) { return $input; } // TODO remove return $this->connection->quote($input, $type); }
[ "public", "function", "literal", "(", "$", "input", ",", "$", "type", "=", "null", ")", "{", "// TODO remove", "if", "(", "!", "is_string", "(", "$", "input", ")", ")", "{", "return", "$", "input", ";", "}", "// TODO remove", "return", "$", "this", "->", "connection", "->", "quote", "(", "$", "input", ",", "$", "type", ")", ";", "}" ]
Quotes a given input parameter. @param mixed $input the parameter to be quoted @param string|null $type the type of the parameter @return string
[ "Quotes", "a", "given", "input", "parameter", "." ]
fc486454786f3d38887dd7246802ea11e2954e54
https://github.com/MindyPHP/QueryBuilder/blob/fc486454786f3d38887dd7246802ea11e2954e54/ExpressionBuilder.php#L358-L367
train
CatLabInteractive/Accounts
src/CatLab/Accounts/Authenticators/Password.php
Password.processChangePassword
private function processChangePassword(User $user, $password, $confirmPassword) { if (empty($password)) { return Errors::PASSWORD_INVALID; } if ($password !== $confirmPassword) { return Errors::CONFIRM_PASSWORD_INVALID; } /** @var UserMapper $mapper */ $mapper = MapperFactory::getUserMapper(); $user->setPassword($password); $mapper->update($user); // Now login this user. return $this->module->login($this->request, $user); }
php
private function processChangePassword(User $user, $password, $confirmPassword) { if (empty($password)) { return Errors::PASSWORD_INVALID; } if ($password !== $confirmPassword) { return Errors::CONFIRM_PASSWORD_INVALID; } /** @var UserMapper $mapper */ $mapper = MapperFactory::getUserMapper(); $user->setPassword($password); $mapper->update($user); // Now login this user. return $this->module->login($this->request, $user); }
[ "private", "function", "processChangePassword", "(", "User", "$", "user", ",", "$", "password", ",", "$", "confirmPassword", ")", "{", "if", "(", "empty", "(", "$", "password", ")", ")", "{", "return", "Errors", "::", "PASSWORD_INVALID", ";", "}", "if", "(", "$", "password", "!==", "$", "confirmPassword", ")", "{", "return", "Errors", "::", "CONFIRM_PASSWORD_INVALID", ";", "}", "/** @var UserMapper $mapper */", "$", "mapper", "=", "MapperFactory", "::", "getUserMapper", "(", ")", ";", "$", "user", "->", "setPassword", "(", "$", "password", ")", ";", "$", "mapper", "->", "update", "(", "$", "user", ")", ";", "// Now login this user.", "return", "$", "this", "->", "module", "->", "login", "(", "$", "this", "->", "request", ",", "$", "user", ")", ";", "}" ]
Change the password of a user and sent them on their way. @param User $user @param $password @param $confirmPassword @return string @throws \Neuron\Exceptions\DataNotSet
[ "Change", "the", "password", "of", "a", "user", "and", "sent", "them", "on", "their", "way", "." ]
e5465ad815c3caba5b7c1fde7b465a5fa05f3298
https://github.com/CatLabInteractive/Accounts/blob/e5465ad815c3caba5b7c1fde7b465a5fa05f3298/src/CatLab/Accounts/Authenticators/Password.php#L377-L395
train
CatLabInteractive/Accounts
src/CatLab/Accounts/Authenticators/Password.php
Password.verifyRecaptcha
private function verifyRecaptcha() { if (!isset($this->recaptchaClientKey)) { return true; } $recaptcha = $this->request->input('g-recaptcha-response'); if (!$recaptcha) { return false; } $request = new Request(); $request->setUrl('https://www.google.com/recaptcha/api/siteverify'); $request->setBody([ 'secret' => $this->recaptchaClientSecret, 'response' => $recaptcha, 'remoteip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null ]); $client = Client::getInstance(); $response = $client->post($request); if (!$response->getBody()) { return false; } $responseData = json_decode($response->getBody(), true); return isset($responseData['success']) && $responseData['success']; }
php
private function verifyRecaptcha() { if (!isset($this->recaptchaClientKey)) { return true; } $recaptcha = $this->request->input('g-recaptcha-response'); if (!$recaptcha) { return false; } $request = new Request(); $request->setUrl('https://www.google.com/recaptcha/api/siteverify'); $request->setBody([ 'secret' => $this->recaptchaClientSecret, 'response' => $recaptcha, 'remoteip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null ]); $client = Client::getInstance(); $response = $client->post($request); if (!$response->getBody()) { return false; } $responseData = json_decode($response->getBody(), true); return isset($responseData['success']) && $responseData['success']; }
[ "private", "function", "verifyRecaptcha", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "recaptchaClientKey", ")", ")", "{", "return", "true", ";", "}", "$", "recaptcha", "=", "$", "this", "->", "request", "->", "input", "(", "'g-recaptcha-response'", ")", ";", "if", "(", "!", "$", "recaptcha", ")", "{", "return", "false", ";", "}", "$", "request", "=", "new", "Request", "(", ")", ";", "$", "request", "->", "setUrl", "(", "'https://www.google.com/recaptcha/api/siteverify'", ")", ";", "$", "request", "->", "setBody", "(", "[", "'secret'", "=>", "$", "this", "->", "recaptchaClientSecret", ",", "'response'", "=>", "$", "recaptcha", ",", "'remoteip'", "=>", "isset", "(", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ")", "?", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ":", "null", "]", ")", ";", "$", "client", "=", "Client", "::", "getInstance", "(", ")", ";", "$", "response", "=", "$", "client", "->", "post", "(", "$", "request", ")", ";", "if", "(", "!", "$", "response", "->", "getBody", "(", ")", ")", "{", "return", "false", ";", "}", "$", "responseData", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "isset", "(", "$", "responseData", "[", "'success'", "]", ")", "&&", "$", "responseData", "[", "'success'", "]", ";", "}" ]
Verify recaptcha code
[ "Verify", "recaptcha", "code" ]
e5465ad815c3caba5b7c1fde7b465a5fa05f3298
https://github.com/CatLabInteractive/Accounts/blob/e5465ad815c3caba5b7c1fde7b465a5fa05f3298/src/CatLab/Accounts/Authenticators/Password.php#L459-L487
train
CommonApi/Cache
CacheTrait.php
CacheTrait.setCache
public function setCache($key, $value, $ttl = 0) { $cache_function = $this->set_cache_callback; return $cache_function($this->cache_type, array('key' => $key, 'value' => $value, 'ttl' => $ttl)); }
php
public function setCache($key, $value, $ttl = 0) { $cache_function = $this->set_cache_callback; return $cache_function($this->cache_type, array('key' => $key, 'value' => $value, 'ttl' => $ttl)); }
[ "public", "function", "setCache", "(", "$", "key", ",", "$", "value", ",", "$", "ttl", "=", "0", ")", "{", "$", "cache_function", "=", "$", "this", "->", "set_cache_callback", ";", "return", "$", "cache_function", "(", "$", "this", "->", "cache_type", ",", "array", "(", "'key'", "=>", "$", "key", ",", "'value'", "=>", "$", "value", ",", "'ttl'", "=>", "$", "ttl", ")", ")", ";", "}" ]
Persist data in cache @param string $key @param mixed $value @param integer $ttl (number of seconds) @return bool @since 1.0.0
[ "Persist", "data", "in", "cache" ]
6ff22d7d5f75f0e7b857bdec518f56d5c4682850
https://github.com/CommonApi/Cache/blob/6ff22d7d5f75f0e7b857bdec518f56d5c4682850/CacheTrait.php#L78-L83
train
CommonApi/Cache
CacheTrait.php
CacheTrait.useCache
public function useCache() { if (is_callable($this->get_cache_callback) && is_callable($this->set_cache_callback) && is_callable($this->delete_cache_callback)) { return true; } return false; }
php
public function useCache() { if (is_callable($this->get_cache_callback) && is_callable($this->set_cache_callback) && is_callable($this->delete_cache_callback)) { return true; } return false; }
[ "public", "function", "useCache", "(", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "get_cache_callback", ")", "&&", "is_callable", "(", "$", "this", "->", "set_cache_callback", ")", "&&", "is_callable", "(", "$", "this", "->", "delete_cache_callback", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determine if Cache is activated for this type @return boolean @since 1.0
[ "Determine", "if", "Cache", "is", "activated", "for", "this", "type" ]
6ff22d7d5f75f0e7b857bdec518f56d5c4682850
https://github.com/CommonApi/Cache/blob/6ff22d7d5f75f0e7b857bdec518f56d5c4682850/CacheTrait.php#L119-L128
train
pixelpolishers/makedocs
src/MakeDocs/Builder/AbstractBuilder.php
AbstractBuilder.setConfig
public function setConfig(array $config) { foreach ($config as $name => $value) { $setter = 'set' . ucfirst($name); call_user_func_array(array($this, $setter), array($value)); } }
php
public function setConfig(array $config) { foreach ($config as $name => $value) { $setter = 'set' . ucfirst($name); call_user_func_array(array($this, $setter), array($value)); } }
[ "public", "function", "setConfig", "(", "array", "$", "config", ")", "{", "foreach", "(", "$", "config", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "setter", "=", "'set'", ".", "ucfirst", "(", "$", "name", ")", ";", "call_user_func_array", "(", "array", "(", "$", "this", ",", "$", "setter", ")", ",", "array", "(", "$", "value", ")", ")", ";", "}", "}" ]
Sets the configuration of the builder. @param array $config The configuration to set.
[ "Sets", "the", "configuration", "of", "the", "builder", "." ]
1fa243b52565b5de417ef2dbdfbcae9896b6b483
https://github.com/pixelpolishers/makedocs/blob/1fa243b52565b5de417ef2dbdfbcae9896b6b483/src/MakeDocs/Builder/AbstractBuilder.php#L18-L25
train
kaiohken1982/Neobazaar
src/Neobazaar/Service/MainModuleService.php
MainModuleService.getDocumentEntityRepository
public function getDocumentEntityRepository() { if(isset($this->er['Document'])) { return $this->er['Document']; } $sphinxClient = $this->getServiceManager()->get('sphinxsearch.client.default'); $entityRepository = $this->getEntityManager()->getRepository('Neobazaar\Entity\Document'); $entityRepository->setSphinxClient($sphinxClient); $entityRepository->setSphinxSearch(true); $entityRepository->setServiceLocator($this->getServiceManager()); $this->er['Document'] = $entityRepository; return $entityRepository; }
php
public function getDocumentEntityRepository() { if(isset($this->er['Document'])) { return $this->er['Document']; } $sphinxClient = $this->getServiceManager()->get('sphinxsearch.client.default'); $entityRepository = $this->getEntityManager()->getRepository('Neobazaar\Entity\Document'); $entityRepository->setSphinxClient($sphinxClient); $entityRepository->setSphinxSearch(true); $entityRepository->setServiceLocator($this->getServiceManager()); $this->er['Document'] = $entityRepository; return $entityRepository; }
[ "public", "function", "getDocumentEntityRepository", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "er", "[", "'Document'", "]", ")", ")", "{", "return", "$", "this", "->", "er", "[", "'Document'", "]", ";", "}", "$", "sphinxClient", "=", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'sphinxsearch.client.default'", ")", ";", "$", "entityRepository", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getRepository", "(", "'Neobazaar\\Entity\\Document'", ")", ";", "$", "entityRepository", "->", "setSphinxClient", "(", "$", "sphinxClient", ")", ";", "$", "entityRepository", "->", "setSphinxSearch", "(", "true", ")", ";", "$", "entityRepository", "->", "setServiceLocator", "(", "$", "this", "->", "getServiceManager", "(", ")", ")", ";", "$", "this", "->", "er", "[", "'Document'", "]", "=", "$", "entityRepository", ";", "return", "$", "entityRepository", ";", "}" ]
Get Neobazaar\Entity\Document entity repository
[ "Get", "Neobazaar", "\\", "Entity", "\\", "Document", "entity", "repository" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Service/MainModuleService.php#L96-L109
train
kaiohken1982/Neobazaar
src/Neobazaar/Service/MainModuleService.php
MainModuleService.getTermTaxonomyEntityRepository
public function getTermTaxonomyEntityRepository() { if(isset($this->er['TermTaxonomy'])) { return $this->er['TermTaxonomy']; } $this->er['TermTaxonomy'] = $this->getEntityManager()->getRepository('Neobazaar\Entity\TermTaxonomy'); return $this->er['TermTaxonomy']; }
php
public function getTermTaxonomyEntityRepository() { if(isset($this->er['TermTaxonomy'])) { return $this->er['TermTaxonomy']; } $this->er['TermTaxonomy'] = $this->getEntityManager()->getRepository('Neobazaar\Entity\TermTaxonomy'); return $this->er['TermTaxonomy']; }
[ "public", "function", "getTermTaxonomyEntityRepository", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "er", "[", "'TermTaxonomy'", "]", ")", ")", "{", "return", "$", "this", "->", "er", "[", "'TermTaxonomy'", "]", ";", "}", "$", "this", "->", "er", "[", "'TermTaxonomy'", "]", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getRepository", "(", "'Neobazaar\\Entity\\TermTaxonomy'", ")", ";", "return", "$", "this", "->", "er", "[", "'TermTaxonomy'", "]", ";", "}" ]
Get Neobazaar\Entity\TermTaxonomy entity repository
[ "Get", "Neobazaar", "\\", "Entity", "\\", "TermTaxonomy", "entity", "repository" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Service/MainModuleService.php#L114-L122
train
kaiohken1982/Neobazaar
src/Neobazaar/Service/MainModuleService.php
MainModuleService.getGeonamesEntityRepository
public function getGeonamesEntityRepository() { if(isset($this->er['Geonames'])) { return $this->er['Geonames']; } $this->er['Geonames'] = $this->getEntityManager()->getRepository('Neobazaar\Entity\Geonames'); return $this->er['Geonames']; }
php
public function getGeonamesEntityRepository() { if(isset($this->er['Geonames'])) { return $this->er['Geonames']; } $this->er['Geonames'] = $this->getEntityManager()->getRepository('Neobazaar\Entity\Geonames'); return $this->er['Geonames']; }
[ "public", "function", "getGeonamesEntityRepository", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "er", "[", "'Geonames'", "]", ")", ")", "{", "return", "$", "this", "->", "er", "[", "'Geonames'", "]", ";", "}", "$", "this", "->", "er", "[", "'Geonames'", "]", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getRepository", "(", "'Neobazaar\\Entity\\Geonames'", ")", ";", "return", "$", "this", "->", "er", "[", "'Geonames'", "]", ";", "}" ]
Get Neobazaar\Entity\Geonames entity repository
[ "Get", "Neobazaar", "\\", "Entity", "\\", "Geonames", "entity", "repository" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Service/MainModuleService.php#L127-L135
train
kaiohken1982/Neobazaar
src/Neobazaar/Service/MainModuleService.php
MainModuleService.getUserEntityRepository
public function getUserEntityRepository() { if(isset($this->er['User'])) { return $this->er['User']; } $entityRepository = $this->getEntityManager()->getRepository('Neobazaar\Entity\User'); $entityRepository->setServiceLocator($this->getServiceManager()); $this->er['User'] = $entityRepository; return $this->er['User']; }
php
public function getUserEntityRepository() { if(isset($this->er['User'])) { return $this->er['User']; } $entityRepository = $this->getEntityManager()->getRepository('Neobazaar\Entity\User'); $entityRepository->setServiceLocator($this->getServiceManager()); $this->er['User'] = $entityRepository; return $this->er['User']; }
[ "public", "function", "getUserEntityRepository", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "er", "[", "'User'", "]", ")", ")", "{", "return", "$", "this", "->", "er", "[", "'User'", "]", ";", "}", "$", "entityRepository", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getRepository", "(", "'Neobazaar\\Entity\\User'", ")", ";", "$", "entityRepository", "->", "setServiceLocator", "(", "$", "this", "->", "getServiceManager", "(", ")", ")", ";", "$", "this", "->", "er", "[", "'User'", "]", "=", "$", "entityRepository", ";", "return", "$", "this", "->", "er", "[", "'User'", "]", ";", "}" ]
Get Neobazaar\Entity\USer entity repository
[ "Get", "Neobazaar", "\\", "Entity", "\\", "USer", "entity", "repository" ]
288c972dea981d715c4e136edb5dba0318c9e6cb
https://github.com/kaiohken1982/Neobazaar/blob/288c972dea981d715c4e136edb5dba0318c9e6cb/src/Neobazaar/Service/MainModuleService.php#L140-L150
train
rollerworks/search-core
Loader/InputProcessorLoader.php
InputProcessorLoader.create
public static function create(Validator $validator = null): self { return new self( new ClosureContainer( [ 'rollerworks_search.input.json' => function () use ($validator) { return new Input\JsonInput($validator); }, 'rollerworks_search.input.string_query' => function () use ($validator) { return new Input\StringQueryInput($validator); }, 'rollerworks_search.input.norm_string_query' => function () use ($validator) { return new Input\NormStringQueryInput($validator); }, ] ), [ 'json' => 'rollerworks_search.input.json', 'string_query' => 'rollerworks_search.input.string_query', 'norm_string_query' => 'rollerworks_search.input.norm_string_query', ] ); }
php
public static function create(Validator $validator = null): self { return new self( new ClosureContainer( [ 'rollerworks_search.input.json' => function () use ($validator) { return new Input\JsonInput($validator); }, 'rollerworks_search.input.string_query' => function () use ($validator) { return new Input\StringQueryInput($validator); }, 'rollerworks_search.input.norm_string_query' => function () use ($validator) { return new Input\NormStringQueryInput($validator); }, ] ), [ 'json' => 'rollerworks_search.input.json', 'string_query' => 'rollerworks_search.input.string_query', 'norm_string_query' => 'rollerworks_search.input.norm_string_query', ] ); }
[ "public", "static", "function", "create", "(", "Validator", "$", "validator", "=", "null", ")", ":", "self", "{", "return", "new", "self", "(", "new", "ClosureContainer", "(", "[", "'rollerworks_search.input.json'", "=>", "function", "(", ")", "use", "(", "$", "validator", ")", "{", "return", "new", "Input", "\\", "JsonInput", "(", "$", "validator", ")", ";", "}", ",", "'rollerworks_search.input.string_query'", "=>", "function", "(", ")", "use", "(", "$", "validator", ")", "{", "return", "new", "Input", "\\", "StringQueryInput", "(", "$", "validator", ")", ";", "}", ",", "'rollerworks_search.input.norm_string_query'", "=>", "function", "(", ")", "use", "(", "$", "validator", ")", "{", "return", "new", "Input", "\\", "NormStringQueryInput", "(", "$", "validator", ")", ";", "}", ",", "]", ")", ",", "[", "'json'", "=>", "'rollerworks_search.input.json'", ",", "'string_query'", "=>", "'rollerworks_search.input.string_query'", ",", "'norm_string_query'", "=>", "'rollerworks_search.input.norm_string_query'", ",", "]", ")", ";", "}" ]
Create a new InputProcessorLoader with the build-in InputProcessors loadable.
[ "Create", "a", "new", "InputProcessorLoader", "with", "the", "build", "-", "in", "InputProcessors", "loadable", "." ]
6b5671b8c4d6298906ded768261b0a59845140fb
https://github.com/rollerworks/search-core/blob/6b5671b8c4d6298906ded768261b0a59845140fb/Loader/InputProcessorLoader.php#L46-L68
train
alphalemon/BootstrapBundle
Core/Json/JsonAutoloaderCollection.php
JsonAutoloaderCollection.load
protected function load() { $path = $this->vendorDir . '/composer'; if (!is_dir($path)) throw new InvalidProjectException('"composer" folder has not been found. Be sure to use this bundle on a project managed by Composer'); $map = require $path . '/autoload_namespaces.php'; foreach ($map as $namespace => $paths) { if ( ! is_array($paths)) { $paths = array($paths); } foreach ($paths as $path) { if (substr($path, -1) != '/') { $path .= '/'; } $dir = $path . str_replace('\\', '/', $namespace); $bundleName = $this->getBundleName($dir); $this->addBundle($bundleName, $dir); } } $this->parseExtraFolders(); }
php
protected function load() { $path = $this->vendorDir . '/composer'; if (!is_dir($path)) throw new InvalidProjectException('"composer" folder has not been found. Be sure to use this bundle on a project managed by Composer'); $map = require $path . '/autoload_namespaces.php'; foreach ($map as $namespace => $paths) { if ( ! is_array($paths)) { $paths = array($paths); } foreach ($paths as $path) { if (substr($path, -1) != '/') { $path .= '/'; } $dir = $path . str_replace('\\', '/', $namespace); $bundleName = $this->getBundleName($dir); $this->addBundle($bundleName, $dir); } } $this->parseExtraFolders(); }
[ "protected", "function", "load", "(", ")", "{", "$", "path", "=", "$", "this", "->", "vendorDir", ".", "'/composer'", ";", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "throw", "new", "InvalidProjectException", "(", "'\"composer\" folder has not been found. Be sure to use this bundle on a project managed by Composer'", ")", ";", "$", "map", "=", "require", "$", "path", ".", "'/autoload_namespaces.php'", ";", "foreach", "(", "$", "map", "as", "$", "namespace", "=>", "$", "paths", ")", "{", "if", "(", "!", "is_array", "(", "$", "paths", ")", ")", "{", "$", "paths", "=", "array", "(", "$", "paths", ")", ";", "}", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "if", "(", "substr", "(", "$", "path", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "path", ".=", "'/'", ";", "}", "$", "dir", "=", "$", "path", ".", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "namespace", ")", ";", "$", "bundleName", "=", "$", "this", "->", "getBundleName", "(", "$", "dir", ")", ";", "$", "this", "->", "addBundle", "(", "$", "bundleName", ",", "$", "dir", ")", ";", "}", "}", "$", "this", "->", "parseExtraFolders", "(", ")", ";", "}" ]
Loads the bundles when the autoload.json file exists, parsing the autoload_namespaces.php file generated by composer @throws InvalidProjectException
[ "Loads", "the", "bundles", "when", "the", "autoload", ".", "json", "file", "exists", "parsing", "the", "autoload_namespaces", ".", "php", "file", "generated", "by", "composer" ]
27ff5cbc58d58149ec72a974f2a9d765a6fd37a6
https://github.com/alphalemon/BootstrapBundle/blob/27ff5cbc58d58149ec72a974f2a9d765a6fd37a6/Core/Json/JsonAutoloaderCollection.php#L101-L125
train
alphalemon/BootstrapBundle
Core/Json/JsonAutoloaderCollection.php
JsonAutoloaderCollection.parseExtraFolders
protected function parseExtraFolders() { foreach ($this->extraFolders as $folder) { $finder = new Finder(); if (is_dir($folder)) { $bundleFolders = $finder->directories()->depth(0)->in($folder); foreach ($bundleFolders as $bundleFolder) { $bundleName = basename($bundleFolder); $this->addBundle($bundleName, (string)$bundleFolder); } } } }
php
protected function parseExtraFolders() { foreach ($this->extraFolders as $folder) { $finder = new Finder(); if (is_dir($folder)) { $bundleFolders = $finder->directories()->depth(0)->in($folder); foreach ($bundleFolders as $bundleFolder) { $bundleName = basename($bundleFolder); $this->addBundle($bundleName, (string)$bundleFolder); } } } }
[ "protected", "function", "parseExtraFolders", "(", ")", "{", "foreach", "(", "$", "this", "->", "extraFolders", "as", "$", "folder", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "if", "(", "is_dir", "(", "$", "folder", ")", ")", "{", "$", "bundleFolders", "=", "$", "finder", "->", "directories", "(", ")", "->", "depth", "(", "0", ")", "->", "in", "(", "$", "folder", ")", ";", "foreach", "(", "$", "bundleFolders", "as", "$", "bundleFolder", ")", "{", "$", "bundleName", "=", "basename", "(", "$", "bundleFolder", ")", ";", "$", "this", "->", "addBundle", "(", "$", "bundleName", ",", "(", "string", ")", "$", "bundleFolder", ")", ";", "}", "}", "}", "}" ]
parses extra folders to look for autoloaders in different path than the ones saved into the composer file
[ "parses", "extra", "folders", "to", "look", "for", "autoloaders", "in", "different", "path", "than", "the", "ones", "saved", "into", "the", "composer", "file" ]
27ff5cbc58d58149ec72a974f2a9d765a6fd37a6
https://github.com/alphalemon/BootstrapBundle/blob/27ff5cbc58d58149ec72a974f2a9d765a6fd37a6/Core/Json/JsonAutoloaderCollection.php#L131-L143
train
alphalemon/BootstrapBundle
Core/Json/JsonAutoloaderCollection.php
JsonAutoloaderCollection.hasAutoloader
protected function hasAutoloader($path) { if (is_dir($path)) { $finder = new \Symfony\Component\Finder\Finder(); $bundles = $finder->files()->depth(0)->name('autoload.json')->in($path); if (count($bundles) == 1) { return true; } } return false; }
php
protected function hasAutoloader($path) { if (is_dir($path)) { $finder = new \Symfony\Component\Finder\Finder(); $bundles = $finder->files()->depth(0)->name('autoload.json')->in($path); if (count($bundles) == 1) { return true; } } return false; }
[ "protected", "function", "hasAutoloader", "(", "$", "path", ")", "{", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "$", "finder", "=", "new", "\\", "Symfony", "\\", "Component", "\\", "Finder", "\\", "Finder", "(", ")", ";", "$", "bundles", "=", "$", "finder", "->", "files", "(", ")", "->", "depth", "(", "0", ")", "->", "name", "(", "'autoload.json'", ")", "->", "in", "(", "$", "path", ")", ";", "if", "(", "count", "(", "$", "bundles", ")", "==", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the bundle has an autoloader.json file @param string $path The bundle's path @return boolean
[ "Checks", "if", "the", "bundle", "has", "an", "autoloader", ".", "json", "file" ]
27ff5cbc58d58149ec72a974f2a9d765a6fd37a6
https://github.com/alphalemon/BootstrapBundle/blob/27ff5cbc58d58149ec72a974f2a9d765a6fd37a6/Core/Json/JsonAutoloaderCollection.php#L170-L181
train
blainesch/prettyArray
src/prettyArray/PrettyArray.php
PrettyArray.getRange_
public function getRange_($start, $end) { $ret = new PrettyArray(); $collecting = false; $start = (string)$start; $end = (string)$end; foreach($this->data as $key => &$value) { $key = (string)$key; if($start == $key || $collecting) { $collecting = true; $ret->setByReference($key, $value); if($end == $key) { break; } } } return $ret; }
php
public function getRange_($start, $end) { $ret = new PrettyArray(); $collecting = false; $start = (string)$start; $end = (string)$end; foreach($this->data as $key => &$value) { $key = (string)$key; if($start == $key || $collecting) { $collecting = true; $ret->setByReference($key, $value); if($end == $key) { break; } } } return $ret; }
[ "public", "function", "getRange_", "(", "$", "start", ",", "$", "end", ")", "{", "$", "ret", "=", "new", "PrettyArray", "(", ")", ";", "$", "collecting", "=", "false", ";", "$", "start", "=", "(", "string", ")", "$", "start", ";", "$", "end", "=", "(", "string", ")", "$", "end", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "$", "key", "=", "(", "string", ")", "$", "key", ";", "if", "(", "$", "start", "==", "$", "key", "||", "$", "collecting", ")", "{", "$", "collecting", "=", "true", ";", "$", "ret", "->", "setByReference", "(", "$", "key", ",", "$", "value", ")", ";", "if", "(", "$", "end", "==", "$", "key", ")", "{", "break", ";", "}", "}", "}", "return", "$", "ret", ";", "}" ]
Will get a 'range' from PrettyArray. Calling it destructively will force the return value to be references to the current PrettyArray. <code> $arr = new PrettyArray(['swamp', 'desert', 'snow', 'rain', 'fog']); $arr->getSet(1,3); // [ 1 => desert, 2 => snow, 3 => rain] </code> <code> $arr = new PrettyArray(); $arr['nasty'] = 'swamp'; $arr['hot'] = 'desert'; $arr['cold'] = 'snow'; $arr[] = 'rain'; $arr[] = 'fog'; $o = $arr->getRange('hot', 0)->to_a(); print_r($o); </code> <pre> Array ( [hot] => desert [cold] => snow [0] => rain ) </pre> @param mixed $start @param mixed $end @return PrettyArray
[ "Will", "get", "a", "range", "from", "PrettyArray", ".", "Calling", "it", "destructively", "will", "force", "the", "return", "value", "to", "be", "references", "to", "the", "current", "PrettyArray", "." ]
2c18672e45a0ed9b67a0e321213c4055d224a334
https://github.com/blainesch/prettyArray/blob/2c18672e45a0ed9b67a0e321213c4055d224a334/src/prettyArray/PrettyArray.php#L386-L402
train