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
stubbles/stubbles-console
src/main/php/Executor.php
Executor.executeAsync
public function executeAsync(string $command, string $redirect = '2>&1'): InputStream { return new class( $this->runCommand($command, $redirect), $command ) extends ResourceInputStream { public function __construct($resource, string $command) { $this->setHandle($resource); $this->command = $command; } public function __destruct() { try { $this->close(); } catch (\Exception $e) { // ignore exception } } /** * reads given amount of bytes * * @param int $length optional max amount of bytes to read * @return string * @throws \LogicException * @throws \stubbles\streams\StreamException */ public function read(int $length = 8192): string { if (null === $this->handle) { throw new \LogicException('Can not read from closed input stream.'); } $data = @fgets($this->handle, $length); if (false === $data) { if (!@feof($this->handle)) { throw new StreamException('Can not read from input stream.'); } return ''; } return $data; } /** * closes the stream * * @throws \RuntimeException */ public function close() { if (null === $this->handle) { return; } $returnCode = pclose($this->handle); $this->handle = null; if (0 != $returnCode) { throw new \RuntimeException( 'Executing command "' . $this->command . '"' . ' failed: #' . $returnCode ); } } }; }
php
public function executeAsync(string $command, string $redirect = '2>&1'): InputStream { return new class( $this->runCommand($command, $redirect), $command ) extends ResourceInputStream { public function __construct($resource, string $command) { $this->setHandle($resource); $this->command = $command; } public function __destruct() { try { $this->close(); } catch (\Exception $e) { // ignore exception } } /** * reads given amount of bytes * * @param int $length optional max amount of bytes to read * @return string * @throws \LogicException * @throws \stubbles\streams\StreamException */ public function read(int $length = 8192): string { if (null === $this->handle) { throw new \LogicException('Can not read from closed input stream.'); } $data = @fgets($this->handle, $length); if (false === $data) { if (!@feof($this->handle)) { throw new StreamException('Can not read from input stream.'); } return ''; } return $data; } /** * closes the stream * * @throws \RuntimeException */ public function close() { if (null === $this->handle) { return; } $returnCode = pclose($this->handle); $this->handle = null; if (0 != $returnCode) { throw new \RuntimeException( 'Executing command "' . $this->command . '"' . ' failed: #' . $returnCode ); } } }; }
[ "public", "function", "executeAsync", "(", "string", "$", "command", ",", "string", "$", "redirect", "=", "'2>&1'", ")", ":", "InputStream", "{", "return", "new", "class", "(", "$", "this", "->", "runCommand", "(", "$", "command", ",", "$", "redirect", "...
executes given command asynchronous The method starts the command, and returns an input stream which can be used to read the output of the command at a later point in time. @param string $command @param string $redirect optional how to redirect error output @return \stubbles\streams\InputStream
[ "executes", "given", "command", "asynchronous" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/Executor.php#L75-L143
train
stubbles/stubbles-console
src/main/php/Executor.php
Executor.outputOf
public function outputOf(string $command, string $redirect = '2>&1') { $pd = $this->runCommand($command, $redirect); while (!feof($pd) && false !== ($line = fgets($pd, 4096))) { yield rtrim($line); } $returnCode = pclose($pd); if (0 != $returnCode) { throw new \RuntimeException( 'Executing command "' . $command . '"' . ' failed: #' . $returnCode ); } }
php
public function outputOf(string $command, string $redirect = '2>&1') { $pd = $this->runCommand($command, $redirect); while (!feof($pd) && false !== ($line = fgets($pd, 4096))) { yield rtrim($line); } $returnCode = pclose($pd); if (0 != $returnCode) { throw new \RuntimeException( 'Executing command "' . $command . '"' . ' failed: #' . $returnCode ); } }
[ "public", "function", "outputOf", "(", "string", "$", "command", ",", "string", "$", "redirect", "=", "'2>&1'", ")", "{", "$", "pd", "=", "$", "this", "->", "runCommand", "(", "$", "command", ",", "$", "redirect", ")", ";", "while", "(", "!", "feof",...
returns output from a command as it occurs @param string $command @param string $redirect optional how to redirect error output @return \Generator @since 6.0.0
[ "returns", "output", "from", "a", "command", "as", "it", "occurs" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/Executor.php#L153-L167
train
stubbles/stubbles-console
src/main/php/Executor.php
Executor.runCommand
private function runCommand(string $command, string $redirect = '2>&1') { $pd = popen($command . ' ' . $redirect, 'r'); if (false === $pd) { throw new \RuntimeException('Can not execute ' . $command); } return $pd; }
php
private function runCommand(string $command, string $redirect = '2>&1') { $pd = popen($command . ' ' . $redirect, 'r'); if (false === $pd) { throw new \RuntimeException('Can not execute ' . $command); } return $pd; }
[ "private", "function", "runCommand", "(", "string", "$", "command", ",", "string", "$", "redirect", "=", "'2>&1'", ")", "{", "$", "pd", "=", "popen", "(", "$", "command", ".", "' '", ".", "$", "redirect", ",", "'r'", ")", ";", "if", "(", "false", "...
runs given command and returns a handle to it @param string $command @param string $redirect optional how to redirect error output @return resource @throws \RuntimeException
[ "runs", "given", "command", "and", "returns", "a", "handle", "to", "it" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/Executor.php#L177-L185
train
edineibauer/uebConfig
public/include/Conn.php
Conn.databaseExist
public function databaseExist(): bool { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return true; } catch (\PDOException $e) { return false; } }
php
public function databaseExist(): bool { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return true; } catch (\PDOException $e) { return false; } }
[ "public", "function", "databaseExist", "(", ")", ":", "bool", "{", "try", "{", "$", "dsn", "=", "'mysql:host='", ".", "$", "this", "->", "host", ".", "';dbname='", ".", "$", "this", "->", "database", ";", "$", "options", "=", "[", "\\", "PDO", "::", ...
Verifica se credenciais e database Mysql exist @return bool
[ "Verifica", "se", "credenciais", "e", "database", "Mysql", "exist" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/include/Conn.php#L38-L50
train
edineibauer/uebConfig
public/include/Conn.php
Conn.createDatabase
public function createDatabase() { try { $dsn = 'mysql:host=' . $this->host . ';'; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("CREATE DATABASE {$this->database}"); $command->execute(); } catch (\PDOException $e) { return false; } }
php
public function createDatabase() { try { $dsn = 'mysql:host=' . $this->host . ';'; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("CREATE DATABASE {$this->database}"); $command->execute(); } catch (\PDOException $e) { return false; } }
[ "public", "function", "createDatabase", "(", ")", "{", "try", "{", "$", "dsn", "=", "'mysql:host='", ".", "$", "this", "->", "host", ".", "';'", ";", "$", "options", "=", "[", "\\", "PDO", "::", "MYSQL_ATTR_INIT_COMMAND", "=>", "'SET NAMES UTF8'", "]", "...
Cria a database informada no construtor
[ "Cria", "a", "database", "informada", "no", "construtor" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/include/Conn.php#L73-L87
train
edineibauer/uebConfig
public/include/Conn.php
Conn.databaseIsEmpty
public function databaseIsEmpty() { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("show tables"); $command->setFetchMode(\PDO::FETCH_ASSOC); $command->execute(); return empty($command->fetchAll()); } catch (\PDOException $e) { return false; } }
php
public function databaseIsEmpty() { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("show tables"); $command->setFetchMode(\PDO::FETCH_ASSOC); $command->execute(); return empty($command->fetchAll()); } catch (\PDOException $e) { return false; } }
[ "public", "function", "databaseIsEmpty", "(", ")", "{", "try", "{", "$", "dsn", "=", "'mysql:host='", ".", "$", "this", "->", "host", ".", "';dbname='", ".", "$", "this", "->", "database", ";", "$", "options", "=", "[", "\\", "PDO", "::", "MYSQL_ATTR_I...
Verifica se database esta vazia
[ "Verifica", "se", "database", "esta", "vazia" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/include/Conn.php#L92-L108
train
edineibauer/uebConfig
public/include/Conn.php
Conn.clearDatabase
public function clearDatabase() { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("show tables"); $command->setFetchMode(\PDO::FETCH_ASSOC); $command->execute(); $results = $command->fetchAll(); if(!empty($results)) { foreach ($results as $result) { foreach ($result as $dba => $table){ $command = $connect->prepare("DROP TABLE IF EXISTS {$table}"); $command->execute(); } } } } catch (\PDOException $e) { return false; } }
php
public function clearDatabase() { try { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database; $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']; $connect = new \PDO($dsn, $this->user, $this->pass, $options); $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $command = $connect->prepare("show tables"); $command->setFetchMode(\PDO::FETCH_ASSOC); $command->execute(); $results = $command->fetchAll(); if(!empty($results)) { foreach ($results as $result) { foreach ($result as $dba => $table){ $command = $connect->prepare("DROP TABLE IF EXISTS {$table}"); $command->execute(); } } } } catch (\PDOException $e) { return false; } }
[ "public", "function", "clearDatabase", "(", ")", "{", "try", "{", "$", "dsn", "=", "'mysql:host='", ".", "$", "this", "->", "host", ".", "';dbname='", ".", "$", "this", "->", "database", ";", "$", "options", "=", "[", "\\", "PDO", "::", "MYSQL_ATTR_INI...
Limpa as tabelas presentes na database
[ "Limpa", "as", "tabelas", "presentes", "na", "database" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/include/Conn.php#L113-L138
train
CharlotteDunois/Validator
src/Validator.php
Validator.addRule
static function addRule(\CharlotteDunois\Validation\RuleInterface $rule) { if(static::$rulesets === null) { static::initRules(); } $class = \get_class($rule); $arrname = \explode('\\', $class); $name = \array_pop($arrname); $rname = \str_replace('rule', '', \strtolower($name)); static::$rulesets[$rname] = $rule; if(\stripos($name, 'rule') !== false) { static::$typeRules[] = $rname; } }
php
static function addRule(\CharlotteDunois\Validation\RuleInterface $rule) { if(static::$rulesets === null) { static::initRules(); } $class = \get_class($rule); $arrname = \explode('\\', $class); $name = \array_pop($arrname); $rname = \str_replace('rule', '', \strtolower($name)); static::$rulesets[$rname] = $rule; if(\stripos($name, 'rule') !== false) { static::$typeRules[] = $rname; } }
[ "static", "function", "addRule", "(", "\\", "CharlotteDunois", "\\", "Validation", "\\", "RuleInterface", "$", "rule", ")", "{", "if", "(", "static", "::", "$", "rulesets", "===", "null", ")", "{", "static", "::", "initRules", "(", ")", ";", "}", "$", ...
Adds a new rule. @param \CharlotteDunois\Validation\RuleInterface $rule @return void @throws \InvalidArgumentException
[ "Adds", "a", "new", "rule", "." ]
0c7abddc87174039145bf0ce21d56937f1851365
https://github.com/CharlotteDunois/Validator/blob/0c7abddc87174039145bf0ce21d56937f1851365/src/Validator.php#L77-L92
train
CharlotteDunois/Validator
src/Validator.php
Validator.setDefaultLanguage
static function setDefaultLanguage(string $language) { if(!\class_exists($language, true)) { throw new \InvalidArgumentException('Unknown language class'); } elseif(!\in_array(\CharlotteDunois\Validation\LanguageInterface::class, \class_implements($language), true)) { throw new \InvalidArgumentException('Invalid language class (not implementing language interface)'); } static::$defaultLanguage = $language; }
php
static function setDefaultLanguage(string $language) { if(!\class_exists($language, true)) { throw new \InvalidArgumentException('Unknown language class'); } elseif(!\in_array(\CharlotteDunois\Validation\LanguageInterface::class, \class_implements($language), true)) { throw new \InvalidArgumentException('Invalid language class (not implementing language interface)'); } static::$defaultLanguage = $language; }
[ "static", "function", "setDefaultLanguage", "(", "string", "$", "language", ")", "{", "if", "(", "!", "\\", "class_exists", "(", "$", "language", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown language class'", ")"...
Sets the default language for the Validator. @param string $language @return void @throws \InvalidArgumentException
[ "Sets", "the", "default", "language", "for", "the", "Validator", "." ]
0c7abddc87174039145bf0ce21d56937f1851365
https://github.com/CharlotteDunois/Validator/blob/0c7abddc87174039145bf0ce21d56937f1851365/src/Validator.php#L100-L108
train
marczhermo/search-list
src/SearchList.php
SearchList.addFilter
public function addFilter($filterArray) { foreach ($filterArray as $expression => $value) { $this->filters[][$expression] = $value; } return $this; }
php
public function addFilter($filterArray) { foreach ($filterArray as $expression => $value) { $this->filters[][$expression] = $value; } return $this; }
[ "public", "function", "addFilter", "(", "$", "filterArray", ")", "{", "foreach", "(", "$", "filterArray", "as", "$", "expression", "=>", "$", "value", ")", "{", "$", "this", "->", "filters", "[", "]", "[", "$", "expression", "]", "=", "$", "value", "...
Collates an array of filter requirements @param array $filterArray @return $this
[ "Collates", "an", "array", "of", "filter", "requirements" ]
851f42b021c5934a2905026d57feb85e595b8f80
https://github.com/marczhermo/search-list/blob/851f42b021c5934a2905026d57feb85e595b8f80/src/SearchList.php#L100-L107
train
matthewbdaly/proper
src/Traits/IsString.php
IsString.replace
public function replace(string $find, string $replace): Stringable { return new static(str_replace($find, $replace, $this->string)); }
php
public function replace(string $find, string $replace): Stringable { return new static(str_replace($find, $replace, $this->string)); }
[ "public", "function", "replace", "(", "string", "$", "find", ",", "string", "$", "replace", ")", ":", "Stringable", "{", "return", "new", "static", "(", "str_replace", "(", "$", "find", ",", "$", "replace", ",", "$", "this", "->", "string", ")", ")", ...
Find and replace text @param string $find Text to find. @param string $replace Text to replace. @return Stringable
[ "Find", "and", "replace", "text" ]
dac8d6f9ff245b189c57139b79b9dd08cb13bfdd
https://github.com/matthewbdaly/proper/blob/dac8d6f9ff245b189c57139b79b9dd08cb13bfdd/src/Traits/IsString.php#L153-L156
train
GrottoPress/jentil
app/libraries/Jentil/Utilities/Loader.php
Loader.load
private function load(string $type, string $slug, string $name = ''): string { $slug = \ltrim($slug, '/'); $slug = \rtrim($slug, '.php'); $this->doAction($type, $slug, $name); $slug = $this->rewriteSlug($type, $slug); $rel_dir = $this->utilities->fileSystem->relativeDir(); $templates = []; if ($name) { $templates[] = "{$slug}-{$name}.php"; if ($rel_dir) { $templates[] = "{$rel_dir}/{$slug}-{$name}.php"; } } $templates[] = "{$slug}.php"; if ($rel_dir) { $templates[] = "{$rel_dir}/{$slug}.php"; } return \locate_template($templates, true, false); }
php
private function load(string $type, string $slug, string $name = ''): string { $slug = \ltrim($slug, '/'); $slug = \rtrim($slug, '.php'); $this->doAction($type, $slug, $name); $slug = $this->rewriteSlug($type, $slug); $rel_dir = $this->utilities->fileSystem->relativeDir(); $templates = []; if ($name) { $templates[] = "{$slug}-{$name}.php"; if ($rel_dir) { $templates[] = "{$rel_dir}/{$slug}-{$name}.php"; } } $templates[] = "{$slug}.php"; if ($rel_dir) { $templates[] = "{$rel_dir}/{$slug}.php"; } return \locate_template($templates, true, false); }
[ "private", "function", "load", "(", "string", "$", "type", ",", "string", "$", "slug", ",", "string", "$", "name", "=", "''", ")", ":", "string", "{", "$", "slug", "=", "\\", "ltrim", "(", "$", "slug", ",", "'/'", ")", ";", "$", "slug", "=", "\...
Helper to load partial or template This mimics WordPress' `\get_template_part()` function. @see https://developer.wordpress.org/reference/functions/get_template_part/ @param string $type 'template' or 'partial'
[ "Helper", "to", "load", "partial", "or", "template" ]
ad3341c91e0386256d4a2fbe8b7a201c9b706c10
https://github.com/GrottoPress/jentil/blob/ad3341c91e0386256d4a2fbe8b7a201c9b706c10/app/libraries/Jentil/Utilities/Loader.php#L58-L85
train
br-monteiro/htr-core
src/Common/Authenticator.php
Authenticator.generateToken
public static function generateToken(array $options): string { $issuedAt = time(); $expire = $issuedAt + $options['expiration_sec']; // tempo de expiracao do token $tokenParam = [ 'iat' => $issuedAt, // timestamp de geracao do token 'iss' => $options['host'], // dominio, pode ser usado para descartar tokens de outros dominios 'exp' => $expire, // expiracao do token 'nbf' => $issuedAt - 1, // token nao eh valido Antes de 'data' => $options['userdata'], // Dados do usuario logado ]; return JWT::encode($tokenParam, cfg::SALT_KEY); }
php
public static function generateToken(array $options): string { $issuedAt = time(); $expire = $issuedAt + $options['expiration_sec']; // tempo de expiracao do token $tokenParam = [ 'iat' => $issuedAt, // timestamp de geracao do token 'iss' => $options['host'], // dominio, pode ser usado para descartar tokens de outros dominios 'exp' => $expire, // expiracao do token 'nbf' => $issuedAt - 1, // token nao eh valido Antes de 'data' => $options['userdata'], // Dados do usuario logado ]; return JWT::encode($tokenParam, cfg::SALT_KEY); }
[ "public", "static", "function", "generateToken", "(", "array", "$", "options", ")", ":", "string", "{", "$", "issuedAt", "=", "time", "(", ")", ";", "$", "expire", "=", "$", "issuedAt", "+", "$", "options", "[", "'expiration_sec'", "]", ";", "// tempo de...
Generate the JSON Web Token @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param array $options @return string
[ "Generate", "the", "JSON", "Web", "Token" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Common/Authenticator.php#L24-L38
train
AeonDigital/PHP-Tools
src/Date.php
Date.firstWeekOfYear
public static function firstWeekOfYear(int $y) : \Datetime { $date = (string)$y . "-01-01 00:00:00"; $format = "Y-m-d H:i:s"; $o = \DateTime::createFromFormat($format, $date); $wnDay = date("N", strtotime($date)); $addD = (integer)((11 - $wnDay) % 7); $o->add(new \DateInterval("P" . $addD . "D")); $o->sub(new \DateInterval("P3D")); return $o; }
php
public static function firstWeekOfYear(int $y) : \Datetime { $date = (string)$y . "-01-01 00:00:00"; $format = "Y-m-d H:i:s"; $o = \DateTime::createFromFormat($format, $date); $wnDay = date("N", strtotime($date)); $addD = (integer)((11 - $wnDay) % 7); $o->add(new \DateInterval("P" . $addD . "D")); $o->sub(new \DateInterval("P3D")); return $o; }
[ "public", "static", "function", "firstWeekOfYear", "(", "int", "$", "y", ")", ":", "\\", "Datetime", "{", "$", "date", "=", "(", "string", ")", "$", "y", ".", "\"-01-01 00:00:00\"", ";", "$", "format", "=", "\"Y-m-d H:i:s\"", ";", "$", "o", "=", "\\", ...
Retorna um objeto DateTime referente ao primeiro dia da primeira semana do ano informado. @param int $y Ano. @return DateTime
[ "Retorna", "um", "objeto", "DateTime", "referente", "ao", "primeiro", "dia", "da", "primeira", "semana", "do", "ano", "informado", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/Date.php#L181-L194
train
AeonDigital/PHP-Tools
src/Date.php
Date.weeksInYear
public static function weeksInYear(int $y) : int { $lWeek = self::lastWeekOfYear($y); return (int)$lWeek->format("W"); }
php
public static function weeksInYear(int $y) : int { $lWeek = self::lastWeekOfYear($y); return (int)$lWeek->format("W"); }
[ "public", "static", "function", "weeksInYear", "(", "int", "$", "y", ")", ":", "int", "{", "$", "lWeek", "=", "self", "::", "lastWeekOfYear", "(", "$", "y", ")", ";", "return", "(", "int", ")", "$", "lWeek", "->", "format", "(", "\"W\"", ")", ";", ...
Calcula a quantidade de semanas que o ano informado tem. @param int $y Ano. @return int
[ "Calcula", "a", "quantidade", "de", "semanas", "que", "o", "ano", "informado", "tem", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/Date.php#L224-L228
train
AeonDigital/PHP-Tools
src/Date.php
Date.dateOfWeek
public static function dateOfWeek($obj) : ?\DateTime { $oD = null; $wM = null; if ($obj !== null) { if (is_string($obj) === true) { $wM = self::weekMember($obj); $oD = self::dateOfWeek($wM); } else { if (is_array($obj) === true && isset($obj["year"]) === true && isset($obj["week"]) === true && isset($obj["day"]) === true) { // ANO - Corrige valor fora dos limites válidos $y = ($obj["year"] > 9999) ? 9999 : $obj["year"]; $y = ($y < 1) ? 1 : $y; // SEMANA - Corrige valor fora dos limites válidos $mW = self::weeksInYear($y); $n = $obj["week"]; $n = ($n < 1) ? 1 : (($n > $mW) ? $mW : $n); // Verifica set do dia da semana $d = $obj["day"]; // DIA - Corrige valor fora dos limites válidos $d = ($d < 1) ? 1 : (($d > 7) ? 7 : $d); // Seta instância para o primeiro dia da primeira semana do ano alvo $oD = self::firstWeekOfYear($y); // Calcula quantidade de dias passados $addD = ((($n - 1) * 7) + $d - 1); $oD->add(new \DateInterval("P" . $addD . "D")); } } } return $oD; }
php
public static function dateOfWeek($obj) : ?\DateTime { $oD = null; $wM = null; if ($obj !== null) { if (is_string($obj) === true) { $wM = self::weekMember($obj); $oD = self::dateOfWeek($wM); } else { if (is_array($obj) === true && isset($obj["year"]) === true && isset($obj["week"]) === true && isset($obj["day"]) === true) { // ANO - Corrige valor fora dos limites válidos $y = ($obj["year"] > 9999) ? 9999 : $obj["year"]; $y = ($y < 1) ? 1 : $y; // SEMANA - Corrige valor fora dos limites válidos $mW = self::weeksInYear($y); $n = $obj["week"]; $n = ($n < 1) ? 1 : (($n > $mW) ? $mW : $n); // Verifica set do dia da semana $d = $obj["day"]; // DIA - Corrige valor fora dos limites válidos $d = ($d < 1) ? 1 : (($d > 7) ? 7 : $d); // Seta instância para o primeiro dia da primeira semana do ano alvo $oD = self::firstWeekOfYear($y); // Calcula quantidade de dias passados $addD = ((($n - 1) * 7) + $d - 1); $oD->add(new \DateInterval("P" . $addD . "D")); } } } return $oD; }
[ "public", "static", "function", "dateOfWeek", "(", "$", "obj", ")", ":", "?", "\\", "DateTime", "{", "$", "oD", "=", "null", ";", "$", "wM", "=", "null", ";", "if", "(", "$", "obj", "!==", "null", ")", "{", "if", "(", "is_string", "(", "$", "ob...
Retorna um DateTime conforme parametros passados. @param mixed $sW Texto no formato "week" ou array associativo com os dados brutos da data. @return ?DateTime
[ "Retorna", "um", "DateTime", "conforme", "parametros", "passados", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/Date.php#L325-L363
train
CMProductions/http-client
src/ClientBuilder.php
ClientBuilder.withGuzzleSender
public function withGuzzleSender(GuzzleClientInterface $client = null) { $this->sender = $this->buildGuzzleSender($client); return $this; }
php
public function withGuzzleSender(GuzzleClientInterface $client = null) { $this->sender = $this->buildGuzzleSender($client); return $this; }
[ "public", "function", "withGuzzleSender", "(", "GuzzleClientInterface", "$", "client", "=", "null", ")", "{", "$", "this", "->", "sender", "=", "$", "this", "->", "buildGuzzleSender", "(", "$", "client", ")", ";", "return", "$", "this", ";", "}" ]
Automatically generates a sender to use guzzle as a http client behind the scenes IMPORTANT: you need to install 'guzzlehttp/guzzle' to use this feature @param GuzzleClientInterface|null $client @return $this
[ "Automatically", "generates", "a", "sender", "to", "use", "guzzle", "as", "a", "http", "client", "behind", "the", "scenes" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/ClientBuilder.php#L69-L74
train
CMProductions/http-client
src/ClientBuilder.php
ClientBuilder.withYamlConfig
public function withYamlConfig($file) { if (!class_exists(Yaml::class)) { throw new RuntimeException("You need to install 'symfony/yaml' to use this feature"); } if (!is_readable($file)) { throw new RuntimeException("The configuration file is not readable"); } $config = Yaml::parse(file_get_contents($file)); if (!is_array($config)) { throw new RuntimeException("The configuration is not valid"); } $this->withConfig($config); return $this; }
php
public function withYamlConfig($file) { if (!class_exists(Yaml::class)) { throw new RuntimeException("You need to install 'symfony/yaml' to use this feature"); } if (!is_readable($file)) { throw new RuntimeException("The configuration file is not readable"); } $config = Yaml::parse(file_get_contents($file)); if (!is_array($config)) { throw new RuntimeException("The configuration is not valid"); } $this->withConfig($config); return $this; }
[ "public", "function", "withYamlConfig", "(", "$", "file", ")", "{", "if", "(", "!", "class_exists", "(", "Yaml", "::", "class", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"You need to install 'symfony/yaml' to use this feature\"", ")", ";", "}", "...
Allows you load the configuration from a yaml file IMPORTANT: you need to install 'symfony/yaml' to use this feature @param string $file @return $this
[ "Allows", "you", "load", "the", "configuration", "from", "a", "yaml", "file" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/ClientBuilder.php#L113-L131
train
CMProductions/http-client
src/ClientBuilder.php
ClientBuilder.withConsoleDebug
public function withConsoleDebug() { if (!class_exists(ConsoleLogger::class)) { throw new RuntimeException("You need to install 'symfony/console' to use this feature"); } $this->logger = new ConsoleLogger(new ConsoleOutput(), [LogLevel::DEBUG => ConsoleOutput::VERBOSITY_NORMAL]); return $this; }
php
public function withConsoleDebug() { if (!class_exists(ConsoleLogger::class)) { throw new RuntimeException("You need to install 'symfony/console' to use this feature"); } $this->logger = new ConsoleLogger(new ConsoleOutput(), [LogLevel::DEBUG => ConsoleOutput::VERBOSITY_NORMAL]); return $this; }
[ "public", "function", "withConsoleDebug", "(", ")", "{", "if", "(", "!", "class_exists", "(", "ConsoleLogger", "::", "class", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"You need to install 'symfony/console' to use this feature\"", ")", ";", "}", "$",...
Setups a logger to output debug information to the console @return $this
[ "Setups", "a", "logger", "to", "output", "debug", "information", "to", "the", "console" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/ClientBuilder.php#L152-L161
train
CMProductions/http-client
src/ClientBuilder.php
ClientBuilder.build
public function build($service = null) { if (!$this->sender) { $this->sender = $this->buildGuzzleSender(); } if (!$this->factory) { throw new RuntimeException("You need to provide a configuration or a factory for requests"); } if (!$this->logger) { $this->logger = new NullLogger(); } return $this->buildClient($this->factory, $this->sender, $this->logger, $service); }
php
public function build($service = null) { if (!$this->sender) { $this->sender = $this->buildGuzzleSender(); } if (!$this->factory) { throw new RuntimeException("You need to provide a configuration or a factory for requests"); } if (!$this->logger) { $this->logger = new NullLogger(); } return $this->buildClient($this->factory, $this->sender, $this->logger, $service); }
[ "public", "function", "build", "(", "$", "service", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "sender", ")", "{", "$", "this", "->", "sender", "=", "$", "this", "->", "buildGuzzleSender", "(", ")", ";", "}", "if", "(", "!", "$", ...
Builds the client with the configured values @param string|null $service @return Client
[ "Builds", "the", "client", "with", "the", "configured", "values" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/ClientBuilder.php#L170-L185
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.inputValidate
protected static function inputValidate($data, string $jsonShemaFile): bool { $fullPath = cfg::baseDir() . cfg::JSON_SCHEMA . cfg::DS; $jsonSchema = $fullPath . $jsonShemaFile; if (Json::validate($data, $jsonSchema)) { return true; } return false; }
php
protected static function inputValidate($data, string $jsonShemaFile): bool { $fullPath = cfg::baseDir() . cfg::JSON_SCHEMA . cfg::DS; $jsonSchema = $fullPath . $jsonShemaFile; if (Json::validate($data, $jsonSchema)) { return true; } return false; }
[ "protected", "static", "function", "inputValidate", "(", "$", "data", ",", "string", "$", "jsonShemaFile", ")", ":", "bool", "{", "$", "fullPath", "=", "cfg", "::", "baseDir", "(", ")", ".", "cfg", "::", "JSON_SCHEMA", ".", "cfg", "::", "DS", ";", "$",...
Validate the inpute of request @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param \stdClass|array $data @param string $jsonShemaFile @return bool
[ "Validate", "the", "inpute", "of", "request" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L25-L35
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.commonError
protected static function commonError(Response $response, \Exception $ex): Response { $data = [ "message" => "Somethings are wrong", "status" => "error" ]; if (cfg::htrFileConfigs()->devmode ?? false) { $data['dev_error'] = $ex->getMessage(); } return $response->withJson($data, 500); }
php
protected static function commonError(Response $response, \Exception $ex): Response { $data = [ "message" => "Somethings are wrong", "status" => "error" ]; if (cfg::htrFileConfigs()->devmode ?? false) { $data['dev_error'] = $ex->getMessage(); } return $response->withJson($data, 500); }
[ "protected", "static", "function", "commonError", "(", "Response", "$", "response", ",", "\\", "Exception", "$", "ex", ")", ":", "Response", "{", "$", "data", "=", "[", "\"message\"", "=>", "\"Somethings are wrong\"", ",", "\"status\"", "=>", "\"error\"", "]",...
Return the Response Object configured with common error @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param Response $response @param \Exception $ex @return Response
[ "Return", "the", "Response", "Object", "configured", "with", "common", "error" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L46-L57
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.outputValidate
protected static function outputValidate($data): AbstractModel { if (!self::$that) { self::$that = new AbstractModel; } self::$that->setData(result::adapter($data)); self::$that->setRawData($data); return self::$that; }
php
protected static function outputValidate($data): AbstractModel { if (!self::$that) { self::$that = new AbstractModel; } self::$that->setData(result::adapter($data)); self::$that->setRawData($data); return self::$that; }
[ "protected", "static", "function", "outputValidate", "(", "$", "data", ")", ":", "AbstractModel", "{", "if", "(", "!", "self", "::", "$", "that", ")", "{", "self", "::", "$", "that", "=", "new", "AbstractModel", ";", "}", "self", "::", "$", "that", "...
Initialize one new instance of AbstractModel and configure it with the results of query @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param mixed $data @return \App\System\AbstractModel
[ "Initialize", "one", "new", "instance", "of", "AbstractModel", "and", "configure", "it", "with", "the", "results", "of", "query" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L68-L78
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.addingAttribute
private function addingAttribute(\stdClass $obj, array $elements, int $dataKey) { foreach ($elements as $name => $value) { try { $obj->$name = is_callable($value) ? $value($this->rawData[$dataKey]) : $value; } catch (\Exception $ex) { throw new \Exception("Could not process attribute {$name}"); } } return $obj; }
php
private function addingAttribute(\stdClass $obj, array $elements, int $dataKey) { foreach ($elements as $name => $value) { try { $obj->$name = is_callable($value) ? $value($this->rawData[$dataKey]) : $value; } catch (\Exception $ex) { throw new \Exception("Could not process attribute {$name}"); } } return $obj; }
[ "private", "function", "addingAttribute", "(", "\\", "stdClass", "$", "obj", ",", "array", "$", "elements", ",", "int", "$", "dataKey", ")", "{", "foreach", "(", "$", "elements", "as", "$", "name", "=>", "$", "value", ")", "{", "try", "{", "$", "obj"...
Adding new attributes into results for response @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param \stdClass $obj @param array $elements @param int $dataKey @return \stdClass @throws \Exception
[ "Adding", "new", "attributes", "into", "results", "for", "response" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L128-L138
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.withAttribute
final public function withAttribute($name, $value = null, bool $inAllElements = false): self { // insert or update one or more attributes into all elements if (is_array($this->data) && $inAllElements === true) { foreach ($this->data as $dataKey => $element) { if (is_array($name)) { $element = $this->addingAttribute($element, $name, $dataKey); continue; } if (!is_array($name) && is_callable($value)) { $element->$name = $value($this->rawData[$dataKey]); continue; } $element->$name = $value; } return $this; } else { if ($inAllElements === true) { throw new \Exception("The results is not an array"); } } if (is_array($name)) { foreach ($name as $attributeKey => $attributeValue) { if (is_array($this->data)) { $this->data[$attributeKey] = is_callable($attributeValue) ? $attributeValue($this->rawData) : $attributeValue; } else { $this->data->$attributeKey = is_callable($attributeValue) ? $attributeValue($this->rawData) : $attributeValue; } } return $this; } if (is_array($this->data)) { $this->data[$name] = is_callable($value) ? $value($this->rawData) : $value; } else { $this->data->$name = is_callable($value) ? $value($this->rawData) : $value; } return $this; }
php
final public function withAttribute($name, $value = null, bool $inAllElements = false): self { // insert or update one or more attributes into all elements if (is_array($this->data) && $inAllElements === true) { foreach ($this->data as $dataKey => $element) { if (is_array($name)) { $element = $this->addingAttribute($element, $name, $dataKey); continue; } if (!is_array($name) && is_callable($value)) { $element->$name = $value($this->rawData[$dataKey]); continue; } $element->$name = $value; } return $this; } else { if ($inAllElements === true) { throw new \Exception("The results is not an array"); } } if (is_array($name)) { foreach ($name as $attributeKey => $attributeValue) { if (is_array($this->data)) { $this->data[$attributeKey] = is_callable($attributeValue) ? $attributeValue($this->rawData) : $attributeValue; } else { $this->data->$attributeKey = is_callable($attributeValue) ? $attributeValue($this->rawData) : $attributeValue; } } return $this; } if (is_array($this->data)) { $this->data[$name] = is_callable($value) ? $value($this->rawData) : $value; } else { $this->data->$name = is_callable($value) ? $value($this->rawData) : $value; } return $this; }
[ "final", "public", "function", "withAttribute", "(", "$", "name", ",", "$", "value", "=", "null", ",", "bool", "$", "inAllElements", "=", "false", ")", ":", "self", "{", "// insert or update one or more attributes into all elements", "if", "(", "is_array", "(", ...
Interface to adding new attributes into results @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param mixed $name @param mixed $value @param bool $inAllElements @return \self @throws \Exception
[ "Interface", "to", "adding", "new", "attributes", "into", "results" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L151-L192
train
br-monteiro/htr-core
src/Database/AbstractModel.php
AbstractModel.withoutAttribute
final public function withoutAttribute($name): self { // remove attributes when $name is a list (array) of attributes to be removed // remove attributes from root data value if (is_array($name)) { foreach ($name as $attribute) { if ($this->attributeExists($attribute)) { unset($this->data->$attribute); } } } // remove attribute from root data value if (is_string($name) && $this->attributeExists($name)) { unset($this->data->$name); } // remove attributes from elements of data value if (is_array($this->data)) { foreach ($this->data as $value) { // remove just one attribute if (is_string($name) && isset($value->$name)) { unset($value->$name); } // remove one or more attributes from elements of data value if (is_array($name)) { foreach ($name as $attribute) { if (is_string($attribute) && isset($value->$attribute)) { unset($value->$attribute); } } } } } return $this; }
php
final public function withoutAttribute($name): self { // remove attributes when $name is a list (array) of attributes to be removed // remove attributes from root data value if (is_array($name)) { foreach ($name as $attribute) { if ($this->attributeExists($attribute)) { unset($this->data->$attribute); } } } // remove attribute from root data value if (is_string($name) && $this->attributeExists($name)) { unset($this->data->$name); } // remove attributes from elements of data value if (is_array($this->data)) { foreach ($this->data as $value) { // remove just one attribute if (is_string($name) && isset($value->$name)) { unset($value->$name); } // remove one or more attributes from elements of data value if (is_array($name)) { foreach ($name as $attribute) { if (is_string($attribute) && isset($value->$attribute)) { unset($value->$attribute); } } } } } return $this; }
[ "final", "public", "function", "withoutAttribute", "(", "$", "name", ")", ":", "self", "{", "// remove attributes when $name is a list (array) of attributes to be removed", "// remove attributes from root data value", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", ...
Remove one attribute of result @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param mixed $name @return \self
[ "Remove", "one", "attribute", "of", "result" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/AbstractModel.php#L202-L236
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.map
public static function map(array $arr, callable $callback): array { $arrResult = []; foreach ($arr as $index => $value) { $arrResult[] = $callback($value, $index); } return $arrResult; }
php
public static function map(array $arr, callable $callback): array { $arrResult = []; foreach ($arr as $index => $value) { $arrResult[] = $callback($value, $index); } return $arrResult; }
[ "public", "static", "function", "map", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", ":", "array", "{", "$", "arrResult", "=", "[", "]", ";", "foreach", "(", "$", "arr", "as", "$", "index", "=>", "$", "value", ")", "{", "$", "a...
It goes through all the elements and performs the function of callabck @param array $arr The array to be used @param callable $callback Function fired in array elements @return array
[ "It", "goes", "through", "all", "the", "elements", "and", "performs", "the", "function", "of", "callabck" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L14-L23
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.find
public static function find(array $arr, callable $callback) { foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { return $value; } } return null; }
php
public static function find(array $arr, callable $callback) { foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { return $value; } } return null; }
[ "public", "static", "function", "find", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", "{", "foreach", "(", "$", "arr", "as", "$", "index", "=>", "$", "value", ")", "{", "if", "(", "$", "callback", "(", "$", "value", ",", "$", "...
Find a value in array. Return the first found @param array $arr The array to be used @param callable $callback Function fired in array elements @return mixed
[ "Find", "a", "value", "in", "array", ".", "Return", "the", "first", "found" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L32-L41
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.filter
public static function filter(array $arr, callable $callback): array { $arrResult = []; foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { $arrResult[] = $value; } } return $arrResult; }
php
public static function filter(array $arr, callable $callback): array { $arrResult = []; foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { $arrResult[] = $value; } } return $arrResult; }
[ "public", "static", "function", "filter", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", ":", "array", "{", "$", "arrResult", "=", "[", "]", ";", "foreach", "(", "$", "arr", "as", "$", "index", "=>", "$", "value", ")", "{", "if", ...
Filter the array according callback @param array $arr The array to be used @param callable $callback Function fired in array elements @return array The array filtered
[ "Filter", "the", "array", "according", "callback" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L50-L61
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.only
public static function only(array $arr, callable $callback): bool { $arrLength = 0; foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { $arrLength++; } } return $arrLength === 1; }
php
public static function only(array $arr, callable $callback): bool { $arrLength = 0; foreach ($arr as $index => $value) { if ($callback($value, $index) === true) { $arrLength++; } } return $arrLength === 1; }
[ "public", "static", "function", "only", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", ":", "bool", "{", "$", "arrLength", "=", "0", ";", "foreach", "(", "$", "arr", "as", "$", "index", "=>", "$", "value", ")", "{", "if", "(", "...
Verify if in all elements the condition is once accepted @param array $arr The array to be used @param $callback Function fired in array elements @return bool
[ "Verify", "if", "in", "all", "elements", "the", "condition", "is", "once", "accepted" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L70-L81
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.even
public static function even(array $arr, callable $callback): bool { if (count($arr) === 0) { return false; } foreach ($arr as $index => $value) { if ($callback($value, $index) !== true) { // false, 0 or null return false; } } return true; }
php
public static function even(array $arr, callable $callback): bool { if (count($arr) === 0) { return false; } foreach ($arr as $index => $value) { if ($callback($value, $index) !== true) { // false, 0 or null return false; } } return true; }
[ "public", "static", "function", "even", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", ":", "bool", "{", "if", "(", "count", "(", "$", "arr", ")", "===", "0", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "arr", "a...
Verify if in all elements the condition is always accepted @param array $arr The array to be used @param $callback Function fired in array elements @return bool
[ "Verify", "if", "in", "all", "elements", "the", "condition", "is", "always", "accepted" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L90-L103
train
br-monteiro/htr-core
src/Utils/IterableUtils.php
IterableUtils.last
public static function last(array $arr, callable $callback) { $arrLength = count($arr); if ($arrLength === 0) { return null; } $index = $arrLength - 1; while($index >= 0) { if ($callback($arr[$index], $index) === true) { return $arr[$index]; } $index--; } return null; }
php
public static function last(array $arr, callable $callback) { $arrLength = count($arr); if ($arrLength === 0) { return null; } $index = $arrLength - 1; while($index >= 0) { if ($callback($arr[$index], $index) === true) { return $arr[$index]; } $index--; } return null; }
[ "public", "static", "function", "last", "(", "array", "$", "arr", ",", "callable", "$", "callback", ")", "{", "$", "arrLength", "=", "count", "(", "$", "arr", ")", ";", "if", "(", "$", "arrLength", "===", "0", ")", "{", "return", "null", ";", "}", ...
Find a value in array. Return the last found @param array $arr The array to be used @param callable $callback Function fired in array elements @return mixed
[ "Find", "a", "value", "in", "array", ".", "Return", "the", "last", "found" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Utils/IterableUtils.php#L112-L130
train
br-monteiro/htr-core
src/Common/DefaultContainer.php
DefaultContainer.setUp
private static function setUp(): Container { if (!self::$container) { //Create Your container self::$container = new Container(); } $c = self::$container; //$c['settings'] = Configuration::SLIM_SETTINGS['settings']; // Not Found Configs $c['notFoundHandler'] = function ($c) { return function ($request, $response) use ($c) { return $c['response'] ->withStatus(404) ->withJson([ "message" => "Route not found", "status" => "error" ]); }; }; // Not Allowed Methods $c['notAllowedHandler'] = function ($c) { return function ($request, $response, $methods) use ($c) { return $c['response'] ->withStatus(405) ->withHeader('Allow', implode(', ', $methods)) ->withJson([ "message" => 'Method must be one of: ' . implode(', ', $methods), "status" => "error"]); }; }; // Error 500 $c['errorHandler'] = function ($c) { return function ($request, $response, $exception) use ($c) { $dataError = [ "message" => 'Something went wrong!', "status" => 'error' ]; if (cfg::htrFileConfigs()->devmode ?? false) { $dataError['error'] = $exception->getMessage(); } return $c['response'] ->withStatus(500) ->withJson($dataError); }; }; // Settings configs $c['settings']['addContentLengthHeader'] = false; $c['settings']['displayErrorDetails'] = cfg::htrFileConfigs()->devmode ?? false; // return $c; }
php
private static function setUp(): Container { if (!self::$container) { //Create Your container self::$container = new Container(); } $c = self::$container; //$c['settings'] = Configuration::SLIM_SETTINGS['settings']; // Not Found Configs $c['notFoundHandler'] = function ($c) { return function ($request, $response) use ($c) { return $c['response'] ->withStatus(404) ->withJson([ "message" => "Route not found", "status" => "error" ]); }; }; // Not Allowed Methods $c['notAllowedHandler'] = function ($c) { return function ($request, $response, $methods) use ($c) { return $c['response'] ->withStatus(405) ->withHeader('Allow', implode(', ', $methods)) ->withJson([ "message" => 'Method must be one of: ' . implode(', ', $methods), "status" => "error"]); }; }; // Error 500 $c['errorHandler'] = function ($c) { return function ($request, $response, $exception) use ($c) { $dataError = [ "message" => 'Something went wrong!', "status" => 'error' ]; if (cfg::htrFileConfigs()->devmode ?? false) { $dataError['error'] = $exception->getMessage(); } return $c['response'] ->withStatus(500) ->withJson($dataError); }; }; // Settings configs $c['settings']['addContentLengthHeader'] = false; $c['settings']['displayErrorDetails'] = cfg::htrFileConfigs()->devmode ?? false; // return $c; }
[ "private", "static", "function", "setUp", "(", ")", ":", "Container", "{", "if", "(", "!", "self", "::", "$", "container", ")", "{", "//Create Your container", "self", "::", "$", "container", "=", "new", "Container", "(", ")", ";", "}", "$", "c", "=", ...
Config the container used in Slim Framework @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @return Slim\Container
[ "Config", "the", "container", "used", "in", "Slim", "Framework" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Common/DefaultContainer.php#L28-L79
train
hiqdev/hipanel-module-client
src/grid/ClientColumn.php
ClientColumn.init
public function init() { parent::init(); $this->visible = Yii::$app->user->can('access-subclients'); if (!$this->visible) { return null; } if (!$this->sortAttribute) { $this->sortAttribute = $this->nameAttribute; } if ($this->value === null) { $this->value = function ($model) { if (Yii::$app->user->identity->hasSeller($model->{$this->idAttribute})) { return $model->{$this->nameAttribute}; } else { return Html::a($model->{$this->nameAttribute}, ['@client/view', 'id' => $model->{$this->idAttribute}]); } }; } if (!empty($this->grid->filterModel)) { if (!isset($this->filterInputOptions['id'])) { $this->filterInputOptions['id'] = $this->attribute; } if ($this->filter === null && strpos($this->attribute, '_like') === false) { $this->filter = $this->getDefaultFilter(); } } return true; }
php
public function init() { parent::init(); $this->visible = Yii::$app->user->can('access-subclients'); if (!$this->visible) { return null; } if (!$this->sortAttribute) { $this->sortAttribute = $this->nameAttribute; } if ($this->value === null) { $this->value = function ($model) { if (Yii::$app->user->identity->hasSeller($model->{$this->idAttribute})) { return $model->{$this->nameAttribute}; } else { return Html::a($model->{$this->nameAttribute}, ['@client/view', 'id' => $model->{$this->idAttribute}]); } }; } if (!empty($this->grid->filterModel)) { if (!isset($this->filterInputOptions['id'])) { $this->filterInputOptions['id'] = $this->attribute; } if ($this->filter === null && strpos($this->attribute, '_like') === false) { $this->filter = $this->getDefaultFilter(); } } return true; }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "$", "this", "->", "visible", "=", "Yii", "::", "$", "app", "->", "user", "->", "can", "(", "'access-subclients'", ")", ";", "if", "(", "!", "$", "this", "->", "v...
Sets visibility and default behaviour for value and filter when visible.
[ "Sets", "visibility", "and", "default", "behaviour", "for", "value", "and", "filter", "when", "visible", "." ]
569d87de369ccf8646087dde566d26a41995c8cb
https://github.com/hiqdev/hipanel-module-client/blob/569d87de369ccf8646087dde566d26a41995c8cb/src/grid/ClientColumn.php#L36-L67
train
symbiote/php-wordpress-database-tools
src/WordpressAttachmentFileResolver.php
WordpressAttachmentFileResolver.isFileExtensionImage
public function isFileExtensionImage($name) { static $imageExtensions = array( 'jpg' => true, 'png' => true, 'jpeg' => true, 'bmp' => true, 'ico' => true, 'gif' => true, 'tiff' => true, 'jpeg-large' => true, 'jpg-large' => true, ); $ext = pathinfo($name, PATHINFO_EXTENSION); return ($imageExtensions && isset($imageExtensions[$ext]) && $imageExtensions[$ext]); }
php
public function isFileExtensionImage($name) { static $imageExtensions = array( 'jpg' => true, 'png' => true, 'jpeg' => true, 'bmp' => true, 'ico' => true, 'gif' => true, 'tiff' => true, 'jpeg-large' => true, 'jpg-large' => true, ); $ext = pathinfo($name, PATHINFO_EXTENSION); return ($imageExtensions && isset($imageExtensions[$ext]) && $imageExtensions[$ext]); }
[ "public", "function", "isFileExtensionImage", "(", "$", "name", ")", "{", "static", "$", "imageExtensions", "=", "array", "(", "'jpg'", "=>", "true", ",", "'png'", "=>", "true", ",", "'jpeg'", "=>", "true", ",", "'bmp'", "=>", "true", ",", "'ico'", "=>",...
Check if filename is image based on filename @return boolean
[ "Check", "if", "filename", "is", "image", "based", "on", "filename" ]
93b1ae969722d7235dbbe6374f381daea0e0d5d7
https://github.com/symbiote/php-wordpress-database-tools/blob/93b1ae969722d7235dbbe6374f381daea0e0d5d7/src/WordpressAttachmentFileResolver.php#L54-L68
train
symbiote/php-wordpress-database-tools
src/WordpressAttachmentFileResolver.php
WordpressAttachmentFileResolver.getFilepathsFromRecord
public function getFilepathsFromRecord($wpData) { if (isset($wpData['guid'])) { // NOTE(Jake): Attempts to access cache to avoid function call overhead. $files = ($this->_runtime_cache !== null) ? $this->_runtime_cache : $this->getFilesRecursive(); $basename = basename($wpData['guid']); if (isset($files[$basename])) { return $files[$basename]; } return false; } return null; }
php
public function getFilepathsFromRecord($wpData) { if (isset($wpData['guid'])) { // NOTE(Jake): Attempts to access cache to avoid function call overhead. $files = ($this->_runtime_cache !== null) ? $this->_runtime_cache : $this->getFilesRecursive(); $basename = basename($wpData['guid']); if (isset($files[$basename])) { return $files[$basename]; } return false; } return null; }
[ "public", "function", "getFilepathsFromRecord", "(", "$", "wpData", ")", "{", "if", "(", "isset", "(", "$", "wpData", "[", "'guid'", "]", ")", ")", "{", "// NOTE(Jake): Attempts to access cache to avoid function call overhead.", "$", "files", "=", "(", "$", "this"...
Returns an array of the files that have that basename. If false = Cannot find file in database or on HDD If null = Invalid data/array passed in. @return array|false|null
[ "Returns", "an", "array", "of", "the", "files", "that", "have", "that", "basename", "." ]
93b1ae969722d7235dbbe6374f381daea0e0d5d7
https://github.com/symbiote/php-wordpress-database-tools/blob/93b1ae969722d7235dbbe6374f381daea0e0d5d7/src/WordpressAttachmentFileResolver.php#L190-L201
train
stubbles/stubbles-console
src/main/php/creator/ConsoleAppCreator.php
ConsoleAppCreator.run
public function run(): int { $className = $this->console->writeLine('Stubbles ConsoleAppCreator') ->writeLine(' (c) 2012-2016 Stubbles Development Group') ->writeEmptyLine() ->prompt('Please enter the full qualified class name for the console app: ') ->withFilter(ClassNameFilter::instance()); if (null === $className) { $this->console->writeLine('The entered class name is not a valid class name'); return -10; } $this->classFile->create($className); $this->scriptFile->create($className); $this->testFile->create($className); return 0; }
php
public function run(): int { $className = $this->console->writeLine('Stubbles ConsoleAppCreator') ->writeLine(' (c) 2012-2016 Stubbles Development Group') ->writeEmptyLine() ->prompt('Please enter the full qualified class name for the console app: ') ->withFilter(ClassNameFilter::instance()); if (null === $className) { $this->console->writeLine('The entered class name is not a valid class name'); return -10; } $this->classFile->create($className); $this->scriptFile->create($className); $this->testFile->create($className); return 0; }
[ "public", "function", "run", "(", ")", ":", "int", "{", "$", "className", "=", "$", "this", "->", "console", "->", "writeLine", "(", "'Stubbles ConsoleAppCreator'", ")", "->", "writeLine", "(", "' (c) 2012-2016 Stubbles Development Group'", ")", "->", "writeEmptyL...
runs the command and returns an exit code @return int
[ "runs", "the", "command", "and", "returns", "an", "exit", "code" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/creator/ConsoleAppCreator.php#L69-L85
train
gdbots/query-parser-php
src/Builder/ElasticaQueryBuilder.php
ElasticaQueryBuilder.addTermToQuery
protected function addTermToQuery(string $method, Node $node, ?Field $field = null, bool $cacheable = false): void { if ($node instanceof Emoji && $this->ignoreEmojis) { return; } if ($node instanceof Emoticon && $this->ignoreEmoticons) { return; } $value = $this->lowerCaseTerms && !$node instanceof Numbr ? strtolower((string)$node->getValue()) : $node->getValue(); $fieldName = $this->inField() ? $field->getName() : $this->defaultFieldName; if ($this->inField() && !$this->inSubquery()) { $useBoost = $field->useBoost(); $boost = $field->getBoost(); } else { $useBoost = $node->useBoost(); $boost = $node->getBoost(); } if ('_exists_' === $fieldName) { $term = new Exists($value); $method = 'addMust'; $cacheable = true; } elseif ('_missing_' === $fieldName) { $term = new Exists($value); $method = 'addMustNot'; $cacheable = true; } elseif ($node instanceof Date) { $term = $this->createDateRangeForSingleNode( $fieldName, $node, $cacheable, $useBoost ? $boost : Date::DEFAULT_BOOST ); } elseif ($node instanceof Numbr && $node->useComparisonOperator()) { $data = [$node->getComparisonOperator()->getValue() => $value]; if ($useBoost) { $data['boost'] = $boost; } $term = $this->qb->query()->range($fieldName, $data); } else { $term = $this->qb->query()->term(); $term->setTerm($fieldName, $value, $boost); } if ($cacheable) { if ('addMustNot' === $method) { $this->addToBoolQuery($method, $fieldName, $term); } else { $this->addToBoolQuery('addFilter', $fieldName, $term); } } else { $this->addToBoolQuery($method, $fieldName, $term); } }
php
protected function addTermToQuery(string $method, Node $node, ?Field $field = null, bool $cacheable = false): void { if ($node instanceof Emoji && $this->ignoreEmojis) { return; } if ($node instanceof Emoticon && $this->ignoreEmoticons) { return; } $value = $this->lowerCaseTerms && !$node instanceof Numbr ? strtolower((string)$node->getValue()) : $node->getValue(); $fieldName = $this->inField() ? $field->getName() : $this->defaultFieldName; if ($this->inField() && !$this->inSubquery()) { $useBoost = $field->useBoost(); $boost = $field->getBoost(); } else { $useBoost = $node->useBoost(); $boost = $node->getBoost(); } if ('_exists_' === $fieldName) { $term = new Exists($value); $method = 'addMust'; $cacheable = true; } elseif ('_missing_' === $fieldName) { $term = new Exists($value); $method = 'addMustNot'; $cacheable = true; } elseif ($node instanceof Date) { $term = $this->createDateRangeForSingleNode( $fieldName, $node, $cacheable, $useBoost ? $boost : Date::DEFAULT_BOOST ); } elseif ($node instanceof Numbr && $node->useComparisonOperator()) { $data = [$node->getComparisonOperator()->getValue() => $value]; if ($useBoost) { $data['boost'] = $boost; } $term = $this->qb->query()->range($fieldName, $data); } else { $term = $this->qb->query()->term(); $term->setTerm($fieldName, $value, $boost); } if ($cacheable) { if ('addMustNot' === $method) { $this->addToBoolQuery($method, $fieldName, $term); } else { $this->addToBoolQuery('addFilter', $fieldName, $term); } } else { $this->addToBoolQuery($method, $fieldName, $term); } }
[ "protected", "function", "addTermToQuery", "(", "string", "$", "method", ",", "Node", "$", "node", ",", "?", "Field", "$", "field", "=", "null", ",", "bool", "$", "cacheable", "=", "false", ")", ":", "void", "{", "if", "(", "$", "node", "instanceof", ...
Adds a term to the bool query or filter context. Filter context is used when the request for that item could be cached, like documents with hashtag of cats. @param string $method @param Node $node @param Field $field @param bool $cacheable
[ "Adds", "a", "term", "to", "the", "bool", "query", "or", "filter", "context", ".", "Filter", "context", "is", "used", "when", "the", "request", "for", "that", "item", "could", "be", "cached", "like", "documents", "with", "hashtag", "of", "cats", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/Builder/ElasticaQueryBuilder.php#L444-L500
train
gdbots/query-parser-php
src/Node/Date.php
Date.toDateTime
public function toDateTime(\DateTimeZone $timeZone = null): \DateTime { if (null === self::$utc) { self::$utc = new \DateTimeZone('UTC'); } $date = \DateTime::createFromFormat('!Y-m-d', $this->getValue(), $timeZone ?: self::$utc); if (!$date instanceof \DateTime) { $date = \DateTime::createFromFormat('!Y-m-d', (new \DateTime())->format('Y-m-d'), $timeZone ?: self::$utc); } if ($date->getOffset() !== 0) { $date->setTimezone(self::$utc); } return $date; }
php
public function toDateTime(\DateTimeZone $timeZone = null): \DateTime { if (null === self::$utc) { self::$utc = new \DateTimeZone('UTC'); } $date = \DateTime::createFromFormat('!Y-m-d', $this->getValue(), $timeZone ?: self::$utc); if (!$date instanceof \DateTime) { $date = \DateTime::createFromFormat('!Y-m-d', (new \DateTime())->format('Y-m-d'), $timeZone ?: self::$utc); } if ($date->getOffset() !== 0) { $date->setTimezone(self::$utc); } return $date; }
[ "public", "function", "toDateTime", "(", "\\", "DateTimeZone", "$", "timeZone", "=", "null", ")", ":", "\\", "DateTime", "{", "if", "(", "null", "===", "self", "::", "$", "utc", ")", "{", "self", "::", "$", "utc", "=", "new", "\\", "DateTimeZone", "(...
Always returns a DateTime in UTC. Use the time zone option to inform this class that the value it holds is localized and should be converted to UTC. @param \DateTimeZone $timeZone @return \DateTime
[ "Always", "returns", "a", "DateTime", "in", "UTC", ".", "Use", "the", "time", "zone", "option", "to", "inform", "this", "class", "that", "the", "value", "it", "holds", "is", "localized", "and", "should", "be", "converted", "to", "UTC", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/Node/Date.php#L116-L132
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.reset
public function reset(): self { $this->position = 0; $this->current = isset($this->tokens[$this->position]) ? $this->tokens[$this->position] : self::$eoi; return $this; }
php
public function reset(): self { $this->position = 0; $this->current = isset($this->tokens[$this->position]) ? $this->tokens[$this->position] : self::$eoi; return $this; }
[ "public", "function", "reset", "(", ")", ":", "self", "{", "$", "this", "->", "position", "=", "0", ";", "$", "this", "->", "current", "=", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "?", "$", "this",...
Resets the stream. @return self
[ "Resets", "the", "stream", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L38-L43
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.next
public function next(): bool { $this->current = isset($this->tokens[$this->position]) ? $this->tokens[$this->position++] : self::$eoi; return !$this->current->typeEquals(Token::T_EOI); }
php
public function next(): bool { $this->current = isset($this->tokens[$this->position]) ? $this->tokens[$this->position++] : self::$eoi; return !$this->current->typeEquals(Token::T_EOI); }
[ "public", "function", "next", "(", ")", ":", "bool", "{", "$", "this", "->", "current", "=", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "?", "$", "this", "->", "tokens", "[", "$", "this", "->", "posit...
Increments the position and sets the current token to the previous token. Returns true if the new "current" is not EOI. @return bool
[ "Increments", "the", "position", "and", "sets", "the", "current", "token", "to", "the", "previous", "token", ".", "Returns", "true", "if", "the", "new", "current", "is", "not", "EOI", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L51-L55
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.skipUntil
public function skipUntil(int $type): void { while (!$this->current->typeEquals($type) && !$this->current->typeEquals(Token::T_EOI)) { $this->next(); } }
php
public function skipUntil(int $type): void { while (!$this->current->typeEquals($type) && !$this->current->typeEquals(Token::T_EOI)) { $this->next(); } }
[ "public", "function", "skipUntil", "(", "int", "$", "type", ")", ":", "void", "{", "while", "(", "!", "$", "this", "->", "current", "->", "typeEquals", "(", "$", "type", ")", "&&", "!", "$", "this", "->", "current", "->", "typeEquals", "(", "Token", ...
Skips tokens until it sees a token with the given value. @param int $type
[ "Skips", "tokens", "until", "it", "sees", "a", "token", "with", "the", "given", "value", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L62-L67
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.nextIf
public function nextIf(int $type): bool { if (!$this->current->typeEquals($type)) { return false; } $this->next(); return true; }
php
public function nextIf(int $type): bool { if (!$this->current->typeEquals($type)) { return false; } $this->next(); return true; }
[ "public", "function", "nextIf", "(", "int", "$", "type", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "current", "->", "typeEquals", "(", "$", "type", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "next", "(", ")", ...
If the current token type matches the given type, move to the next token. Returns true if next was fired. @param int $type @return bool
[ "If", "the", "current", "token", "type", "matches", "the", "given", "type", "move", "to", "the", "next", "token", ".", "Returns", "true", "if", "next", "was", "fired", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L77-L85
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.nextIfAnyOf
public function nextIfAnyOf(array $types): bool { if (!$this->current->typeEqualsAnyOf($types)) { return false; } $this->next(); return true; }
php
public function nextIfAnyOf(array $types): bool { if (!$this->current->typeEqualsAnyOf($types)) { return false; } $this->next(); return true; }
[ "public", "function", "nextIfAnyOf", "(", "array", "$", "types", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "current", "->", "typeEqualsAnyOf", "(", "$", "types", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "next", ...
If the current token type matches any of the given types, move to the next token. Returns true if next was fired. @param int[] $types @return bool
[ "If", "the", "current", "token", "type", "matches", "any", "of", "the", "given", "types", "move", "to", "the", "next", "token", ".", "Returns", "true", "if", "next", "was", "fired", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L95-L103
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.nextIfLookahead
public function nextIfLookahead(int $type): bool { if (!isset($this->tokens[$this->position]) || !$this->tokens[$this->position]->typeEquals($type)) { return false; } $this->next(); return true; }
php
public function nextIfLookahead(int $type): bool { if (!isset($this->tokens[$this->position]) || !$this->tokens[$this->position]->typeEquals($type)) { return false; } $this->next(); return true; }
[ "public", "function", "nextIfLookahead", "(", "int", "$", "type", ")", ":", "bool", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "||", "!", "$", "this", "->", "tokens", "[", "$", "t...
If the lookahead token type matches the given type, move to the next token. @param int $type @return bool
[ "If", "the", "lookahead", "token", "type", "matches", "the", "given", "type", "move", "to", "the", "next", "token", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L112-L120
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.nextIfLookaheadAnyOf
public function nextIfLookaheadAnyOf(array $types): bool { if (!isset($this->tokens[$this->position]) || !$this->tokens[$this->position]->typeEqualsAnyOf($types)) { return false; } $this->next(); return true; }
php
public function nextIfLookaheadAnyOf(array $types): bool { if (!isset($this->tokens[$this->position]) || !$this->tokens[$this->position]->typeEqualsAnyOf($types)) { return false; } $this->next(); return true; }
[ "public", "function", "nextIfLookaheadAnyOf", "(", "array", "$", "types", ")", ":", "bool", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "||", "!", "$", "this", "->", "tokens", "[", "...
If the lookahead token type matches any of the given types, move to the next token. @param int[] $types @return bool
[ "If", "the", "lookahead", "token", "type", "matches", "any", "of", "the", "given", "types", "move", "to", "the", "next", "token", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L129-L137
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.lookaheadTypeIs
public function lookaheadTypeIs(int $type): bool { return isset($this->tokens[$this->position]) && $this->tokens[$this->position]->typeEquals($type); }
php
public function lookaheadTypeIs(int $type): bool { return isset($this->tokens[$this->position]) && $this->tokens[$this->position]->typeEquals($type); }
[ "public", "function", "lookaheadTypeIs", "(", "int", "$", "type", ")", ":", "bool", "{", "return", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "&&", "$", "this", "->", "tokens", "[", "$", "this", "->", "...
Returns true if the lookahead type equals the given type. @param int $type @return bool
[ "Returns", "true", "if", "the", "lookahead", "type", "equals", "the", "given", "type", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L170-L173
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.lookaheadTypeIsAnyOf
public function lookaheadTypeIsAnyOf(array $types): bool { return isset($this->tokens[$this->position]) && $this->tokens[$this->position]->typeEqualsAnyOf($types); }
php
public function lookaheadTypeIsAnyOf(array $types): bool { return isset($this->tokens[$this->position]) && $this->tokens[$this->position]->typeEqualsAnyOf($types); }
[ "public", "function", "lookaheadTypeIsAnyOf", "(", "array", "$", "types", ")", ":", "bool", "{", "return", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "]", ")", "&&", "$", "this", "->", "tokens", "[", "$", "this", "...
Returns true if the lookahead type equals any of the given types. @param array $types @return bool
[ "Returns", "true", "if", "the", "lookahead", "type", "equals", "any", "of", "the", "given", "types", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L182-L185
train
gdbots/query-parser-php
src/TokenStream.php
TokenStream.prevTypeIsAnyOf
public function prevTypeIsAnyOf(array $types): bool { return isset($this->tokens[$this->position - 2]) && $this->tokens[$this->position - 2]->typeEqualsAnyOf($types); }
php
public function prevTypeIsAnyOf(array $types): bool { return isset($this->tokens[$this->position - 2]) && $this->tokens[$this->position - 2]->typeEqualsAnyOf($types); }
[ "public", "function", "prevTypeIsAnyOf", "(", "array", "$", "types", ")", ":", "bool", "{", "return", "isset", "(", "$", "this", "->", "tokens", "[", "$", "this", "->", "position", "-", "2", "]", ")", "&&", "$", "this", "->", "tokens", "[", "$", "t...
Returns true if the previous token type equals any of the given types. @param array $types @return bool
[ "Returns", "true", "if", "the", "previous", "token", "type", "equals", "any", "of", "the", "given", "types", "." ]
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/TokenStream.php#L206-L209
train
gdbots/query-parser-php
src/ParsedQuery.php
ParsedQuery.hasAMatchableNode
public function hasAMatchableNode(): bool { foreach ($this->nodes as $node) { if (!$node->isProhibited()) { return true; } } return false; }
php
public function hasAMatchableNode(): bool { foreach ($this->nodes as $node) { if (!$node->isProhibited()) { return true; } } return false; }
[ "public", "function", "hasAMatchableNode", "(", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "nodes", "as", "$", "node", ")", "{", "if", "(", "!", "$", "node", "->", "isProhibited", "(", ")", ")", "{", "return", "true", ";", "}", "}", ...
Returns true if the parsed query contains at least one request for an item matching the query. If all of the nodes are "prohibited" values it can easily review your entire index. @return bool
[ "Returns", "true", "if", "the", "parsed", "query", "contains", "at", "least", "one", "request", "for", "an", "item", "matching", "the", "query", ".", "If", "all", "of", "the", "nodes", "are", "prohibited", "values", "it", "can", "easily", "review", "your",...
bc5d0238d7fe3481ec9649875581d26571d6851b
https://github.com/gdbots/query-parser-php/blob/bc5d0238d7fe3481ec9649875581d26571d6851b/src/ParsedQuery.php#L102-L111
train
timtoday/voyager-cn
src/Http/Controllers/Traits/BreadRelationshipParser.php
BreadRelationshipParser.getRelationships
protected function getRelationships(DataType $dataType) { $relationships = []; $dataType->browseRows->each(function ($item) use (&$relationships) { $details = json_decode($item->details); if (isset($details->relationship) && isset($item->field)) { $relation = $details->relationship; if (isset($relation->method)) { $method = $relation->method; $this->patchId[$method] = true; } else { $method = camel_case($item->field); $this->patchId[$method] = false; } if (strpos($relation->key, '.') > 0) { $this->patchId[$method] = false; } $relationships[$method] = function ($query) use ($relation) { // select only what we need $query->select($relation->key, $relation->label); }; } }); return $relationships; }
php
protected function getRelationships(DataType $dataType) { $relationships = []; $dataType->browseRows->each(function ($item) use (&$relationships) { $details = json_decode($item->details); if (isset($details->relationship) && isset($item->field)) { $relation = $details->relationship; if (isset($relation->method)) { $method = $relation->method; $this->patchId[$method] = true; } else { $method = camel_case($item->field); $this->patchId[$method] = false; } if (strpos($relation->key, '.') > 0) { $this->patchId[$method] = false; } $relationships[$method] = function ($query) use ($relation) { // select only what we need $query->select($relation->key, $relation->label); }; } }); return $relationships; }
[ "protected", "function", "getRelationships", "(", "DataType", "$", "dataType", ")", "{", "$", "relationships", "=", "[", "]", ";", "$", "dataType", "->", "browseRows", "->", "each", "(", "function", "(", "$", "item", ")", "use", "(", "&", "$", "relations...
Build the relationships array for the model's eager load. @param DataType $dataType @return array
[ "Build", "the", "relationships", "array", "for", "the", "model", "s", "eager", "load", "." ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Http/Controllers/Traits/BreadRelationshipParser.php#L20-L48
train
timtoday/voyager-cn
src/Http/Controllers/Traits/BreadRelationshipParser.php
BreadRelationshipParser.resolveRelations
protected function resolveRelations($dataTypeContent, DataType $dataType) { // In case of using server-side pagination, we need to work on the Collection (BROWSE) if ($dataTypeContent instanceof LengthAwarePaginator) { $dataTypeCollection = $dataTypeContent->getCollection(); } // If it's a model just make the changes directly on it (READ / EDIT) elseif ($dataTypeContent instanceof Model) { return $this->relationToLink($dataTypeContent, $dataType); } // Or we assume it's a Collection else { $dataTypeCollection = $dataTypeContent; } $dataTypeCollection->transform(function ($item) use ($dataType) { return $this->relationToLink($item, $dataType); }); return $dataTypeContent instanceof LengthAwarePaginator ? $dataTypeContent->setCollection($dataTypeCollection) : $dataTypeCollection; }
php
protected function resolveRelations($dataTypeContent, DataType $dataType) { // In case of using server-side pagination, we need to work on the Collection (BROWSE) if ($dataTypeContent instanceof LengthAwarePaginator) { $dataTypeCollection = $dataTypeContent->getCollection(); } // If it's a model just make the changes directly on it (READ / EDIT) elseif ($dataTypeContent instanceof Model) { return $this->relationToLink($dataTypeContent, $dataType); } // Or we assume it's a Collection else { $dataTypeCollection = $dataTypeContent; } $dataTypeCollection->transform(function ($item) use ($dataType) { return $this->relationToLink($item, $dataType); }); return $dataTypeContent instanceof LengthAwarePaginator ? $dataTypeContent->setCollection($dataTypeCollection) : $dataTypeCollection; }
[ "protected", "function", "resolveRelations", "(", "$", "dataTypeContent", ",", "DataType", "$", "dataType", ")", "{", "// In case of using server-side pagination, we need to work on the Collection (BROWSE)", "if", "(", "$", "dataTypeContent", "instanceof", "LengthAwarePaginator",...
Replace relationships' keys for labels and create READ links if a slug is provided. @param $dataTypeContent Can be either an eloquent Model, Collection or LengthAwarePaginator instance. @param DataType $dataType @return $dataTypeContent
[ "Replace", "relationships", "keys", "for", "labels", "and", "create", "READ", "links", "if", "a", "slug", "is", "provided", "." ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Http/Controllers/Traits/BreadRelationshipParser.php#L58-L78
train
timtoday/voyager-cn
src/Traits/Translatable.php
Translatable.translate
public function translate($language = null, $fallback = true) { if ($this->relationLoaded('translations')) { $this->load('translations'); } return (new Translator($this))->translate($language, $fallback); }
php
public function translate($language = null, $fallback = true) { if ($this->relationLoaded('translations')) { $this->load('translations'); } return (new Translator($this))->translate($language, $fallback); }
[ "public", "function", "translate", "(", "$", "language", "=", "null", ",", "$", "fallback", "=", "true", ")", "{", "if", "(", "$", "this", "->", "relationLoaded", "(", "'translations'", ")", ")", "{", "$", "this", "->", "load", "(", "'translations'", "...
Translate the whole model. @param null|string $language @param bool[string $fallback @return Translator
[ "Translate", "the", "whole", "model", "." ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Traits/Translatable.php#L108-L115
train
timtoday/voyager-cn
src/Http/Controllers/VoyagerMenuController.php
VoyagerMenuController.saveMenuTranslations
protected function saveMenuTranslations($_menuItem, &$data, $action) { if (isBreadTranslatable($_menuItem)) { $key = $action.'_title_i18n'; $trans = json_decode($data[$key], true); // Set field value with the default locale $data['title'] = $trans[config('voyager.multilingual.default', 'en')]; unset($data[$key]); // Remove hidden input holding translations unset($data['i18n_selector']); // Remove language selector input radio $_menuItem->setAttributeTranslations( 'title', $trans, true ); } }
php
protected function saveMenuTranslations($_menuItem, &$data, $action) { if (isBreadTranslatable($_menuItem)) { $key = $action.'_title_i18n'; $trans = json_decode($data[$key], true); // Set field value with the default locale $data['title'] = $trans[config('voyager.multilingual.default', 'en')]; unset($data[$key]); // Remove hidden input holding translations unset($data['i18n_selector']); // Remove language selector input radio $_menuItem->setAttributeTranslations( 'title', $trans, true ); } }
[ "protected", "function", "saveMenuTranslations", "(", "$", "_menuItem", ",", "&", "$", "data", ",", "$", "action", ")", "{", "if", "(", "isBreadTranslatable", "(", "$", "_menuItem", ")", ")", "{", "$", "key", "=", "$", "action", ".", "'_title_i18n'", ";"...
Save menu translations. @param object $_menuItem @param array $data menu data @param string $action add or edit action @return JSON translated item
[ "Save", "menu", "translations", "." ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Http/Controllers/VoyagerMenuController.php#L145-L161
train
timtoday/voyager-cn
src/Http/Controllers/VoyagerMediaController.php
VoyagerMediaController.get_all_dirs
public function get_all_dirs(Request $request) { $folderLocation = $request->folder_location; if (is_array($folderLocation)) { $folderLocation = rtrim(implode('/', $folderLocation), '/'); } $location = "{$this->directory}/{$folderLocation}"; return response()->json( str_replace($location, '', Storage::disk($this->filesystem)->directories($location)) ); }
php
public function get_all_dirs(Request $request) { $folderLocation = $request->folder_location; if (is_array($folderLocation)) { $folderLocation = rtrim(implode('/', $folderLocation), '/'); } $location = "{$this->directory}/{$folderLocation}"; return response()->json( str_replace($location, '', Storage::disk($this->filesystem)->directories($location)) ); }
[ "public", "function", "get_all_dirs", "(", "Request", "$", "request", ")", "{", "$", "folderLocation", "=", "$", "request", "->", "folder_location", ";", "if", "(", "is_array", "(", "$", "folderLocation", ")", ")", "{", "$", "folderLocation", "=", "rtrim", ...
GET ALL DIRECTORIES Working with Laravel 5.3
[ "GET", "ALL", "DIRECTORIES", "Working", "with", "Laravel", "5", ".", "3" ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Http/Controllers/VoyagerMediaController.php#L99-L112
train
timtoday/voyager-cn
src/Http/Controllers/VoyagerDatabaseController.php
VoyagerDatabaseController.update
public function update(Request $request) { Voyager::canOrFail('browse_database'); $table = json_decode($request->table, true); try { DatabaseUpdater::update($table); // TODO: synch BREAD with Table // $this->cleanOldAndCreateNew($request->original_name, $request->name); } catch (Exception $e) { return back()->with($this->alertException($e))->withInput(); } return redirect() ->route('voyager.database.edit', $table['name']) ->with($this->alertSuccess("Successfully updated {$table['name']} table")); }
php
public function update(Request $request) { Voyager::canOrFail('browse_database'); $table = json_decode($request->table, true); try { DatabaseUpdater::update($table); // TODO: synch BREAD with Table // $this->cleanOldAndCreateNew($request->original_name, $request->name); } catch (Exception $e) { return back()->with($this->alertException($e))->withInput(); } return redirect() ->route('voyager.database.edit', $table['name']) ->with($this->alertSuccess("Successfully updated {$table['name']} table")); }
[ "public", "function", "update", "(", "Request", "$", "request", ")", "{", "Voyager", "::", "canOrFail", "(", "'browse_database'", ")", ";", "$", "table", "=", "json_decode", "(", "$", "request", "->", "table", ",", "true", ")", ";", "try", "{", "Database...
Update database table. @param \Illuminate\Http\Request $request @return \Illuminate\Http\RedirectResponse
[ "Update", "database", "table", "." ]
4c36c25ee411aefecea13a95d99497810e49e418
https://github.com/timtoday/voyager-cn/blob/4c36c25ee411aefecea13a95d99497810e49e418/src/Http/Controllers/VoyagerDatabaseController.php#L110-L127
train
yawik/install
src/Filter/DbNameExtractor.php
DbNameExtractor.filter
public function filter($value) { // extract database $dbName = preg_match('~^mongodb://[^/]+/([^\?]+)~', $value, $match) ? $match[1] : $this->getDefaultDatabaseName(); return $dbName; }
php
public function filter($value) { // extract database $dbName = preg_match('~^mongodb://[^/]+/([^\?]+)~', $value, $match) ? $match[1] : $this->getDefaultDatabaseName(); return $dbName; }
[ "public", "function", "filter", "(", "$", "value", ")", "{", "// extract database", "$", "dbName", "=", "preg_match", "(", "'~^mongodb://[^/]+/([^\\?]+)~'", ",", "$", "value", ",", "$", "match", ")", "?", "$", "match", "[", "1", "]", ":", "$", "this", "-...
Extracts the database name of a mongo db connection string. If no database is specified in the connection string, the default value {@link defaultDatabaseName} is returned. @param mixed $value @return string
[ "Extracts", "the", "database", "name", "of", "a", "mongo", "db", "connection", "string", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Filter/DbNameExtractor.php#L81-L89
train
n2n/n2n-web
src/app/n2n/web/ui/view/View.php
View.compile
protected function compile(OutputBuffer $contentBuffer, BuildContext $buildContext) { $n2nContext = $this->getN2nContext(); return $this->bufferContents(array('request' => $this->getHttpContext()->getRequest(), 'response' => $this->getHttpContext()->getResponse(), 'view' => $this, 'httpContext' => $this->getHttpContext())); }
php
protected function compile(OutputBuffer $contentBuffer, BuildContext $buildContext) { $n2nContext = $this->getN2nContext(); return $this->bufferContents(array('request' => $this->getHttpContext()->getRequest(), 'response' => $this->getHttpContext()->getResponse(), 'view' => $this, 'httpContext' => $this->getHttpContext())); }
[ "protected", "function", "compile", "(", "OutputBuffer", "$", "contentBuffer", ",", "BuildContext", "$", "buildContext", ")", "{", "$", "n2nContext", "=", "$", "this", "->", "getN2nContext", "(", ")", ";", "return", "$", "this", "->", "bufferContents", "(", ...
Builds view content @return OutputBuffer
[ "Builds", "view", "content" ]
1640c79f05d10d73093b98b70860ef8076d23e81
https://github.com/n2n/n2n-web/blob/1640c79f05d10d73093b98b70860ef8076d23e81/src/app/n2n/web/ui/view/View.php#L461-L466
train
yawik/install
src/Controller/Plugin/UserCreator.php
UserCreator.process
public function process($username, $password, $email) { $dm = $this->documentManager; /* @var UserRepository $repo */ $repo = $dm->getRepository(User::class); $credential = $this->credentialFilter->filter($password); $info = new Info(); $info->setEmail($email); $user = new User(); $user ->setIsDraft(false) ->setRole('admin') ->setLogin($username) ->setCredential($credential) ->setInfo($info) ; $repo->setEntityPrototype(new User()); $result = true; try{ $repo->store($user); }catch (\Exception $e){ throw $e; } return $result; }
php
public function process($username, $password, $email) { $dm = $this->documentManager; /* @var UserRepository $repo */ $repo = $dm->getRepository(User::class); $credential = $this->credentialFilter->filter($password); $info = new Info(); $info->setEmail($email); $user = new User(); $user ->setIsDraft(false) ->setRole('admin') ->setLogin($username) ->setCredential($credential) ->setInfo($info) ; $repo->setEntityPrototype(new User()); $result = true; try{ $repo->store($user); }catch (\Exception $e){ throw $e; } return $result; }
[ "public", "function", "process", "(", "$", "username", ",", "$", "password", ",", "$", "email", ")", "{", "$", "dm", "=", "$", "this", "->", "documentManager", ";", "/* @var UserRepository $repo */", "$", "repo", "=", "$", "dm", "->", "getRepository", "(",...
Inserts a minimalistic user document into the database. @param string $username Login name @param string $password Credential @param string $email Email @throws \Exception when fail store user entity @return bool
[ "Inserts", "a", "minimalistic", "user", "document", "into", "the", "database", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/UserCreator.php#L63-L89
train
yawik/install
src/Validator/MongoDbConnectionString.php
MongoDbConnectionString.isValid
public function isValid($value) { $this->databaseError = null; // Empty connection string is valid (defaults to localhost:defaultPort) if (!empty($value) && !preg_match($this->pattern, $value)) { $this->error(self::INVALID); return false; } return true; }
php
public function isValid($value) { $this->databaseError = null; // Empty connection string is valid (defaults to localhost:defaultPort) if (!empty($value) && !preg_match($this->pattern, $value)) { $this->error(self::INVALID); return false; } return true; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "this", "->", "databaseError", "=", "null", ";", "// Empty connection string is valid (defaults to localhost:defaultPort)", "if", "(", "!", "empty", "(", "$", "value", ")", "&&", "!", "preg_match",...
Returns true if the passed string is a valid mongodb connection string. {@inheritDoc} @param string $value
[ "Returns", "true", "if", "the", "passed", "string", "is", "a", "valid", "mongodb", "connection", "string", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Validator/MongoDbConnectionString.php#L59-L71
train
yawik/install
src/Factory/Controller/Plugin/UserCreatorFactory.php
UserCreatorFactory.createDocumentManager
public function createDocumentManager($connection,$config) { $dbConn = new Connection($connection); $dm = DocumentManager::create($dbConn,$config); return $dm; }
php
public function createDocumentManager($connection,$config) { $dbConn = new Connection($connection); $dm = DocumentManager::create($dbConn,$config); return $dm; }
[ "public", "function", "createDocumentManager", "(", "$", "connection", ",", "$", "config", ")", "{", "$", "dbConn", "=", "new", "Connection", "(", "$", "connection", ")", ";", "$", "dm", "=", "DocumentManager", "::", "create", "(", "$", "dbConn", ",", "$...
Create a document manager @param $connection @param $config @return DocumentManager @codeCoverageIgnore
[ "Create", "a", "document", "manager" ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Factory/Controller/Plugin/UserCreatorFactory.php#L67-L72
train
yawik/install
src/Validator/MongoDbConnection.php
MongoDbConnection.isValid
public function isValid($value) { $this->databaseError = null; // @codeCoverageIgnoreStart // This cannot be testes until we have a test database environment. try { $connection = new Client($value); $connection->listDatabases(); } catch (ConnectionTimeoutException $e) { $this->databaseError = $e->getMessage(); $this->error(self::NO_CONNECTION); return false; } catch (\Exception $e) { $this->databaseError = $e->getMessage(); $this->error(self::NO_CONNECTION); return false; } return true; // @codeCoverageIgnoreEnd }
php
public function isValid($value) { $this->databaseError = null; // @codeCoverageIgnoreStart // This cannot be testes until we have a test database environment. try { $connection = new Client($value); $connection->listDatabases(); } catch (ConnectionTimeoutException $e) { $this->databaseError = $e->getMessage(); $this->error(self::NO_CONNECTION); return false; } catch (\Exception $e) { $this->databaseError = $e->getMessage(); $this->error(self::NO_CONNECTION); return false; } return true; // @codeCoverageIgnoreEnd }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "this", "->", "databaseError", "=", "null", ";", "// @codeCoverageIgnoreStart", "// This cannot be testes until we have a test database environment.", "try", "{", "$", "connection", "=", "new", "Client",...
Returns true if and only if a mongodb connection can be established. @param string $value The mongodb connection string @return bool
[ "Returns", "true", "if", "and", "only", "if", "a", "mongodb", "connection", "can", "be", "established", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Validator/MongoDbConnection.php#L72-L93
train
eccube2/plugin-installer
src/Eccube2/Composer/Installers/Installer.php
Installer.getLocationPattern
protected function getLocationPattern($frameworkType) { $pattern = false; if (!empty($this->supportedTypes[$frameworkType])) { $frameworkClass = 'Eccube2\\Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; /** @var BaseInstaller $framework */ $framework = new $frameworkClass(null, $this->composer, $this->getIO()); $locations = array_keys($framework->getLocations()); $pattern = $locations ? '(' . implode('|', $locations) . ')' : false; } return $pattern ? $pattern : '(\w+)'; }
php
protected function getLocationPattern($frameworkType) { $pattern = false; if (!empty($this->supportedTypes[$frameworkType])) { $frameworkClass = 'Eccube2\\Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; /** @var BaseInstaller $framework */ $framework = new $frameworkClass(null, $this->composer, $this->getIO()); $locations = array_keys($framework->getLocations()); $pattern = $locations ? '(' . implode('|', $locations) . ')' : false; } return $pattern ? $pattern : '(\w+)'; }
[ "protected", "function", "getLocationPattern", "(", "$", "frameworkType", ")", "{", "$", "pattern", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "supportedTypes", "[", "$", "frameworkType", "]", ")", ")", "{", "$", "frameworkClass", ...
Get the second part of the regular expression to check for support of a package type @param string $frameworkType @return string
[ "Get", "the", "second", "part", "of", "the", "regular", "expression", "to", "check", "for", "support", "of", "a", "package", "type" ]
809e24b241410693f5f5e0a9d73c0633a1acfc7d
https://github.com/eccube2/plugin-installer/blob/809e24b241410693f5f5e0a9d73c0633a1acfc7d/src/Eccube2/Composer/Installers/Installer.php#L45-L57
train
yawik/install
src/Controller/Index.php
Index.preDispatch
public function preDispatch(MvcEvent $event) { $this->layout()->setVariable('lang', $this->params('lang')); $p = $this->params()->fromQuery('p'); $request = $this->getRequest(); if ($p && $request->isXmlHttpRequest()) { $routeMatch = $event->getRouteMatch(); $routeMatch->setParam('action', $p); $response = $this->getResponse(); $response->getHeaders() ->addHeaderLine('Content-Type', 'application/json') ->addHeaderLine('Content-Encoding', 'utf8'); } }
php
public function preDispatch(MvcEvent $event) { $this->layout()->setVariable('lang', $this->params('lang')); $p = $this->params()->fromQuery('p'); $request = $this->getRequest(); if ($p && $request->isXmlHttpRequest()) { $routeMatch = $event->getRouteMatch(); $routeMatch->setParam('action', $p); $response = $this->getResponse(); $response->getHeaders() ->addHeaderLine('Content-Type', 'application/json') ->addHeaderLine('Content-Encoding', 'utf8'); } }
[ "public", "function", "preDispatch", "(", "MvcEvent", "$", "event", ")", "{", "$", "this", "->", "layout", "(", ")", "->", "setVariable", "(", "'lang'", ",", "$", "this", "->", "params", "(", "'lang'", ")", ")", ";", "$", "p", "=", "$", "this", "->...
Hook for custom preDispatch event. @param MvcEvent $event
[ "Hook", "for", "custom", "preDispatch", "event", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Index.php#L52-L67
train
yawik/install
src/Controller/Index.php
Index.prereqAction
public function prereqAction() { $prereqs = $this->plugin('Install/Prerequisites')->check(); $model = $this->createViewModel(array('prerequisites' => $prereqs), true); $model->setTemplate('install/index/prerequisites.ajax.phtml'); return $model; }
php
public function prereqAction() { $prereqs = $this->plugin('Install/Prerequisites')->check(); $model = $this->createViewModel(array('prerequisites' => $prereqs), true); $model->setTemplate('install/index/prerequisites.ajax.phtml'); return $model; }
[ "public", "function", "prereqAction", "(", ")", "{", "$", "prereqs", "=", "$", "this", "->", "plugin", "(", "'Install/Prerequisites'", ")", "->", "check", "(", ")", ";", "$", "model", "=", "$", "this", "->", "createViewModel", "(", "array", "(", "'prereq...
Action to check prerequisites via ajax request. @return ViewModel|ResponseInterface
[ "Action", "to", "check", "prerequisites", "via", "ajax", "request", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Index.php#L99-L107
train
yawik/install
src/Controller/Index.php
Index.installAction
public function installAction() { $form = $this->installForm; $form->setData($_POST); if (!$form->isValid()) { return $this->createJsonResponse( array( 'ok' => false, 'errors' => $form->getMessages(), ) ); } $data = $form->getData(); try { $options = [ 'connection' => $data['db_conn'], ]; $userOk = $this->plugin('Install/UserCreator', $options)->process($data['username'], $data['password'], $data['email']); $ok = $this->plugin('Install/ConfigCreator')->process($data['db_conn'], $data['email']); } catch (\Exception $exception) { /* @TODO: provide a way to handle global error message */ return $this->createJsonResponse([ 'ok' => false, 'errors' => [ 'global' => [$exception->getMessage()] ] ]); } /* * Make sure there's no cached config files */ $this->cacheService->clearCache(); $model = $this->createViewModel(array('ok' => $ok), true); $model->setTemplate('install/index/install.ajax.phtml'); return $model; }
php
public function installAction() { $form = $this->installForm; $form->setData($_POST); if (!$form->isValid()) { return $this->createJsonResponse( array( 'ok' => false, 'errors' => $form->getMessages(), ) ); } $data = $form->getData(); try { $options = [ 'connection' => $data['db_conn'], ]; $userOk = $this->plugin('Install/UserCreator', $options)->process($data['username'], $data['password'], $data['email']); $ok = $this->plugin('Install/ConfigCreator')->process($data['db_conn'], $data['email']); } catch (\Exception $exception) { /* @TODO: provide a way to handle global error message */ return $this->createJsonResponse([ 'ok' => false, 'errors' => [ 'global' => [$exception->getMessage()] ] ]); } /* * Make sure there's no cached config files */ $this->cacheService->clearCache(); $model = $this->createViewModel(array('ok' => $ok), true); $model->setTemplate('install/index/install.ajax.phtml'); return $model; }
[ "public", "function", "installAction", "(", ")", "{", "$", "form", "=", "$", "this", "->", "installForm", ";", "$", "form", "->", "setData", "(", "$", "_POST", ")", ";", "if", "(", "!", "$", "form", "->", "isValid", "(", ")", ")", "{", "return", ...
Main working action. Creates the configuration. @return ResponseInterface|ViewModel
[ "Main", "working", "action", ".", "Creates", "the", "configuration", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Index.php#L114-L155
train
yawik/install
src/Controller/Index.php
Index.createViewModel
protected function createViewModel(array $params, $terminal = false) { if (!isset($params['lang'])) { $params['lang'] = $this->params('lang'); } $model = new ViewModel($params); $terminal && $model->setTerminal($terminal); return $model; }
php
protected function createViewModel(array $params, $terminal = false) { if (!isset($params['lang'])) { $params['lang'] = $this->params('lang'); } $model = new ViewModel($params); $terminal && $model->setTerminal($terminal); return $model; }
[ "protected", "function", "createViewModel", "(", "array", "$", "params", ",", "$", "terminal", "=", "false", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "'lang'", "]", ")", ")", "{", "$", "params", "[", "'lang'", "]", "=", "$", "thi...
Creates a view model @param array $params @param bool $terminal @return ViewModel
[ "Creates", "a", "view", "model" ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Index.php#L176-L187
train
yawik/install
src/Controller/Index.php
Index.createJsonResponse
protected function createJsonResponse(array $variables) { $response = $this->getResponse(); $json = Json::encode($variables); $response->setContent($json); return $response; }
php
protected function createJsonResponse(array $variables) { $response = $this->getResponse(); $json = Json::encode($variables); $response->setContent($json); return $response; }
[ "protected", "function", "createJsonResponse", "(", "array", "$", "variables", ")", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "json", "=", "Json", "::", "encode", "(", "$", "variables", ")", ";", "$", "response", ...
Create a json response object for ajax requests. @param array $variables @return \Zend\Stdlib\ResponseInterface
[ "Create", "a", "json", "response", "object", "for", "ajax", "requests", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Index.php#L196-L203
train
systemson/cache
src/Driver/Base/FileCache.php
FileCache.filesystem
public function filesystem(string $path = null) { if (!$this->filesystem instanceof Filesystem) { $local = new Local($path); $this->filesystem = new Filesystem($local); } return $this->filesystem; }
php
public function filesystem(string $path = null) { if (!$this->filesystem instanceof Filesystem) { $local = new Local($path); $this->filesystem = new Filesystem($local); } return $this->filesystem; }
[ "public", "function", "filesystem", "(", "string", "$", "path", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "filesystem", "instanceof", "Filesystem", ")", "{", "$", "local", "=", "new", "Local", "(", "$", "path", ")", ";", "$", "this", ...
Gets a Filesystem instance. @return instance Filesystem
[ "Gets", "a", "Filesystem", "instance", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/Base/FileCache.php#L37-L46
train
systemson/cache
src/Driver/Base/FileCache.php
FileCache.clear
public function clear() { foreach ($this->filesystem()->listContents() as $file) { $this->filesystem()->delete($file['path']); } return true; }
php
public function clear() { foreach ($this->filesystem()->listContents() as $file) { $this->filesystem()->delete($file['path']); } return true; }
[ "public", "function", "clear", "(", ")", "{", "foreach", "(", "$", "this", "->", "filesystem", "(", ")", "->", "listContents", "(", ")", "as", "$", "file", ")", "{", "$", "this", "->", "filesystem", "(", ")", "->", "delete", "(", "$", "file", "[", ...
Deletes the cache folder. @return bool True on success and false on failure.
[ "Deletes", "the", "cache", "folder", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/Base/FileCache.php#L129-L136
train
systemson/cache
src/Driver/Base/FileCache.php
FileCache.has
public function has($key) { /* If $key is not valid string throws InvalidArgumentException */ if (!$this->isString($key)) { throw new InvalidArgumentException('Cache key must be not empty string'); } if ($this->getRaw($key)) { return true; } return false; }
php
public function has($key) { /* If $key is not valid string throws InvalidArgumentException */ if (!$this->isString($key)) { throw new InvalidArgumentException('Cache key must be not empty string'); } if ($this->getRaw($key)) { return true; } return false; }
[ "public", "function", "has", "(", "$", "key", ")", "{", "/* If $key is not valid string throws InvalidArgumentException */", "if", "(", "!", "$", "this", "->", "isString", "(", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cache key...
Whether an item is present in the cache. @param string $key The cache item key. @throws \Psr\SimpleCache\InvalidArgumentException @return bool
[ "Whether", "an", "item", "is", "present", "in", "the", "cache", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/Base/FileCache.php#L147-L159
train
systemson/cache
src/Driver/Base/FileCache.php
FileCache.getCachedItem
public function getCachedItem($key) { $path = sha1($key); if ($this->filesystem()->has($path)) { $item = explode(PHP_EOL, $this->filesystem()->read($path), 2); return new CacheItemClass($key, $item[1] ?? null, $item[0] ?? null); } }
php
public function getCachedItem($key) { $path = sha1($key); if ($this->filesystem()->has($path)) { $item = explode(PHP_EOL, $this->filesystem()->read($path), 2); return new CacheItemClass($key, $item[1] ?? null, $item[0] ?? null); } }
[ "public", "function", "getCachedItem", "(", "$", "key", ")", "{", "$", "path", "=", "sha1", "(", "$", "key", ")", ";", "if", "(", "$", "this", "->", "filesystem", "(", ")", "->", "has", "(", "$", "path", ")", ")", "{", "$", "item", "=", "explod...
Returns a CacheItemClass for the. @param string $key The cache item key. @throws \Psr\SimpleCache\InvalidArgumentException @return CacheItemInterface
[ "Returns", "a", "CacheItemClass", "for", "the", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/Base/FileCache.php#L170-L179
train
systemson/cache
src/Driver/Base/FileCache.php
FileCache.isExpired
public function isExpired(CacheItemInterface $item) { if ($item->isExpired()) { $this->delete($item->getKey()); return true; } return false; }
php
public function isExpired(CacheItemInterface $item) { if ($item->isExpired()) { $this->delete($item->getKey()); return true; } return false; }
[ "public", "function", "isExpired", "(", "CacheItemInterface", "$", "item", ")", "{", "if", "(", "$", "item", "->", "isExpired", "(", ")", ")", "{", "$", "this", "->", "delete", "(", "$", "item", "->", "getKey", "(", ")", ")", ";", "return", "true", ...
Whether an item from the cache is expired. If it does, deletes it from the file system. @param CacheItemInterface $item The item to evaluate. @return
[ "Whether", "an", "item", "from", "the", "cache", "is", "expired", ".", "If", "it", "does", "deletes", "it", "from", "the", "file", "system", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/Base/FileCache.php#L188-L197
train
yawik/install
src/Controller/Plugin/Prerequisites.php
Prerequisites.check
public function check($directories = null) { null == $directories && $directories = $this->directories; $return = array(); $valid = true; foreach ($directories as $path => $validationSpec) { $result = $this->checkDirectory($path, $validationSpec); $return['directories'][$path] = $result; $valid = $valid && $result['valid']; } $return['valid'] = $valid; return $return; }
php
public function check($directories = null) { null == $directories && $directories = $this->directories; $return = array(); $valid = true; foreach ($directories as $path => $validationSpec) { $result = $this->checkDirectory($path, $validationSpec); $return['directories'][$path] = $result; $valid = $valid && $result['valid']; } $return['valid'] = $valid; return $return; }
[ "public", "function", "check", "(", "$", "directories", "=", "null", ")", "{", "null", "==", "$", "directories", "&&", "$", "directories", "=", "$", "this", "->", "directories", ";", "$", "return", "=", "array", "(", ")", ";", "$", "valid", "=", "tru...
Checks directories. Calls {@link checkDirectory()} for each directory in the array. Checks, if all directories has passed as valid according to the specs. @param null|array $directories @return array
[ "Checks", "directories", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/Prerequisites.php#L63-L77
train
yawik/install
src/Controller/Plugin/Prerequisites.php
Prerequisites.checkDirectory
public function checkDirectory($dir, $validationSpec) { $exists = file_exists($dir); $writable = $exists && is_writable($dir); $missing = !$exists; $creatable = $missing && is_writable(dirname($dir)); $return = array( 'exists' => $exists, 'writable' => $writable, 'missing' => $missing, 'creatable' => $creatable ); $return['valid'] = $this->validateDirectory($return, $validationSpec); return $return; }
php
public function checkDirectory($dir, $validationSpec) { $exists = file_exists($dir); $writable = $exists && is_writable($dir); $missing = !$exists; $creatable = $missing && is_writable(dirname($dir)); $return = array( 'exists' => $exists, 'writable' => $writable, 'missing' => $missing, 'creatable' => $creatable ); $return['valid'] = $this->validateDirectory($return, $validationSpec); return $return; }
[ "public", "function", "checkDirectory", "(", "$", "dir", ",", "$", "validationSpec", ")", "{", "$", "exists", "=", "file_exists", "(", "$", "dir", ")", ";", "$", "writable", "=", "$", "exists", "&&", "is_writable", "(", "$", "dir", ")", ";", "$", "mi...
Checks a directory. @param string $dir @param string $validationSpec @return array
[ "Checks", "a", "directory", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/Prerequisites.php#L87-L104
train
yawik/install
src/Controller/Plugin/Prerequisites.php
Prerequisites.validateDirectory
public function validateDirectory($result, $spec) { $spec = explode('|', $spec); $valid = false; foreach ($spec as $s) { if (isset($result[$s]) && $result[$s]) { $valid = true; break; } } return $valid; }
php
public function validateDirectory($result, $spec) { $spec = explode('|', $spec); $valid = false; foreach ($spec as $s) { if (isset($result[$s]) && $result[$s]) { $valid = true; break; } } return $valid; }
[ "public", "function", "validateDirectory", "(", "$", "result", ",", "$", "spec", ")", "{", "$", "spec", "=", "explode", "(", "'|'", ",", "$", "spec", ")", ";", "$", "valid", "=", "false", ";", "foreach", "(", "$", "spec", "as", "$", "s", ")", "{"...
Validates a directory according to the spec @param array $result @param string $spec @return bool
[ "Validates", "a", "directory", "according", "to", "the", "spec" ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/Prerequisites.php#L114-L127
train
n2n/n2n-web
src/app/n2n/web/http/Response.php
Response.serverPush
public function serverPush(ServerPushDirective $directive) { if ($this->request->getProtocolVersion()->getMajorNum() < 2) { return; } $this->setHeader($directive->toHeader()); }
php
public function serverPush(ServerPushDirective $directive) { if ($this->request->getProtocolVersion()->getMajorNum() < 2) { return; } $this->setHeader($directive->toHeader()); }
[ "public", "function", "serverPush", "(", "ServerPushDirective", "$", "directive", ")", "{", "if", "(", "$", "this", "->", "request", "->", "getProtocolVersion", "(", ")", "->", "getMajorNum", "(", ")", "<", "2", ")", "{", "return", ";", "}", "$", "this",...
Server push will be ignored if HTTP version of request is lower than 2 or if sever push is disabled in app.ini @param ServerPushDirective $directive
[ "Server", "push", "will", "be", "ignored", "if", "HTTP", "version", "of", "request", "is", "lower", "than", "2", "or", "if", "sever", "push", "is", "disabled", "in", "app", ".", "ini" ]
1640c79f05d10d73093b98b70860ef8076d23e81
https://github.com/n2n/n2n-web/blob/1640c79f05d10d73093b98b70860ef8076d23e81/src/app/n2n/web/http/Response.php#L493-L499
train
yawik/install
src/Listener/LanguageSetter.php
LanguageSetter.onRoute
public function onRoute(MvcEvent $e) { /* @var $request \Zend\Http\PhpEnvironment\Request */ $request = $e->getRequest(); /* Detect language */ $lang = $request->getQuery('lang'); if (!$lang) { $headers = $request->getHeaders(); if ($headers->has('Accept-Language')) { /* @var $acceptLangs \Zend\Http\Header\AcceptLanguage */ $acceptLangs = $headers->get('Accept-Language'); $locales = $acceptLangs->getPrioritized(); $locale = $locales[0]; $lang = $locale->type; } else { $lang = 'en'; } } /* Set locale */ $translator = $e->getApplication()->getServiceManager()->get('mvctranslator'); $locale = $lang . '_' . strtoupper($lang); setlocale( LC_ALL, array( $locale . ".utf8", $locale . ".iso88591", $locale, substr($locale, 0, 2), 'de_DE.utf8', 'de_DE', 'de' ) ); \Locale::setDefault($locale); $translator->setLocale($locale); $routeMatch = $e->getRouteMatch(); if ($routeMatch && $routeMatch->getParam('lang') === null) { $routeMatch->setParam('lang', $lang); } /* @var $router \Zend\Mvc\Router\SimpleRouteStack */ $router = $e->getRouter(); $router->setDefaultParam('lang', $lang); }
php
public function onRoute(MvcEvent $e) { /* @var $request \Zend\Http\PhpEnvironment\Request */ $request = $e->getRequest(); /* Detect language */ $lang = $request->getQuery('lang'); if (!$lang) { $headers = $request->getHeaders(); if ($headers->has('Accept-Language')) { /* @var $acceptLangs \Zend\Http\Header\AcceptLanguage */ $acceptLangs = $headers->get('Accept-Language'); $locales = $acceptLangs->getPrioritized(); $locale = $locales[0]; $lang = $locale->type; } else { $lang = 'en'; } } /* Set locale */ $translator = $e->getApplication()->getServiceManager()->get('mvctranslator'); $locale = $lang . '_' . strtoupper($lang); setlocale( LC_ALL, array( $locale . ".utf8", $locale . ".iso88591", $locale, substr($locale, 0, 2), 'de_DE.utf8', 'de_DE', 'de' ) ); \Locale::setDefault($locale); $translator->setLocale($locale); $routeMatch = $e->getRouteMatch(); if ($routeMatch && $routeMatch->getParam('lang') === null) { $routeMatch->setParam('lang', $lang); } /* @var $router \Zend\Mvc\Router\SimpleRouteStack */ $router = $e->getRouter(); $router->setDefaultParam('lang', $lang); }
[ "public", "function", "onRoute", "(", "MvcEvent", "$", "e", ")", "{", "/* @var $request \\Zend\\Http\\PhpEnvironment\\Request */", "$", "request", "=", "$", "e", "->", "getRequest", "(", ")", ";", "/* Detect language */", "$", "lang", "=", "$", "request", "->", ...
Listens to the route event. Detects the language to use and sets translator locale. The language is detected either via query parameter "lang" or browser setting (ACCEPT-LANGUAGE header) @param MvcEvent $e
[ "Listens", "to", "the", "route", "event", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Listener/LanguageSetter.php#L59-L106
train
systemson/cache
src/Driver/ApcuCache.php
ApcuCache.isCli
public static function isCli() { if (defined('STDIN')) { return true; } if (php_sapi_name() === 'cli') { return true; } if (array_key_exists('SHELL', $_ENV)) { return true; } if (empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) { return true; } if (!array_key_exists('REQUEST_METHOD', $_SERVER)) { return true; } return false; }
php
public static function isCli() { if (defined('STDIN')) { return true; } if (php_sapi_name() === 'cli') { return true; } if (array_key_exists('SHELL', $_ENV)) { return true; } if (empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) { return true; } if (!array_key_exists('REQUEST_METHOD', $_SERVER)) { return true; } return false; }
[ "public", "static", "function", "isCli", "(", ")", "{", "if", "(", "defined", "(", "'STDIN'", ")", ")", "{", "return", "true", ";", "}", "if", "(", "php_sapi_name", "(", ")", "===", "'cli'", ")", "{", "return", "true", ";", "}", "if", "(", "array_k...
Determines whether the script is being run on the CLI. @todo This method MUST be move to a helper. @return bool
[ "Determines", "whether", "the", "script", "is", "being", "run", "on", "the", "CLI", "." ]
a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c
https://github.com/systemson/cache/blob/a85de2648fe8c1f73be6cfdcea4d1ee27e42f15c/src/Driver/ApcuCache.php#L130-L153
train
yawik/install
src/Controller/Plugin/YawikConfigCreator.php
YawikConfigCreator.process
public function process($dbConn, $email) { // extract database $dbName = $this->dbNameExctractor->filter($dbConn); $config = array( 'doctrine' => array( 'connection' => array( 'odm_default' => array( 'connectionString' => $dbConn, ), ), 'configuration' => array( 'odm_default' => array( 'default_db' => $dbName, ), ), ), 'core_options' => array( 'system_message_email' => $email, ), ); $content = $this->generateConfigContent($config); $ok = $this->writeConfigFile($content); return $ok ? true : $content; }
php
public function process($dbConn, $email) { // extract database $dbName = $this->dbNameExctractor->filter($dbConn); $config = array( 'doctrine' => array( 'connection' => array( 'odm_default' => array( 'connectionString' => $dbConn, ), ), 'configuration' => array( 'odm_default' => array( 'default_db' => $dbName, ), ), ), 'core_options' => array( 'system_message_email' => $email, ), ); $content = $this->generateConfigContent($config); $ok = $this->writeConfigFile($content); return $ok ? true : $content; }
[ "public", "function", "process", "(", "$", "dbConn", ",", "$", "email", ")", "{", "// extract database", "$", "dbName", "=", "$", "this", "->", "dbNameExctractor", "->", "filter", "(", "$", "dbConn", ")", ";", "$", "config", "=", "array", "(", "'doctrine...
Generates a configuration file. @param string $dbConn @param string $email @return bool|string
[ "Generates", "a", "configuration", "file", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/YawikConfigCreator.php#L52-L80
train
yawik/install
src/Controller/Plugin/YawikConfigCreator.php
YawikConfigCreator.generateConfigContent
protected function generateConfigContent(array $config) { /* This code is taken from ZF2s' classmap_generator.php script. */ // Create a file with the class/file map. // Stupid syntax highlighters make separating < from PHP declaration necessary $content = '<' . "?php\n" . "\n" . 'return ' . var_export($config, true) . ';'; // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); // Remove unnecessary double-backslashes $content = str_replace('\\\\', '\\', $content); // Exchange "array (" width "array(" $content = str_replace('array (', 'array(', $content); // Make the file end by EOL $content = rtrim($content, "\n") . "\n"; var_export($config, true); return $content; }
php
protected function generateConfigContent(array $config) { /* This code is taken from ZF2s' classmap_generator.php script. */ // Create a file with the class/file map. // Stupid syntax highlighters make separating < from PHP declaration necessary $content = '<' . "?php\n" . "\n" . 'return ' . var_export($config, true) . ';'; // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); // Remove unnecessary double-backslashes $content = str_replace('\\\\', '\\', $content); // Exchange "array (" width "array(" $content = str_replace('array (', 'array(', $content); // Make the file end by EOL $content = rtrim($content, "\n") . "\n"; var_export($config, true); return $content; }
[ "protected", "function", "generateConfigContent", "(", "array", "$", "config", ")", "{", "/* This code is taken from ZF2s' classmap_generator.php script. */", "// Create a file with the class/file map.", "// Stupid syntax highlighters make separating < from PHP declaration necessary", "$", ...
Generates the content for the configuration file. @param array $config @return string
[ "Generates", "the", "content", "for", "the", "configuration", "file", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/YawikConfigCreator.php#L89-L115
train
yawik/install
src/Controller/Plugin/YawikConfigCreator.php
YawikConfigCreator.writeConfigFile
protected function writeConfigFile($content) { if (!is_writable('config/autoload')) { return false; } $file = 'config/autoload/yawik.config.global.php'; // need to chmod 777 to be usable by docker and local environment @touch($file); @chmod($file, 0777); return (bool) @file_put_contents($file, $content, LOCK_EX); }
php
protected function writeConfigFile($content) { if (!is_writable('config/autoload')) { return false; } $file = 'config/autoload/yawik.config.global.php'; // need to chmod 777 to be usable by docker and local environment @touch($file); @chmod($file, 0777); return (bool) @file_put_contents($file, $content, LOCK_EX); }
[ "protected", "function", "writeConfigFile", "(", "$", "content", ")", "{", "if", "(", "!", "is_writable", "(", "'config/autoload'", ")", ")", "{", "return", "false", ";", "}", "$", "file", "=", "'config/autoload/yawik.config.global.php'", ";", "// need to chmod 77...
Writes the configuration content in a file. Returns false, if file cannot be created. @param string $content @return bool
[ "Writes", "the", "configuration", "content", "in", "a", "file", "." ]
1283d512a852d305e18d311c3eb1a84da98b9656
https://github.com/yawik/install/blob/1283d512a852d305e18d311c3eb1a84da98b9656/src/Controller/Plugin/YawikConfigCreator.php#L126-L137
train
elgentos/parser
src/Parser/StoryMetrics.php
StoryMetrics.addStories
public function addStories(Story ...$stories): void { \array_walk($stories, function ($story) { $this->stories[] = $story; $this->storyCount++; }); }
php
public function addStories(Story ...$stories): void { \array_walk($stories, function ($story) { $this->stories[] = $story; $this->storyCount++; }); }
[ "public", "function", "addStories", "(", "Story", "...", "$", "stories", ")", ":", "void", "{", "\\", "array_walk", "(", "$", "stories", ",", "function", "(", "$", "story", ")", "{", "$", "this", "->", "stories", "[", "]", "=", "$", "story", ";", "...
Add story to book @param []Story ...$stories
[ "Add", "story", "to", "book" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser/StoryMetrics.php#L26-L32
train
elgentos/parser
src/Parser/StoryMetrics.php
StoryMetrics.createStory
public function createStory(string $name, RuleInterface ...$rules): Story { $story = new Story($name, ...$rules); $this->addStories($story); return $story; }
php
public function createStory(string $name, RuleInterface ...$rules): Story { $story = new Story($name, ...$rules); $this->addStories($story); return $story; }
[ "public", "function", "createStory", "(", "string", "$", "name", ",", "RuleInterface", "...", "$", "rules", ")", ":", "Story", "{", "$", "story", "=", "new", "Story", "(", "$", "name", ",", "...", "$", "rules", ")", ";", "$", "this", "->", "addStorie...
Create a story from rules and add to book @param string $name @param RuleInterface ...$rules @return Story
[ "Create", "a", "story", "from", "rules", "and", "add", "to", "book" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser/StoryMetrics.php#L41-L47
train
elgentos/parser
src/Parser/StoryMetrics.php
StoryMetrics.getStoriesSortedByName
private function getStoriesSortedByName(): array { $stories = $this->stories; \usort($stories, function(Story $storyA, Story $storyB) { return $storyA->getName() <=> $storyB->getName(); }); return $stories; }
php
private function getStoriesSortedByName(): array { $stories = $this->stories; \usort($stories, function(Story $storyA, Story $storyB) { return $storyA->getName() <=> $storyB->getName(); }); return $stories; }
[ "private", "function", "getStoriesSortedByName", "(", ")", ":", "array", "{", "$", "stories", "=", "$", "this", "->", "stories", ";", "\\", "usort", "(", "$", "stories", ",", "function", "(", "Story", "$", "storyA", ",", "Story", "$", "storyB", ")", "{...
Sort stories by name @return array
[ "Sort", "stories", "by", "name" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser/StoryMetrics.php#L130-L138
train
elgentos/parser
src/Parser.php
Parser.readFile
public static function readFile(string $filename, string $rootDir = '.', ParserInterface $parser = null): array { $data = ['@import' => $filename]; $story = new Complex($rootDir); $parser = $parser ?? new Standard; $parser->parse($data, $story); return $data; }
php
public static function readFile(string $filename, string $rootDir = '.', ParserInterface $parser = null): array { $data = ['@import' => $filename]; $story = new Complex($rootDir); $parser = $parser ?? new Standard; $parser->parse($data, $story); return $data; }
[ "public", "static", "function", "readFile", "(", "string", "$", "filename", ",", "string", "$", "rootDir", "=", "'.'", ",", "ParserInterface", "$", "parser", "=", "null", ")", ":", "array", "{", "$", "data", "=", "[", "'@import'", "=>", "$", "filename", ...
Read a file in a given basedir defaults to current workdir optional, give a own parser if you want to debug @param string $filename @param string $rootDir @param ParserInterface|null $parser @return array
[ "Read", "a", "file", "in", "a", "given", "basedir", "defaults", "to", "current", "workdir" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser.php#L33-L42
train
elgentos/parser
src/Parser.php
Parser.readSimple
public static function readSimple(string $filename, string $rootDir = '.', ParserInterface $parser = null): array { $data = ['@import' => $filename]; $story = new Simple($rootDir); $parser = $parser ?? new Standard; $parser->parse($data, $story); return $data; }
php
public static function readSimple(string $filename, string $rootDir = '.', ParserInterface $parser = null): array { $data = ['@import' => $filename]; $story = new Simple($rootDir); $parser = $parser ?? new Standard; $parser->parse($data, $story); return $data; }
[ "public", "static", "function", "readSimple", "(", "string", "$", "filename", ",", "string", "$", "rootDir", "=", "'.'", ",", "ParserInterface", "$", "parser", "=", "null", ")", ":", "array", "{", "$", "data", "=", "[", "'@import'", "=>", "$", "filename"...
Read a file without recursion @param string $filename @param string $rootDir @param ParserInterface|null $parser @return array
[ "Read", "a", "file", "without", "recursion" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser.php#L52-L61
train
elgentos/parser
src/Parser/Rule/FileAbstract.php
FileAbstract.safePath
private function safePath(string $path): string { while (($newPath = \str_replace('..', '', $path)) !== $path) { $path = $newPath; } return $path; }
php
private function safePath(string $path): string { while (($newPath = \str_replace('..', '', $path)) !== $path) { $path = $newPath; } return $path; }
[ "private", "function", "safePath", "(", "string", "$", "path", ")", ":", "string", "{", "while", "(", "(", "$", "newPath", "=", "\\", "str_replace", "(", "'..'", ",", "''", ",", "$", "path", ")", ")", "!==", "$", "path", ")", "{", "$", "path", "=...
Filter nasty strings from path @param string $path @return string
[ "Filter", "nasty", "strings", "from", "path" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser/Rule/FileAbstract.php#L22-L29
train
elgentos/parser
src/Parser/Rule/MergeDown.php
MergeDown.niceMerge
private function niceMerge(array &$source, array &$destination): array { $merged = $source; foreach ($destination as $key => &$value) { if ( $this->mergeRecursive && isset($merged[$key]) && is_array($merged[$key]) ) { $merged[$key] = $this->niceMerge($source[$key], $value); continue; } $merged[$key] = $value; } return $merged; }
php
private function niceMerge(array &$source, array &$destination): array { $merged = $source; foreach ($destination as $key => &$value) { if ( $this->mergeRecursive && isset($merged[$key]) && is_array($merged[$key]) ) { $merged[$key] = $this->niceMerge($source[$key], $value); continue; } $merged[$key] = $value; } return $merged; }
[ "private", "function", "niceMerge", "(", "array", "&", "$", "source", ",", "array", "&", "$", "destination", ")", ":", "array", "{", "$", "merged", "=", "$", "source", ";", "foreach", "(", "$", "destination", "as", "$", "key", "=>", "&", "$", "value"...
Recursive nice merge @param array $source @param array $destination @return array
[ "Recursive", "nice", "merge" ]
3580a4f55c725123eab643628d1fc3d5dd0968b3
https://github.com/elgentos/parser/blob/3580a4f55c725123eab643628d1fc3d5dd0968b3/src/Parser/Rule/MergeDown.php#L65-L83
train
KnpLabs/KnpPiwikBundle
DependencyInjection/KnpPiwikExtension.php
KnpPiwikExtension.load
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (!$container->hasDefinition('piwik.client')) { $loader->load('piwik.xml'); } $config = $this->mergeConfigs($configs); if (isset($config['connection'])) { $definition = $container->getDefinition('piwik.client'); $arguments = $definition->getArguments(); $arguments[0] = new Reference($config['connection']); $definition->setArguments($arguments); } if (isset($config['url'])) { $container->setParameter('piwik.connection.http.url', $config['url']); } if (isset($config['init'])) { $container->setParameter('piwik.connection.piwik.init', (bool) $config['init']); } if (isset($config['token'])) { $container->setParameter('piwik.client.token', $config['token']); } }
php
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (!$container->hasDefinition('piwik.client')) { $loader->load('piwik.xml'); } $config = $this->mergeConfigs($configs); if (isset($config['connection'])) { $definition = $container->getDefinition('piwik.client'); $arguments = $definition->getArguments(); $arguments[0] = new Reference($config['connection']); $definition->setArguments($arguments); } if (isset($config['url'])) { $container->setParameter('piwik.connection.http.url', $config['url']); } if (isset($config['init'])) { $container->setParameter('piwik.connection.piwik.init', (bool) $config['init']); } if (isset($config['token'])) { $container->setParameter('piwik.client.token', $config['token']); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "loader", "=", "new", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ...
Loads the piwik configuration. @param array $config An array of configuration settings @param \Symfony\Component\DependencyInjection\ContainerBuilder $container A ContainerBuilder instance
[ "Loads", "the", "piwik", "configuration", "." ]
e905ed745237fb6fc71175a5b571b771b97b3f7f
https://github.com/KnpLabs/KnpPiwikBundle/blob/e905ed745237fb6fc71175a5b571b771b97b3f7f/DependencyInjection/KnpPiwikExtension.php#L28-L56
train
KnpLabs/KnpPiwikBundle
DependencyInjection/KnpPiwikExtension.php
KnpPiwikExtension.mergeConfigs
protected function mergeConfigs(array $configs) { $merged = array(); foreach ($configs as $config) { $merged = array_merge($merged, $config); } return $merged; }
php
protected function mergeConfigs(array $configs) { $merged = array(); foreach ($configs as $config) { $merged = array_merge($merged, $config); } return $merged; }
[ "protected", "function", "mergeConfigs", "(", "array", "$", "configs", ")", "{", "$", "merged", "=", "array", "(", ")", ";", "foreach", "(", "$", "configs", "as", "$", "config", ")", "{", "$", "merged", "=", "array_merge", "(", "$", "merged", ",", "$...
Merges the given configurations array @param array $config @return array
[ "Merges", "the", "given", "configurations", "array" ]
e905ed745237fb6fc71175a5b571b771b97b3f7f
https://github.com/KnpLabs/KnpPiwikBundle/blob/e905ed745237fb6fc71175a5b571b771b97b3f7f/DependencyInjection/KnpPiwikExtension.php#L65-L73
train
matthiasnoback/phpunit-asynchronicity
src/Asynchronicity/Polling/Poller.php
Poller.poll
public function poll(callable $probe, Timeout $timeout): void { $timeout->start(); $lastException = null; while (true) { try { $probe(); // the probe was successful, so we can return now return; } catch (Exception $exception) { // the probe was unsuccessful, we remember the last exception $lastException = $exception; } if ($timeout->hasTimedOut()) { throw new Interrupted('A timeout has occurred', 0, $lastException); } // we wait before trying again $timeout->wait(); } }
php
public function poll(callable $probe, Timeout $timeout): void { $timeout->start(); $lastException = null; while (true) { try { $probe(); // the probe was successful, so we can return now return; } catch (Exception $exception) { // the probe was unsuccessful, we remember the last exception $lastException = $exception; } if ($timeout->hasTimedOut()) { throw new Interrupted('A timeout has occurred', 0, $lastException); } // we wait before trying again $timeout->wait(); } }
[ "public", "function", "poll", "(", "callable", "$", "probe", ",", "Timeout", "$", "timeout", ")", ":", "void", "{", "$", "timeout", "->", "start", "(", ")", ";", "$", "lastException", "=", "null", ";", "while", "(", "true", ")", "{", "try", "{", "$...
Invoke the provided callable until it doesn't throw an exception anymore, or a timeout occurs. The poller will wait before invoking the callable again. @param callable $probe @param Timeout $timeout
[ "Invoke", "the", "provided", "callable", "until", "it", "doesn", "t", "throw", "an", "exception", "anymore", "or", "a", "timeout", "occurs", ".", "The", "poller", "will", "wait", "before", "invoking", "the", "callable", "again", "." ]
b7f7ff4485de7d569be18e4343855c1fcbe05c14
https://github.com/matthiasnoback/phpunit-asynchronicity/blob/b7f7ff4485de7d569be18e4343855c1fcbe05c14/src/Asynchronicity/Polling/Poller.php#L17-L40
train
KnpLabs/PiwikClient
src/Knp/PiwikClient/Client.php
Client.call
public function call($method, array $params = array(), $format = 'php') { $params['method'] = $method; $params['token_auth'] = $this->token; $params['format'] = $format; $data = $this->getConnection()->send($params); if ('php' === $format) { $object = unserialize($data); if (isset($object['result']) && 'error' === $object['result']) { throw new Exception($object['message']); } return $object; } else { return $data; } }
php
public function call($method, array $params = array(), $format = 'php') { $params['method'] = $method; $params['token_auth'] = $this->token; $params['format'] = $format; $data = $this->getConnection()->send($params); if ('php' === $format) { $object = unserialize($data); if (isset($object['result']) && 'error' === $object['result']) { throw new Exception($object['message']); } return $object; } else { return $data; } }
[ "public", "function", "call", "(", "$", "method", ",", "array", "$", "params", "=", "array", "(", ")", ",", "$", "format", "=", "'php'", ")", "{", "$", "params", "[", "'method'", "]", "=", "$", "method", ";", "$", "params", "[", "'token_auth'", "]"...
Call specific method & return it's response. @param string $method method name @param array $params method parameters @param string $format return format (php, json, xml, csv, tsv, html, rss) @return mixed
[ "Call", "specific", "method", "&", "return", "it", "s", "response", "." ]
853f427b7506141477dc2a699945be1473baa8d3
https://github.com/KnpLabs/PiwikClient/blob/853f427b7506141477dc2a699945be1473baa8d3/src/Knp/PiwikClient/Client.php#L49-L68
train
KnpLabs/PiwikClient
src/Knp/PiwikClient/Connection/PiwikConnection.php
PiwikConnection.convertParamsToQuery
protected function convertParamsToQuery(array $params) { $query = array(); foreach ($params as $key => $val) { if (is_array($val)) { $val = implode(',', $val); } elseif ($val instanceof \DateTime) { $val = $val->format('Y-m-d'); } elseif (is_bool($val)) { if ($val) { $val = 1; } else { continue; } } else { $val = urlencode($val); } $query[] = $key . '=' . $val; } return implode('&', $query); }
php
protected function convertParamsToQuery(array $params) { $query = array(); foreach ($params as $key => $val) { if (is_array($val)) { $val = implode(',', $val); } elseif ($val instanceof \DateTime) { $val = $val->format('Y-m-d'); } elseif (is_bool($val)) { if ($val) { $val = 1; } else { continue; } } else { $val = urlencode($val); } $query[] = $key . '=' . $val; } return implode('&', $query); }
[ "protected", "function", "convertParamsToQuery", "(", "array", "$", "params", ")", "{", "$", "query", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ...
Convert hash of parameters to query string. @param array $params hash @return string query string
[ "Convert", "hash", "of", "parameters", "to", "query", "string", "." ]
853f427b7506141477dc2a699945be1473baa8d3
https://github.com/KnpLabs/PiwikClient/blob/853f427b7506141477dc2a699945be1473baa8d3/src/Knp/PiwikClient/Connection/PiwikConnection.php#L47-L69
train
fillup/walmart-partner-api-sdk-php
src/mock/MockResponse.php
MockResponse.getResourceTypeFromUrl
public static function getResourceTypeFromUrl($url) { $matchFound = preg_match('/\/v[23]\/(\w+)[\/?]?/', $url, $matches); if( ! $matchFound || ! is_array($matches) || ! isset($matches[1])) { throw new \Exception('Unable to find resource type in url', 1462733277); } if ($matches[1] == 'getReport') { return 'report'; } elseif ($matches[1] == 'price') { return 'prices'; } return $matches[1]; }
php
public static function getResourceTypeFromUrl($url) { $matchFound = preg_match('/\/v[23]\/(\w+)[\/?]?/', $url, $matches); if( ! $matchFound || ! is_array($matches) || ! isset($matches[1])) { throw new \Exception('Unable to find resource type in url', 1462733277); } if ($matches[1] == 'getReport') { return 'report'; } elseif ($matches[1] == 'price') { return 'prices'; } return $matches[1]; }
[ "public", "static", "function", "getResourceTypeFromUrl", "(", "$", "url", ")", "{", "$", "matchFound", "=", "preg_match", "(", "'/\\/v[23]\\/(\\w+)[\\/?]?/'", ",", "$", "url", ",", "$", "matches", ")", ";", "if", "(", "!", "$", "matchFound", "||", "!", "i...
Parse resource type out of url @param string $url @return string @throws \Exception
[ "Parse", "resource", "type", "out", "of", "url" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/mock/MockResponse.php#L94-L108
train
fillup/walmart-partner-api-sdk-php
src/mock/MockResponse.php
MockResponse.getPath
public static function getPath($url) { $matchFound = preg_match('/(\/v[23]\/.*$)/', $url, $matches); if( ! $matchFound || ! is_array($matches) || ! isset($matches[1])) { throw new \Exception('Unable to parse url path', 1462733286); } return $matches[1]; }
php
public static function getPath($url) { $matchFound = preg_match('/(\/v[23]\/.*$)/', $url, $matches); if( ! $matchFound || ! is_array($matches) || ! isset($matches[1])) { throw new \Exception('Unable to parse url path', 1462733286); } return $matches[1]; }
[ "public", "static", "function", "getPath", "(", "$", "url", ")", "{", "$", "matchFound", "=", "preg_match", "(", "'/(\\/v[23]\\/.*$)/'", ",", "$", "url", ",", "$", "matches", ")", ";", "if", "(", "!", "$", "matchFound", "||", "!", "is_array", "(", "$",...
Parse request path out of url @param string $url @return string @throws \Exception
[ "Parse", "request", "path", "out", "of", "url" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/mock/MockResponse.php#L116-L124
train
fillup/walmart-partner-api-sdk-php
src/BaseClient.php
BaseClient.getEnvBaseUrl
public function getEnvBaseUrl($env) { switch ($env) { case self::ENV_PROD: return self::BASE_URL_PROD; case self::ENV_STAGE: return self::BASE_URL_STAGE; case self::ENV_MOCK: return null; } }
php
public function getEnvBaseUrl($env) { switch ($env) { case self::ENV_PROD: return self::BASE_URL_PROD; case self::ENV_STAGE: return self::BASE_URL_STAGE; case self::ENV_MOCK: return null; } }
[ "public", "function", "getEnvBaseUrl", "(", "$", "env", ")", "{", "switch", "(", "$", "env", ")", "{", "case", "self", "::", "ENV_PROD", ":", "return", "self", "::", "BASE_URL_PROD", ";", "case", "self", "::", "ENV_STAGE", ":", "return", "self", "::", ...
Get baseUrl for given environment @param string $env @return null|string
[ "Get", "baseUrl", "for", "given", "environment" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/BaseClient.php#L93-L103
train
fillup/walmart-partner-api-sdk-php
src/Order.php
Order.listReleased
public function listReleased(array $config = []) { try { return $this->privateListReleased($config); } catch (\Exception $e) { if ($e instanceof RequestException) { /* * ListReleased and List return 404 error if no results are found, even for successful API calls, * So if result status is 404, transform to 200 with empty results. */ /** @var ResponseInterface $response */ $response = $e->getResponse(); if (strval($response->getStatusCode()) === '404') { return [ 'statusCode' => 200, 'list' => [ 'meta' => [ 'totalCount' => 0 ] ], 'elements' => [] ]; } throw $e; } else { throw $e; } } }
php
public function listReleased(array $config = []) { try { return $this->privateListReleased($config); } catch (\Exception $e) { if ($e instanceof RequestException) { /* * ListReleased and List return 404 error if no results are found, even for successful API calls, * So if result status is 404, transform to 200 with empty results. */ /** @var ResponseInterface $response */ $response = $e->getResponse(); if (strval($response->getStatusCode()) === '404') { return [ 'statusCode' => 200, 'list' => [ 'meta' => [ 'totalCount' => 0 ] ], 'elements' => [] ]; } throw $e; } else { throw $e; } } }
[ "public", "function", "listReleased", "(", "array", "$", "config", "=", "[", "]", ")", "{", "try", "{", "return", "$", "this", "->", "privateListReleased", "(", "$", "config", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", ...
List released orders @param array $config @return array @throws \Exception
[ "List", "released", "orders" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/Order.php#L76-L104
train
fillup/walmart-partner-api-sdk-php
src/Order.php
Order.listAll
public function listAll(array $config = []) { try { return $this->privateList($config); } catch (\Exception $e) { if ($e instanceof RequestException) { /* * ListReleased and List return 404 error if no results are found, even for successful API calls, * So if result status is 404, transform to 200 with empty results. */ /** @var ResponseInterface $response */ $response = $e->getResponse(); if (strval($response->getStatusCode()) === '404') { return [ 'statusCode' => 200, 'list' => [ 'meta' => [ 'totalCount' => 0 ] ], 'elements' => [] ]; } throw $e; } else { throw $e; } } }
php
public function listAll(array $config = []) { try { return $this->privateList($config); } catch (\Exception $e) { if ($e instanceof RequestException) { /* * ListReleased and List return 404 error if no results are found, even for successful API calls, * So if result status is 404, transform to 200 with empty results. */ /** @var ResponseInterface $response */ $response = $e->getResponse(); if (strval($response->getStatusCode()) === '404') { return [ 'statusCode' => 200, 'list' => [ 'meta' => [ 'totalCount' => 0 ] ], 'elements' => [] ]; } throw $e; } else { throw $e; } } }
[ "public", "function", "listAll", "(", "array", "$", "config", "=", "[", "]", ")", "{", "try", "{", "return", "$", "this", "->", "privateList", "(", "$", "config", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$",...
List all orders @param array $config @return array @throws \Exception
[ "List", "all", "orders" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/Order.php#L112-L140
train
fillup/walmart-partner-api-sdk-php
src/Order.php
Order.ship
public function ship($purchaseOrderId, $order) { if(!is_numeric($purchaseOrderId)){ throw new \Exception("purchaseOrderId must be numeric",1448480750); } $schema = [ '/orderShipment' => [ 'namespace' => 'ns3', 'childNamespace' => 'ns3', ], '/orderShipment/orderLines' => [ 'sendItemsAs' => 'orderLine', ], '/orderShipment/orderLines/orderLine/orderLineStatuses' => [ 'sendItemsAs' => 'orderLineStatus', ], '@namespaces' => [ 'ns3' => 'http://walmart.com/mp/v3/orders' ], ]; $a2x = new A2X($order, $schema); $xml = $a2x->asXml(); return $this->shipOrder([ 'purchaseOrderId' => $purchaseOrderId, 'order' => $xml, ]); }
php
public function ship($purchaseOrderId, $order) { if(!is_numeric($purchaseOrderId)){ throw new \Exception("purchaseOrderId must be numeric",1448480750); } $schema = [ '/orderShipment' => [ 'namespace' => 'ns3', 'childNamespace' => 'ns3', ], '/orderShipment/orderLines' => [ 'sendItemsAs' => 'orderLine', ], '/orderShipment/orderLines/orderLine/orderLineStatuses' => [ 'sendItemsAs' => 'orderLineStatus', ], '@namespaces' => [ 'ns3' => 'http://walmart.com/mp/v3/orders' ], ]; $a2x = new A2X($order, $schema); $xml = $a2x->asXml(); return $this->shipOrder([ 'purchaseOrderId' => $purchaseOrderId, 'order' => $xml, ]); }
[ "public", "function", "ship", "(", "$", "purchaseOrderId", ",", "$", "order", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "purchaseOrderId", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"purchaseOrderId must be numeric\"", ",", "1448480750", ...
Ship an order @param string $purchaseOrderId @param array $order @return array @throws \Exception
[ "Ship", "an", "order" ]
8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7
https://github.com/fillup/walmart-partner-api-sdk-php/blob/8344dc8e7580364a6ad9ce6f3cf8f050e0a463c7/src/Order.php#L188-L217
train