repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
lelivrescolaire/SQSBundle
Model/Queue.php
Queue.getAttributes
public function getAttributes(array $attributes = array()) { $arguments = array( 'QueueUrl' => $this->getUrl(), 'AttributeNames' => $attributes ); $response = $this->sqs->getClient() ->getQueueAttributes($arguments); return $response->get('Attributes'); }
php
public function getAttributes(array $attributes = array()) { $arguments = array( 'QueueUrl' => $this->getUrl(), 'AttributeNames' => $attributes ); $response = $this->sqs->getClient() ->getQueueAttributes($arguments); return $response->get('Attributes'); }
[ "public", "function", "getAttributes", "(", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "$", "arguments", "=", "array", "(", "'QueueUrl'", "=>", "$", "this", "->", "getUrl", "(", ")", ",", "'AttributeNames'", "=>", "$", "attributes", ")", ";", "$", "response", "=", "$", "this", "->", "sqs", "->", "getClient", "(", ")", "->", "getQueueAttributes", "(", "$", "arguments", ")", ";", "return", "$", "response", "->", "get", "(", "'Attributes'", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lelivrescolaire/SQSBundle/blob/bba3fa6d63d0ae1bddbc7b2fe3c2e737f49d6559/Model/Queue.php#L177-L188
lelivrescolaire/SQSBundle
Model/Queue.php
Queue.fetchMessages
public function fetchMessages($nb=1, array $opt = array()) { $arguments = array( 'QueueUrl' => $this->getUrl(), 'MaxNumberOfMessages' => $nb, ); if ($opt) { $arguments = array_merge($opt, $arguments); } $response = $this->sqs->getClient()->receiveMessage($arguments); $service = $this; $messages = array(); if (!is_null($response->get('Messages'))) { $messages = array_map(function ($definition) use ($service) { return $service->getMessageFactory() ->create(trim($definition['Body'])) ->setId(trim($definition['MessageId'])) ->setReceipthandle(trim($definition['ReceiptHandle'])); }, $response->get('Messages')); } return $messages; }
php
public function fetchMessages($nb=1, array $opt = array()) { $arguments = array( 'QueueUrl' => $this->getUrl(), 'MaxNumberOfMessages' => $nb, ); if ($opt) { $arguments = array_merge($opt, $arguments); } $response = $this->sqs->getClient()->receiveMessage($arguments); $service = $this; $messages = array(); if (!is_null($response->get('Messages'))) { $messages = array_map(function ($definition) use ($service) { return $service->getMessageFactory() ->create(trim($definition['Body'])) ->setId(trim($definition['MessageId'])) ->setReceipthandle(trim($definition['ReceiptHandle'])); }, $response->get('Messages')); } return $messages; }
[ "public", "function", "fetchMessages", "(", "$", "nb", "=", "1", ",", "array", "$", "opt", "=", "array", "(", ")", ")", "{", "$", "arguments", "=", "array", "(", "'QueueUrl'", "=>", "$", "this", "->", "getUrl", "(", ")", ",", "'MaxNumberOfMessages'", "=>", "$", "nb", ",", ")", ";", "if", "(", "$", "opt", ")", "{", "$", "arguments", "=", "array_merge", "(", "$", "opt", ",", "$", "arguments", ")", ";", "}", "$", "response", "=", "$", "this", "->", "sqs", "->", "getClient", "(", ")", "->", "receiveMessage", "(", "$", "arguments", ")", ";", "$", "service", "=", "$", "this", ";", "$", "messages", "=", "array", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "response", "->", "get", "(", "'Messages'", ")", ")", ")", "{", "$", "messages", "=", "array_map", "(", "function", "(", "$", "definition", ")", "use", "(", "$", "service", ")", "{", "return", "$", "service", "->", "getMessageFactory", "(", ")", "->", "create", "(", "trim", "(", "$", "definition", "[", "'Body'", "]", ")", ")", "->", "setId", "(", "trim", "(", "$", "definition", "[", "'MessageId'", "]", ")", ")", "->", "setReceipthandle", "(", "trim", "(", "$", "definition", "[", "'ReceiptHandle'", "]", ")", ")", ";", "}", ",", "$", "response", "->", "get", "(", "'Messages'", ")", ")", ";", "}", "return", "$", "messages", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lelivrescolaire/SQSBundle/blob/bba3fa6d63d0ae1bddbc7b2fe3c2e737f49d6559/Model/Queue.php#L193-L219
lelivrescolaire/SQSBundle
Model/Queue.php
Queue.sendMessage
public function sendMessage(MessageInterface $message, $delay = 0) { $response = $this->sqs->getClient() ->sendMessage(array( 'QueueUrl' => $this->getUrl(), 'MessageBody' => $message->getBody(), 'DelaySeconds' => $delay, )); $message->setId(trim($response->get('MessageId'))); return $message; }
php
public function sendMessage(MessageInterface $message, $delay = 0) { $response = $this->sqs->getClient() ->sendMessage(array( 'QueueUrl' => $this->getUrl(), 'MessageBody' => $message->getBody(), 'DelaySeconds' => $delay, )); $message->setId(trim($response->get('MessageId'))); return $message; }
[ "public", "function", "sendMessage", "(", "MessageInterface", "$", "message", ",", "$", "delay", "=", "0", ")", "{", "$", "response", "=", "$", "this", "->", "sqs", "->", "getClient", "(", ")", "->", "sendMessage", "(", "array", "(", "'QueueUrl'", "=>", "$", "this", "->", "getUrl", "(", ")", ",", "'MessageBody'", "=>", "$", "message", "->", "getBody", "(", ")", ",", "'DelaySeconds'", "=>", "$", "delay", ",", ")", ")", ";", "$", "message", "->", "setId", "(", "trim", "(", "$", "response", "->", "get", "(", "'MessageId'", ")", ")", ")", ";", "return", "$", "message", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lelivrescolaire/SQSBundle/blob/bba3fa6d63d0ae1bddbc7b2fe3c2e737f49d6559/Model/Queue.php#L224-L236
Nozemi/SlickBoard-Library
lib/SBLib/Plugin/PluginHandler.php
PluginHandler.loadPlugins
private function loadPlugins($pluginsDirectory) { $pluginsDirectory = MISC::findFile($pluginsDirectory); if(file_exists($pluginsDirectory)) { $tmp_plugins = array(); foreach (glob($pluginsDirectory . '/*/*.json') as $file) { $config = json_decode(file_get_contents($file), true); $tmp_plugins[] = array( 'name' => $config['name'], 'priority' => $config['priority'], 'directory' => dirname($file), 'mainClass' => $config['mainClass'], 'classes' => $config['classes'] ); } MISC::array_sort_key($tmp_plugins, 'priority'); foreach($tmp_plugins as $tmp_plugin) { $plugin = new Plugin($tmp_plugin['name']); $plugin->setMainClass($tmp_plugin['mainClass']) ->setDirectory($tmp_plugin['directory']) ->setPriority($tmp_plugin['priority']) ->setClasses($tmp_plugin['classes']); $this->plugins[] = $plugin; new Logger('Plugin ['. $plugin->getName() .'] successfully loaded.', Logger::INFO, __FILE__, __LINE__); } new Logger('Plugins successfully loaded.', Logger::INFO, __FILE__, __LINE__); return true; } else { new Logger('Plugins directory wasn\'t found. (' . $pluginsDirectory . ')', Logger::WARNING, __FILE__, __LINE__); return false; } }
php
private function loadPlugins($pluginsDirectory) { $pluginsDirectory = MISC::findFile($pluginsDirectory); if(file_exists($pluginsDirectory)) { $tmp_plugins = array(); foreach (glob($pluginsDirectory . '/*/*.json') as $file) { $config = json_decode(file_get_contents($file), true); $tmp_plugins[] = array( 'name' => $config['name'], 'priority' => $config['priority'], 'directory' => dirname($file), 'mainClass' => $config['mainClass'], 'classes' => $config['classes'] ); } MISC::array_sort_key($tmp_plugins, 'priority'); foreach($tmp_plugins as $tmp_plugin) { $plugin = new Plugin($tmp_plugin['name']); $plugin->setMainClass($tmp_plugin['mainClass']) ->setDirectory($tmp_plugin['directory']) ->setPriority($tmp_plugin['priority']) ->setClasses($tmp_plugin['classes']); $this->plugins[] = $plugin; new Logger('Plugin ['. $plugin->getName() .'] successfully loaded.', Logger::INFO, __FILE__, __LINE__); } new Logger('Plugins successfully loaded.', Logger::INFO, __FILE__, __LINE__); return true; } else { new Logger('Plugins directory wasn\'t found. (' . $pluginsDirectory . ')', Logger::WARNING, __FILE__, __LINE__); return false; } }
[ "private", "function", "loadPlugins", "(", "$", "pluginsDirectory", ")", "{", "$", "pluginsDirectory", "=", "MISC", "::", "findFile", "(", "$", "pluginsDirectory", ")", ";", "if", "(", "file_exists", "(", "$", "pluginsDirectory", ")", ")", "{", "$", "tmp_plugins", "=", "array", "(", ")", ";", "foreach", "(", "glob", "(", "$", "pluginsDirectory", ".", "'/*/*.json'", ")", "as", "$", "file", ")", "{", "$", "config", "=", "json_decode", "(", "file_get_contents", "(", "$", "file", ")", ",", "true", ")", ";", "$", "tmp_plugins", "[", "]", "=", "array", "(", "'name'", "=>", "$", "config", "[", "'name'", "]", ",", "'priority'", "=>", "$", "config", "[", "'priority'", "]", ",", "'directory'", "=>", "dirname", "(", "$", "file", ")", ",", "'mainClass'", "=>", "$", "config", "[", "'mainClass'", "]", ",", "'classes'", "=>", "$", "config", "[", "'classes'", "]", ")", ";", "}", "MISC", "::", "array_sort_key", "(", "$", "tmp_plugins", ",", "'priority'", ")", ";", "foreach", "(", "$", "tmp_plugins", "as", "$", "tmp_plugin", ")", "{", "$", "plugin", "=", "new", "Plugin", "(", "$", "tmp_plugin", "[", "'name'", "]", ")", ";", "$", "plugin", "->", "setMainClass", "(", "$", "tmp_plugin", "[", "'mainClass'", "]", ")", "->", "setDirectory", "(", "$", "tmp_plugin", "[", "'directory'", "]", ")", "->", "setPriority", "(", "$", "tmp_plugin", "[", "'priority'", "]", ")", "->", "setClasses", "(", "$", "tmp_plugin", "[", "'classes'", "]", ")", ";", "$", "this", "->", "plugins", "[", "]", "=", "$", "plugin", ";", "new", "Logger", "(", "'Plugin ['", ".", "$", "plugin", "->", "getName", "(", ")", ".", "'] successfully loaded.'", ",", "Logger", "::", "INFO", ",", "__FILE__", ",", "__LINE__", ")", ";", "}", "new", "Logger", "(", "'Plugins successfully loaded.'", ",", "Logger", "::", "INFO", ",", "__FILE__", ",", "__LINE__", ")", ";", "return", "true", ";", "}", "else", "{", "new", "Logger", "(", "'Plugins directory wasn\\'t found. ('", ".", "$", "pluginsDirectory", ".", "')'", ",", "Logger", "::", "WARNING", ",", "__FILE__", ",", "__LINE__", ")", ";", "return", "false", ";", "}", "}" ]
@param string $pluginsDirectory @return bool
[ "@param", "string", "$pluginsDirectory" ]
train
https://github.com/Nozemi/SlickBoard-Library/blob/c9f0a26a30f8127c997f75d7232eac170972418d/lib/SBLib/Plugin/PluginHandler.php#L31-L68
mle86/php-wq
src/WQ/WorkProcessor.php
WorkProcessor.processNextJob
public function processNextJob( $workQueue, callable $callback, int $timeout = WorkServerAdapter::DEFAULT_TIMEOUT ): void { $qe = $this->server->getNextQueueEntry($workQueue, $timeout); if (!$qe) { $this->onNoJobAvailable((array)$workQueue); return; } $job = $qe->getJob(); if ($job->jobIsExpired()) { $this->handleExpiredJob($qe); return; } $this->log(LogLevel::INFO, "got job", $qe); $this->onJobAvailable($qe); $ret = null; try { $ret = $callback($job); } catch (\Throwable $e) { // The job failed. $this->handleFailedJob($qe, $e); if ($this->options[self::WP_RETHROW_EXCEPTIONS]) { // pass exception to caller throw $e; } else { // drop it return; } } switch ($ret ?? JobResult::DEFAULT) { case JobResult::SUCCESS: // The job succeeded! $this->handleFinishedJob($qe); break; case JobResult::FAILED: // The job failed. $this->handleFailedJob($qe); break; default: // We'll assume the job went well. $this->handleFinishedJob($qe); throw new \UnexpectedValueException('unexpected job handler return value, should be JobResult::... or null or void'); } }
php
public function processNextJob( $workQueue, callable $callback, int $timeout = WorkServerAdapter::DEFAULT_TIMEOUT ): void { $qe = $this->server->getNextQueueEntry($workQueue, $timeout); if (!$qe) { $this->onNoJobAvailable((array)$workQueue); return; } $job = $qe->getJob(); if ($job->jobIsExpired()) { $this->handleExpiredJob($qe); return; } $this->log(LogLevel::INFO, "got job", $qe); $this->onJobAvailable($qe); $ret = null; try { $ret = $callback($job); } catch (\Throwable $e) { // The job failed. $this->handleFailedJob($qe, $e); if ($this->options[self::WP_RETHROW_EXCEPTIONS]) { // pass exception to caller throw $e; } else { // drop it return; } } switch ($ret ?? JobResult::DEFAULT) { case JobResult::SUCCESS: // The job succeeded! $this->handleFinishedJob($qe); break; case JobResult::FAILED: // The job failed. $this->handleFailedJob($qe); break; default: // We'll assume the job went well. $this->handleFinishedJob($qe); throw new \UnexpectedValueException('unexpected job handler return value, should be JobResult::... or null or void'); } }
[ "public", "function", "processNextJob", "(", "$", "workQueue", ",", "callable", "$", "callback", ",", "int", "$", "timeout", "=", "WorkServerAdapter", "::", "DEFAULT_TIMEOUT", ")", ":", "void", "{", "$", "qe", "=", "$", "this", "->", "server", "->", "getNextQueueEntry", "(", "$", "workQueue", ",", "$", "timeout", ")", ";", "if", "(", "!", "$", "qe", ")", "{", "$", "this", "->", "onNoJobAvailable", "(", "(", "array", ")", "$", "workQueue", ")", ";", "return", ";", "}", "$", "job", "=", "$", "qe", "->", "getJob", "(", ")", ";", "if", "(", "$", "job", "->", "jobIsExpired", "(", ")", ")", "{", "$", "this", "->", "handleExpiredJob", "(", "$", "qe", ")", ";", "return", ";", "}", "$", "this", "->", "log", "(", "LogLevel", "::", "INFO", ",", "\"got job\"", ",", "$", "qe", ")", ";", "$", "this", "->", "onJobAvailable", "(", "$", "qe", ")", ";", "$", "ret", "=", "null", ";", "try", "{", "$", "ret", "=", "$", "callback", "(", "$", "job", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "// The job failed.", "$", "this", "->", "handleFailedJob", "(", "$", "qe", ",", "$", "e", ")", ";", "if", "(", "$", "this", "->", "options", "[", "self", "::", "WP_RETHROW_EXCEPTIONS", "]", ")", "{", "// pass exception to caller", "throw", "$", "e", ";", "}", "else", "{", "// drop it", "return", ";", "}", "}", "switch", "(", "$", "ret", "??", "JobResult", "::", "DEFAULT", ")", "{", "case", "JobResult", "::", "SUCCESS", ":", "// The job succeeded!", "$", "this", "->", "handleFinishedJob", "(", "$", "qe", ")", ";", "break", ";", "case", "JobResult", "::", "FAILED", ":", "// The job failed.", "$", "this", "->", "handleFailedJob", "(", "$", "qe", ")", ";", "break", ";", "default", ":", "// We'll assume the job went well.", "$", "this", "->", "handleFinishedJob", "(", "$", "qe", ")", ";", "throw", "new", "\\", "UnexpectedValueException", "(", "'unexpected job handler return value, should be JobResult::... or null or void'", ")", ";", "}", "}" ]
Executes the next job in the Work Queue by passing it to the callback function. If that results in a {@see \RuntimeException}, the method will try to re-queue the job and re-throw the exception. If the execution results in any other {@see \Throwable}, no re-queueing will be attempted; the job will be buried immediately. If the next job in the Work Queue is expired, it will be silently deleted. @param string|string[] $workQueue See {@see WorkServerAdapter::getNextJob()}. @param callable $callback The handler callback to execute each Job. Expected signature: <tt>function(Job): ?int|void</tt>. See {@see JobResult} for possible return values. @param int $timeout See {@see WorkServerAdapter::getNextJob()}. @throws \Throwable Will re-throw on any Exceptions/Throwables from the <tt>$callback</tt>. @throws \UnexpectedValueException in case of an unexpected callback return value (should be a {@see JobResult} constant or NULL or void).
[ "Executes", "the", "next", "job", "in", "the", "Work", "Queue", "by", "passing", "it", "to", "the", "callback", "function", "." ]
train
https://github.com/mle86/php-wq/blob/e1ca1dcfd3d40edb0085f6dfa83d90db74253de4/src/WQ/WorkProcessor.php#L78-L129
mle86/php-wq
src/WQ/WorkProcessor.php
WorkProcessor.setOption
public function setOption(int $option, $value): self { $this->options[$option] = $value; return $this; }
php
public function setOption(int $option, $value): self { $this->options[$option] = $value; return $this; }
[ "public", "function", "setOption", "(", "int", "$", "option", ",", "$", "value", ")", ":", "self", "{", "$", "this", "->", "options", "[", "$", "option", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Sets one of the configuration options. @param int $option One of the <tt>WP_</tt> constants. @param mixed $value The option's new value. The required type depends on the option. @see setOptions() to change multiple options at once. @return self
[ "Sets", "one", "of", "the", "configuration", "options", "." ]
train
https://github.com/mle86/php-wq/blob/e1ca1dcfd3d40edb0085f6dfa83d90db74253de4/src/WQ/WorkProcessor.php#L286-L290
haldayne/boost
src/Map.php
Map.keys
public function keys() { $map = new Map; foreach (array_keys($this->array) as $hash) { $map[] = $this->hash_to_key($hash); } return $map; }
php
public function keys() { $map = new Map; foreach (array_keys($this->array) as $hash) { $map[] = $this->hash_to_key($hash); } return $map; }
[ "public", "function", "keys", "(", ")", "{", "$", "map", "=", "new", "Map", ";", "foreach", "(", "array_keys", "(", "$", "this", "->", "array", ")", "as", "$", "hash", ")", "{", "$", "map", "[", "]", "=", "$", "this", "->", "hash_to_key", "(", "$", "hash", ")", ";", "}", "return", "$", "map", ";", "}" ]
Get the keys of this map as a new map. @return new Map @api @since 1.0.5
[ "Get", "the", "keys", "of", "this", "map", "as", "a", "new", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L85-L92
haldayne/boost
src/Map.php
Map.filter
public function filter($expression) { $new = new static; $this->walk(function ($v, $k) use ($expression, $new) { $result = $this->call($expression, $v, $k); if ($this->passes($result)) { $new[$k] = $v; } }); return $new; }
php
public function filter($expression) { $new = new static; $this->walk(function ($v, $k) use ($expression, $new) { $result = $this->call($expression, $v, $k); if ($this->passes($result)) { $new[$k] = $v; } }); return $new; }
[ "public", "function", "filter", "(", "$", "expression", ")", "{", "$", "new", "=", "new", "static", ";", "$", "this", "->", "walk", "(", "function", "(", "$", "v", ",", "$", "k", ")", "use", "(", "$", "expression", ",", "$", "new", ")", "{", "$", "result", "=", "$", "this", "->", "call", "(", "$", "expression", ",", "$", "v", ",", "$", "k", ")", ";", "if", "(", "$", "this", "->", "passes", "(", "$", "result", ")", ")", "{", "$", "new", "[", "$", "k", "]", "=", "$", "v", ";", "}", "}", ")", ";", "return", "$", "new", ";", "}" ]
Apply the filter to every element, creating a new map with only those elements from the original map that do not fail this filter. The filter expressions receives two arguments: - The current value - The current key If the filter returns exactly boolean false, the element is not copied into the new map. Otherwise, it is. Keys from the original map carry into the new map. @param callable|string $expression @return new static @api
[ "Apply", "the", "filter", "to", "every", "element", "creating", "a", "new", "map", "with", "only", "those", "elements", "from", "the", "original", "map", "that", "do", "not", "fail", "this", "filter", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L133-L145
haldayne/boost
src/Map.php
Map.first
public function first($expression, $n = 1) { if (is_numeric($n) && intval($n) <= 0) { throw new \InvalidArgumentException('Argument $n must be whole number'); } return $this->grep($expression, intval($n)); }
php
public function first($expression, $n = 1) { if (is_numeric($n) && intval($n) <= 0) { throw new \InvalidArgumentException('Argument $n must be whole number'); } return $this->grep($expression, intval($n)); }
[ "public", "function", "first", "(", "$", "expression", ",", "$", "n", "=", "1", ")", "{", "if", "(", "is_numeric", "(", "$", "n", ")", "&&", "intval", "(", "$", "n", ")", "<=", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Argument $n must be whole number'", ")", ";", "}", "return", "$", "this", "->", "grep", "(", "$", "expression", ",", "intval", "(", "$", "n", ")", ")", ";", "}" ]
Return a new map containing the first N elements passing the expression. Like `find`, but stop after finding N elements from the front. Defaults to N = 1. ``` $nums = new Map(range(0, 9)); $odd3 = $nums->first('1 == ($_0 % 2)', 3); // first three odds ``` @param callable|string $expression @param int $n @return new static @api
[ "Return", "a", "new", "map", "containing", "the", "first", "N", "elements", "passing", "the", "expression", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L164-L170
haldayne/boost
src/Map.php
Map.last
public function last($expression, $n = 1) { if (is_numeric($n) && intval($n) <= 0) { throw new \InvalidArgumentException('Argument $n must be whole number'); } return $this->grep($expression, -intval($n)); }
php
public function last($expression, $n = 1) { if (is_numeric($n) && intval($n) <= 0) { throw new \InvalidArgumentException('Argument $n must be whole number'); } return $this->grep($expression, -intval($n)); }
[ "public", "function", "last", "(", "$", "expression", ",", "$", "n", "=", "1", ")", "{", "if", "(", "is_numeric", "(", "$", "n", ")", "&&", "intval", "(", "$", "n", ")", "<=", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Argument $n must be whole number'", ")", ";", "}", "return", "$", "this", "->", "grep", "(", "$", "expression", ",", "-", "intval", "(", "$", "n", ")", ")", ";", "}" ]
Return a new map containing the last N elements passing the expression. Like `first`, but stop after finding N elements from the *end*. Defaults to N = 1. ``` $nums = new Map(range(0, 9)); $odds = $nums->last('1 == ($_0 % 2)', 2); // last two odd numbers ``` @param callable|string $expression @param int $n @return new static @api
[ "Return", "a", "new", "map", "containing", "the", "last", "N", "elements", "passing", "the", "expression", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L188-L194
haldayne/boost
src/Map.php
Map.get
public function get($key, $default = null) { $hash = $this->key_to_hash($key); if (array_key_exists($hash, $this->array)) { return $this->array[$hash]; } else { return $default; } }
php
public function get($key, $default = null) { $hash = $this->key_to_hash($key); if (array_key_exists($hash, $this->array)) { return $this->array[$hash]; } else { return $default; } }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "hash", "=", "$", "this", "->", "key_to_hash", "(", "$", "key", ")", ";", "if", "(", "array_key_exists", "(", "$", "hash", ",", "$", "this", "->", "array", ")", ")", "{", "return", "$", "this", "->", "array", "[", "$", "hash", "]", ";", "}", "else", "{", "return", "$", "default", ";", "}", "}" ]
Get the value corresponding to the given key. If the key does not exist in the map, return the default. This is the object method equivalent of the magic $map[$key]. @param mixed $key @param mixed $default @return mixed @api
[ "Get", "the", "value", "corresponding", "to", "the", "given", "key", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L259-L267
haldayne/boost
src/Map.php
Map.set
public function set($key, $value) { $hash = $this->key_to_hash($key); $this->array[$hash] = $value; return $this; }
php
public function set($key, $value) { $hash = $this->key_to_hash($key); $this->array[$hash] = $value; return $this; }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "$", "hash", "=", "$", "this", "->", "key_to_hash", "(", "$", "key", ")", ";", "$", "this", "->", "array", "[", "$", "hash", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Set a key and its corresponding value into the map. This is the object method equivalent of the magic $map[$key] = 'foo'. @param mixed $key @param mixed $value @return $this @api
[ "Set", "a", "key", "and", "its", "corresponding", "value", "into", "the", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L279-L284
haldayne/boost
src/Map.php
Map.diff
public function diff($collection, $comparison = Map::LOOSE) { $func = ($comparison === Map::LOOSE ? 'array_diff' : 'array_diff_assoc'); return new static( $func($this->toArray(), $this->collection_to_array($collection)) ); }
php
public function diff($collection, $comparison = Map::LOOSE) { $func = ($comparison === Map::LOOSE ? 'array_diff' : 'array_diff_assoc'); return new static( $func($this->toArray(), $this->collection_to_array($collection)) ); }
[ "public", "function", "diff", "(", "$", "collection", ",", "$", "comparison", "=", "Map", "::", "LOOSE", ")", "{", "$", "func", "=", "(", "$", "comparison", "===", "Map", "::", "LOOSE", "?", "'array_diff'", ":", "'array_diff_assoc'", ")", ";", "return", "new", "static", "(", "$", "func", "(", "$", "this", "->", "toArray", "(", ")", ",", "$", "this", "->", "collection_to_array", "(", "$", "collection", ")", ")", ")", ";", "}" ]
Return a new map containing those keys and values that are not present in the given collection. If comparison is loose, then only those elements whose values match will be removed. Otherwise, comparison is strict, and elements whose keys and values match will be removed. @param Map|Arrayable|Jsonable|Traversable|object|array $collection @param enum $comparison @return new static @api
[ "Return", "a", "new", "map", "containing", "those", "keys", "and", "values", "that", "are", "not", "present", "in", "the", "given", "collection", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L325-L331
haldayne/boost
src/Map.php
Map.partition
public function partition($expression) { $outer = new MapOfCollections; $proto = new static; $this->walk(function ($v, $k) use ($expression, $outer, $proto) { $partition = $this->call($expression, $v, $k); $inner = $outer->has($partition) ? $outer->get($partition) : clone $proto; $inner->set($k, $v); $outer->set($partition, $inner); }); return $outer; }
php
public function partition($expression) { $outer = new MapOfCollections; $proto = new static; $this->walk(function ($v, $k) use ($expression, $outer, $proto) { $partition = $this->call($expression, $v, $k); $inner = $outer->has($partition) ? $outer->get($partition) : clone $proto; $inner->set($k, $v); $outer->set($partition, $inner); }); return $outer; }
[ "public", "function", "partition", "(", "$", "expression", ")", "{", "$", "outer", "=", "new", "MapOfCollections", ";", "$", "proto", "=", "new", "static", ";", "$", "this", "->", "walk", "(", "function", "(", "$", "v", ",", "$", "k", ")", "use", "(", "$", "expression", ",", "$", "outer", ",", "$", "proto", ")", "{", "$", "partition", "=", "$", "this", "->", "call", "(", "$", "expression", ",", "$", "v", ",", "$", "k", ")", ";", "$", "inner", "=", "$", "outer", "->", "has", "(", "$", "partition", ")", "?", "$", "outer", "->", "get", "(", "$", "partition", ")", ":", "clone", "$", "proto", ";", "$", "inner", "->", "set", "(", "$", "k", ",", "$", "v", ")", ";", "$", "outer", "->", "set", "(", "$", "partition", ",", "$", "inner", ")", ";", "}", ")", ";", "return", "$", "outer", ";", "}" ]
Groups elements of this map based on the result of an expression. Calls the expression for each element in this map. The expression receives the value and key, respectively. The expression may return any value: this value is the grouping key and the element is put into that group. ``` $nums = new Map(range(0, 9)); $part = $nums->partition(function ($value, $key) { return 0 == $value % 2 ? 'even' : 'odd'; }); var_dump( $part['odd']->count(), // 5 array_sum($part['even']->toArray()) // 20 ); ``` @param callable|string $expression @return MapOfCollections @api
[ "Groups", "elements", "of", "this", "map", "based", "on", "the", "result", "of", "an", "expression", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L377-L392
haldayne/boost
src/Map.php
Map.map
public function map($expression) { $new = new self; $this->walk(function ($v, $k) use ($expression, $new) { $new[$k] = $this->call($expression, $v, $k); }); return $new; }
php
public function map($expression) { $new = new self; $this->walk(function ($v, $k) use ($expression, $new) { $new[$k] = $this->call($expression, $v, $k); }); return $new; }
[ "public", "function", "map", "(", "$", "expression", ")", "{", "$", "new", "=", "new", "self", ";", "$", "this", "->", "walk", "(", "function", "(", "$", "v", ",", "$", "k", ")", "use", "(", "$", "expression", ",", "$", "new", ")", "{", "$", "new", "[", "$", "k", "]", "=", "$", "this", "->", "call", "(", "$", "expression", ",", "$", "v", ",", "$", "k", ")", ";", "}", ")", ";", "return", "$", "new", ";", "}" ]
Walk the map, applying the expression to every element, transforming them into a new map. ``` $nums = new Map(range(0, 9)); $doubled = $nums->map('$_0 * 2'); ``` The expression receives two arguments: - The current value in `$_0` - The current key in `$_1` The keys in the resulting map will be the same as the keys in the original map: only the values have (potentially) changed. Recommended to use this method when you are mapping from one type to the same type: int to int, string to string, etc. If you are changing types, use the more powerful `transform` method. @param callable|string $expression @return Map @api
[ "Walk", "the", "map", "applying", "the", "expression", "to", "every", "element", "transforming", "them", "into", "a", "new", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L418-L427
haldayne/boost
src/Map.php
Map.reduce
public function reduce($reducer, $initial = null, $finisher = null) { $reduced = $initial; $this->walk(function ($value, $key) use ($reducer, &$reduced) { $reduced = $this->call($reducer, $reduced, $value, $key); }); if (null === $finisher) { return $reduced; } else { return $this->call($finisher, $reduced); } }
php
public function reduce($reducer, $initial = null, $finisher = null) { $reduced = $initial; $this->walk(function ($value, $key) use ($reducer, &$reduced) { $reduced = $this->call($reducer, $reduced, $value, $key); }); if (null === $finisher) { return $reduced; } else { return $this->call($finisher, $reduced); } }
[ "public", "function", "reduce", "(", "$", "reducer", ",", "$", "initial", "=", "null", ",", "$", "finisher", "=", "null", ")", "{", "$", "reduced", "=", "$", "initial", ";", "$", "this", "->", "walk", "(", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "$", "reducer", ",", "&", "$", "reduced", ")", "{", "$", "reduced", "=", "$", "this", "->", "call", "(", "$", "reducer", ",", "$", "reduced", ",", "$", "value", ",", "$", "key", ")", ";", "}", ")", ";", "if", "(", "null", "===", "$", "finisher", ")", "{", "return", "$", "reduced", ";", "}", "else", "{", "return", "$", "this", "->", "call", "(", "$", "finisher", ",", "$", "reduced", ")", ";", "}", "}" ]
Walk the map, applying a reducing expression to every element, so as to reduce the map to a single value. The `$reducer` expression receives three arguments: - The current reduction (`$_0`) - The current value (`$_1`) - The current key (`$_2`) The initial value, if given or null if not, is passed as the current reduction on the first invocation of `$reducer`. The return value from `$reducer` then becomes the new, current reduced value. ``` $nums = new Map(range(0, 3)); $sum = $nums->reduce('$_0 + $_1'); // $sum == 6 ``` If `$finisher` is a callable or string expression, then it will be called last, after iterating over all elements. It will be passed reduced value. The `$finisher` must return the new final value. @param callable|string $reducer @param mixed $initial @param callable|string|null $finisher @return mixed @api @see http://php.net/manual/en/function.array-reduce.php
[ "Walk", "the", "map", "applying", "a", "reducing", "expression", "to", "every", "element", "so", "as", "to", "reduce", "the", "map", "to", "a", "single", "value", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L460-L472
haldayne/boost
src/Map.php
Map.rekey
public function rekey($expression) { $new = new static; $this->walk(function ($v, $k) use ($expression, $new) { $new_key = $this->call($expression, $v, $k); $new[$new_key] = $v; }); return $new; }
php
public function rekey($expression) { $new = new static; $this->walk(function ($v, $k) use ($expression, $new) { $new_key = $this->call($expression, $v, $k); $new[$new_key] = $v; }); return $new; }
[ "public", "function", "rekey", "(", "$", "expression", ")", "{", "$", "new", "=", "new", "static", ";", "$", "this", "->", "walk", "(", "function", "(", "$", "v", ",", "$", "k", ")", "use", "(", "$", "expression", ",", "$", "new", ")", "{", "$", "new_key", "=", "$", "this", "->", "call", "(", "$", "expression", ",", "$", "v", ",", "$", "k", ")", ";", "$", "new", "[", "$", "new_key", "]", "=", "$", "v", ";", "}", ")", ";", "return", "$", "new", ";", "}" ]
Change the key for every element in the map using an expression to calculate the new key. ``` $keyed_by_bytecode = new Map(count_chars('war of the worlds', 1)); $keyed_by_letter = $keyed_by_bytecode->rekey('chr($_1)'); ``` @param callable|string $expression @return new static @api
[ "Change", "the", "key", "for", "every", "element", "in", "the", "map", "using", "an", "expression", "to", "calculate", "the", "new", "key", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L487-L497
haldayne/boost
src/Map.php
Map.merge
public function merge($collection, callable $merger, $default = null) { $array = $this->collection_to_array($collection); foreach ($array as $key => $value) { $current = $this->get($key, $default); $this->set($key, $merger($current, $value)); } return $this; }
php
public function merge($collection, callable $merger, $default = null) { $array = $this->collection_to_array($collection); foreach ($array as $key => $value) { $current = $this->get($key, $default); $this->set($key, $merger($current, $value)); } return $this; }
[ "public", "function", "merge", "(", "$", "collection", ",", "callable", "$", "merger", ",", "$", "default", "=", "null", ")", "{", "$", "array", "=", "$", "this", "->", "collection_to_array", "(", "$", "collection", ")", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "current", "=", "$", "this", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "$", "this", "->", "set", "(", "$", "key", ",", "$", "merger", "(", "$", "current", ",", "$", "value", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Merge the given collection into this map. The merger callable decides how to merge the current map's value with the given collection's value. The merger callable receives two arguments: - This map's value at the given key - The collection's value at the given key If the current map does not have a value for a key in the collection, then the default value is assumed. @param Map|Arrayable|Jsonable|Traversable|object|array $collection @param callable $merger @param mixed $default @return $this @api
[ "Merge", "the", "given", "collection", "into", "this", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L517-L525
haldayne/boost
src/Map.php
Map.transform
public function transform(callable $transformer, callable $creator = null, callable $finisher = null) { // create the initial object, using as needed the default creator function if (null === $creator) { $creator = function (Map $original) { return new Map(); }; } $initial = $creator($this); // transform the initial value using the transformer $this->walk(function ($value, $key) use ($transformer, &$initial) { $transformer($initial, $value, $key); }); // finish up if (null === $finisher) { return $initial; } else { return $finisher($initial); } }
php
public function transform(callable $transformer, callable $creator = null, callable $finisher = null) { // create the initial object, using as needed the default creator function if (null === $creator) { $creator = function (Map $original) { return new Map(); }; } $initial = $creator($this); // transform the initial value using the transformer $this->walk(function ($value, $key) use ($transformer, &$initial) { $transformer($initial, $value, $key); }); // finish up if (null === $finisher) { return $initial; } else { return $finisher($initial); } }
[ "public", "function", "transform", "(", "callable", "$", "transformer", ",", "callable", "$", "creator", "=", "null", ",", "callable", "$", "finisher", "=", "null", ")", "{", "// create the initial object, using as needed the default creator function", "if", "(", "null", "===", "$", "creator", ")", "{", "$", "creator", "=", "function", "(", "Map", "$", "original", ")", "{", "return", "new", "Map", "(", ")", ";", "}", ";", "}", "$", "initial", "=", "$", "creator", "(", "$", "this", ")", ";", "// transform the initial value using the transformer", "$", "this", "->", "walk", "(", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "$", "transformer", ",", "&", "$", "initial", ")", "{", "$", "transformer", "(", "$", "initial", ",", "$", "value", ",", "$", "key", ")", ";", "}", ")", ";", "// finish up", "if", "(", "null", "===", "$", "finisher", ")", "{", "return", "$", "initial", ";", "}", "else", "{", "return", "$", "finisher", "(", "$", "initial", ")", ";", "}", "}" ]
Flexibly and thoroughly change this map into another map. ``` // transform a word list into a map of word to frequency in the list use Haldayne\Boost\Map; $words = new Map([ 'bear', 'bee', 'goose', 'bee' ]); $lengths = $words->transform( function (Map $new, $word) { if ($new->has($word)) { $new->set($word, $new->get($word)+1); } else { $new->set($word, 1); } } ); ``` Sometimes you need to create one map from another using a strategy that isn't one-to-one. You may need to change keys. You may need to add multiple elements. You may need to delete elements. You may need to change from a map to a number. Whatever the case, the other simpler methods in Map don't quite fit the problem. What you need, and what this method provides, is a complete machine to transform this map into something else: ``` // convert a word list into a count of unique letters in those words use Haldayne\Boost\Map; $words = new Map([ 'bear', 'bee', 'goose', 'bee' ]); $letters = $words->transform( function ($frequencies, $word) { foreach (count_chars($word, 1) as $byte => $frequency) { $letter = chr($byte); if ($frequencies->has($letter)) { $new->set($letter, $frequencies->get($letter)+1); } else { $new->set($letter, 1); } } }, function (Map $original) { return new MapOfIntegers(); }, function (MapOfIntegers $new) { return $new->sum(); } ); ``` This method accepts three callables 1. `$creator`, which is called first with the current map, performs any initialization needed. The result of this callable will be passed to all the other callables. If no creator is given, then use a default one that returns an empty Map. 2. `$transformer`, which is called for every element in this map and receives the initialized value, the current value, and the current key in that order. The transformer should modify the initialized value appropriately. Often this means adding to a new map zero or more tranformed values. 3. `$finisher`, which is called last, receives the initialized value that was modified by the transformer calls. The finisher may transform that value once more as needed. If no finisher given, then no finishing step is made. @param callable $tranformer @param callable|null $creator @param callable|null $finisher @return mixed @api
[ "Flexibly", "and", "thoroughly", "change", "this", "map", "into", "another", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L597-L616
haldayne/boost
src/Map.php
Map.into
public function into(Map $target) { $this->walk(function ($value, $key) use ($target) { $target->set($key, $value); }); return $target; }
php
public function into(Map $target) { $this->walk(function ($value, $key) use ($target) { $target->set($key, $value); }); return $target; }
[ "public", "function", "into", "(", "Map", "$", "target", ")", "{", "$", "this", "->", "walk", "(", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "$", "target", ")", "{", "$", "target", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}", ")", ";", "return", "$", "target", ";", "}" ]
Put all of this map's elements into the target and return the target. ``` $words = new MapOfStrings([ 'foo', 'bar' ]); $words->map('strlen($_0)')->into(new MapOfInts)->sum(); // 6 ``` Use when you've mapped your elements into a different type, and you want to fluently perform operations on the new type. In the example, the sum of the words' lengths was calculated. @return $target @api
[ "Put", "all", "of", "this", "map", "s", "elements", "into", "the", "target", "and", "return", "the", "target", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L633-L639
haldayne/boost
src/Map.php
Map.push
public function push($element) { // ask PHP to give me the next index // http://stackoverflow.com/q/3698743/2908724 $this->array[] = 'probe'; end($this->array); $next = key($this->array); unset($this->array[$next]); // hash that and store $this->set($next, $element); return $this; }
php
public function push($element) { // ask PHP to give me the next index // http://stackoverflow.com/q/3698743/2908724 $this->array[] = 'probe'; end($this->array); $next = key($this->array); unset($this->array[$next]); // hash that and store $this->set($next, $element); return $this; }
[ "public", "function", "push", "(", "$", "element", ")", "{", "// ask PHP to give me the next index", "// http://stackoverflow.com/q/3698743/2908724", "$", "this", "->", "array", "[", "]", "=", "'probe'", ";", "end", "(", "$", "this", "->", "array", ")", ";", "$", "next", "=", "key", "(", "$", "this", "->", "array", ")", ";", "unset", "(", "$", "this", "->", "array", "[", "$", "next", "]", ")", ";", "// hash that and store", "$", "this", "->", "set", "(", "$", "next", ",", "$", "element", ")", ";", "return", "$", "this", ";", "}" ]
Treat the map as a stack and push an element onto its end. @return $this @api
[ "Treat", "the", "map", "as", "a", "stack", "and", "push", "an", "element", "onto", "its", "end", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L647-L660
haldayne/boost
src/Map.php
Map.pop
public function pop() { if (0 === count($this->array)) { return null; } // get the last hash of array end($this->array); $hash = key($this->array); // temporarily hold the element at that spot $element = $this->array[$hash]; // forget it in our map and return our temporary $this->forget($this->hash_to_key($hash)); return $element; }
php
public function pop() { if (0 === count($this->array)) { return null; } // get the last hash of array end($this->array); $hash = key($this->array); // temporarily hold the element at that spot $element = $this->array[$hash]; // forget it in our map and return our temporary $this->forget($this->hash_to_key($hash)); return $element; }
[ "public", "function", "pop", "(", ")", "{", "if", "(", "0", "===", "count", "(", "$", "this", "->", "array", ")", ")", "{", "return", "null", ";", "}", "// get the last hash of array", "end", "(", "$", "this", "->", "array", ")", ";", "$", "hash", "=", "key", "(", "$", "this", "->", "array", ")", ";", "// temporarily hold the element at that spot", "$", "element", "=", "$", "this", "->", "array", "[", "$", "hash", "]", ";", "// forget it in our map and return our temporary", "$", "this", "->", "forget", "(", "$", "this", "->", "hash_to_key", "(", "$", "hash", ")", ")", ";", "return", "$", "element", ";", "}" ]
Treat the map as a stack and pop an element off its end. @return mixed|null @api
[ "Treat", "the", "map", "as", "a", "stack", "and", "pop", "an", "element", "off", "its", "end", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L668-L685
haldayne/boost
src/Map.php
Map.toArray
public function toArray() { $array = []; foreach ($this->array as $hash => $value) { $key = $this->hash_to_key($hash); if ($this->is_collection_like($value)) { $array[$key] = $this->collection_to_array($value); } else { $array[$key] = $value; } } return $array; }
php
public function toArray() { $array = []; foreach ($this->array as $hash => $value) { $key = $this->hash_to_key($hash); if ($this->is_collection_like($value)) { $array[$key] = $this->collection_to_array($value); } else { $array[$key] = $value; } } return $array; }
[ "public", "function", "toArray", "(", ")", "{", "$", "array", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "array", "as", "$", "hash", "=>", "$", "value", ")", "{", "$", "key", "=", "$", "this", "->", "hash_to_key", "(", "$", "hash", ")", ";", "if", "(", "$", "this", "->", "is_collection_like", "(", "$", "value", ")", ")", "{", "$", "array", "[", "$", "key", "]", "=", "$", "this", "->", "collection_to_array", "(", "$", "value", ")", ";", "}", "else", "{", "$", "array", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "array", ";", "}" ]
Copy this map into an array, recursing as necessary to convert contained collections into arrays. @api
[ "Copy", "this", "map", "into", "an", "array", "recursing", "as", "necessary", "to", "convert", "contained", "collections", "into", "arrays", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L710-L722
haldayne/boost
src/Map.php
Map.offsetSet
public function offsetSet($key, $value) { if (null === $key) { $this->push($value); } else { $this->set($key, $value); } }
php
public function offsetSet($key, $value) { if (null === $key) { $this->push($value); } else { $this->set($key, $value); } }
[ "public", "function", "offsetSet", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "null", "===", "$", "key", ")", "{", "$", "this", "->", "push", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}" ]
Set the value at a given key. If key is null, the value is appended to the array using numeric indexes, just like native PHP. Unlike native-PHP, $key can be of any type: boolean, int, float, string, array, object, closure, resource. @param mixed $key @param mixed $value @return void
[ "Set", "the", "value", "at", "a", "given", "key", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L773-L780
haldayne/boost
src/Map.php
Map.getIterator
public function getIterator() { $keys = $this->keys(); $count = count($keys); $index = 0; while ($index < $count) { $key = $keys[$index]; $value = $this->get($key); yield $key => $value; $index++; } }
php
public function getIterator() { $keys = $this->keys(); $count = count($keys); $index = 0; while ($index < $count) { $key = $keys[$index]; $value = $this->get($key); yield $key => $value; $index++; } }
[ "public", "function", "getIterator", "(", ")", "{", "$", "keys", "=", "$", "this", "->", "keys", "(", ")", ";", "$", "count", "=", "count", "(", "$", "keys", ")", ";", "$", "index", "=", "0", ";", "while", "(", "$", "index", "<", "$", "count", ")", "{", "$", "key", "=", "$", "keys", "[", "$", "index", "]", ";", "$", "value", "=", "$", "this", "->", "get", "(", "$", "key", ")", ";", "yield", "$", "key", "=>", "$", "value", ";", "$", "index", "++", ";", "}", "}" ]
Get an iterator for the map. @return \Generator @api
[ "Get", "an", "iterator", "for", "the", "map", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L802-L816
haldayne/boost
src/Map.php
Map.is_collection_like
protected function is_collection_like($value) { if ($value instanceof self) { return true; } else if ($value instanceof \Traversable) { return true; } else if ($value instanceof Arrayable) { return true; } else if ($value instanceof Jsonable) { return true; } else if (is_object($value) || is_array($value)) { return true; } else { return false; } }
php
protected function is_collection_like($value) { if ($value instanceof self) { return true; } else if ($value instanceof \Traversable) { return true; } else if ($value instanceof Arrayable) { return true; } else if ($value instanceof Jsonable) { return true; } else if (is_object($value) || is_array($value)) { return true; } else { return false; } }
[ "protected", "function", "is_collection_like", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "self", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "value", "instanceof", "\\", "Traversable", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "value", "instanceof", "Arrayable", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "value", "instanceof", "Jsonable", ")", "{", "return", "true", ";", "}", "else", "if", "(", "is_object", "(", "$", "value", ")", "||", "is_array", "(", "$", "value", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Decide if the given value is considered collection-like. @param mixed $value @return bool
[ "Decide", "if", "the", "given", "value", "is", "considered", "collection", "-", "like", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L844-L864
haldayne/boost
src/Map.php
Map.collection_to_array
protected function collection_to_array($collection) { if ($collection instanceof self) { return $collection->toArray(); } else if ($collection instanceof \Traversable) { return iterator_to_array($collection); } else if ($collection instanceof Arrayable) { return $collection->toArray(); } else if ($collection instanceof Jsonable) { return json_decode($collection->toJson(), true); } else if (is_object($collection) || is_array($collection)) { return (array)$collection; } else { throw new \InvalidArgumentException(sprintf( '$collection has type %s, which is not collection-like', gettype($collection) )); } }
php
protected function collection_to_array($collection) { if ($collection instanceof self) { return $collection->toArray(); } else if ($collection instanceof \Traversable) { return iterator_to_array($collection); } else if ($collection instanceof Arrayable) { return $collection->toArray(); } else if ($collection instanceof Jsonable) { return json_decode($collection->toJson(), true); } else if (is_object($collection) || is_array($collection)) { return (array)$collection; } else { throw new \InvalidArgumentException(sprintf( '$collection has type %s, which is not collection-like', gettype($collection) )); } }
[ "protected", "function", "collection_to_array", "(", "$", "collection", ")", "{", "if", "(", "$", "collection", "instanceof", "self", ")", "{", "return", "$", "collection", "->", "toArray", "(", ")", ";", "}", "else", "if", "(", "$", "collection", "instanceof", "\\", "Traversable", ")", "{", "return", "iterator_to_array", "(", "$", "collection", ")", ";", "}", "else", "if", "(", "$", "collection", "instanceof", "Arrayable", ")", "{", "return", "$", "collection", "->", "toArray", "(", ")", ";", "}", "else", "if", "(", "$", "collection", "instanceof", "Jsonable", ")", "{", "return", "json_decode", "(", "$", "collection", "->", "toJson", "(", ")", ",", "true", ")", ";", "}", "else", "if", "(", "is_object", "(", "$", "collection", ")", "||", "is_array", "(", "$", "collection", ")", ")", "{", "return", "(", "array", ")", "$", "collection", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'$collection has type %s, which is not collection-like'", ",", "gettype", "(", "$", "collection", ")", ")", ")", ";", "}", "}" ]
Give me a native PHP array, regardless of what kind of collection-like structure is given. @param Map|Traversable|Arrayable|Jsonable|object|array $items @return array|boolean @throws \InvalidArgumentException
[ "Give", "me", "a", "native", "PHP", "array", "regardless", "of", "what", "kind", "of", "collection", "-", "like", "structure", "is", "given", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L874-L897
haldayne/boost
src/Map.php
Map.grep
protected function grep($expression, $limit = null) { // initialize our return map and book-keeping values $map = new static; $bnd = empty($limit) ? null : abs($limit); $cnt = 0; // define a helper to add matching values to our new map, stopping when // any designated limit is reached $helper = function ($value, $key) use ($expression, $map, $bnd, &$cnt) { if ($this->passes($this->call($expression, $value, $key))) { $map->set($key, $value); if (null !== $bnd && $bnd <= ++$cnt) { return false; } } }; // walk the array in the right direction if (0 <= $limit) { $this->walk($helper); } else { $this->walk_backward($helper); } return $map; }
php
protected function grep($expression, $limit = null) { // initialize our return map and book-keeping values $map = new static; $bnd = empty($limit) ? null : abs($limit); $cnt = 0; // define a helper to add matching values to our new map, stopping when // any designated limit is reached $helper = function ($value, $key) use ($expression, $map, $bnd, &$cnt) { if ($this->passes($this->call($expression, $value, $key))) { $map->set($key, $value); if (null !== $bnd && $bnd <= ++$cnt) { return false; } } }; // walk the array in the right direction if (0 <= $limit) { $this->walk($helper); } else { $this->walk_backward($helper); } return $map; }
[ "protected", "function", "grep", "(", "$", "expression", ",", "$", "limit", "=", "null", ")", "{", "// initialize our return map and book-keeping values", "$", "map", "=", "new", "static", ";", "$", "bnd", "=", "empty", "(", "$", "limit", ")", "?", "null", ":", "abs", "(", "$", "limit", ")", ";", "$", "cnt", "=", "0", ";", "// define a helper to add matching values to our new map, stopping when", "// any designated limit is reached", "$", "helper", "=", "function", "(", "$", "value", ",", "$", "key", ")", "use", "(", "$", "expression", ",", "$", "map", ",", "$", "bnd", ",", "&", "$", "cnt", ")", "{", "if", "(", "$", "this", "->", "passes", "(", "$", "this", "->", "call", "(", "$", "expression", ",", "$", "value", ",", "$", "key", ")", ")", ")", "{", "$", "map", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "if", "(", "null", "!==", "$", "bnd", "&&", "$", "bnd", "<=", "++", "$", "cnt", ")", "{", "return", "false", ";", "}", "}", "}", ";", "// walk the array in the right direction", "if", "(", "0", "<=", "$", "limit", ")", "{", "$", "this", "->", "walk", "(", "$", "helper", ")", ";", "}", "else", "{", "$", "this", "->", "walk_backward", "(", "$", "helper", ")", ";", "}", "return", "$", "map", ";", "}" ]
Finds elements for which the given code passes, optionally limited to a maximum count. If limit is null, no limit on number of matches. If limit is positive, return that many from the front of the array. If limit is negative, return that many from the end of the array. @param callable|string $expression @param int|null $limit @return new static
[ "Finds", "elements", "for", "which", "the", "given", "code", "passes", "optionally", "limited", "to", "a", "maximum", "count", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L911-L938
haldayne/boost
src/Map.php
Map.walk
protected function walk(callable $code) { foreach ($this->array as $hash => &$value) { $key = $this->hash_to_key($hash); if (! $this->passes($this->call($code, $value, $key))) { break; } } return $this; }
php
protected function walk(callable $code) { foreach ($this->array as $hash => &$value) { $key = $this->hash_to_key($hash); if (! $this->passes($this->call($code, $value, $key))) { break; } } return $this; }
[ "protected", "function", "walk", "(", "callable", "$", "code", ")", "{", "foreach", "(", "$", "this", "->", "array", "as", "$", "hash", "=>", "&", "$", "value", ")", "{", "$", "key", "=", "$", "this", "->", "hash_to_key", "(", "$", "hash", ")", ";", "if", "(", "!", "$", "this", "->", "passes", "(", "$", "this", "->", "call", "(", "$", "code", ",", "$", "value", ",", "$", "key", ")", ")", ")", "{", "break", ";", "}", "}", "return", "$", "this", ";", "}" ]
Execute the given code over each element of the map. The code receives the value by reference and then the key as formal parameters. The items are walked in the order they exist in the map. If the code returns boolean false, then the iteration halts. Values can be modified from within the callback, but not keys. Example: ``` $map->each(function (&$value, $key) { $value++; return true; })->sum(); ``` @param callable $code @return $this
[ "Execute", "the", "given", "code", "over", "each", "element", "of", "the", "map", ".", "The", "code", "receives", "the", "value", "by", "reference", "and", "then", "the", "key", "as", "formal", "parameters", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L956-L965
haldayne/boost
src/Map.php
Map.walk_backward
protected function walk_backward(callable $code) { for (end($this->array); null !== ($hash = key($this->array)); prev($this->array)) { $key = $this->hash_to_key($hash); $current = current($this->array); $value =& $current; if (! $this->passes($this->call($code, $value, $key))) { break; } } return $this; }
php
protected function walk_backward(callable $code) { for (end($this->array); null !== ($hash = key($this->array)); prev($this->array)) { $key = $this->hash_to_key($hash); $current = current($this->array); $value =& $current; if (! $this->passes($this->call($code, $value, $key))) { break; } } return $this; }
[ "protected", "function", "walk_backward", "(", "callable", "$", "code", ")", "{", "for", "(", "end", "(", "$", "this", "->", "array", ")", ";", "null", "!==", "(", "$", "hash", "=", "key", "(", "$", "this", "->", "array", ")", ")", ";", "prev", "(", "$", "this", "->", "array", ")", ")", "{", "$", "key", "=", "$", "this", "->", "hash_to_key", "(", "$", "hash", ")", ";", "$", "current", "=", "current", "(", "$", "this", "->", "array", ")", ";", "$", "value", "=", "&", "$", "current", ";", "if", "(", "!", "$", "this", "->", "passes", "(", "$", "this", "->", "call", "(", "$", "code", ",", "$", "value", ",", "$", "key", ")", ")", ")", "{", "break", ";", "}", "}", "return", "$", "this", ";", "}" ]
Like `walk`, except walk from the end toward the front. @param callable $code @return $this
[ "Like", "walk", "except", "walk", "from", "the", "end", "toward", "the", "front", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L973-L984
haldayne/boost
src/Map.php
Map.key_to_hash
private function key_to_hash($key) { if (null === $key) { $hash = 'null'; } else if (is_int($key)) { $hash = $key; } else if (is_float($key)) { $hash = "f_$key"; } else if (is_bool($key)) { $hash = "b_$key"; } else if (is_string($key)) { $hash = "s_$key"; } else if (is_object($key) || is_callable($key)) { $hash = spl_object_hash($key); } else if (is_array($key)) { $hash = 'a_' . md5(json_encode($key)); } else if (is_resource($key)) { $hash = "r_$key"; } else { throw new \InvalidArgumentException(sprintf( 'Unsupported key type "%s"', gettype($key) )); } $this->map_hash_to_key[$hash] = $key; return $hash; }
php
private function key_to_hash($key) { if (null === $key) { $hash = 'null'; } else if (is_int($key)) { $hash = $key; } else if (is_float($key)) { $hash = "f_$key"; } else if (is_bool($key)) { $hash = "b_$key"; } else if (is_string($key)) { $hash = "s_$key"; } else if (is_object($key) || is_callable($key)) { $hash = spl_object_hash($key); } else if (is_array($key)) { $hash = 'a_' . md5(json_encode($key)); } else if (is_resource($key)) { $hash = "r_$key"; } else { throw new \InvalidArgumentException(sprintf( 'Unsupported key type "%s"', gettype($key) )); } $this->map_hash_to_key[$hash] = $key; return $hash; }
[ "private", "function", "key_to_hash", "(", "$", "key", ")", "{", "if", "(", "null", "===", "$", "key", ")", "{", "$", "hash", "=", "'null'", ";", "}", "else", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "$", "key", ";", "}", "else", "if", "(", "is_float", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "\"f_$key\"", ";", "}", "else", "if", "(", "is_bool", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "\"b_$key\"", ";", "}", "else", "if", "(", "is_string", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "\"s_$key\"", ";", "}", "else", "if", "(", "is_object", "(", "$", "key", ")", "||", "is_callable", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "spl_object_hash", "(", "$", "key", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "'a_'", ".", "md5", "(", "json_encode", "(", "$", "key", ")", ")", ";", "}", "else", "if", "(", "is_resource", "(", "$", "key", ")", ")", "{", "$", "hash", "=", "\"r_$key\"", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Unsupported key type \"%s\"'", ",", "gettype", "(", "$", "key", ")", ")", ")", ";", "}", "$", "this", "->", "map_hash_to_key", "[", "$", "hash", "]", "=", "$", "key", ";", "return", "$", "hash", ";", "}" ]
Lookup the hash for the given key. If a hash does not yet exist, one is created. @param mixed $key @return string @throws \InvalidArgumentException
[ "Lookup", "the", "hash", "for", "the", "given", "key", ".", "If", "a", "hash", "does", "not", "yet", "exist", "one", "is", "created", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L1009-L1044
haldayne/boost
src/Map.php
Map.hash_to_key
private function hash_to_key($hash) { if (array_key_exists($hash, $this->map_hash_to_key)) { return $this->map_hash_to_key[$hash]; } else { throw new \OutOfBoundsException(sprintf( 'Hash "%s" has not been created', $hash )); } }
php
private function hash_to_key($hash) { if (array_key_exists($hash, $this->map_hash_to_key)) { return $this->map_hash_to_key[$hash]; } else { throw new \OutOfBoundsException(sprintf( 'Hash "%s" has not been created', $hash )); } }
[ "private", "function", "hash_to_key", "(", "$", "hash", ")", "{", "if", "(", "array_key_exists", "(", "$", "hash", ",", "$", "this", "->", "map_hash_to_key", ")", ")", "{", "return", "$", "this", "->", "map_hash_to_key", "[", "$", "hash", "]", ";", "}", "else", "{", "throw", "new", "\\", "OutOfBoundsException", "(", "sprintf", "(", "'Hash \"%s\" has not been created'", ",", "$", "hash", ")", ")", ";", "}", "}" ]
Lookup the key for the given hash. @param string $hash @return mixed
[ "Lookup", "the", "key", "for", "the", "given", "hash", "." ]
train
https://github.com/haldayne/boost/blob/d18cc398557e23f9c316ea7fb40b90f84cc53650/src/Map.php#L1052-L1062
iocaste/microservice-foundation
src/Repository/Repository.php
Repository.getColumnsNames
public function getColumnsNames(array $columns, $model = null): array { return array_map(function ($column) use ($model) { return $this->getColumnName($column, $model); }, $columns); }
php
public function getColumnsNames(array $columns, $model = null): array { return array_map(function ($column) use ($model) { return $this->getColumnName($column, $model); }, $columns); }
[ "public", "function", "getColumnsNames", "(", "array", "$", "columns", ",", "$", "model", "=", "null", ")", ":", "array", "{", "return", "array_map", "(", "function", "(", "$", "column", ")", "use", "(", "$", "model", ")", "{", "return", "$", "this", "->", "getColumnName", "(", "$", "column", ",", "$", "model", ")", ";", "}", ",", "$", "columns", ")", ";", "}" ]
@param array $columns @param mixed $model @return array
[ "@param", "array", "$columns", "@param", "mixed", "$model" ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Repository/Repository.php#L41-L46
iocaste/microservice-foundation
src/Repository/Repository.php
Repository.getTableName
public function getTableName($model = null) { $model = $model ?? $this->model; if ($model instanceof Model) { return $model->getTable(); } elseif ($model instanceof EloquentBuilder) { return $model->getModel()->getTable(); } return $model->from; }
php
public function getTableName($model = null) { $model = $model ?? $this->model; if ($model instanceof Model) { return $model->getTable(); } elseif ($model instanceof EloquentBuilder) { return $model->getModel()->getTable(); } return $model->from; }
[ "public", "function", "getTableName", "(", "$", "model", "=", "null", ")", "{", "$", "model", "=", "$", "model", "??", "$", "this", "->", "model", ";", "if", "(", "$", "model", "instanceof", "Model", ")", "{", "return", "$", "model", "->", "getTable", "(", ")", ";", "}", "elseif", "(", "$", "model", "instanceof", "EloquentBuilder", ")", "{", "return", "$", "model", "->", "getModel", "(", ")", "->", "getTable", "(", ")", ";", "}", "return", "$", "model", "->", "from", ";", "}" ]
@param mixed $model @return string
[ "@param", "mixed", "$model" ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Repository/Repository.php#L53-L64
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.initialize
public function initialize(Table $table) { $this->table = $table; $this->table->isProcessing(true); $this->table->isServerSide(true); if (!is_null($this->ajax)) { $this->table->setAjax($this->ajax); } }
php
public function initialize(Table $table) { $this->table = $table; $this->table->isProcessing(true); $this->table->isServerSide(true); if (!is_null($this->ajax)) { $this->table->setAjax($this->ajax); } }
[ "public", "function", "initialize", "(", "Table", "$", "table", ")", "{", "$", "this", "->", "table", "=", "$", "table", ";", "$", "this", "->", "table", "->", "isProcessing", "(", "true", ")", ";", "$", "this", "->", "table", "->", "isServerSide", "(", "true", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "ajax", ")", ")", "{", "$", "this", "->", "table", "->", "setAjax", "(", "$", "this", "->", "ajax", ")", ";", "}", "}" ]
Initialize data source @param Table $table Table object @return void
[ "Initialize", "data", "source" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L67-L76
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.getResponse
public function getResponse(Response $response, Request $request) { $this->prepareSearch($request); $this->preparePaging($request); $this->prepareOrder($request); $data = []; /** @var $entity Entity */ foreach ($this->query as $entity) { $row = []; foreach ($this->table->getColumns() as $column) { if ($column instanceof ColumnInterface) { $row[$column->getData()] = $column->getContent($entity); continue; } $property = $this->getProperty($column->getData()); $columnData = explode('.', $column->getData()); $tableAlias = $columnData[0]; $colName = $columnData[1]; /** * If property is association */ if (is_array($property)) { if (is_callable($column->getFormatter())) { $row[$tableAlias][$colName] = $this->doFormatter( $column->getFormatter(), [ $entity->get($property['propertyPath']) instanceof Entity ? $entity->get($property['propertyPath'])->get($property['field']) : $entity->get($property['propertyPath']), $entity, $entity->get($property['propertyPath']) ] ); } else { if ($entity->get($property['propertyPath']) instanceof Entity) { $row[$tableAlias][$colName] = (string)$entity->get($property['propertyPath'])->get($property['field']); /** * BelongsToMany Association */ } elseif (is_array($entity->get($property['propertyPath']))) { $output = []; /** @var Entity $belongsToManyEntity */ foreach ($entity->get($property['propertyPath']) as $belongsToManyEntity) { $output[] = $belongsToManyEntity->get($property['field']); } $row[$tableAlias][$colName] = implode(', ', $output); } } } else { if (is_callable($column->getFormatter())) { $row[$tableAlias][$colName] = $this->doFormatter( $column->getFormatter(), [$entity->get($property), $entity] ); } else { $row[$tableAlias][$colName] = (string)$entity->get($property); } } } $data[] = $row; } $response->setDraw($request->getDraw()) ->setRecordsTotal($this->clonedQuery->count()) ->setRecordsFiltered(self::$countBeforePaging) ->setData($data); }
php
public function getResponse(Response $response, Request $request) { $this->prepareSearch($request); $this->preparePaging($request); $this->prepareOrder($request); $data = []; /** @var $entity Entity */ foreach ($this->query as $entity) { $row = []; foreach ($this->table->getColumns() as $column) { if ($column instanceof ColumnInterface) { $row[$column->getData()] = $column->getContent($entity); continue; } $property = $this->getProperty($column->getData()); $columnData = explode('.', $column->getData()); $tableAlias = $columnData[0]; $colName = $columnData[1]; /** * If property is association */ if (is_array($property)) { if (is_callable($column->getFormatter())) { $row[$tableAlias][$colName] = $this->doFormatter( $column->getFormatter(), [ $entity->get($property['propertyPath']) instanceof Entity ? $entity->get($property['propertyPath'])->get($property['field']) : $entity->get($property['propertyPath']), $entity, $entity->get($property['propertyPath']) ] ); } else { if ($entity->get($property['propertyPath']) instanceof Entity) { $row[$tableAlias][$colName] = (string)$entity->get($property['propertyPath'])->get($property['field']); /** * BelongsToMany Association */ } elseif (is_array($entity->get($property['propertyPath']))) { $output = []; /** @var Entity $belongsToManyEntity */ foreach ($entity->get($property['propertyPath']) as $belongsToManyEntity) { $output[] = $belongsToManyEntity->get($property['field']); } $row[$tableAlias][$colName] = implode(', ', $output); } } } else { if (is_callable($column->getFormatter())) { $row[$tableAlias][$colName] = $this->doFormatter( $column->getFormatter(), [$entity->get($property), $entity] ); } else { $row[$tableAlias][$colName] = (string)$entity->get($property); } } } $data[] = $row; } $response->setDraw($request->getDraw()) ->setRecordsTotal($this->clonedQuery->count()) ->setRecordsFiltered(self::$countBeforePaging) ->setData($data); }
[ "public", "function", "getResponse", "(", "Response", "$", "response", ",", "Request", "$", "request", ")", "{", "$", "this", "->", "prepareSearch", "(", "$", "request", ")", ";", "$", "this", "->", "preparePaging", "(", "$", "request", ")", ";", "$", "this", "->", "prepareOrder", "(", "$", "request", ")", ";", "$", "data", "=", "[", "]", ";", "/** @var $entity Entity */", "foreach", "(", "$", "this", "->", "query", "as", "$", "entity", ")", "{", "$", "row", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "table", "->", "getColumns", "(", ")", "as", "$", "column", ")", "{", "if", "(", "$", "column", "instanceof", "ColumnInterface", ")", "{", "$", "row", "[", "$", "column", "->", "getData", "(", ")", "]", "=", "$", "column", "->", "getContent", "(", "$", "entity", ")", ";", "continue", ";", "}", "$", "property", "=", "$", "this", "->", "getProperty", "(", "$", "column", "->", "getData", "(", ")", ")", ";", "$", "columnData", "=", "explode", "(", "'.'", ",", "$", "column", "->", "getData", "(", ")", ")", ";", "$", "tableAlias", "=", "$", "columnData", "[", "0", "]", ";", "$", "colName", "=", "$", "columnData", "[", "1", "]", ";", "/**\n * If property is association\n */", "if", "(", "is_array", "(", "$", "property", ")", ")", "{", "if", "(", "is_callable", "(", "$", "column", "->", "getFormatter", "(", ")", ")", ")", "{", "$", "row", "[", "$", "tableAlias", "]", "[", "$", "colName", "]", "=", "$", "this", "->", "doFormatter", "(", "$", "column", "->", "getFormatter", "(", ")", ",", "[", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "instanceof", "Entity", "?", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "->", "get", "(", "$", "property", "[", "'field'", "]", ")", ":", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", ",", "$", "entity", ",", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "]", ")", ";", "}", "else", "{", "if", "(", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "instanceof", "Entity", ")", "{", "$", "row", "[", "$", "tableAlias", "]", "[", "$", "colName", "]", "=", "(", "string", ")", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "->", "get", "(", "$", "property", "[", "'field'", "]", ")", ";", "/**\n * BelongsToMany Association\n */", "}", "elseif", "(", "is_array", "(", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", ")", ")", "{", "$", "output", "=", "[", "]", ";", "/** @var Entity $belongsToManyEntity */", "foreach", "(", "$", "entity", "->", "get", "(", "$", "property", "[", "'propertyPath'", "]", ")", "as", "$", "belongsToManyEntity", ")", "{", "$", "output", "[", "]", "=", "$", "belongsToManyEntity", "->", "get", "(", "$", "property", "[", "'field'", "]", ")", ";", "}", "$", "row", "[", "$", "tableAlias", "]", "[", "$", "colName", "]", "=", "implode", "(", "', '", ",", "$", "output", ")", ";", "}", "}", "}", "else", "{", "if", "(", "is_callable", "(", "$", "column", "->", "getFormatter", "(", ")", ")", ")", "{", "$", "row", "[", "$", "tableAlias", "]", "[", "$", "colName", "]", "=", "$", "this", "->", "doFormatter", "(", "$", "column", "->", "getFormatter", "(", ")", ",", "[", "$", "entity", "->", "get", "(", "$", "property", ")", ",", "$", "entity", "]", ")", ";", "}", "else", "{", "$", "row", "[", "$", "tableAlias", "]", "[", "$", "colName", "]", "=", "(", "string", ")", "$", "entity", "->", "get", "(", "$", "property", ")", ";", "}", "}", "}", "$", "data", "[", "]", "=", "$", "row", ";", "}", "$", "response", "->", "setDraw", "(", "$", "request", "->", "getDraw", "(", ")", ")", "->", "setRecordsTotal", "(", "$", "this", "->", "clonedQuery", "->", "count", "(", ")", ")", "->", "setRecordsFiltered", "(", "self", "::", "$", "countBeforePaging", ")", "->", "setData", "(", "$", "data", ")", ";", "}" ]
Get DataTable response @param Response $response DataTable response object @param Request $request DataTable request object @return void
[ "Get", "DataTable", "response" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L86-L157
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.setQuery
public function setQuery(Query $query) { $this->query = $query; $this->clonedQuery = clone $query; return $this; }
php
public function setQuery(Query $query) { $this->query = $query; $this->clonedQuery = clone $query; return $this; }
[ "public", "function", "setQuery", "(", "Query", "$", "query", ")", "{", "$", "this", "->", "query", "=", "$", "query", ";", "$", "this", "->", "clonedQuery", "=", "clone", "$", "query", ";", "return", "$", "this", ";", "}" ]
Set CakePHP query @param Query $query CakePHP query @return CakePHP
[ "Set", "CakePHP", "query" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L166-L172
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.preparePaging
protected function preparePaging(Request $request) { self::$countBeforePaging = $this->query->count(); $this->query->limit($request->getLength()); $this->query->offset($request->getStart()); }
php
protected function preparePaging(Request $request) { self::$countBeforePaging = $this->query->count(); $this->query->limit($request->getLength()); $this->query->offset($request->getStart()); }
[ "protected", "function", "preparePaging", "(", "Request", "$", "request", ")", "{", "self", "::", "$", "countBeforePaging", "=", "$", "this", "->", "query", "->", "count", "(", ")", ";", "$", "this", "->", "query", "->", "limit", "(", "$", "request", "->", "getLength", "(", ")", ")", ";", "$", "this", "->", "query", "->", "offset", "(", "$", "request", "->", "getStart", "(", ")", ")", ";", "}" ]
Prepare CakePHP paging @param Request $request DataTable request
[ "Prepare", "CakePHP", "paging" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L179-L184
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.prepareSearch
protected function prepareSearch(Request $request) { $value = $request->getSearch()->getValue(); if (!empty($value)) { $where = []; foreach ($request->getColumns() as $column) { if ($column->getSearchable() === true) { $where[$column->getData() . ' LIKE'] = '%' . $value . '%'; } } $this->query->andWhere( function (QueryExpression $exp) use ($where) { return $exp->or_($where); } ); } }
php
protected function prepareSearch(Request $request) { $value = $request->getSearch()->getValue(); if (!empty($value)) { $where = []; foreach ($request->getColumns() as $column) { if ($column->getSearchable() === true) { $where[$column->getData() . ' LIKE'] = '%' . $value . '%'; } } $this->query->andWhere( function (QueryExpression $exp) use ($where) { return $exp->or_($where); } ); } }
[ "protected", "function", "prepareSearch", "(", "Request", "$", "request", ")", "{", "$", "value", "=", "$", "request", "->", "getSearch", "(", ")", "->", "getValue", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "where", "=", "[", "]", ";", "foreach", "(", "$", "request", "->", "getColumns", "(", ")", "as", "$", "column", ")", "{", "if", "(", "$", "column", "->", "getSearchable", "(", ")", "===", "true", ")", "{", "$", "where", "[", "$", "column", "->", "getData", "(", ")", ".", "' LIKE'", "]", "=", "'%'", ".", "$", "value", ".", "'%'", ";", "}", "}", "$", "this", "->", "query", "->", "andWhere", "(", "function", "(", "QueryExpression", "$", "exp", ")", "use", "(", "$", "where", ")", "{", "return", "$", "exp", "->", "or_", "(", "$", "where", ")", ";", "}", ")", ";", "}", "}" ]
Prepare CakePHP search @param Request $request DataTable request
[ "Prepare", "CakePHP", "search" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L191-L209
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.prepareOrder
protected function prepareOrder(Request $request) { foreach ($request->getOrder() as $order) { $this->query->order( [$this->table->getColumns()[$order->getColumn()]->getData() => strtoupper($order->getDir())] ); } }
php
protected function prepareOrder(Request $request) { foreach ($request->getOrder() as $order) { $this->query->order( [$this->table->getColumns()[$order->getColumn()]->getData() => strtoupper($order->getDir())] ); } }
[ "protected", "function", "prepareOrder", "(", "Request", "$", "request", ")", "{", "foreach", "(", "$", "request", "->", "getOrder", "(", ")", "as", "$", "order", ")", "{", "$", "this", "->", "query", "->", "order", "(", "[", "$", "this", "->", "table", "->", "getColumns", "(", ")", "[", "$", "order", "->", "getColumn", "(", ")", "]", "->", "getData", "(", ")", "=>", "strtoupper", "(", "$", "order", "->", "getDir", "(", ")", ")", "]", ")", ";", "}", "}" ]
Prepare CakePHP order @param Request $request DataTable request
[ "Prepare", "CakePHP", "order" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L216-L223
atkrad/data-tables
src/DataSource/ServerSide/CakePHP.php
CakePHP.getProperty
protected function getProperty($dataName) { $dataName = explode('.', trim($dataName)); if (count($dataName) != 2) { throw new Exception('You are set invalid date.'); } $tableAlias = $dataName[0]; $colName = $dataName[1]; if ($this->query->repository()->alias() == $tableAlias) { return $colName; } elseif (array_key_exists($tableAlias, $this->query->contain())) { return [ 'propertyPath' => $this->query ->eagerLoader()->normalized($this->query->repository())[$tableAlias]['propertyPath'], 'field' => $colName ]; } }
php
protected function getProperty($dataName) { $dataName = explode('.', trim($dataName)); if (count($dataName) != 2) { throw new Exception('You are set invalid date.'); } $tableAlias = $dataName[0]; $colName = $dataName[1]; if ($this->query->repository()->alias() == $tableAlias) { return $colName; } elseif (array_key_exists($tableAlias, $this->query->contain())) { return [ 'propertyPath' => $this->query ->eagerLoader()->normalized($this->query->repository())[$tableAlias]['propertyPath'], 'field' => $colName ]; } }
[ "protected", "function", "getProperty", "(", "$", "dataName", ")", "{", "$", "dataName", "=", "explode", "(", "'.'", ",", "trim", "(", "$", "dataName", ")", ")", ";", "if", "(", "count", "(", "$", "dataName", ")", "!=", "2", ")", "{", "throw", "new", "Exception", "(", "'You are set invalid date.'", ")", ";", "}", "$", "tableAlias", "=", "$", "dataName", "[", "0", "]", ";", "$", "colName", "=", "$", "dataName", "[", "1", "]", ";", "if", "(", "$", "this", "->", "query", "->", "repository", "(", ")", "->", "alias", "(", ")", "==", "$", "tableAlias", ")", "{", "return", "$", "colName", ";", "}", "elseif", "(", "array_key_exists", "(", "$", "tableAlias", ",", "$", "this", "->", "query", "->", "contain", "(", ")", ")", ")", "{", "return", "[", "'propertyPath'", "=>", "$", "this", "->", "query", "->", "eagerLoader", "(", ")", "->", "normalized", "(", "$", "this", "->", "query", "->", "repository", "(", ")", ")", "[", "$", "tableAlias", "]", "[", "'propertyPath'", "]", ",", "'field'", "=>", "$", "colName", "]", ";", "}", "}" ]
Get CakePHP property @param string $dataName Column data name @throws Exception @return array|string
[ "Get", "CakePHP", "property" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/ServerSide/CakePHP.php#L233-L253
qcubed/orm
src/Query/Clause/OrderBy.php
OrderBy.collapseNodes
protected function collapseNodes($mixParameterArray) { /** @var Node\NodeBase[] $objNodeArray */ $objNodeArray = array(); foreach ($mixParameterArray as $mixParameter) { if (is_array($mixParameter)) { $objNodeArray = array_merge($objNodeArray, $mixParameter); } else { array_push($objNodeArray, $mixParameter); } } $blnPreviousIsNode = false; $objFinalNodeArray = array(); foreach ($objNodeArray as $objNode) { if (!($objNode instanceof Node\NodeBase || $objNode instanceof iCondition)) { if (!$blnPreviousIsNode) { throw new Caller('OrderBy clause parameters must all be Node\NodeBase or iCondition objects followed by an optional true/false "Ascending Order" option', 3); } $blnPreviousIsNode = false; array_push($objFinalNodeArray, $objNode); } elseif ($objNode instanceof iCondition) { $blnPreviousIsNode = true; array_push($objFinalNodeArray, $objNode); } else { if (!$objNode->_ParentNode) { throw new InvalidCast('Unable to cast "' . $objNode->_Name . '" table to Column-based Node\NodeBase', 4); } if ($objNode->_PrimaryKeyNode) { // if a table node, then use the primary key of the table array_push($objFinalNodeArray, $objNode->_PrimaryKeyNode); } else { array_push($objFinalNodeArray, $objNode); } $blnPreviousIsNode = true; } } if (count($objFinalNodeArray)) { return $objFinalNodeArray; } else { throw new Caller('No parameters passed in to OrderBy clause', 3); } }
php
protected function collapseNodes($mixParameterArray) { /** @var Node\NodeBase[] $objNodeArray */ $objNodeArray = array(); foreach ($mixParameterArray as $mixParameter) { if (is_array($mixParameter)) { $objNodeArray = array_merge($objNodeArray, $mixParameter); } else { array_push($objNodeArray, $mixParameter); } } $blnPreviousIsNode = false; $objFinalNodeArray = array(); foreach ($objNodeArray as $objNode) { if (!($objNode instanceof Node\NodeBase || $objNode instanceof iCondition)) { if (!$blnPreviousIsNode) { throw new Caller('OrderBy clause parameters must all be Node\NodeBase or iCondition objects followed by an optional true/false "Ascending Order" option', 3); } $blnPreviousIsNode = false; array_push($objFinalNodeArray, $objNode); } elseif ($objNode instanceof iCondition) { $blnPreviousIsNode = true; array_push($objFinalNodeArray, $objNode); } else { if (!$objNode->_ParentNode) { throw new InvalidCast('Unable to cast "' . $objNode->_Name . '" table to Column-based Node\NodeBase', 4); } if ($objNode->_PrimaryKeyNode) { // if a table node, then use the primary key of the table array_push($objFinalNodeArray, $objNode->_PrimaryKeyNode); } else { array_push($objFinalNodeArray, $objNode); } $blnPreviousIsNode = true; } } if (count($objFinalNodeArray)) { return $objFinalNodeArray; } else { throw new Caller('No parameters passed in to OrderBy clause', 3); } }
[ "protected", "function", "collapseNodes", "(", "$", "mixParameterArray", ")", "{", "/** @var Node\\NodeBase[] $objNodeArray */", "$", "objNodeArray", "=", "array", "(", ")", ";", "foreach", "(", "$", "mixParameterArray", "as", "$", "mixParameter", ")", "{", "if", "(", "is_array", "(", "$", "mixParameter", ")", ")", "{", "$", "objNodeArray", "=", "array_merge", "(", "$", "objNodeArray", ",", "$", "mixParameter", ")", ";", "}", "else", "{", "array_push", "(", "$", "objNodeArray", ",", "$", "mixParameter", ")", ";", "}", "}", "$", "blnPreviousIsNode", "=", "false", ";", "$", "objFinalNodeArray", "=", "array", "(", ")", ";", "foreach", "(", "$", "objNodeArray", "as", "$", "objNode", ")", "{", "if", "(", "!", "(", "$", "objNode", "instanceof", "Node", "\\", "NodeBase", "||", "$", "objNode", "instanceof", "iCondition", ")", ")", "{", "if", "(", "!", "$", "blnPreviousIsNode", ")", "{", "throw", "new", "Caller", "(", "'OrderBy clause parameters must all be Node\\NodeBase or iCondition objects followed by an optional true/false \"Ascending Order\" option'", ",", "3", ")", ";", "}", "$", "blnPreviousIsNode", "=", "false", ";", "array_push", "(", "$", "objFinalNodeArray", ",", "$", "objNode", ")", ";", "}", "elseif", "(", "$", "objNode", "instanceof", "iCondition", ")", "{", "$", "blnPreviousIsNode", "=", "true", ";", "array_push", "(", "$", "objFinalNodeArray", ",", "$", "objNode", ")", ";", "}", "else", "{", "if", "(", "!", "$", "objNode", "->", "_ParentNode", ")", "{", "throw", "new", "InvalidCast", "(", "'Unable to cast \"'", ".", "$", "objNode", "->", "_Name", ".", "'\" table to Column-based Node\\NodeBase'", ",", "4", ")", ";", "}", "if", "(", "$", "objNode", "->", "_PrimaryKeyNode", ")", "{", "// if a table node, then use the primary key of the table", "array_push", "(", "$", "objFinalNodeArray", ",", "$", "objNode", "->", "_PrimaryKeyNode", ")", ";", "}", "else", "{", "array_push", "(", "$", "objFinalNodeArray", ",", "$", "objNode", ")", ";", "}", "$", "blnPreviousIsNode", "=", "true", ";", "}", "}", "if", "(", "count", "(", "$", "objFinalNodeArray", ")", ")", "{", "return", "$", "objFinalNodeArray", ";", "}", "else", "{", "throw", "new", "Caller", "(", "'No parameters passed in to OrderBy clause'", ",", "3", ")", ";", "}", "}" ]
CollapseNodes makes sure a node list is vetted, and turned into a node list. This also allows table nodes to be used in certain column node contexts, in which it will substitute the primary key node in this situation. @param $mixParameterArray @return array @throws Caller @throws InvalidCast
[ "CollapseNodes", "makes", "sure", "a", "node", "list", "is", "vetted", "and", "turned", "into", "a", "node", "list", ".", "This", "also", "allows", "table", "nodes", "to", "be", "used", "in", "certain", "column", "node", "contexts", "in", "which", "it", "will", "substitute", "the", "primary", "key", "node", "in", "this", "situation", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Query/Clause/OrderBy.php#L40-L84
qcubed/orm
src/Query/Clause/OrderBy.php
OrderBy._UpdateQueryBuilder
public function _UpdateQueryBuilder(Builder $objBuilder) { $intLength = count($this->objNodeArray); for ($intIndex = 0; $intIndex < $intLength; $intIndex++) { $objNode = $this->objNodeArray[$intIndex]; if ($objNode instanceof Node\Virtual) { if ($objNode->hasSubquery()) { throw new Caller('You cannot define a virtual node in an order by clause. You must use an Expand clause to define it.'); } $strOrderByCommand = '__' . $objNode->getAttributeName(); } elseif ($objNode instanceof Node\Column) { /** @var Node\Column $objNode */ $strOrderByCommand = $objNode->getColumnAlias($objBuilder); } elseif ($objNode instanceof iCondition) { /** @var iCondition $objNode */ $strOrderByCommand = $objNode->getWhereClause($objBuilder); } else { $strOrderByCommand = ''; } // Check to see if they want a ASC/DESC declarator if ((($intIndex + 1) < $intLength) && !($this->objNodeArray[$intIndex + 1] instanceof Node\NodeBase) ) { if ((!$this->objNodeArray[$intIndex + 1]) || (trim(strtolower($this->objNodeArray[$intIndex + 1])) == 'desc') ) { $strOrderByCommand .= ' DESC'; } else { $strOrderByCommand .= ' ASC'; } $intIndex++; } $objBuilder->addOrderByItem($strOrderByCommand); } }
php
public function _UpdateQueryBuilder(Builder $objBuilder) { $intLength = count($this->objNodeArray); for ($intIndex = 0; $intIndex < $intLength; $intIndex++) { $objNode = $this->objNodeArray[$intIndex]; if ($objNode instanceof Node\Virtual) { if ($objNode->hasSubquery()) { throw new Caller('You cannot define a virtual node in an order by clause. You must use an Expand clause to define it.'); } $strOrderByCommand = '__' . $objNode->getAttributeName(); } elseif ($objNode instanceof Node\Column) { /** @var Node\Column $objNode */ $strOrderByCommand = $objNode->getColumnAlias($objBuilder); } elseif ($objNode instanceof iCondition) { /** @var iCondition $objNode */ $strOrderByCommand = $objNode->getWhereClause($objBuilder); } else { $strOrderByCommand = ''; } // Check to see if they want a ASC/DESC declarator if ((($intIndex + 1) < $intLength) && !($this->objNodeArray[$intIndex + 1] instanceof Node\NodeBase) ) { if ((!$this->objNodeArray[$intIndex + 1]) || (trim(strtolower($this->objNodeArray[$intIndex + 1])) == 'desc') ) { $strOrderByCommand .= ' DESC'; } else { $strOrderByCommand .= ' ASC'; } $intIndex++; } $objBuilder->addOrderByItem($strOrderByCommand); } }
[ "public", "function", "_UpdateQueryBuilder", "(", "Builder", "$", "objBuilder", ")", "{", "$", "intLength", "=", "count", "(", "$", "this", "->", "objNodeArray", ")", ";", "for", "(", "$", "intIndex", "=", "0", ";", "$", "intIndex", "<", "$", "intLength", ";", "$", "intIndex", "++", ")", "{", "$", "objNode", "=", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "]", ";", "if", "(", "$", "objNode", "instanceof", "Node", "\\", "Virtual", ")", "{", "if", "(", "$", "objNode", "->", "hasSubquery", "(", ")", ")", "{", "throw", "new", "Caller", "(", "'You cannot define a virtual node in an order by clause. You must use an Expand clause to define it.'", ")", ";", "}", "$", "strOrderByCommand", "=", "'__'", ".", "$", "objNode", "->", "getAttributeName", "(", ")", ";", "}", "elseif", "(", "$", "objNode", "instanceof", "Node", "\\", "Column", ")", "{", "/** @var Node\\Column $objNode */", "$", "strOrderByCommand", "=", "$", "objNode", "->", "getColumnAlias", "(", "$", "objBuilder", ")", ";", "}", "elseif", "(", "$", "objNode", "instanceof", "iCondition", ")", "{", "/** @var iCondition $objNode */", "$", "strOrderByCommand", "=", "$", "objNode", "->", "getWhereClause", "(", "$", "objBuilder", ")", ";", "}", "else", "{", "$", "strOrderByCommand", "=", "''", ";", "}", "// Check to see if they want a ASC/DESC declarator", "if", "(", "(", "(", "$", "intIndex", "+", "1", ")", "<", "$", "intLength", ")", "&&", "!", "(", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", "instanceof", "Node", "\\", "NodeBase", ")", ")", "{", "if", "(", "(", "!", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", ")", "||", "(", "trim", "(", "strtolower", "(", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", ")", ")", "==", "'desc'", ")", ")", "{", "$", "strOrderByCommand", ".=", "' DESC'", ";", "}", "else", "{", "$", "strOrderByCommand", ".=", "' ASC'", ";", "}", "$", "intIndex", "++", ";", "}", "$", "objBuilder", "->", "addOrderByItem", "(", "$", "strOrderByCommand", ")", ";", "}", "}" ]
Updates the query builder according to this clause. This is called by the query builder only. @param Builder $objBuilder @throws Caller
[ "Updates", "the", "query", "builder", "according", "to", "this", "clause", ".", "This", "is", "called", "by", "the", "query", "builder", "only", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Query/Clause/OrderBy.php#L114-L150
qcubed/orm
src/Query/Clause/OrderBy.php
OrderBy.getAsManualSql
public function getAsManualSql() { $strOrderByArray = array(); $intLength = count($this->objNodeArray); for ($intIndex = 0; $intIndex < $intLength; $intIndex++) { $strOrderByCommand = $this->objNodeArray[$intIndex]->getAsManualSqlColumn(); // Check to see if they want a ASC/DESC declarator if ((($intIndex + 1) < $intLength) && !($this->objNodeArray[$intIndex + 1] instanceof Node\NodeBase) ) { if ((!$this->objNodeArray[$intIndex + 1]) || (trim(strtolower($this->objNodeArray[$intIndex + 1])) == 'desc') ) { $strOrderByCommand .= ' DESC'; } else { $strOrderByCommand .= ' ASC'; } $intIndex++; } array_push($strOrderByArray, $strOrderByCommand); } return implode(',', $strOrderByArray); }
php
public function getAsManualSql() { $strOrderByArray = array(); $intLength = count($this->objNodeArray); for ($intIndex = 0; $intIndex < $intLength; $intIndex++) { $strOrderByCommand = $this->objNodeArray[$intIndex]->getAsManualSqlColumn(); // Check to see if they want a ASC/DESC declarator if ((($intIndex + 1) < $intLength) && !($this->objNodeArray[$intIndex + 1] instanceof Node\NodeBase) ) { if ((!$this->objNodeArray[$intIndex + 1]) || (trim(strtolower($this->objNodeArray[$intIndex + 1])) == 'desc') ) { $strOrderByCommand .= ' DESC'; } else { $strOrderByCommand .= ' ASC'; } $intIndex++; } array_push($strOrderByArray, $strOrderByCommand); } return implode(',', $strOrderByArray); }
[ "public", "function", "getAsManualSql", "(", ")", "{", "$", "strOrderByArray", "=", "array", "(", ")", ";", "$", "intLength", "=", "count", "(", "$", "this", "->", "objNodeArray", ")", ";", "for", "(", "$", "intIndex", "=", "0", ";", "$", "intIndex", "<", "$", "intLength", ";", "$", "intIndex", "++", ")", "{", "$", "strOrderByCommand", "=", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "]", "->", "getAsManualSqlColumn", "(", ")", ";", "// Check to see if they want a ASC/DESC declarator", "if", "(", "(", "(", "$", "intIndex", "+", "1", ")", "<", "$", "intLength", ")", "&&", "!", "(", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", "instanceof", "Node", "\\", "NodeBase", ")", ")", "{", "if", "(", "(", "!", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", ")", "||", "(", "trim", "(", "strtolower", "(", "$", "this", "->", "objNodeArray", "[", "$", "intIndex", "+", "1", "]", ")", ")", "==", "'desc'", ")", ")", "{", "$", "strOrderByCommand", ".=", "' DESC'", ";", "}", "else", "{", "$", "strOrderByCommand", ".=", "' ASC'", ";", "}", "$", "intIndex", "++", ";", "}", "array_push", "(", "$", "strOrderByArray", ",", "$", "strOrderByCommand", ")", ";", "}", "return", "implode", "(", "','", ",", "$", "strOrderByArray", ")", ";", "}" ]
This is used primarly by datagrids wanting to use the "old Beta 2" style of Manual Queries. This allows a datagrid to use QQ::OrderBy even though the manually-written Load method takes in Beta 2 string-based SortByCommand information. @return string
[ "This", "is", "used", "primarly", "by", "datagrids", "wanting", "to", "use", "the", "old", "Beta", "2", "style", "of", "Manual", "Queries", ".", "This", "allows", "a", "datagrid", "to", "use", "QQ", "::", "OrderBy", "even", "though", "the", "manually", "-", "written", "Load", "method", "takes", "in", "Beta", "2", "string", "-", "based", "SortByCommand", "information", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Query/Clause/OrderBy.php#L160-L185
zodream/thirdparty
src/SMS/IHuYi.php
IHuYi.send
public function send($mobile, $content) { $data = $this->getSend()->parameters([ 'mobile' => $mobile, 'content' => $content, 'method' => 'Submit' ])->json(); if ($data['code'] == 2) { return $data['smsid']; } throw new \Exception($data['msg']); }
php
public function send($mobile, $content) { $data = $this->getSend()->parameters([ 'mobile' => $mobile, 'content' => $content, 'method' => 'Submit' ])->json(); if ($data['code'] == 2) { return $data['smsid']; } throw new \Exception($data['msg']); }
[ "public", "function", "send", "(", "$", "mobile", ",", "$", "content", ")", "{", "$", "data", "=", "$", "this", "->", "getSend", "(", ")", "->", "parameters", "(", "[", "'mobile'", "=>", "$", "mobile", ",", "'content'", "=>", "$", "content", ",", "'method'", "=>", "'Submit'", "]", ")", "->", "json", "(", ")", ";", "if", "(", "$", "data", "[", "'code'", "]", "==", "2", ")", "{", "return", "$", "data", "[", "'smsid'", "]", ";", "}", "throw", "new", "\\", "Exception", "(", "$", "data", "[", "'msg'", "]", ")", ";", "}" ]
发送短信 @param $mobile @param $content @return bool @throws \Exception
[ "发送短信" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/SMS/IHuYi.php#L48-L58
zodream/thirdparty
src/SMS/IHuYi.php
IHuYi.sendCode
public function sendCode($mobile, $code) { return $this->send($mobile, str_replace('{code}', $code, $this->get('template'))); }
php
public function sendCode($mobile, $code) { return $this->send($mobile, str_replace('{code}', $code, $this->get('template'))); }
[ "public", "function", "sendCode", "(", "$", "mobile", ",", "$", "code", ")", "{", "return", "$", "this", "->", "send", "(", "$", "mobile", ",", "str_replace", "(", "'{code}'", ",", "$", "code", ",", "$", "this", "->", "get", "(", "'template'", ")", ")", ")", ";", "}" ]
发送验证短信 @param string|integer $mobile @param string|integer $code @return bool|integer false|短信ID @throws \Exception
[ "发送验证短信" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/SMS/IHuYi.php#L67-L69
zodream/thirdparty
src/SMS/IHuYi.php
IHuYi.balance
public function balance() { $data = $this->getSend()->parameters([ 'method' => 'GetNum' ])->json(); if ($data['code'] == 2) { return $data['num']; } throw new \Exception($data['msg']); }
php
public function balance() { $data = $this->getSend()->parameters([ 'method' => 'GetNum' ])->json(); if ($data['code'] == 2) { return $data['num']; } throw new \Exception($data['msg']); }
[ "public", "function", "balance", "(", ")", "{", "$", "data", "=", "$", "this", "->", "getSend", "(", ")", "->", "parameters", "(", "[", "'method'", "=>", "'GetNum'", "]", ")", "->", "json", "(", ")", ";", "if", "(", "$", "data", "[", "'code'", "]", "==", "2", ")", "{", "return", "$", "data", "[", "'num'", "]", ";", "}", "throw", "new", "\\", "Exception", "(", "$", "data", "[", "'msg'", "]", ")", ";", "}" ]
余额查询 @return bool|int @throws \Exception
[ "余额查询" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/SMS/IHuYi.php#L76-L84
nexusnetsoftgmbh/nexuscli
src/Nexus/Shell/Business/Model/Executor/Exec.php
Exec.execute
public function execute(string $command): string { exec($command, $output); return implode(PHP_EOL, $output); }
php
public function execute(string $command): string { exec($command, $output); return implode(PHP_EOL, $output); }
[ "public", "function", "execute", "(", "string", "$", "command", ")", ":", "string", "{", "exec", "(", "$", "command", ",", "$", "output", ")", ";", "return", "implode", "(", "PHP_EOL", ",", "$", "output", ")", ";", "}" ]
@param string $command @return string
[ "@param", "string", "$command" ]
train
https://github.com/nexusnetsoftgmbh/nexuscli/blob/8416b43d31ad56ea379ae2b0bf85d456e78ba67a/src/Nexus/Shell/Business/Model/Executor/Exec.php#L14-L19
2amigos/yiifoundation
widgets/Orbit.php
Orbit.init
public function init() { $this->assets = array( 'js' => YII_DEBUG ? 'foundation/foundation.orbit.js' : 'foundation.min.js' ); Html::addCssClass($this->htmlOptions, Enum::ORBIT_WRAPPER); $this->setId(ArrayHelper::removeValue($this->htmlOptions, 'id', $this->getId())); $this->registerClientScript(); parent::init(); }
php
public function init() { $this->assets = array( 'js' => YII_DEBUG ? 'foundation/foundation.orbit.js' : 'foundation.min.js' ); Html::addCssClass($this->htmlOptions, Enum::ORBIT_WRAPPER); $this->setId(ArrayHelper::removeValue($this->htmlOptions, 'id', $this->getId())); $this->registerClientScript(); parent::init(); }
[ "public", "function", "init", "(", ")", "{", "$", "this", "->", "assets", "=", "array", "(", "'js'", "=>", "YII_DEBUG", "?", "'foundation/foundation.orbit.js'", ":", "'foundation.min.js'", ")", ";", "Html", "::", "addCssClass", "(", "$", "this", "->", "htmlOptions", ",", "Enum", "::", "ORBIT_WRAPPER", ")", ";", "$", "this", "->", "setId", "(", "ArrayHelper", "::", "removeValue", "(", "$", "this", "->", "htmlOptions", ",", "'id'", ",", "$", "this", "->", "getId", "(", ")", ")", ")", ";", "$", "this", "->", "registerClientScript", "(", ")", ";", "parent", "::", "init", "(", ")", ";", "}" ]
Initializes the widget
[ "Initializes", "the", "widget" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/Orbit.php#L88-L98
2amigos/yiifoundation
widgets/Orbit.php
Orbit.renderOrbit
public function renderOrbit() { $contents = $list = array(); foreach ($this->items as $item) { $list[] = $this->renderItem($item); } if ($this->showPreloader) { $contents[] = \CHtml::tag('div', array('class' => Enum::ORBIT_LOADER), '&nbsp;'); } $contents[] = \CHtml::tag( 'ul', array( 'id' => $this->getId(), 'data-orbit' => 'data-orbit' ), implode("\n", $list) ); return \CHtml::tag('div', $this->htmlOptions, implode("\n", $contents)); }
php
public function renderOrbit() { $contents = $list = array(); foreach ($this->items as $item) { $list[] = $this->renderItem($item); } if ($this->showPreloader) { $contents[] = \CHtml::tag('div', array('class' => Enum::ORBIT_LOADER), '&nbsp;'); } $contents[] = \CHtml::tag( 'ul', array( 'id' => $this->getId(), 'data-orbit' => 'data-orbit' ), implode("\n", $list) ); return \CHtml::tag('div', $this->htmlOptions, implode("\n", $contents)); }
[ "public", "function", "renderOrbit", "(", ")", "{", "$", "contents", "=", "$", "list", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "list", "[", "]", "=", "$", "this", "->", "renderItem", "(", "$", "item", ")", ";", "}", "if", "(", "$", "this", "->", "showPreloader", ")", "{", "$", "contents", "[", "]", "=", "\\", "CHtml", "::", "tag", "(", "'div'", ",", "array", "(", "'class'", "=>", "Enum", "::", "ORBIT_LOADER", ")", ",", "'&nbsp;'", ")", ";", "}", "$", "contents", "[", "]", "=", "\\", "CHtml", "::", "tag", "(", "'ul'", ",", "array", "(", "'id'", "=>", "$", "this", "->", "getId", "(", ")", ",", "'data-orbit'", "=>", "'data-orbit'", ")", ",", "implode", "(", "\"\\n\"", ",", "$", "list", ")", ")", ";", "return", "\\", "CHtml", "::", "tag", "(", "'div'", ",", "$", "this", "->", "htmlOptions", ",", "implode", "(", "\"\\n\"", ",", "$", "contents", ")", ")", ";", "}" ]
Renders the orbit plugin @return string the generated HTML string
[ "Renders", "the", "orbit", "plugin" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/Orbit.php#L112-L132
2amigos/yiifoundation
widgets/Orbit.php
Orbit.renderItem
public function renderItem($item) { $content = ArrayHelper::getValue($item, 'content', ''); $caption = ArrayHelper::getValue($item, 'caption'); if ($caption !== null) { $caption = \CHtml::tag('div', array('class' => Enum::ORBIT_CAPTION), $caption); } return \CHtml::tag('li', array(), $content . $caption); }
php
public function renderItem($item) { $content = ArrayHelper::getValue($item, 'content', ''); $caption = ArrayHelper::getValue($item, 'caption'); if ($caption !== null) { $caption = \CHtml::tag('div', array('class' => Enum::ORBIT_CAPTION), $caption); } return \CHtml::tag('li', array(), $content . $caption); }
[ "public", "function", "renderItem", "(", "$", "item", ")", "{", "$", "content", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'content'", ",", "''", ")", ";", "$", "caption", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'caption'", ")", ";", "if", "(", "$", "caption", "!==", "null", ")", "{", "$", "caption", "=", "\\", "CHtml", "::", "tag", "(", "'div'", ",", "array", "(", "'class'", "=>", "Enum", "::", "ORBIT_CAPTION", ")", ",", "$", "caption", ")", ";", "}", "return", "\\", "CHtml", "::", "tag", "(", "'li'", ",", "array", "(", ")", ",", "$", "content", ".", "$", "caption", ")", ";", "}" ]
Returns a generated LI tag item @param array $item the item configuration @return string the resulting li tag
[ "Returns", "a", "generated", "LI", "tag", "item" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/Orbit.php#L139-L148
2amigos/yiifoundation
widgets/Orbit.php
Orbit.registerClientScript
public function registerClientScript() { if (!empty($this->pluginOptions)) { $options = \CJavaScript::encode($this->pluginOptions); \Yii::app()->clientScript ->registerScript('Orbit#' . $this->getId(), "$(document).foundation('orbit', {$options});"); } if (!empty($this->events)) { $this->registerEvents("#{$this->getId()}", $this->events); } }
php
public function registerClientScript() { if (!empty($this->pluginOptions)) { $options = \CJavaScript::encode($this->pluginOptions); \Yii::app()->clientScript ->registerScript('Orbit#' . $this->getId(), "$(document).foundation('orbit', {$options});"); } if (!empty($this->events)) { $this->registerEvents("#{$this->getId()}", $this->events); } }
[ "public", "function", "registerClientScript", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "pluginOptions", ")", ")", "{", "$", "options", "=", "\\", "CJavaScript", "::", "encode", "(", "$", "this", "->", "pluginOptions", ")", ";", "\\", "Yii", "::", "app", "(", ")", "->", "clientScript", "->", "registerScript", "(", "'Orbit#'", ".", "$", "this", "->", "getId", "(", ")", ",", "\"$(document).foundation('orbit', {$options});\"", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "events", ")", ")", "{", "$", "this", "->", "registerEvents", "(", "\"#{$this->getId()}\"", ",", "$", "this", "->", "events", ")", ";", "}", "}" ]
Registers the plugin script
[ "Registers", "the", "plugin", "script" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/Orbit.php#L153-L164
parsnick/steak
src/Console/BuildCommand.php
BuildCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->setIo($input, $output); $sourceDir = $this->container['config']['source.directory']; $outputDir = $this->container['config']['build.directory']; $output->writeln("<info>Compiling <path>{$sourceDir}</path> into <path>{$outputDir}</path></info>"); $total = $this->runTimedTask(function () use ($sourceDir, $outputDir) { if ( ! $this->input->getOption('no-clean')) { $this->runCleanTask($outputDir); } $this->runBuildTask($sourceDir, $outputDir); if ( ! $this->input->getOption('no-gulp')) { $this->runGulpTask(); } }); $output->writeln("<info>Built in <time>{$total}ms</time></info>"); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->setIo($input, $output); $sourceDir = $this->container['config']['source.directory']; $outputDir = $this->container['config']['build.directory']; $output->writeln("<info>Compiling <path>{$sourceDir}</path> into <path>{$outputDir}</path></info>"); $total = $this->runTimedTask(function () use ($sourceDir, $outputDir) { if ( ! $this->input->getOption('no-clean')) { $this->runCleanTask($outputDir); } $this->runBuildTask($sourceDir, $outputDir); if ( ! $this->input->getOption('no-gulp')) { $this->runGulpTask(); } }); $output->writeln("<info>Built in <time>{$total}ms</time></info>"); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "setIo", "(", "$", "input", ",", "$", "output", ")", ";", "$", "sourceDir", "=", "$", "this", "->", "container", "[", "'config'", "]", "[", "'source.directory'", "]", ";", "$", "outputDir", "=", "$", "this", "->", "container", "[", "'config'", "]", "[", "'build.directory'", "]", ";", "$", "output", "->", "writeln", "(", "\"<info>Compiling <path>{$sourceDir}</path> into <path>{$outputDir}</path></info>\"", ")", ";", "$", "total", "=", "$", "this", "->", "runTimedTask", "(", "function", "(", ")", "use", "(", "$", "sourceDir", ",", "$", "outputDir", ")", "{", "if", "(", "!", "$", "this", "->", "input", "->", "getOption", "(", "'no-clean'", ")", ")", "{", "$", "this", "->", "runCleanTask", "(", "$", "outputDir", ")", ";", "}", "$", "this", "->", "runBuildTask", "(", "$", "sourceDir", ",", "$", "outputDir", ")", ";", "if", "(", "!", "$", "this", "->", "input", "->", "getOption", "(", "'no-gulp'", ")", ")", "{", "$", "this", "->", "runGulpTask", "(", ")", ";", "}", "}", ")", ";", "$", "output", "->", "writeln", "(", "\"<info>Built in <time>{$total}ms</time></info>\"", ")", ";", "}" ]
Execute the command. @param InputInterface $input @param OutputInterface $output @return void
[ "Execute", "the", "command", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Console/BuildCommand.php#L61-L85
parsnick/steak
src/Console/BuildCommand.php
BuildCommand.runCleanTask
protected function runCleanTask($outputDir) { $cleanTime = $this->runTimedTask(function () use ($outputDir) { $this->builder->clean($outputDir); }); $this->output->writeln( "<comment>Cleaned <path>{$outputDir}</path> in <time>{$cleanTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); }
php
protected function runCleanTask($outputDir) { $cleanTime = $this->runTimedTask(function () use ($outputDir) { $this->builder->clean($outputDir); }); $this->output->writeln( "<comment>Cleaned <path>{$outputDir}</path> in <time>{$cleanTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); }
[ "protected", "function", "runCleanTask", "(", "$", "outputDir", ")", "{", "$", "cleanTime", "=", "$", "this", "->", "runTimedTask", "(", "function", "(", ")", "use", "(", "$", "outputDir", ")", "{", "$", "this", "->", "builder", "->", "clean", "(", "$", "outputDir", ")", ";", "}", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "\"<comment>Cleaned <path>{$outputDir}</path> in <time>{$cleanTime}ms</time></comment>\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "}" ]
Clean the output build directory. @param string $outputDir
[ "Clean", "the", "output", "build", "directory", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Console/BuildCommand.php#L92-L102
parsnick/steak
src/Console/BuildCommand.php
BuildCommand.runBuildTask
protected function runBuildTask($sourceDir, $outputDir) { $buildTime = $this->runTimedTask(function () use ($sourceDir, $outputDir) { $this->builder->build($sourceDir, $outputDir); }); $this->output->writeln( "<comment>PHP built in <time>{$buildTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); }
php
protected function runBuildTask($sourceDir, $outputDir) { $buildTime = $this->runTimedTask(function () use ($sourceDir, $outputDir) { $this->builder->build($sourceDir, $outputDir); }); $this->output->writeln( "<comment>PHP built in <time>{$buildTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); }
[ "protected", "function", "runBuildTask", "(", "$", "sourceDir", ",", "$", "outputDir", ")", "{", "$", "buildTime", "=", "$", "this", "->", "runTimedTask", "(", "function", "(", ")", "use", "(", "$", "sourceDir", ",", "$", "outputDir", ")", "{", "$", "this", "->", "builder", "->", "build", "(", "$", "sourceDir", ",", "$", "outputDir", ")", ";", "}", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "\"<comment>PHP built in <time>{$buildTime}ms</time></comment>\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "}" ]
Build the new site pages. @param string $sourceDir @param string $outputDir
[ "Build", "the", "new", "site", "pages", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Console/BuildCommand.php#L110-L120
parsnick/steak
src/Console/BuildCommand.php
BuildCommand.runGulpTask
protected function runGulpTask() { $this->output->writeln("<comment>Starting gulp...</comment>", OutputInterface::VERBOSITY_VERY_VERBOSE); $process = $this->createGulpProcess('steak:build'); $callback = $this->getProcessLogger($this->output); $timer = new Stopwatch(); $timer->start('gulp'); try { $process->mustRun($callback); $this->output->writeln( "<comment>gulp published in <time>{$timer->stop('gulp')->getDuration()}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); } catch (ProcessFailedException $exception) { $this->output->writeln( "<error>gulp process failed after <time>{$timer->stop('gulp')->getDuration()}ms</time></error>", OutputInterface::VERBOSITY_VERBOSE ); if (str_contains($process->getOutput(), 'Local gulp not found') || str_contains($process->getErrorOutput(), 'Cannot find module')) { $this->output->writeln("<comment>Missing npm dependencies, attempting install. This might take a minute...</comment>"); $this->output->writeln(' <comment>$</comment> npm install', OutputInterface::VERBOSITY_VERBOSE); try { $npmInstallTime = $this->runTimedTask(function () { (new Process('npm install', $this->container['config']['source.directory']))->setTimeout(180)->mustRun(); }); $this->output->writeln(" <comment>npm installed in in <time>{$npmInstallTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE); $this->output->writeln('<comment>Retrying <b>steak:publish</b> task...</comment>'); $process->mustRun($callback); } catch (RuntimeException $exception) { $this->output->writeln("We tried but <error>npm install</error> failed"); } } } }
php
protected function runGulpTask() { $this->output->writeln("<comment>Starting gulp...</comment>", OutputInterface::VERBOSITY_VERY_VERBOSE); $process = $this->createGulpProcess('steak:build'); $callback = $this->getProcessLogger($this->output); $timer = new Stopwatch(); $timer->start('gulp'); try { $process->mustRun($callback); $this->output->writeln( "<comment>gulp published in <time>{$timer->stop('gulp')->getDuration()}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE ); } catch (ProcessFailedException $exception) { $this->output->writeln( "<error>gulp process failed after <time>{$timer->stop('gulp')->getDuration()}ms</time></error>", OutputInterface::VERBOSITY_VERBOSE ); if (str_contains($process->getOutput(), 'Local gulp not found') || str_contains($process->getErrorOutput(), 'Cannot find module')) { $this->output->writeln("<comment>Missing npm dependencies, attempting install. This might take a minute...</comment>"); $this->output->writeln(' <comment>$</comment> npm install', OutputInterface::VERBOSITY_VERBOSE); try { $npmInstallTime = $this->runTimedTask(function () { (new Process('npm install', $this->container['config']['source.directory']))->setTimeout(180)->mustRun(); }); $this->output->writeln(" <comment>npm installed in in <time>{$npmInstallTime}ms</time></comment>", OutputInterface::VERBOSITY_VERBOSE); $this->output->writeln('<comment>Retrying <b>steak:publish</b> task...</comment>'); $process->mustRun($callback); } catch (RuntimeException $exception) { $this->output->writeln("We tried but <error>npm install</error> failed"); } } } }
[ "protected", "function", "runGulpTask", "(", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "\"<comment>Starting gulp...</comment>\"", ",", "OutputInterface", "::", "VERBOSITY_VERY_VERBOSE", ")", ";", "$", "process", "=", "$", "this", "->", "createGulpProcess", "(", "'steak:build'", ")", ";", "$", "callback", "=", "$", "this", "->", "getProcessLogger", "(", "$", "this", "->", "output", ")", ";", "$", "timer", "=", "new", "Stopwatch", "(", ")", ";", "$", "timer", "->", "start", "(", "'gulp'", ")", ";", "try", "{", "$", "process", "->", "mustRun", "(", "$", "callback", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "\"<comment>gulp published in <time>{$timer->stop('gulp')->getDuration()}ms</time></comment>\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "}", "catch", "(", "ProcessFailedException", "$", "exception", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "\"<error>gulp process failed after <time>{$timer->stop('gulp')->getDuration()}ms</time></error>\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "if", "(", "str_contains", "(", "$", "process", "->", "getOutput", "(", ")", ",", "'Local gulp not found'", ")", "||", "str_contains", "(", "$", "process", "->", "getErrorOutput", "(", ")", ",", "'Cannot find module'", ")", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "\"<comment>Missing npm dependencies, attempting install. This might take a minute...</comment>\"", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "' <comment>$</comment> npm install'", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "try", "{", "$", "npmInstallTime", "=", "$", "this", "->", "runTimedTask", "(", "function", "(", ")", "{", "(", "new", "Process", "(", "'npm install'", ",", "$", "this", "->", "container", "[", "'config'", "]", "[", "'source.directory'", "]", ")", ")", "->", "setTimeout", "(", "180", ")", "->", "mustRun", "(", ")", ";", "}", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "\" <comment>npm installed in in <time>{$npmInstallTime}ms</time></comment>\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "'<comment>Retrying <b>steak:publish</b> task...</comment>'", ")", ";", "$", "process", "->", "mustRun", "(", "$", "callback", ")", ";", "}", "catch", "(", "RuntimeException", "$", "exception", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "\"We tried but <error>npm install</error> failed\"", ")", ";", "}", "}", "}", "}" ]
Trigger gulp to copy other assets to the build dir.
[ "Trigger", "gulp", "to", "copy", "other", "assets", "to", "the", "build", "dir", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Console/BuildCommand.php#L125-L173
thecodingmachine/service-provider-bridge-bundle
src/ServiceProviderCompilationPass.php
ServiceProviderCompilationPass.process
public function process(ContainerBuilder $container) { // Now, let's store the registry in the container (an empty version of it... it will be dynamically added at runtime): $this->registerRegistry($container); $registry = $this->registryProvider->getRegistry($container); // Note: in the 'boot' method of a bundle, the container is available. // We use that to push the lazy array in the container. // The lazy array can be used by the registry that is also part of the container. // The registry can itself be used by a factory that creates services! $this->registerAcclimatedContainer($container); foreach ($registry as $serviceProviderKey => $serviceProvider) { $this->registerFactories($serviceProviderKey, $serviceProvider, $container); } foreach ($registry as $serviceProviderKey => $serviceProvider) { $this->registerExtensions($serviceProviderKey, $serviceProvider, $container); } }
php
public function process(ContainerBuilder $container) { // Now, let's store the registry in the container (an empty version of it... it will be dynamically added at runtime): $this->registerRegistry($container); $registry = $this->registryProvider->getRegistry($container); // Note: in the 'boot' method of a bundle, the container is available. // We use that to push the lazy array in the container. // The lazy array can be used by the registry that is also part of the container. // The registry can itself be used by a factory that creates services! $this->registerAcclimatedContainer($container); foreach ($registry as $serviceProviderKey => $serviceProvider) { $this->registerFactories($serviceProviderKey, $serviceProvider, $container); } foreach ($registry as $serviceProviderKey => $serviceProvider) { $this->registerExtensions($serviceProviderKey, $serviceProvider, $container); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "// Now, let's store the registry in the container (an empty version of it... it will be dynamically added at runtime):", "$", "this", "->", "registerRegistry", "(", "$", "container", ")", ";", "$", "registry", "=", "$", "this", "->", "registryProvider", "->", "getRegistry", "(", "$", "container", ")", ";", "// Note: in the 'boot' method of a bundle, the container is available.", "// We use that to push the lazy array in the container.", "// The lazy array can be used by the registry that is also part of the container.", "// The registry can itself be used by a factory that creates services!", "$", "this", "->", "registerAcclimatedContainer", "(", "$", "container", ")", ";", "foreach", "(", "$", "registry", "as", "$", "serviceProviderKey", "=>", "$", "serviceProvider", ")", "{", "$", "this", "->", "registerFactories", "(", "$", "serviceProviderKey", ",", "$", "serviceProvider", ",", "$", "container", ")", ";", "}", "foreach", "(", "$", "registry", "as", "$", "serviceProviderKey", "=>", "$", "serviceProvider", ")", "{", "$", "this", "->", "registerExtensions", "(", "$", "serviceProviderKey", ",", "$", "serviceProvider", ",", "$", "container", ")", ";", "}", "}" ]
You can modify the container here before it is dumped to PHP code. @param ContainerBuilder $container
[ "You", "can", "modify", "the", "container", "here", "before", "it", "is", "dumped", "to", "PHP", "code", "." ]
train
https://github.com/thecodingmachine/service-provider-bridge-bundle/blob/7ac2d64c6aa7f093ad36fb1f3a4b86b397777c99/src/ServiceProviderCompilationPass.php#L36-L57
comodojo/cookies
src/Comodojo/Cookies/Cookie.php
Cookie.setValue
public function setValue($value, $serialize = true) { if ( !is_scalar($value) && $serialize === false ) throw new CookieException("Cannot set non-scalar value without serialization"); $cookie_value = $serialize === true ? serialize($value) : $value; if ( strlen($cookie_value) > $this->max_cookie_size ) throw new CookieException("Cookie size larger than ".$this->max_cookie_size." bytes"); $this->value = $cookie_value; return $this; }
php
public function setValue($value, $serialize = true) { if ( !is_scalar($value) && $serialize === false ) throw new CookieException("Cannot set non-scalar value without serialization"); $cookie_value = $serialize === true ? serialize($value) : $value; if ( strlen($cookie_value) > $this->max_cookie_size ) throw new CookieException("Cookie size larger than ".$this->max_cookie_size." bytes"); $this->value = $cookie_value; return $this; }
[ "public", "function", "setValue", "(", "$", "value", ",", "$", "serialize", "=", "true", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", "&&", "$", "serialize", "===", "false", ")", "throw", "new", "CookieException", "(", "\"Cannot set non-scalar value without serialization\"", ")", ";", "$", "cookie_value", "=", "$", "serialize", "===", "true", "?", "serialize", "(", "$", "value", ")", ":", "$", "value", ";", "if", "(", "strlen", "(", "$", "cookie_value", ")", ">", "$", "this", "->", "max_cookie_size", ")", "throw", "new", "CookieException", "(", "\"Cookie size larger than \"", ".", "$", "this", "->", "max_cookie_size", ".", "\" bytes\"", ")", ";", "$", "this", "->", "value", "=", "$", "cookie_value", ";", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/comodojo/cookies/blob/a81c7dff37d52c1a75462c0ad30db75d0c3b0081/src/Comodojo/Cookies/Cookie.php#L28-L40
comodojo/cookies
src/Comodojo/Cookies/Cookie.php
Cookie.create
public static function create($name, array $properties = [], $serialize = true) { try { $class = get_called_class(); $cookie = new $class($name); CookieTools::setCookieProperties($cookie, $properties, $serialize); } catch (CookieException $ce) { throw $ce; } return $cookie; }
php
public static function create($name, array $properties = [], $serialize = true) { try { $class = get_called_class(); $cookie = new $class($name); CookieTools::setCookieProperties($cookie, $properties, $serialize); } catch (CookieException $ce) { throw $ce; } return $cookie; }
[ "public", "static", "function", "create", "(", "$", "name", ",", "array", "$", "properties", "=", "[", "]", ",", "$", "serialize", "=", "true", ")", "{", "try", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "cookie", "=", "new", "$", "class", "(", "$", "name", ")", ";", "CookieTools", "::", "setCookieProperties", "(", "$", "cookie", ",", "$", "properties", ",", "$", "serialize", ")", ";", "}", "catch", "(", "CookieException", "$", "ce", ")", "{", "throw", "$", "ce", ";", "}", "return", "$", "cookie", ";", "}" ]
Static method to quickly create a cookie @param string $name The cookie name @param array $properties Array of properties cookie should have @return self @throws CookieException
[ "Static", "method", "to", "quickly", "create", "a", "cookie" ]
train
https://github.com/comodojo/cookies/blob/a81c7dff37d52c1a75462c0ad30db75d0c3b0081/src/Comodojo/Cookies/Cookie.php#L63-L81
comodojo/cookies
src/Comodojo/Cookies/Cookie.php
Cookie.retrieve
public static function retrieve($name) { try { $class = get_called_class(); $cookie = new $class($name); return $cookie->load(); } catch (CookieException $ce) { throw $ce; } }
php
public static function retrieve($name) { try { $class = get_called_class(); $cookie = new $class($name); return $cookie->load(); } catch (CookieException $ce) { throw $ce; } }
[ "public", "static", "function", "retrieve", "(", "$", "name", ")", "{", "try", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "cookie", "=", "new", "$", "class", "(", "$", "name", ")", ";", "return", "$", "cookie", "->", "load", "(", ")", ";", "}", "catch", "(", "CookieException", "$", "ce", ")", "{", "throw", "$", "ce", ";", "}", "}" ]
Static method to quickly get a cookie @param string $name The cookie name @return self @throws CookieException
[ "Static", "method", "to", "quickly", "get", "a", "cookie" ]
train
https://github.com/comodojo/cookies/blob/a81c7dff37d52c1a75462c0ad30db75d0c3b0081/src/Comodojo/Cookies/Cookie.php#L92-L108
ronanguilloux/SilexMarkdownServiceProvider
src/Rg/Markdown/Finder.php
Finder.getContent
public function getContent($path) { // only a page index was given ? if (('0' == $path) || (int) ($path) > 0) { $path = $this->findByIndex($path); } else { $path = $this->basePath . '/' . $path; $infos = pathinfo($path); // was the extension given ? if (empty($infos['extension'])) { $path .= '.md'; } } if (file_exists($path)) { return file_get_contents($path); } return false; }
php
public function getContent($path) { // only a page index was given ? if (('0' == $path) || (int) ($path) > 0) { $path = $this->findByIndex($path); } else { $path = $this->basePath . '/' . $path; $infos = pathinfo($path); // was the extension given ? if (empty($infos['extension'])) { $path .= '.md'; } } if (file_exists($path)) { return file_get_contents($path); } return false; }
[ "public", "function", "getContent", "(", "$", "path", ")", "{", "// only a page index was given ?", "if", "(", "(", "'0'", "==", "$", "path", ")", "||", "(", "int", ")", "(", "$", "path", ")", ">", "0", ")", "{", "$", "path", "=", "$", "this", "->", "findByIndex", "(", "$", "path", ")", ";", "}", "else", "{", "$", "path", "=", "$", "this", "->", "basePath", ".", "'/'", ".", "$", "path", ";", "$", "infos", "=", "pathinfo", "(", "$", "path", ")", ";", "// was the extension given ?", "if", "(", "empty", "(", "$", "infos", "[", "'extension'", "]", ")", ")", "{", "$", "path", ".=", "'.md'", ";", "}", "}", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "return", "file_get_contents", "(", "$", "path", ")", ";", "}", "return", "false", ";", "}" ]
getContent Retrieve a file content using the given path @param string $path the markdown file path @return mixed: false or the markdown file raw content (string)
[ "getContent", "Retrieve", "a", "file", "content", "using", "the", "given", "path" ]
train
https://github.com/ronanguilloux/SilexMarkdownServiceProvider/blob/8266baf0b8a74a98ea32ba1417d767dca6b374b3/src/Rg/Markdown/Finder.php#L51-L69
ronanguilloux/SilexMarkdownServiceProvider
src/Rg/Markdown/Finder.php
Finder.findByIndex
protected function findByIndex($int) { $files = glob($this->basePath . "/$int-*.md"); if (0 < count($files)) { return $files[0]; } return false; }
php
protected function findByIndex($int) { $files = glob($this->basePath . "/$int-*.md"); if (0 < count($files)) { return $files[0]; } return false; }
[ "protected", "function", "findByIndex", "(", "$", "int", ")", "{", "$", "files", "=", "glob", "(", "$", "this", "->", "basePath", ".", "\"/$int-*.md\"", ")", ";", "if", "(", "0", "<", "count", "(", "$", "files", ")", ")", "{", "return", "$", "files", "[", "0", "]", ";", "}", "return", "false", ";", "}" ]
findByIndex Retrieve a filepath using the index that starts the searched file name by ex: 1 stands for 1-summary.md @param mixed $int the page index @return mixed false/string the file path that matches the given $int
[ "findByIndex", "Retrieve", "a", "filepath", "using", "the", "index", "that", "starts", "the", "searched", "file", "name", "by", "ex", ":", "1", "stands", "for", "1", "-", "summary", ".", "md" ]
train
https://github.com/ronanguilloux/SilexMarkdownServiceProvider/blob/8266baf0b8a74a98ea32ba1417d767dca6b374b3/src/Rg/Markdown/Finder.php#L80-L88
ronanguilloux/SilexMarkdownServiceProvider
src/Rg/Markdown/Finder.php
Finder.getList
public function getList() { $list = glob($this->basePath . "/*.md"); foreach ($list as $key=>$item) { $item = pathinfo($item); $item = $item['filename']; $item = preg_split("/^[\d-]+/", $item, 2, PREG_SPLIT_NO_EMPTY); $list[$key] = ucfirst(str_replace('-',' ',$item[0])); } return $list; }
php
public function getList() { $list = glob($this->basePath . "/*.md"); foreach ($list as $key=>$item) { $item = pathinfo($item); $item = $item['filename']; $item = preg_split("/^[\d-]+/", $item, 2, PREG_SPLIT_NO_EMPTY); $list[$key] = ucfirst(str_replace('-',' ',$item[0])); } return $list; }
[ "public", "function", "getList", "(", ")", "{", "$", "list", "=", "glob", "(", "$", "this", "->", "basePath", ".", "\"/*.md\"", ")", ";", "foreach", "(", "$", "list", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "item", "=", "pathinfo", "(", "$", "item", ")", ";", "$", "item", "=", "$", "item", "[", "'filename'", "]", ";", "$", "item", "=", "preg_split", "(", "\"/^[\\d-]+/\"", ",", "$", "item", ",", "2", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "list", "[", "$", "key", "]", "=", "ucfirst", "(", "str_replace", "(", "'-'", ",", "' '", ",", "$", "item", "[", "0", "]", ")", ")", ";", "}", "return", "$", "list", ";", "}" ]
getList In the file list returned, in array values, '-' become spaces. @return array mardown file list
[ "getList", "In", "the", "file", "list", "returned", "in", "array", "values", "-", "become", "spaces", "." ]
train
https://github.com/ronanguilloux/SilexMarkdownServiceProvider/blob/8266baf0b8a74a98ea32ba1417d767dca6b374b3/src/Rg/Markdown/Finder.php#L96-L107
jpcercal/resource-query-language
src/Parser/AbstractParser.php
AbstractParser.process
public function process(ExprBuilder $builder, $field, $expression, $value) { if (!Expr::isValidExpression($expression)) { throw new ParserException(sprintf( 'The expression "%s" is not allowed or not exists.', $expression )); } switch ($expression) { case 'between': set_error_handler(function () use ($value) { throw new ParserException(sprintf( 'The value of "between" expression "%s" is not valid.', $value )); }); list($from, $to) = explode('-', $value); restore_error_handler(); return $builder->between($field, $from, $to); case 'paginate': set_error_handler(function () use ($value) { throw new ParserException(sprintf( 'The value of "paginate" expression "%s" is not valid.', $value )); }); list($currentPageNumber, $maxResultsPerPage) = explode('-', $value); restore_error_handler(); return $builder->paginate($currentPageNumber, $maxResultsPerPage); case 'or': return $builder->orx($value); default: return $builder->{$expression}($field, $value); } }
php
public function process(ExprBuilder $builder, $field, $expression, $value) { if (!Expr::isValidExpression($expression)) { throw new ParserException(sprintf( 'The expression "%s" is not allowed or not exists.', $expression )); } switch ($expression) { case 'between': set_error_handler(function () use ($value) { throw new ParserException(sprintf( 'The value of "between" expression "%s" is not valid.', $value )); }); list($from, $to) = explode('-', $value); restore_error_handler(); return $builder->between($field, $from, $to); case 'paginate': set_error_handler(function () use ($value) { throw new ParserException(sprintf( 'The value of "paginate" expression "%s" is not valid.', $value )); }); list($currentPageNumber, $maxResultsPerPage) = explode('-', $value); restore_error_handler(); return $builder->paginate($currentPageNumber, $maxResultsPerPage); case 'or': return $builder->orx($value); default: return $builder->{$expression}($field, $value); } }
[ "public", "function", "process", "(", "ExprBuilder", "$", "builder", ",", "$", "field", ",", "$", "expression", ",", "$", "value", ")", "{", "if", "(", "!", "Expr", "::", "isValidExpression", "(", "$", "expression", ")", ")", "{", "throw", "new", "ParserException", "(", "sprintf", "(", "'The expression \"%s\" is not allowed or not exists.'", ",", "$", "expression", ")", ")", ";", "}", "switch", "(", "$", "expression", ")", "{", "case", "'between'", ":", "set_error_handler", "(", "function", "(", ")", "use", "(", "$", "value", ")", "{", "throw", "new", "ParserException", "(", "sprintf", "(", "'The value of \"between\" expression \"%s\" is not valid.'", ",", "$", "value", ")", ")", ";", "}", ")", ";", "list", "(", "$", "from", ",", "$", "to", ")", "=", "explode", "(", "'-'", ",", "$", "value", ")", ";", "restore_error_handler", "(", ")", ";", "return", "$", "builder", "->", "between", "(", "$", "field", ",", "$", "from", ",", "$", "to", ")", ";", "case", "'paginate'", ":", "set_error_handler", "(", "function", "(", ")", "use", "(", "$", "value", ")", "{", "throw", "new", "ParserException", "(", "sprintf", "(", "'The value of \"paginate\" expression \"%s\" is not valid.'", ",", "$", "value", ")", ")", ";", "}", ")", ";", "list", "(", "$", "currentPageNumber", ",", "$", "maxResultsPerPage", ")", "=", "explode", "(", "'-'", ",", "$", "value", ")", ";", "restore_error_handler", "(", ")", ";", "return", "$", "builder", "->", "paginate", "(", "$", "currentPageNumber", ",", "$", "maxResultsPerPage", ")", ";", "case", "'or'", ":", "return", "$", "builder", "->", "orx", "(", "$", "value", ")", ";", "default", ":", "return", "$", "builder", "->", "{", "$", "expression", "}", "(", "$", "field", ",", "$", "value", ")", ";", "}", "}" ]
Process one expression an enqueue it using the ExprBuilder instance. @param ExprBuilder $builder @param string $field @param string $expression @param string $value @return ExprBuilder @throws ParserException
[ "Process", "one", "expression", "an", "enqueue", "it", "using", "the", "ExprBuilder", "instance", "." ]
train
https://github.com/jpcercal/resource-query-language/blob/2a1520198c717a8199cd8d3d85ca2557e24cb7f5/src/Parser/AbstractParser.php#L53-L94
yuncms/framework
src/filters/OAuth2Authorize.php
OAuth2Authorize.afterAction
public function afterAction($action, $result) { if (Yii::$app->user->isGuest) { return $result; } else { return $this->finishAuthorization(); } }
php
public function afterAction($action, $result) { if (Yii::$app->user->isGuest) { return $result; } else { return $this->finishAuthorization(); } }
[ "public", "function", "afterAction", "(", "$", "action", ",", "$", "result", ")", "{", "if", "(", "Yii", "::", "$", "app", "->", "user", "->", "isGuest", ")", "{", "return", "$", "result", ";", "}", "else", "{", "return", "$", "this", "->", "finishAuthorization", "(", ")", ";", "}", "}" ]
If user is logged on, do oauth login immediatly, continue authorization in the another case @param \yii\base\Action $action @param mixed $result @return mixed @throws Exception
[ "If", "user", "is", "logged", "on", "do", "oauth", "login", "immediatly", "continue", "authorization", "in", "the", "another", "case" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/filters/OAuth2Authorize.php#L95-L102
EvanDotPro/EdpGithub
src/EdpGithub/Client.php
Client.authenticate
public function authenticate($authMethod, $tokenOrLogin, $password = null) { $filter = new UnderscoreToCamelCase(); $authMethod = $filter->filter($authMethod); $sm = $this->getServiceManager(); $authListener = $sm->get('EdpGithub\Listener\Auth\\' . $authMethod); $authListener->setOptions( array( 'tokenOrLogin' => $tokenOrLogin, 'password' => $password, ) ); $this->getHttpClient()->getEventManager()->attachAggregate($authListener); }
php
public function authenticate($authMethod, $tokenOrLogin, $password = null) { $filter = new UnderscoreToCamelCase(); $authMethod = $filter->filter($authMethod); $sm = $this->getServiceManager(); $authListener = $sm->get('EdpGithub\Listener\Auth\\' . $authMethod); $authListener->setOptions( array( 'tokenOrLogin' => $tokenOrLogin, 'password' => $password, ) ); $this->getHttpClient()->getEventManager()->attachAggregate($authListener); }
[ "public", "function", "authenticate", "(", "$", "authMethod", ",", "$", "tokenOrLogin", ",", "$", "password", "=", "null", ")", "{", "$", "filter", "=", "new", "UnderscoreToCamelCase", "(", ")", ";", "$", "authMethod", "=", "$", "filter", "->", "filter", "(", "$", "authMethod", ")", ";", "$", "sm", "=", "$", "this", "->", "getServiceManager", "(", ")", ";", "$", "authListener", "=", "$", "sm", "->", "get", "(", "'EdpGithub\\Listener\\Auth\\\\'", ".", "$", "authMethod", ")", ";", "$", "authListener", "->", "setOptions", "(", "array", "(", "'tokenOrLogin'", "=>", "$", "tokenOrLogin", ",", "'password'", "=>", "$", "password", ",", ")", ")", ";", "$", "this", "->", "getHttpClient", "(", ")", "->", "getEventManager", "(", ")", "->", "attachAggregate", "(", "$", "authListener", ")", ";", "}" ]
Authenticate a user for all next requests @param string $tokenOrLogin GitHub private token/username/client ID @param null|string $password GitHub password/secret @param string $authMethod
[ "Authenticate", "a", "user", "for", "all", "next", "requests" ]
train
https://github.com/EvanDotPro/EdpGithub/blob/51f3e33e02edbef011103e3c2c1629d46af011a3/src/EdpGithub/Client.php#L50-L64
silverbusters/silverstripe-simplelistfield
forms/SimpleListField/SimpleListField.php
SimpleListField.Field
public function Field($properties = array()) { // Load TinyMCE if needed if( isset(self::$scenarios[$this->scenario]['fields']) ){ $fields = self::$scenarios[$this->scenario]['fields']; foreach($fields as $field){ if(isset($field['type']) && $field['type'] == 'htmleditor'){ HtmlEditorField::include_js(); break; } } } // Assets Requirements::css(SimpleListFieldDir . '/forms/SimpleListField/css/SimpleListField.css'); Requirements::javascript(SimpleListFieldDir . '/forms/SimpleListField/js/jquery.serializejson.min.js'); Requirements::javascript(SimpleListFieldDir . '/forms/SimpleListField/js/SimpleListField.js'); // Set attributes $this->setAttribute('type', 'hidden'); $this->addExtraClass('hide'); if($this->scenario) { $this->setAttribute('data-scenario', (string)$this->scenario); // heading if(( isset(self::$scenarios[$this->scenario]['heading']) && !self::$scenarios[$this->scenario]['heading'] )) $this->setAttribute('data-heading', 0); else $this->setAttribute('data-heading', 1); // fields if( isset(self::$scenarios[$this->scenario]['fields']) && self::$scenarios[$this->scenario]['fields'] && is_array(self::$scenarios[$this->scenario]['fields']) ){ $this->setAttribute('data-fields', json_encode(self::$scenarios[$this->scenario]['fields'])); } } // Render the fields return $this->customise($properties)->renderWith($this->getTemplates()); }
php
public function Field($properties = array()) { // Load TinyMCE if needed if( isset(self::$scenarios[$this->scenario]['fields']) ){ $fields = self::$scenarios[$this->scenario]['fields']; foreach($fields as $field){ if(isset($field['type']) && $field['type'] == 'htmleditor'){ HtmlEditorField::include_js(); break; } } } // Assets Requirements::css(SimpleListFieldDir . '/forms/SimpleListField/css/SimpleListField.css'); Requirements::javascript(SimpleListFieldDir . '/forms/SimpleListField/js/jquery.serializejson.min.js'); Requirements::javascript(SimpleListFieldDir . '/forms/SimpleListField/js/SimpleListField.js'); // Set attributes $this->setAttribute('type', 'hidden'); $this->addExtraClass('hide'); if($this->scenario) { $this->setAttribute('data-scenario', (string)$this->scenario); // heading if(( isset(self::$scenarios[$this->scenario]['heading']) && !self::$scenarios[$this->scenario]['heading'] )) $this->setAttribute('data-heading', 0); else $this->setAttribute('data-heading', 1); // fields if( isset(self::$scenarios[$this->scenario]['fields']) && self::$scenarios[$this->scenario]['fields'] && is_array(self::$scenarios[$this->scenario]['fields']) ){ $this->setAttribute('data-fields', json_encode(self::$scenarios[$this->scenario]['fields'])); } } // Render the fields return $this->customise($properties)->renderWith($this->getTemplates()); }
[ "public", "function", "Field", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "// Load TinyMCE if needed", "if", "(", "isset", "(", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", ")", ")", "{", "$", "fields", "=", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "[", "'type'", "]", ")", "&&", "$", "field", "[", "'type'", "]", "==", "'htmleditor'", ")", "{", "HtmlEditorField", "::", "include_js", "(", ")", ";", "break", ";", "}", "}", "}", "// Assets", "Requirements", "::", "css", "(", "SimpleListFieldDir", ".", "'/forms/SimpleListField/css/SimpleListField.css'", ")", ";", "Requirements", "::", "javascript", "(", "SimpleListFieldDir", ".", "'/forms/SimpleListField/js/jquery.serializejson.min.js'", ")", ";", "Requirements", "::", "javascript", "(", "SimpleListFieldDir", ".", "'/forms/SimpleListField/js/SimpleListField.js'", ")", ";", "// Set attributes", "$", "this", "->", "setAttribute", "(", "'type'", ",", "'hidden'", ")", ";", "$", "this", "->", "addExtraClass", "(", "'hide'", ")", ";", "if", "(", "$", "this", "->", "scenario", ")", "{", "$", "this", "->", "setAttribute", "(", "'data-scenario'", ",", "(", "string", ")", "$", "this", "->", "scenario", ")", ";", "// heading", "if", "(", "(", "isset", "(", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'heading'", "]", ")", "&&", "!", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'heading'", "]", ")", ")", "$", "this", "->", "setAttribute", "(", "'data-heading'", ",", "0", ")", ";", "else", "$", "this", "->", "setAttribute", "(", "'data-heading'", ",", "1", ")", ";", "// fields", "if", "(", "isset", "(", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", ")", "&&", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", "&&", "is_array", "(", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", ")", ")", "{", "$", "this", "->", "setAttribute", "(", "'data-fields'", ",", "json_encode", "(", "self", "::", "$", "scenarios", "[", "$", "this", "->", "scenario", "]", "[", "'fields'", "]", ")", ")", ";", "}", "}", "// Render the fields", "return", "$", "this", "->", "customise", "(", "$", "properties", ")", "->", "renderWith", "(", "$", "this", "->", "getTemplates", "(", ")", ")", ";", "}" ]
/* @return Field
[ "/", "*" ]
train
https://github.com/silverbusters/silverstripe-simplelistfield/blob/c883e13b1b877d74e266edf2a646661039803440/forms/SimpleListField/SimpleListField.php#L26-L68
silverbusters/silverstripe-simplelistfield
forms/SimpleListField/SimpleListField.php
SimpleListField.addScenarioFromYml
public static function addScenarioFromYml($key){ $cfg = Config::inst()->get('SimpleListField', 'Scenarios'); if( isset($cfg[$key]) ){ if( (isset($cfg[$key]['preload']) && !$cfg[$key]['preload']) || !isset($cfg[$key]['preload']) ){ self::$scenarios[$key] = $cfg[$key]; } } }
php
public static function addScenarioFromYml($key){ $cfg = Config::inst()->get('SimpleListField', 'Scenarios'); if( isset($cfg[$key]) ){ if( (isset($cfg[$key]['preload']) && !$cfg[$key]['preload']) || !isset($cfg[$key]['preload']) ){ self::$scenarios[$key] = $cfg[$key]; } } }
[ "public", "static", "function", "addScenarioFromYml", "(", "$", "key", ")", "{", "$", "cfg", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'SimpleListField'", ",", "'Scenarios'", ")", ";", "if", "(", "isset", "(", "$", "cfg", "[", "$", "key", "]", ")", ")", "{", "if", "(", "(", "isset", "(", "$", "cfg", "[", "$", "key", "]", "[", "'preload'", "]", ")", "&&", "!", "$", "cfg", "[", "$", "key", "]", "[", "'preload'", "]", ")", "||", "!", "isset", "(", "$", "cfg", "[", "$", "key", "]", "[", "'preload'", "]", ")", ")", "{", "self", "::", "$", "scenarios", "[", "$", "key", "]", "=", "$", "cfg", "[", "$", "key", "]", ";", "}", "}", "}" ]
Add single scenario by using yml configuration
[ "Add", "single", "scenario", "by", "using", "yml", "configuration" ]
train
https://github.com/silverbusters/silverstripe-simplelistfield/blob/c883e13b1b877d74e266edf2a646661039803440/forms/SimpleListField/SimpleListField.php#L115-L123
AydinHassan/cli-md-renderer
src/Renderer/ListItemRenderer.php
ListItemRenderer.render
public function render(AbstractBlock $block, CliRenderer $renderer) { if (!($block instanceof ListItem)) { throw new \InvalidArgumentException(sprintf('Incompatible block type: "%s"', get_class($block))); } return $renderer->style(' * ', 'yellow') . $renderer->renderBlocks($block->children()); }
php
public function render(AbstractBlock $block, CliRenderer $renderer) { if (!($block instanceof ListItem)) { throw new \InvalidArgumentException(sprintf('Incompatible block type: "%s"', get_class($block))); } return $renderer->style(' * ', 'yellow') . $renderer->renderBlocks($block->children()); }
[ "public", "function", "render", "(", "AbstractBlock", "$", "block", ",", "CliRenderer", "$", "renderer", ")", "{", "if", "(", "!", "(", "$", "block", "instanceof", "ListItem", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Incompatible block type: \"%s\"'", ",", "get_class", "(", "$", "block", ")", ")", ")", ";", "}", "return", "$", "renderer", "->", "style", "(", "' * '", ",", "'yellow'", ")", ".", "$", "renderer", "->", "renderBlocks", "(", "$", "block", "->", "children", "(", ")", ")", ";", "}" ]
@param AbstractBlock $block @param CliRenderer $renderer @return string
[ "@param", "AbstractBlock", "$block", "@param", "CliRenderer", "$renderer" ]
train
https://github.com/AydinHassan/cli-md-renderer/blob/521f9ace2aeadd58bf8a3910704be8360f5bd7b2/src/Renderer/ListItemRenderer.php#L22-L29
phug-php/formatter
src/Phug/Formatter/Partial/HelperTrait.php
HelperTrait.provideHelper
public function provideHelper($name, $provider) { if (is_array($provider)) { $callback = array_pop($provider); $provider = array_map([$this, 'helperName'], $provider); $provider[] = $callback; } $this->formatter->getDependencies()->provider( $this->helperName($name), $provider ); return $this; }
php
public function provideHelper($name, $provider) { if (is_array($provider)) { $callback = array_pop($provider); $provider = array_map([$this, 'helperName'], $provider); $provider[] = $callback; } $this->formatter->getDependencies()->provider( $this->helperName($name), $provider ); return $this; }
[ "public", "function", "provideHelper", "(", "$", "name", ",", "$", "provider", ")", "{", "if", "(", "is_array", "(", "$", "provider", ")", ")", "{", "$", "callback", "=", "array_pop", "(", "$", "provider", ")", ";", "$", "provider", "=", "array_map", "(", "[", "$", "this", ",", "'helperName'", "]", ",", "$", "provider", ")", ";", "$", "provider", "[", "]", "=", "$", "callback", ";", "}", "$", "this", "->", "formatter", "->", "getDependencies", "(", ")", "->", "provider", "(", "$", "this", "->", "helperName", "(", "$", "name", ")", ",", "$", "provider", ")", ";", "return", "$", "this", ";", "}" ]
@param $name @param $provider @return $this
[ "@param", "$name", "@param", "$provider" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter/Partial/HelperTrait.php#L18-L32
phug-php/formatter
src/Phug/Formatter/Partial/HelperTrait.php
HelperTrait.registerHelper
public function registerHelper($name, $provider) { $this->formatter->getDependencies()->register( $this->helperName($name), $provider ); return $this; }
php
public function registerHelper($name, $provider) { $this->formatter->getDependencies()->register( $this->helperName($name), $provider ); return $this; }
[ "public", "function", "registerHelper", "(", "$", "name", ",", "$", "provider", ")", "{", "$", "this", "->", "formatter", "->", "getDependencies", "(", ")", "->", "register", "(", "$", "this", "->", "helperName", "(", "$", "name", ")", ",", "$", "provider", ")", ";", "return", "$", "this", ";", "}" ]
@param $name @param $provider @return $this
[ "@param", "$name", "@param", "$provider" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter/Partial/HelperTrait.php#L40-L48
phug-php/formatter
src/Phug/Formatter/Partial/HelperTrait.php
HelperTrait.helperMethod
public function helperMethod($name, $method, $args) { $args[0] = $this->helperName($name); $dependencies = $this->formatter->getDependencies(); return call_user_func_array([$dependencies, $method], $args); }
php
public function helperMethod($name, $method, $args) { $args[0] = $this->helperName($name); $dependencies = $this->formatter->getDependencies(); return call_user_func_array([$dependencies, $method], $args); }
[ "public", "function", "helperMethod", "(", "$", "name", ",", "$", "method", ",", "$", "args", ")", "{", "$", "args", "[", "0", "]", "=", "$", "this", "->", "helperName", "(", "$", "name", ")", ";", "$", "dependencies", "=", "$", "this", "->", "formatter", "->", "getDependencies", "(", ")", ";", "return", "call_user_func_array", "(", "[", "$", "dependencies", ",", "$", "method", "]", ",", "$", "args", ")", ";", "}" ]
@param $name @param $method @param $args @return mixed
[ "@param", "$name", "@param", "$method", "@param", "$args" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter/Partial/HelperTrait.php#L57-L63
phug-php/formatter
src/Phug/Formatter/Partial/HelperTrait.php
HelperTrait.requireHelper
public function requireHelper($name) { $this->formatter->getDependencies()->setAsRequired( $this->helperName($name) ); return $this; }
php
public function requireHelper($name) { $this->formatter->getDependencies()->setAsRequired( $this->helperName($name) ); return $this; }
[ "public", "function", "requireHelper", "(", "$", "name", ")", "{", "$", "this", "->", "formatter", "->", "getDependencies", "(", ")", "->", "setAsRequired", "(", "$", "this", "->", "helperName", "(", "$", "name", ")", ")", ";", "return", "$", "this", ";", "}" ]
@param $name @return $this
[ "@param", "$name" ]
train
https://github.com/phug-php/formatter/blob/3f9286a169a0d45b8b8acc1fae64e880ebdb567e/src/Phug/Formatter/Partial/HelperTrait.php#L100-L107
askupasoftware/amarkal
Extensions/WordPress/MetaBox/MetaBox.php
MetaBox.add_meta_boxes
public function add_meta_boxes( $post_type ) { if ( in_array( $post_type, $this->settings['post_types'] )) { add_meta_box( $this->settings['id'], $this->settings['title'], array( $this, 'render' ), $post_type, $this->settings['context'], $this->settings['priority'] ); } }
php
public function add_meta_boxes( $post_type ) { if ( in_array( $post_type, $this->settings['post_types'] )) { add_meta_box( $this->settings['id'], $this->settings['title'], array( $this, 'render' ), $post_type, $this->settings['context'], $this->settings['priority'] ); } }
[ "public", "function", "add_meta_boxes", "(", "$", "post_type", ")", "{", "if", "(", "in_array", "(", "$", "post_type", ",", "$", "this", "->", "settings", "[", "'post_types'", "]", ")", ")", "{", "add_meta_box", "(", "$", "this", "->", "settings", "[", "'id'", "]", ",", "$", "this", "->", "settings", "[", "'title'", "]", ",", "array", "(", "$", "this", ",", "'render'", ")", ",", "$", "post_type", ",", "$", "this", "->", "settings", "[", "'context'", "]", ",", "$", "this", "->", "settings", "[", "'priority'", "]", ")", ";", "}", "}" ]
Adds the meta box container.
[ "Adds", "the", "meta", "box", "container", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Extensions/WordPress/MetaBox/MetaBox.php#L114-L126
askupasoftware/amarkal
Extensions/WordPress/MetaBox/MetaBox.php
MetaBox.save
public function save( $post_id ) { /** * A note on security: * * We need to verify this came from the our screen and with proper authorization, * because save_post can be triggered at other times. since metaboxes can * be removed - by having a nonce field in only one metabox there is no * guarantee the nonce will be there. By placing a nonce field in each * metabox you can check if data from that metabox has been sent * (and is actually from where you think it is) prior to processing any data. * @see http://wordpress.stackexchange.com/a/49460/25959 */ // Check if our nonce is set. if ( ! isset( $_POST[$this->nonce_name()] ) ) { return $post_id; } // Verify that the nonce is valid. $nonce = filter_input( INPUT_POST, $this->nonce_name() ); if ( ! wp_verify_nonce( $nonce, $this->action_name() ) ) { return $post_id; } // Bail if this is an autosave (nothing has been submitted) if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; } // Check the user's permissions. $post_type = filter_input( INPUT_POST, 'post_type' ); if( in_array( $post_type, $this->settings['post_types'] ) ) { // NOTE: this might not work for custom post types, unless Amarkal // is used to register them (custom post types might have labels different // than 'edit_{post_type}' $capability = 'edit_'.$post_type; if ( !current_user_can( $capability, $post_id ) ) { return $post_id; } } else { return $post_id; } // OK, it is safe to process data. $old_instance = \get_post_meta( $post_id, $this->settings['id'], true ); $new_instance = $this->form->updater->update( $old_instance === "" ? array() : $old_instance ); \update_post_meta( $post_id, $this->settings['id'], $new_instance ); // Callback $callable = $this->settings['callback']; if(is_callable( $callable ) ) { $callable( $post_id, $new_instance ); } }
php
public function save( $post_id ) { /** * A note on security: * * We need to verify this came from the our screen and with proper authorization, * because save_post can be triggered at other times. since metaboxes can * be removed - by having a nonce field in only one metabox there is no * guarantee the nonce will be there. By placing a nonce field in each * metabox you can check if data from that metabox has been sent * (and is actually from where you think it is) prior to processing any data. * @see http://wordpress.stackexchange.com/a/49460/25959 */ // Check if our nonce is set. if ( ! isset( $_POST[$this->nonce_name()] ) ) { return $post_id; } // Verify that the nonce is valid. $nonce = filter_input( INPUT_POST, $this->nonce_name() ); if ( ! wp_verify_nonce( $nonce, $this->action_name() ) ) { return $post_id; } // Bail if this is an autosave (nothing has been submitted) if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; } // Check the user's permissions. $post_type = filter_input( INPUT_POST, 'post_type' ); if( in_array( $post_type, $this->settings['post_types'] ) ) { // NOTE: this might not work for custom post types, unless Amarkal // is used to register them (custom post types might have labels different // than 'edit_{post_type}' $capability = 'edit_'.$post_type; if ( !current_user_can( $capability, $post_id ) ) { return $post_id; } } else { return $post_id; } // OK, it is safe to process data. $old_instance = \get_post_meta( $post_id, $this->settings['id'], true ); $new_instance = $this->form->updater->update( $old_instance === "" ? array() : $old_instance ); \update_post_meta( $post_id, $this->settings['id'], $new_instance ); // Callback $callable = $this->settings['callback']; if(is_callable( $callable ) ) { $callable( $post_id, $new_instance ); } }
[ "public", "function", "save", "(", "$", "post_id", ")", "{", "/**\n * A note on security:\n * \n * We need to verify this came from the our screen and with proper authorization,\n * because save_post can be triggered at other times. since metaboxes can \n * be removed - by having a nonce field in only one metabox there is no \n * guarantee the nonce will be there. By placing a nonce field in each \n * metabox you can check if data from that metabox has been sent \n * (and is actually from where you think it is) prior to processing any data.\n * @see http://wordpress.stackexchange.com/a/49460/25959\n */", "// Check if our nonce is set.", "if", "(", "!", "isset", "(", "$", "_POST", "[", "$", "this", "->", "nonce_name", "(", ")", "]", ")", ")", "{", "return", "$", "post_id", ";", "}", "// Verify that the nonce is valid.", "$", "nonce", "=", "filter_input", "(", "INPUT_POST", ",", "$", "this", "->", "nonce_name", "(", ")", ")", ";", "if", "(", "!", "wp_verify_nonce", "(", "$", "nonce", ",", "$", "this", "->", "action_name", "(", ")", ")", ")", "{", "return", "$", "post_id", ";", "}", "// Bail if this is an autosave (nothing has been submitted)", "if", "(", "defined", "(", "'DOING_AUTOSAVE'", ")", "&&", "DOING_AUTOSAVE", ")", "{", "return", "$", "post_id", ";", "}", "// Check the user's permissions.", "$", "post_type", "=", "filter_input", "(", "INPUT_POST", ",", "'post_type'", ")", ";", "if", "(", "in_array", "(", "$", "post_type", ",", "$", "this", "->", "settings", "[", "'post_types'", "]", ")", ")", "{", "// NOTE: this might not work for custom post types, unless Amarkal", "// is used to register them (custom post types might have labels different ", "// than 'edit_{post_type}'", "$", "capability", "=", "'edit_'", ".", "$", "post_type", ";", "if", "(", "!", "current_user_can", "(", "$", "capability", ",", "$", "post_id", ")", ")", "{", "return", "$", "post_id", ";", "}", "}", "else", "{", "return", "$", "post_id", ";", "}", "// OK, it is safe to process data.", "$", "old_instance", "=", "\\", "get_post_meta", "(", "$", "post_id", ",", "$", "this", "->", "settings", "[", "'id'", "]", ",", "true", ")", ";", "$", "new_instance", "=", "$", "this", "->", "form", "->", "updater", "->", "update", "(", "$", "old_instance", "===", "\"\"", "?", "array", "(", ")", ":", "$", "old_instance", ")", ";", "\\", "update_post_meta", "(", "$", "post_id", ",", "$", "this", "->", "settings", "[", "'id'", "]", ",", "$", "new_instance", ")", ";", "// Callback", "$", "callable", "=", "$", "this", "->", "settings", "[", "'callback'", "]", ";", "if", "(", "is_callable", "(", "$", "callable", ")", ")", "{", "$", "callable", "(", "$", "post_id", ",", "$", "new_instance", ")", ";", "}", "}" ]
Save the meta when the post is saved. @param int $post_id The ID of the post being saved.
[ "Save", "the", "meta", "when", "the", "post", "is", "saved", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Extensions/WordPress/MetaBox/MetaBox.php#L133-L195
askupasoftware/amarkal
Extensions/WordPress/MetaBox/MetaBox.php
MetaBox.render
public function render( $post ) { $old_instance = \get_post_meta( $post->ID, $this->settings['id'], true ); $this->form->updater->update( $old_instance === "" ? array() : $old_instance ); // Add an nonce field so we can check for it later. wp_nonce_field( $this->action_name(), $this->nonce_name() ); $this->form->render(true); }
php
public function render( $post ) { $old_instance = \get_post_meta( $post->ID, $this->settings['id'], true ); $this->form->updater->update( $old_instance === "" ? array() : $old_instance ); // Add an nonce field so we can check for it later. wp_nonce_field( $this->action_name(), $this->nonce_name() ); $this->form->render(true); }
[ "public", "function", "render", "(", "$", "post", ")", "{", "$", "old_instance", "=", "\\", "get_post_meta", "(", "$", "post", "->", "ID", ",", "$", "this", "->", "settings", "[", "'id'", "]", ",", "true", ")", ";", "$", "this", "->", "form", "->", "updater", "->", "update", "(", "$", "old_instance", "===", "\"\"", "?", "array", "(", ")", ":", "$", "old_instance", ")", ";", "// Add an nonce field so we can check for it later.", "wp_nonce_field", "(", "$", "this", "->", "action_name", "(", ")", ",", "$", "this", "->", "nonce_name", "(", ")", ")", ";", "$", "this", "->", "form", "->", "render", "(", "true", ")", ";", "}" ]
Render Meta Box content. @param WP_Post $post The post object.
[ "Render", "Meta", "Box", "content", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Extensions/WordPress/MetaBox/MetaBox.php#L202-L209
askupasoftware/amarkal
Extensions/WordPress/MetaBox/MetaBox.php
MetaBox.get_meta_value
static function get_meta_value( $post_id, $metabox_id, $field_name = null ) { $meta = \get_post_meta( $post_id, $metabox_id, true ); if( null == $field_name ) { return $meta; } if( isset($meta[$field_name]) ) { return $meta[$field_name]; } }
php
static function get_meta_value( $post_id, $metabox_id, $field_name = null ) { $meta = \get_post_meta( $post_id, $metabox_id, true ); if( null == $field_name ) { return $meta; } if( isset($meta[$field_name]) ) { return $meta[$field_name]; } }
[ "static", "function", "get_meta_value", "(", "$", "post_id", ",", "$", "metabox_id", ",", "$", "field_name", "=", "null", ")", "{", "$", "meta", "=", "\\", "get_post_meta", "(", "$", "post_id", ",", "$", "metabox_id", ",", "true", ")", ";", "if", "(", "null", "==", "$", "field_name", ")", "{", "return", "$", "meta", ";", "}", "if", "(", "isset", "(", "$", "meta", "[", "$", "field_name", "]", ")", ")", "{", "return", "$", "meta", "[", "$", "field_name", "]", ";", "}", "}" ]
Get a meta box value for a given post id, by specifying the metabox id and field name. If no field name is given, an associative array with all the meta box values will be returned. @param int $post_id The post's id @param string $metabox_id The metabox id @param string $field_name (optional) The metabox field name @return mixed
[ "Get", "a", "meta", "box", "value", "for", "a", "given", "post", "id", "by", "specifying", "the", "metabox", "id", "and", "field", "name", ".", "If", "no", "field", "name", "is", "given", "an", "associative", "array", "with", "all", "the", "meta", "box", "values", "will", "be", "returned", "." ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/Extensions/WordPress/MetaBox/MetaBox.php#L221-L233
webforge-labs/psc-cms
lib/Psc/PHPExcel/SimpleImporter.php
SimpleImporter.findAll
public function findAll() { $sheets = array(); foreach ($this->readSelectedSheets() as $selectName => $excelSheet) { $sheets[$selectName] = new Sheet($selectName, $this->readRows($excelSheet)); } return $sheets; }
php
public function findAll() { $sheets = array(); foreach ($this->readSelectedSheets() as $selectName => $excelSheet) { $sheets[$selectName] = new Sheet($selectName, $this->readRows($excelSheet)); } return $sheets; }
[ "public", "function", "findAll", "(", ")", "{", "$", "sheets", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "readSelectedSheets", "(", ")", "as", "$", "selectName", "=>", "$", "excelSheet", ")", "{", "$", "sheets", "[", "$", "selectName", "]", "=", "new", "Sheet", "(", "$", "selectName", ",", "$", "this", "->", "readRows", "(", "$", "excelSheet", ")", ")", ";", "}", "return", "$", "sheets", ";", "}" ]
Returns all selected Sheets with all rows @return Sheet[]
[ "Returns", "all", "selected", "Sheets", "with", "all", "rows" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/PHPExcel/SimpleImporter.php#L65-L73
phpmob/changmin
src/PhpMob/CmsBundle/Slug/URLify.php
URLify.transliterate
public static function transliterate($text) { self::init(); if (preg_match_all(self::$regex, $text, $matches)) { for ($i = 0; $i < count($matches[0]); $i++) { $char = $matches[0][$i]; if (isset (self::$map[$char])) { $text = str_replace($char, self::$map[$char], $text); } } } return $text; }
php
public static function transliterate($text) { self::init(); if (preg_match_all(self::$regex, $text, $matches)) { for ($i = 0; $i < count($matches[0]); $i++) { $char = $matches[0][$i]; if (isset (self::$map[$char])) { $text = str_replace($char, self::$map[$char], $text); } } } return $text; }
[ "public", "static", "function", "transliterate", "(", "$", "text", ")", "{", "self", "::", "init", "(", ")", ";", "if", "(", "preg_match_all", "(", "self", "::", "$", "regex", ",", "$", "text", ",", "$", "matches", ")", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "matches", "[", "0", "]", ")", ";", "$", "i", "++", ")", "{", "$", "char", "=", "$", "matches", "[", "0", "]", "[", "$", "i", "]", ";", "if", "(", "isset", "(", "self", "::", "$", "map", "[", "$", "char", "]", ")", ")", "{", "$", "text", "=", "str_replace", "(", "$", "char", ",", "self", "::", "$", "map", "[", "$", "char", "]", ",", "$", "text", ")", ";", "}", "}", "}", "return", "$", "text", ";", "}" ]
Transliterates characters to their ASCII equivalents. $language specifies a priority for a specific language. The latter is useful if languages have different rules for the same character. @param string $text @return string
[ "Transliterates", "characters", "to", "their", "ASCII", "equivalents", ".", "$language", "specifies", "a", "priority", "for", "a", "specific", "language", ".", "The", "latter", "is", "useful", "if", "languages", "have", "different", "rules", "for", "the", "same", "character", "." ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/CmsBundle/Slug/URLify.php#L181-L195
phpmob/changmin
src/PhpMob/CmsBundle/Slug/URLify.php
URLify.slug
public static function slug($text, $length = 60) { $string = self::transliterate($text); // if downcode doesn't hit, the char will be stripped here $nonsafeChars = preg_quote("&+$,:;=?@\"#{}|^~[`%!'].()*\\"); $string = preg_replace("/[$nonsafeChars\/\s+]/", '-', $string); $string = str_replace('_', ' ', $string); // treat underscores as spaces $string = preg_replace('/^\s+|\s+$/u', '', $string); // trim leading/trailing spaces $string = preg_replace('/[-\s]+/u', '-', $string); // convert spaces to hyphens $string = preg_replace('/’/u', '-', $string); // convert spaces to hyphens $string = preg_replace('/ฺ/u', '-', $string); // convert spaces to hyphens $string = self::typo($string); $string = strtolower($string); // convert to lowercase return trim(mb_substr($string, 0, $length), '-') ?: $text; // trim to first $length chars }
php
public static function slug($text, $length = 60) { $string = self::transliterate($text); // if downcode doesn't hit, the char will be stripped here $nonsafeChars = preg_quote("&+$,:;=?@\"#{}|^~[`%!'].()*\\"); $string = preg_replace("/[$nonsafeChars\/\s+]/", '-', $string); $string = str_replace('_', ' ', $string); // treat underscores as spaces $string = preg_replace('/^\s+|\s+$/u', '', $string); // trim leading/trailing spaces $string = preg_replace('/[-\s]+/u', '-', $string); // convert spaces to hyphens $string = preg_replace('/’/u', '-', $string); // convert spaces to hyphens $string = preg_replace('/ฺ/u', '-', $string); // convert spaces to hyphens $string = self::typo($string); $string = strtolower($string); // convert to lowercase return trim(mb_substr($string, 0, $length), '-') ?: $text; // trim to first $length chars }
[ "public", "static", "function", "slug", "(", "$", "text", ",", "$", "length", "=", "60", ")", "{", "$", "string", "=", "self", "::", "transliterate", "(", "$", "text", ")", ";", "// if downcode doesn't hit, the char will be stripped here", "$", "nonsafeChars", "=", "preg_quote", "(", "\"&+$,:;=?@\\\"#{}|^~[`%!'].()*\\\\\"", ")", ";", "$", "string", "=", "preg_replace", "(", "\"/[$nonsafeChars\\/\\s+]/\"", ",", "'-'", ",", "$", "string", ")", ";", "$", "string", "=", "str_replace", "(", "'_'", ",", "' '", ",", "$", "string", ")", ";", "// treat underscores as spaces", "$", "string", "=", "preg_replace", "(", "'/^\\s+|\\s+$/u'", ",", "''", ",", "$", "string", ")", ";", "// trim leading/trailing spaces", "$", "string", "=", "preg_replace", "(", "'/[-\\s]+/u'", ",", "'-'", ",", "$", "string", ")", ";", "// convert spaces to hyphens", "$", "string", "=", "preg_replace", "(", "'/’/u', ", "'", "', ", "$", "t", "ring);", " ", " ", " convert spaces to hyphens", "$", "string", "=", "preg_replace", "(", "'/ฺ/u', ", "'", "', ", "$", "t", "ring);", " ", " ", " convert spaces to hyphens", "$", "string", "=", "self", "::", "typo", "(", "$", "string", ")", ";", "$", "string", "=", "strtolower", "(", "$", "string", ")", ";", "// convert to lowercase", "return", "trim", "(", "mb_substr", "(", "$", "string", ",", "0", ",", "$", "length", ")", ",", "'-'", ")", "?", ":", "$", "text", ";", "// trim to first $length chars", "}" ]
Filters a string, e.g., "Petty theft" to "petty-theft" @param string $text The text to return filtered @param int $length The length (after filtering) of the string to be returned @return string
[ "Filters", "a", "string", "e", ".", "g", ".", "Petty", "theft", "to", "petty", "-", "theft", "@param", "string", "$text", "The", "text", "to", "return", "filtered", "@param", "int", "$length", "The", "length", "(", "after", "filtering", ")", "of", "the", "string", "to", "be", "returned" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/CmsBundle/Slug/URLify.php#L204-L220
Nozemi/SlickBoard-Library
lib/SBLib/Utilities/MISC.php
MISC.findFile
public static function findFile($file, $loops = 3) { // Checks whether or not $file exists. if (!file_exists($file)) { // How many parent folders it'll check. (3 by default) for ($i = 0; $i < $loops; $i++) { if (!file_exists($file)) { $file = '../' . $file; } } } return $file; }
php
public static function findFile($file, $loops = 3) { // Checks whether or not $file exists. if (!file_exists($file)) { // How many parent folders it'll check. (3 by default) for ($i = 0; $i < $loops; $i++) { if (!file_exists($file)) { $file = '../' . $file; } } } return $file; }
[ "public", "static", "function", "findFile", "(", "$", "file", ",", "$", "loops", "=", "3", ")", "{", "// Checks whether or not $file exists.", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "// How many parent folders it'll check. (3 by default)", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "loops", ";", "$", "i", "++", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "$", "file", "=", "'../'", ".", "$", "file", ";", "}", "}", "}", "return", "$", "file", ";", "}" ]
Finds a file, by default it will try up to 3 parent folders.
[ "Finds", "a", "file", "by", "default", "it", "will", "try", "up", "to", "3", "parent", "folders", "." ]
train
https://github.com/Nozemi/SlickBoard-Library/blob/c9f0a26a30f8127c997f75d7232eac170972418d/lib/SBLib/Utilities/MISC.php#L31-L43
Nozemi/SlickBoard-Library
lib/SBLib/Utilities/MISC.php
MISC.findKey
public static function findKey($aKey, $array) { // Check if an array is provided. if (is_array($array)) { // Loops through the array. foreach ($array as $key => $item) { // Checks if it did find the matching key. If it doesn't, it continues looping until it does, // or until the end of the array. if ($key == $aKey) { return $item; } else { $result = self::findKey($aKey, $item); if ($result != false) { return $result; } } } } return false; }
php
public static function findKey($aKey, $array) { // Check if an array is provided. if (is_array($array)) { // Loops through the array. foreach ($array as $key => $item) { // Checks if it did find the matching key. If it doesn't, it continues looping until it does, // or until the end of the array. if ($key == $aKey) { return $item; } else { $result = self::findKey($aKey, $item); if ($result != false) { return $result; } } } } return false; }
[ "public", "static", "function", "findKey", "(", "$", "aKey", ",", "$", "array", ")", "{", "// Check if an array is provided.", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "// Loops through the array.", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "item", ")", "{", "// Checks if it did find the matching key. If it doesn't, it continues looping until it does,", "// or until the end of the array.", "if", "(", "$", "key", "==", "$", "aKey", ")", "{", "return", "$", "item", ";", "}", "else", "{", "$", "result", "=", "self", "::", "findKey", "(", "$", "aKey", ",", "$", "item", ")", ";", "if", "(", "$", "result", "!=", "false", ")", "{", "return", "$", "result", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
in the array the key is, just that it exists in there somewhere.
[ "in", "the", "array", "the", "key", "is", "just", "that", "it", "exists", "in", "there", "somewhere", "." ]
train
https://github.com/Nozemi/SlickBoard-Library/blob/c9f0a26a30f8127c997f75d7232eac170972418d/lib/SBLib/Utilities/MISC.php#L55-L73
Nozemi/SlickBoard-Library
lib/SBLib/Utilities/MISC.php
MISC.getPageName
public static function getPageName($_file, DBUtil $SQL) { $page = ucfirst(basename($_file, '.php')); if (isset($_GET['page'])) { $page = ucfirst($_GET['page']); } $cat = $top = $trd = null; if (isset($_GET['username'])) { $U = new User($SQL); $user = $U->getUser(str_replace('_', ' ', $_GET['username']), false); if (empty($user->username)) { $page = 'Profile Not Found'; } else { $page = $user->username . '\'s Profile'; } } if (isset($_GET['category'])) { $C = new Category($SQL); $cat = $C->getCategory($_GET['category'], false); $page = $cat->title; } if (isset($_GET['topic'])) { if ($cat instanceof Category) { $T = new Topic($SQL); $top = $T->getTopic($_GET['topic'], false, $cat->id); } $page = $top->title; } if (isset($_GET['thread'])) { if ($top instanceof Topic) { $Tr = new Thread($SQL); $trd = $Tr->getThread($_GET['thread'], false, $top->id); } $page = $trd->title; } return $page; }
php
public static function getPageName($_file, DBUtil $SQL) { $page = ucfirst(basename($_file, '.php')); if (isset($_GET['page'])) { $page = ucfirst($_GET['page']); } $cat = $top = $trd = null; if (isset($_GET['username'])) { $U = new User($SQL); $user = $U->getUser(str_replace('_', ' ', $_GET['username']), false); if (empty($user->username)) { $page = 'Profile Not Found'; } else { $page = $user->username . '\'s Profile'; } } if (isset($_GET['category'])) { $C = new Category($SQL); $cat = $C->getCategory($_GET['category'], false); $page = $cat->title; } if (isset($_GET['topic'])) { if ($cat instanceof Category) { $T = new Topic($SQL); $top = $T->getTopic($_GET['topic'], false, $cat->id); } $page = $top->title; } if (isset($_GET['thread'])) { if ($top instanceof Topic) { $Tr = new Thread($SQL); $trd = $Tr->getThread($_GET['thread'], false, $top->id); } $page = $trd->title; } return $page; }
[ "public", "static", "function", "getPageName", "(", "$", "_file", ",", "DBUtil", "$", "SQL", ")", "{", "$", "page", "=", "ucfirst", "(", "basename", "(", "$", "_file", ",", "'.php'", ")", ")", ";", "if", "(", "isset", "(", "$", "_GET", "[", "'page'", "]", ")", ")", "{", "$", "page", "=", "ucfirst", "(", "$", "_GET", "[", "'page'", "]", ")", ";", "}", "$", "cat", "=", "$", "top", "=", "$", "trd", "=", "null", ";", "if", "(", "isset", "(", "$", "_GET", "[", "'username'", "]", ")", ")", "{", "$", "U", "=", "new", "User", "(", "$", "SQL", ")", ";", "$", "user", "=", "$", "U", "->", "getUser", "(", "str_replace", "(", "'_'", ",", "' '", ",", "$", "_GET", "[", "'username'", "]", ")", ",", "false", ")", ";", "if", "(", "empty", "(", "$", "user", "->", "username", ")", ")", "{", "$", "page", "=", "'Profile Not Found'", ";", "}", "else", "{", "$", "page", "=", "$", "user", "->", "username", ".", "'\\'s Profile'", ";", "}", "}", "if", "(", "isset", "(", "$", "_GET", "[", "'category'", "]", ")", ")", "{", "$", "C", "=", "new", "Category", "(", "$", "SQL", ")", ";", "$", "cat", "=", "$", "C", "->", "getCategory", "(", "$", "_GET", "[", "'category'", "]", ",", "false", ")", ";", "$", "page", "=", "$", "cat", "->", "title", ";", "}", "if", "(", "isset", "(", "$", "_GET", "[", "'topic'", "]", ")", ")", "{", "if", "(", "$", "cat", "instanceof", "Category", ")", "{", "$", "T", "=", "new", "Topic", "(", "$", "SQL", ")", ";", "$", "top", "=", "$", "T", "->", "getTopic", "(", "$", "_GET", "[", "'topic'", "]", ",", "false", ",", "$", "cat", "->", "id", ")", ";", "}", "$", "page", "=", "$", "top", "->", "title", ";", "}", "if", "(", "isset", "(", "$", "_GET", "[", "'thread'", "]", ")", ")", "{", "if", "(", "$", "top", "instanceof", "Topic", ")", "{", "$", "Tr", "=", "new", "Thread", "(", "$", "SQL", ")", ";", "$", "trd", "=", "$", "Tr", "->", "getThread", "(", "$", "_GET", "[", "'thread'", "]", ",", "false", ",", "$", "top", "->", "id", ")", ";", "}", "$", "page", "=", "$", "trd", "->", "title", ";", "}", "return", "$", "page", ";", "}" ]
@param string $_file - Filename @param DBUtil $SQL @return string
[ "@param", "string", "$_file", "-", "Filename", "@param", "DBUtil", "$SQL" ]
train
https://github.com/Nozemi/SlickBoard-Library/blob/c9f0a26a30f8127c997f75d7232eac170972418d/lib/SBLib/Utilities/MISC.php#L81-L125
aedart/laravel-helpers
src/Traits/Cookie/CookieTrait.php
CookieTrait.getCookie
public function getCookie(): ?Factory { if (!$this->hasCookie()) { $this->setCookie($this->getDefaultCookie()); } return $this->cookie; }
php
public function getCookie(): ?Factory { if (!$this->hasCookie()) { $this->setCookie($this->getDefaultCookie()); } return $this->cookie; }
[ "public", "function", "getCookie", "(", ")", ":", "?", "Factory", "{", "if", "(", "!", "$", "this", "->", "hasCookie", "(", ")", ")", "{", "$", "this", "->", "setCookie", "(", "$", "this", "->", "getDefaultCookie", "(", ")", ")", ";", "}", "return", "$", "this", "->", "cookie", ";", "}" ]
Get cookie If no cookie has been set, this method will set and return a default cookie, if any such value is available @see getDefaultCookie() @return Factory|null cookie or null if none cookie has been set
[ "Get", "cookie" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Cookie/CookieTrait.php#L53-L59
atkrad/data-tables
src/DataSource/Dom.php
Dom.initialize
public function initialize(Table $table) { $this->table = $table; $this->table->setTableId($this->tableId); }
php
public function initialize(Table $table) { $this->table = $table; $this->table->setTableId($this->tableId); }
[ "public", "function", "initialize", "(", "Table", "$", "table", ")", "{", "$", "this", "->", "table", "=", "$", "table", ";", "$", "this", "->", "table", "->", "setTableId", "(", "$", "this", "->", "tableId", ")", ";", "}" ]
Initialize data source @param Table $table Table object @return void
[ "Initialize", "data", "source" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/Dom.php#L46-L50
daithi-coombes/bluemix-personality-insights-php
lib/Config.php
Config.getInstance
public static function getInstance($configFile='config.yml') { static $instance = null; if (null === $instance) { $instance = new static(); } $configuration = Yaml::parse(file_get_contents($configFile)); $instance->setParams($configuration); return $instance; }
php
public static function getInstance($configFile='config.yml') { static $instance = null; if (null === $instance) { $instance = new static(); } $configuration = Yaml::parse(file_get_contents($configFile)); $instance->setParams($configuration); return $instance; }
[ "public", "static", "function", "getInstance", "(", "$", "configFile", "=", "'config.yml'", ")", "{", "static", "$", "instance", "=", "null", ";", "if", "(", "null", "===", "$", "instance", ")", "{", "$", "instance", "=", "new", "static", "(", ")", ";", "}", "$", "configuration", "=", "Yaml", "::", "parse", "(", "file_get_contents", "(", "$", "configFile", ")", ")", ";", "$", "instance", "->", "setParams", "(", "$", "configuration", ")", ";", "return", "$", "instance", ";", "}" ]
Config singleton. @param string $configFile The yaml config file relative to project root. @return Config The *Singleton* instance.
[ "Config", "singleton", "." ]
train
https://github.com/daithi-coombes/bluemix-personality-insights-php/blob/171bd0a6deb3e1e9a7b38fc61c2a7ae601d76a9a/lib/Config.php#L26-L37
yoanm/symfony-jsonrpc-http-server-doc
src/Endpoint/DocumentationEndpoint.php
DocumentationEndpoint.httpGet
public function httpGet(Request $request) : Response { // Use Raw doc by default if not provided $filename = $request->get('filename') ?? RawDocProvider::SUPPORTED_FILENAME; $response = new Response(); $response->headers->set('Content-Type', 'application/json'); $doc = $this->normalizedDocFinder->findFor($filename, $request->getHttpHost()); $response->setContent(json_encode($doc)); return $response; }
php
public function httpGet(Request $request) : Response { // Use Raw doc by default if not provided $filename = $request->get('filename') ?? RawDocProvider::SUPPORTED_FILENAME; $response = new Response(); $response->headers->set('Content-Type', 'application/json'); $doc = $this->normalizedDocFinder->findFor($filename, $request->getHttpHost()); $response->setContent(json_encode($doc)); return $response; }
[ "public", "function", "httpGet", "(", "Request", "$", "request", ")", ":", "Response", "{", "// Use Raw doc by default if not provided", "$", "filename", "=", "$", "request", "->", "get", "(", "'filename'", ")", "??", "RawDocProvider", "::", "SUPPORTED_FILENAME", ";", "$", "response", "=", "new", "Response", "(", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "$", "doc", "=", "$", "this", "->", "normalizedDocFinder", "->", "findFor", "(", "$", "filename", ",", "$", "request", "->", "getHttpHost", "(", ")", ")", ";", "$", "response", "->", "setContent", "(", "json_encode", "(", "$", "doc", ")", ")", ";", "return", "$", "response", ";", "}" ]
@param Request $request @return Response @throws \Exception
[ "@param", "Request", "$request" ]
train
https://github.com/yoanm/symfony-jsonrpc-http-server-doc/blob/7a59862f74fef29d0e2ad017188977419503ad94/src/Endpoint/DocumentationEndpoint.php#L55-L67
PortaText/php-sdk
src/PortaText/Client/Base.php
Base.run
public function run( $endpoint, $method, $contentType, $acceptContentType, $body, $outputFile = null, $authType = null ) { $uri = implode("/", array($this->endpoint, $endpoint)); $result = null; /* * When there's not a specific auth type defined, try to guess one as * follows: * - If there is a session token in use, try to use it. * - If not, but there are credentials specified, try to login and * then retry the request with the new session token. * - If there aren't any session tokens and credentials specified * fallback to the api key. */ if (is_null($authType)) { $authType = $this->authType(); if ($authType === "basic") { $this->login(); $authType = "sessionToken"; } } $this->logger->debug("Calling $method $uri with $authType"); $headers = array( "Content-Type" => $contentType, "Accept" => $acceptContentType ); switch ($authType) { case "apiKey": $headers["X-Api-Key"] = $this->apiKey; break; case "sessionToken": $headers["X-Session-Token"] = $this->sessionToken; break; case "basic": $auth = base64_encode( $this->credentials[0] . ":" . $this->credentials[1] ); $headers["Authorization"] = "Basic $auth"; break; default: throw new \InvalidArgumentException( "Invalid auth type: $authType" ); } $descriptor = new Descriptor( $uri, $method, $headers, $body, $outputFile ); list($code, $resultHeaders, $resultBody) = $this->execute($descriptor); $result = new Result( $code, $resultHeaders, json_decode($resultBody, true) ); /* * It could happen that the session token expires, so try * to login again and then reissue the request if the login was * successful. */ if ($code === 401 && $authType === "sessionToken") { $this->login(); return $this->run( $endpoint, $method, $contentType, $acceptContentType, $body ); } $this->assertResult($descriptor, $result); return $result; }
php
public function run( $endpoint, $method, $contentType, $acceptContentType, $body, $outputFile = null, $authType = null ) { $uri = implode("/", array($this->endpoint, $endpoint)); $result = null; /* * When there's not a specific auth type defined, try to guess one as * follows: * - If there is a session token in use, try to use it. * - If not, but there are credentials specified, try to login and * then retry the request with the new session token. * - If there aren't any session tokens and credentials specified * fallback to the api key. */ if (is_null($authType)) { $authType = $this->authType(); if ($authType === "basic") { $this->login(); $authType = "sessionToken"; } } $this->logger->debug("Calling $method $uri with $authType"); $headers = array( "Content-Type" => $contentType, "Accept" => $acceptContentType ); switch ($authType) { case "apiKey": $headers["X-Api-Key"] = $this->apiKey; break; case "sessionToken": $headers["X-Session-Token"] = $this->sessionToken; break; case "basic": $auth = base64_encode( $this->credentials[0] . ":" . $this->credentials[1] ); $headers["Authorization"] = "Basic $auth"; break; default: throw new \InvalidArgumentException( "Invalid auth type: $authType" ); } $descriptor = new Descriptor( $uri, $method, $headers, $body, $outputFile ); list($code, $resultHeaders, $resultBody) = $this->execute($descriptor); $result = new Result( $code, $resultHeaders, json_decode($resultBody, true) ); /* * It could happen that the session token expires, so try * to login again and then reissue the request if the login was * successful. */ if ($code === 401 && $authType === "sessionToken") { $this->login(); return $this->run( $endpoint, $method, $contentType, $acceptContentType, $body ); } $this->assertResult($descriptor, $result); return $result; }
[ "public", "function", "run", "(", "$", "endpoint", ",", "$", "method", ",", "$", "contentType", ",", "$", "acceptContentType", ",", "$", "body", ",", "$", "outputFile", "=", "null", ",", "$", "authType", "=", "null", ")", "{", "$", "uri", "=", "implode", "(", "\"/\"", ",", "array", "(", "$", "this", "->", "endpoint", ",", "$", "endpoint", ")", ")", ";", "$", "result", "=", "null", ";", "/*\n * When there's not a specific auth type defined, try to guess one as\n * follows:\n * - If there is a session token in use, try to use it.\n * - If not, but there are credentials specified, try to login and\n * then retry the request with the new session token.\n * - If there aren't any session tokens and credentials specified\n * fallback to the api key.\n */", "if", "(", "is_null", "(", "$", "authType", ")", ")", "{", "$", "authType", "=", "$", "this", "->", "authType", "(", ")", ";", "if", "(", "$", "authType", "===", "\"basic\"", ")", "{", "$", "this", "->", "login", "(", ")", ";", "$", "authType", "=", "\"sessionToken\"", ";", "}", "}", "$", "this", "->", "logger", "->", "debug", "(", "\"Calling $method $uri with $authType\"", ")", ";", "$", "headers", "=", "array", "(", "\"Content-Type\"", "=>", "$", "contentType", ",", "\"Accept\"", "=>", "$", "acceptContentType", ")", ";", "switch", "(", "$", "authType", ")", "{", "case", "\"apiKey\"", ":", "$", "headers", "[", "\"X-Api-Key\"", "]", "=", "$", "this", "->", "apiKey", ";", "break", ";", "case", "\"sessionToken\"", ":", "$", "headers", "[", "\"X-Session-Token\"", "]", "=", "$", "this", "->", "sessionToken", ";", "break", ";", "case", "\"basic\"", ":", "$", "auth", "=", "base64_encode", "(", "$", "this", "->", "credentials", "[", "0", "]", ".", "\":\"", ".", "$", "this", "->", "credentials", "[", "1", "]", ")", ";", "$", "headers", "[", "\"Authorization\"", "]", "=", "\"Basic $auth\"", ";", "break", ";", "default", ":", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid auth type: $authType\"", ")", ";", "}", "$", "descriptor", "=", "new", "Descriptor", "(", "$", "uri", ",", "$", "method", ",", "$", "headers", ",", "$", "body", ",", "$", "outputFile", ")", ";", "list", "(", "$", "code", ",", "$", "resultHeaders", ",", "$", "resultBody", ")", "=", "$", "this", "->", "execute", "(", "$", "descriptor", ")", ";", "$", "result", "=", "new", "Result", "(", "$", "code", ",", "$", "resultHeaders", ",", "json_decode", "(", "$", "resultBody", ",", "true", ")", ")", ";", "/*\n * It could happen that the session token expires, so try\n * to login again and then reissue the request if the login was\n * successful.\n */", "if", "(", "$", "code", "===", "401", "&&", "$", "authType", "===", "\"sessionToken\"", ")", "{", "$", "this", "->", "login", "(", ")", ";", "return", "$", "this", "->", "run", "(", "$", "endpoint", ",", "$", "method", ",", "$", "contentType", ",", "$", "acceptContentType", ",", "$", "body", ")", ";", "}", "$", "this", "->", "assertResult", "(", "$", "descriptor", ",", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Runs the given command. @param string $endpoint Endpoint to invoke. @param string $method HTTP method to use. @param string $contentType Content-Type value. @param string $acceptContentType Accept value. @param string $body Payload to send. @param string $outputFile File where to write the result to. @param string $authType One of "apiKey", "sessionToken", or "basic" @return PortaText\Command\Result @throws PortaText\Exception\RequestError @throws PortaText\Exception\ServerError @throws PortaText\Exception\ClientError @throws PortaText\Exception\InvalidCredentials @throws PortaText\Exception\PaymentRequired @throws PortaText\Exception\Forbidden @throws PortaText\Exception\NotFound @throws PortaText\Exception\InvalidMedia @throws PortaText\Exception\NotAcceptable @throws PortaText\Exception\InvalidMethod @throws PortaText\Exception\RateLimited @throws InvalidArgumentException
[ "Runs", "the", "given", "command", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Base.php#L147-L227
PortaText/php-sdk
src/PortaText/Client/Base.php
Base.assertResult
protected function assertResult($descriptor, $result) { $errors = array( 401 => "InvalidCredentials", 402 => "PaymentRequired", 403 => "Forbidden", 404 => "NotFound", 405 => "InvalidMethod", 406 => "NotAcceptable", 415 => "InvalidMedia", 429 => "RateLimited", 500 => "ServerError", 400 => "ClientError" ); if (isset($errors[$result->code])) { $class = $errors[$result->code]; $class = "PortaText\\Exception\\$class"; throw new $class($descriptor, $result); } }
php
protected function assertResult($descriptor, $result) { $errors = array( 401 => "InvalidCredentials", 402 => "PaymentRequired", 403 => "Forbidden", 404 => "NotFound", 405 => "InvalidMethod", 406 => "NotAcceptable", 415 => "InvalidMedia", 429 => "RateLimited", 500 => "ServerError", 400 => "ClientError" ); if (isset($errors[$result->code])) { $class = $errors[$result->code]; $class = "PortaText\\Exception\\$class"; throw new $class($descriptor, $result); } }
[ "protected", "function", "assertResult", "(", "$", "descriptor", ",", "$", "result", ")", "{", "$", "errors", "=", "array", "(", "401", "=>", "\"InvalidCredentials\"", ",", "402", "=>", "\"PaymentRequired\"", ",", "403", "=>", "\"Forbidden\"", ",", "404", "=>", "\"NotFound\"", ",", "405", "=>", "\"InvalidMethod\"", ",", "406", "=>", "\"NotAcceptable\"", ",", "415", "=>", "\"InvalidMedia\"", ",", "429", "=>", "\"RateLimited\"", ",", "500", "=>", "\"ServerError\"", ",", "400", "=>", "\"ClientError\"", ")", ";", "if", "(", "isset", "(", "$", "errors", "[", "$", "result", "->", "code", "]", ")", ")", "{", "$", "class", "=", "$", "errors", "[", "$", "result", "->", "code", "]", ";", "$", "class", "=", "\"PortaText\\\\Exception\\\\$class\"", ";", "throw", "new", "$", "class", "(", "$", "descriptor", ",", "$", "result", ")", ";", "}", "}" ]
Will assert that the request finished successfuly. @param PortaText\Command\Descriptor $descriptor The Command execution descriptor. @param PortaText\Command\Result $result Request execution result. @return void @throws PortaText\Exception\ServerError @throws PortaText\Exception\ClientError @throws PortaText\Exception\InvalidCredentials @throws PortaText\Exception\PaymentRequired @throws PortaText\Exception\Forbidden @throws PortaText\Exception\NotFound @throws PortaText\Exception\InvalidMedia @throws PortaText\Exception\NotAcceptable @throws PortaText\Exception\InvalidMethod @throws PortaText\Exception\RateLimited
[ "Will", "assert", "that", "the", "request", "finished", "successfuly", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Base.php#L275-L294
webforge-labs/psc-cms
lib/Psc/Form/ValidationPackage.php
ValidationPackage.createValidator
public function createValidator(Array $simpleRules = array()) { $validator = new Validator(); if (count($simpleRules) > 0) { $validator->addSimpleRules($simpleRules); } return $validator; }
php
public function createValidator(Array $simpleRules = array()) { $validator = new Validator(); if (count($simpleRules) > 0) { $validator->addSimpleRules($simpleRules); } return $validator; }
[ "public", "function", "createValidator", "(", "Array", "$", "simpleRules", "=", "array", "(", ")", ")", "{", "$", "validator", "=", "new", "Validator", "(", ")", ";", "if", "(", "count", "(", "$", "simpleRules", ")", ">", "0", ")", "{", "$", "validator", "->", "addSimpleRules", "(", "$", "simpleRules", ")", ";", "}", "return", "$", "validator", ";", "}" ]
Erstellt einen Validator mit den SimpleRules 'field'=>'nes' $validator->validate('field', $formValue);
[ "Erstellt", "einen", "Validator", "mit", "den", "SimpleRules" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/ValidationPackage.php#L74-L81
webforge-labs/psc-cms
lib/Psc/Form/ValidationPackage.php
ValidationPackage.validateRequestData
public function validateRequestData(FormData $requestData, Validator $validator, \Psc\Net\ServiceErrorPackage $err) { try { return (object) $validator->validateFields($requestData); // dieser Cast muss angepasst werden wenn FormData mal was andres ist } catch (\Psc\Form\ValidatorExceptionList $e) { throw $err->validationResponse($e); } }
php
public function validateRequestData(FormData $requestData, Validator $validator, \Psc\Net\ServiceErrorPackage $err) { try { return (object) $validator->validateFields($requestData); // dieser Cast muss angepasst werden wenn FormData mal was andres ist } catch (\Psc\Form\ValidatorExceptionList $e) { throw $err->validationResponse($e); } }
[ "public", "function", "validateRequestData", "(", "FormData", "$", "requestData", ",", "Validator", "$", "validator", ",", "\\", "Psc", "\\", "Net", "\\", "ServiceErrorPackage", "$", "err", ")", "{", "try", "{", "return", "(", "object", ")", "$", "validator", "->", "validateFields", "(", "$", "requestData", ")", ";", "// dieser Cast muss angepasst werden wenn FormData mal was andres ist", "}", "catch", "(", "\\", "Psc", "\\", "Form", "\\", "ValidatorExceptionList", "$", "e", ")", "{", "throw", "$", "err", "->", "validationResponse", "(", "$", "e", ")", ";", "}", "}" ]
Validiert alle Felder im Validator anhand der Daten von FormData und benutzt $err um eine ValidationResponse zu erzeugen (falls es Fehler gab) @return FormData (aber validated + cleaned)
[ "Validiert", "alle", "Felder", "im", "Validator", "anhand", "der", "Daten", "von", "FormData", "und", "benutzt", "$err", "um", "eine", "ValidationResponse", "zu", "erzeugen", "(", "falls", "es", "Fehler", "gab", ")" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/ValidationPackage.php#L94-L101
webforge-labs/psc-cms
lib/Psc/Form/ValidationPackage.php
ValidationPackage.createComponentsValidator
public function createComponentsValidator(FormData $requestData, EntityFormPanel $panel, DCPackage $dc, Array $components = NULL) { $this->validationEntity = $entity = $panel->getEntityForm()->getEntity(); $components = isset($components) ? Code::castCollection($components) : $panel->getEntityForm()->getComponents(); return $this->componentsValidator = new ComponentsValidator($this->createFormDataSet($requestData, $panel, $entity), $components, $this->componentRuleMapper ); }
php
public function createComponentsValidator(FormData $requestData, EntityFormPanel $panel, DCPackage $dc, Array $components = NULL) { $this->validationEntity = $entity = $panel->getEntityForm()->getEntity(); $components = isset($components) ? Code::castCollection($components) : $panel->getEntityForm()->getComponents(); return $this->componentsValidator = new ComponentsValidator($this->createFormDataSet($requestData, $panel, $entity), $components, $this->componentRuleMapper ); }
[ "public", "function", "createComponentsValidator", "(", "FormData", "$", "requestData", ",", "EntityFormPanel", "$", "panel", ",", "DCPackage", "$", "dc", ",", "Array", "$", "components", "=", "NULL", ")", "{", "$", "this", "->", "validationEntity", "=", "$", "entity", "=", "$", "panel", "->", "getEntityForm", "(", ")", "->", "getEntity", "(", ")", ";", "$", "components", "=", "isset", "(", "$", "components", ")", "?", "Code", "::", "castCollection", "(", "$", "components", ")", ":", "$", "panel", "->", "getEntityForm", "(", ")", "->", "getComponents", "(", ")", ";", "return", "$", "this", "->", "componentsValidator", "=", "new", "ComponentsValidator", "(", "$", "this", "->", "createFormDataSet", "(", "$", "requestData", ",", "$", "panel", ",", "$", "entity", ")", ",", "$", "components", ",", "$", "this", "->", "componentRuleMapper", ")", ";", "}" ]
Erstellt einen ComponentsValidator anhand des EntityFormPanels Der FormPanel muss die Componenten schon erstellt haben sie werden mit getComponents() aus dem Formular genommen
[ "Erstellt", "einen", "ComponentsValidator", "anhand", "des", "EntityFormPanels" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/ValidationPackage.php#L108-L118
webforge-labs/psc-cms
lib/Psc/Form/ValidationPackage.php
ValidationPackage.onPostValidation
public function onPostValidation(ComponentsValidator $validator, \Closure $do) { $entity = $this->validationEntity; $validator->addPostValidation( new \Psc\Code\Callback(function($componentsValidator, $validatedComponents) use ($entity, $do) { $do($entity, $componentsValidator, $validatedComponents); }) ); }
php
public function onPostValidation(ComponentsValidator $validator, \Closure $do) { $entity = $this->validationEntity; $validator->addPostValidation( new \Psc\Code\Callback(function($componentsValidator, $validatedComponents) use ($entity, $do) { $do($entity, $componentsValidator, $validatedComponents); }) ); }
[ "public", "function", "onPostValidation", "(", "ComponentsValidator", "$", "validator", ",", "\\", "Closure", "$", "do", ")", "{", "$", "entity", "=", "$", "this", "->", "validationEntity", ";", "$", "validator", "->", "addPostValidation", "(", "new", "\\", "Psc", "\\", "Code", "\\", "Callback", "(", "function", "(", "$", "componentsValidator", ",", "$", "validatedComponents", ")", "use", "(", "$", "entity", ",", "$", "do", ")", "{", "$", "do", "(", "$", "entity", ",", "$", "componentsValidator", ",", "$", "validatedComponents", ")", ";", "}", ")", ")", ";", "}" ]
dirty: und einmal genutzt in tiptoi GameController für Patch Workaround: todo: schöner bauen
[ "dirty", ":", "und", "einmal", "genutzt", "in", "tiptoi", "GameController", "für", "Patch", "Workaround", ":", "todo", ":", "schöner", "bauen" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/ValidationPackage.php#L121-L129
webforge-labs/psc-cms
lib/Psc/Form/ValidationPackage.php
ValidationPackage.createFormDataSet
public function createFormDataSet(FormData $requestData, EntityFormPanel $panel, Entity $entity) { $meta = $entity->getSetMeta(); // wir müssen die Spezial-Felder vom EntityFormPanel hier tracken foreach ($panel->getControlFields() as $field) { $meta->setFieldType($field, Type::create('String')); } // sonderfeld disabled wird ignored $meta->setFieldType('disabled', Type::create('Array')); try { $set = new Set((array) $requestData, $meta); } catch (\Psc\Data\FieldNotDefinedException $e) { throw \Psc\Exception::create("In den FormularDaten befindet sich ein Feld '%s', welches kein Feld aus Entity getSetMeta ist (%s).", implode('.',$e->field), implode(', ',$e->avaibleFields)); } return $set; }
php
public function createFormDataSet(FormData $requestData, EntityFormPanel $panel, Entity $entity) { $meta = $entity->getSetMeta(); // wir müssen die Spezial-Felder vom EntityFormPanel hier tracken foreach ($panel->getControlFields() as $field) { $meta->setFieldType($field, Type::create('String')); } // sonderfeld disabled wird ignored $meta->setFieldType('disabled', Type::create('Array')); try { $set = new Set((array) $requestData, $meta); } catch (\Psc\Data\FieldNotDefinedException $e) { throw \Psc\Exception::create("In den FormularDaten befindet sich ein Feld '%s', welches kein Feld aus Entity getSetMeta ist (%s).", implode('.',$e->field), implode(', ',$e->avaibleFields)); } return $set; }
[ "public", "function", "createFormDataSet", "(", "FormData", "$", "requestData", ",", "EntityFormPanel", "$", "panel", ",", "Entity", "$", "entity", ")", "{", "$", "meta", "=", "$", "entity", "->", "getSetMeta", "(", ")", ";", "// wir müssen die Spezial-Felder vom EntityFormPanel hier tracken", "foreach", "(", "$", "panel", "->", "getControlFields", "(", ")", "as", "$", "field", ")", "{", "$", "meta", "->", "setFieldType", "(", "$", "field", ",", "Type", "::", "create", "(", "'String'", ")", ")", ";", "}", "// sonderfeld disabled wird ignored", "$", "meta", "->", "setFieldType", "(", "'disabled'", ",", "Type", "::", "create", "(", "'Array'", ")", ")", ";", "try", "{", "$", "set", "=", "new", "Set", "(", "(", "array", ")", "$", "requestData", ",", "$", "meta", ")", ";", "}", "catch", "(", "\\", "Psc", "\\", "Data", "\\", "FieldNotDefinedException", "$", "e", ")", "{", "throw", "\\", "Psc", "\\", "Exception", "::", "create", "(", "\"In den FormularDaten befindet sich ein Feld '%s', welches kein Feld aus Entity getSetMeta ist (%s).\"", ",", "implode", "(", "'.'", ",", "$", "e", "->", "field", ")", ",", "implode", "(", "', '", ",", "$", "e", "->", "avaibleFields", ")", ")", ";", "}", "return", "$", "set", ";", "}" ]
Erstellt aus dem Request und dem FormPanel ein Set mit allen FormularDaten man könnte sich hier auch mal vorstellen die formulardaten im set aufzusplitten Sicherheit: alle Felder die nicht registriert sind durch Componenten oder den Formpanel (getControlFields) schmeissen hier eine Exception
[ "Erstellt", "aus", "dem", "Request", "und", "dem", "FormPanel", "ein", "Set", "mit", "allen", "FormularDaten" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/ValidationPackage.php#L137-L156
arsengoian/viper-framework
src/Viper/Daemon/Platforms/Linux.php
Linux.newProcess
function newProcess(int $sleep, string $phpAction, string $logfile, string $errlogfile) : string { $interpreter = PHP_BIN; return trim(shell_exec(" nohup bash -c \" while [ true ] do sleep $sleep; echo \\\" <?php $phpAction \\\" | $interpreter done \" > $logfile.shell 2> $errlogfile.shell & echo $! ")); }
php
function newProcess(int $sleep, string $phpAction, string $logfile, string $errlogfile) : string { $interpreter = PHP_BIN; return trim(shell_exec(" nohup bash -c \" while [ true ] do sleep $sleep; echo \\\" <?php $phpAction \\\" | $interpreter done \" > $logfile.shell 2> $errlogfile.shell & echo $! ")); }
[ "function", "newProcess", "(", "int", "$", "sleep", ",", "string", "$", "phpAction", ",", "string", "$", "logfile", ",", "string", "$", "errlogfile", ")", ":", "string", "{", "$", "interpreter", "=", "PHP_BIN", ";", "return", "trim", "(", "shell_exec", "(", "\"\n nohup bash -c \\\"\n while [ true ]\n do\n sleep $sleep;\n echo \\\\\\\" <?php\n $phpAction\n \\\\\\\" | $interpreter\n done\n \\\" > $logfile.shell 2> $errlogfile.shell & echo $!\n \"", ")", ")", ";", "}" ]
Add process @param int $sleep @param string $phpAction @param string $logfile @param string $errlogfile @return string Process ID
[ "Add", "process" ]
train
https://github.com/arsengoian/viper-framework/blob/22796c5cc219cae3ca0b4af370a347ba2acab0f2/src/Viper/Daemon/Platforms/Linux.php#L23-L37
aedart/laravel-helpers
src/Traits/Cache/CacheTrait.php
CacheTrait.getCache
public function getCache(): ?Repository { if (!$this->hasCache()) { $this->setCache($this->getDefaultCache()); } return $this->cache; }
php
public function getCache(): ?Repository { if (!$this->hasCache()) { $this->setCache($this->getDefaultCache()); } return $this->cache; }
[ "public", "function", "getCache", "(", ")", ":", "?", "Repository", "{", "if", "(", "!", "$", "this", "->", "hasCache", "(", ")", ")", "{", "$", "this", "->", "setCache", "(", "$", "this", "->", "getDefaultCache", "(", ")", ")", ";", "}", "return", "$", "this", "->", "cache", ";", "}" ]
Get cache If no cache has been set, this method will set and return a default cache, if any such value is available @see getDefaultCache() @return Repository|null cache or null if none cache has been set
[ "Get", "cache" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Cache/CacheTrait.php#L53-L59
aedart/laravel-helpers
src/Traits/Cache/CacheTrait.php
CacheTrait.getDefaultCache
public function getDefaultCache(): ?Repository { // By default, the Cache Facade does not return the // any actual cache repository, but rather an // instance of \Illuminate\Cache\CacheManager. // Therefore, we make sure only to obtain its // "store", to make sure that its only the cache repository // instance that we obtain. $manager = Cache::getFacadeRoot(); if (isset($manager)) { return $cache = $manager->store(); } return $manager; }
php
public function getDefaultCache(): ?Repository { // By default, the Cache Facade does not return the // any actual cache repository, but rather an // instance of \Illuminate\Cache\CacheManager. // Therefore, we make sure only to obtain its // "store", to make sure that its only the cache repository // instance that we obtain. $manager = Cache::getFacadeRoot(); if (isset($manager)) { return $cache = $manager->store(); } return $manager; }
[ "public", "function", "getDefaultCache", "(", ")", ":", "?", "Repository", "{", "// By default, the Cache Facade does not return the", "// any actual cache repository, but rather an", "// instance of \\Illuminate\\Cache\\CacheManager.", "// Therefore, we make sure only to obtain its", "// \"store\", to make sure that its only the cache repository", "// instance that we obtain.", "$", "manager", "=", "Cache", "::", "getFacadeRoot", "(", ")", ";", "if", "(", "isset", "(", "$", "manager", ")", ")", "{", "return", "$", "cache", "=", "$", "manager", "->", "store", "(", ")", ";", "}", "return", "$", "manager", ";", "}" ]
Get a default cache value, if any is available @return Repository|null A default cache value or Null if no default value is available
[ "Get", "a", "default", "cache", "value", "if", "any", "is", "available" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Cache/CacheTrait.php#L76-L89
aryelgois/yasql-php
src/Composer.php
Composer.build
public static function build(Event $event) { $args = $event->getArguments(); $config = null; $output = null; $vendors = []; foreach ($args as $arg) { $tokens = explode('=', $arg, 2); if (count($tokens) === 1 && $arg[0] !== '-') { throw new \InvalidArgumentException("Invalid argument '$arg'"); } switch ($tokens[0]) { case '-c': $tokens[1] = ''; case 'config': if ($config === null) { $config = $tokens[1]; } else { throw new \LogicException("Repeated 'config' argument"); } break; case 'output': if ($output === null) { $output = $tokens[1]; } else { throw new \LogicException("Repeated 'output' argument"); } break; case 'vendor': $vendors[] = $tokens[1]; break; default: $message = "Unknown argument '$tokens[0]' in '$arg'"; throw new \DomainException($message); break; } } if ($config === '' && count($vendors) === 0) { echo "Nothing to do.\n"; die(1); } Controller::build( $output ?? 'build/', $config ?? 'config/databases.yml', self::getVendorDir($event), $vendors ); }
php
public static function build(Event $event) { $args = $event->getArguments(); $config = null; $output = null; $vendors = []; foreach ($args as $arg) { $tokens = explode('=', $arg, 2); if (count($tokens) === 1 && $arg[0] !== '-') { throw new \InvalidArgumentException("Invalid argument '$arg'"); } switch ($tokens[0]) { case '-c': $tokens[1] = ''; case 'config': if ($config === null) { $config = $tokens[1]; } else { throw new \LogicException("Repeated 'config' argument"); } break; case 'output': if ($output === null) { $output = $tokens[1]; } else { throw new \LogicException("Repeated 'output' argument"); } break; case 'vendor': $vendors[] = $tokens[1]; break; default: $message = "Unknown argument '$tokens[0]' in '$arg'"; throw new \DomainException($message); break; } } if ($config === '' && count($vendors) === 0) { echo "Nothing to do.\n"; die(1); } Controller::build( $output ?? 'build/', $config ?? 'config/databases.yml', self::getVendorDir($event), $vendors ); }
[ "public", "static", "function", "build", "(", "Event", "$", "event", ")", "{", "$", "args", "=", "$", "event", "->", "getArguments", "(", ")", ";", "$", "config", "=", "null", ";", "$", "output", "=", "null", ";", "$", "vendors", "=", "[", "]", ";", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "$", "tokens", "=", "explode", "(", "'='", ",", "$", "arg", ",", "2", ")", ";", "if", "(", "count", "(", "$", "tokens", ")", "===", "1", "&&", "$", "arg", "[", "0", "]", "!==", "'-'", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid argument '$arg'\"", ")", ";", "}", "switch", "(", "$", "tokens", "[", "0", "]", ")", "{", "case", "'-c'", ":", "$", "tokens", "[", "1", "]", "=", "''", ";", "case", "'config'", ":", "if", "(", "$", "config", "===", "null", ")", "{", "$", "config", "=", "$", "tokens", "[", "1", "]", ";", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "\"Repeated 'config' argument\"", ")", ";", "}", "break", ";", "case", "'output'", ":", "if", "(", "$", "output", "===", "null", ")", "{", "$", "output", "=", "$", "tokens", "[", "1", "]", ";", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "\"Repeated 'output' argument\"", ")", ";", "}", "break", ";", "case", "'vendor'", ":", "$", "vendors", "[", "]", "=", "$", "tokens", "[", "1", "]", ";", "break", ";", "default", ":", "$", "message", "=", "\"Unknown argument '$tokens[0]' in '$arg'\"", ";", "throw", "new", "\\", "DomainException", "(", "$", "message", ")", ";", "break", ";", "}", "}", "if", "(", "$", "config", "===", "''", "&&", "count", "(", "$", "vendors", ")", "===", "0", ")", "{", "echo", "\"Nothing to do.\\n\"", ";", "die", "(", "1", ")", ";", "}", "Controller", "::", "build", "(", "$", "output", "??", "'build/'", ",", "$", "config", "??", "'config/databases.yml'", ",", "self", "::", "getVendorDir", "(", "$", "event", ")", ",", "$", "vendors", ")", ";", "}" ]
Builds database schemas into a directory Arguments: (any order) config=path/to/config_file.yml (default 'config/databases.yml') output=path/to/output/ (default 'build/') vendor=vendor/package (multiple allowed) @param Event $event Composer run-script event
[ "Builds", "database", "schemas", "into", "a", "directory" ]
train
https://github.com/aryelgois/yasql-php/blob/f428b180d35bfc1ddf1f9b3323f9b085fbc09ac7/src/Composer.php#L36-L89
aryelgois/yasql-php
src/Composer.php
Composer.generate
public static function generate(Event $event) { $args = $event->getArguments(); if (empty($args)) { echo "Usage:\n\n" . " composer yasql-generate -- YASQL_FILE [INDENTATION]\n\n" . "By default, INDENTATION is 2\n"; die(1); } echo Controller::generate( file_get_contents($args[0]), null, $args[1] ?? 2 ); }
php
public static function generate(Event $event) { $args = $event->getArguments(); if (empty($args)) { echo "Usage:\n\n" . " composer yasql-generate -- YASQL_FILE [INDENTATION]\n\n" . "By default, INDENTATION is 2\n"; die(1); } echo Controller::generate( file_get_contents($args[0]), null, $args[1] ?? 2 ); }
[ "public", "static", "function", "generate", "(", "Event", "$", "event", ")", "{", "$", "args", "=", "$", "event", "->", "getArguments", "(", ")", ";", "if", "(", "empty", "(", "$", "args", ")", ")", "{", "echo", "\"Usage:\\n\\n\"", ".", "\" composer yasql-generate -- YASQL_FILE [INDENTATION]\\n\\n\"", ".", "\"By default, INDENTATION is 2\\n\"", ";", "die", "(", "1", ")", ";", "}", "echo", "Controller", "::", "generate", "(", "file_get_contents", "(", "$", "args", "[", "0", "]", ")", ",", "null", ",", "$", "args", "[", "1", "]", "??", "2", ")", ";", "}" ]
Generates the SQL from a YASQL file Arguments: string $1 Path to YASQL file int $2 How many spaces per indentation level @param Event $event Composer run-script event
[ "Generates", "the", "SQL", "from", "a", "YASQL", "file" ]
train
https://github.com/aryelgois/yasql-php/blob/f428b180d35bfc1ddf1f9b3323f9b085fbc09ac7/src/Composer.php#L101-L116
askupasoftware/amarkal
UI/Components/Composite/controller.php
Composite.get_default_value
public function get_default_value() { $default = $this->template; foreach( $this->components as $component ) { $name = $component->get_name(); $default = str_replace("<% $name %>", $component->get_default_value(), $default); } return $default; }
php
public function get_default_value() { $default = $this->template; foreach( $this->components as $component ) { $name = $component->get_name(); $default = str_replace("<% $name %>", $component->get_default_value(), $default); } return $default; }
[ "public", "function", "get_default_value", "(", ")", "{", "$", "default", "=", "$", "this", "->", "template", ";", "foreach", "(", "$", "this", "->", "components", "as", "$", "component", ")", "{", "$", "name", "=", "$", "component", "->", "get_name", "(", ")", ";", "$", "default", "=", "str_replace", "(", "\"<% $name %>\"", ",", "$", "component", "->", "get_default_value", "(", ")", ",", "$", "default", ")", ";", "}", "return", "$", "default", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/askupasoftware/amarkal/blob/fe8283e2d6847ef697abec832da7ee741a85058c/UI/Components/Composite/controller.php#L95-L104