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
Eresus/EresusCMS
src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/ZendFramework/View.php
Dwoo_Adapters_ZendFramework_View.assign
public function assign($name, $val = null) { $this->getDataProvider()->assign($name, $val); return $this; }
php
public function assign($name, $val = null) { $this->getDataProvider()->assign($name, $val); return $this; }
[ "public", "function", "assign", "(", "$", "name", ",", "$", "val", "=", "null", ")", "{", "$", "this", "->", "getDataProvider", "(", ")", "->", "assign", "(", "$", "name", ",", "$", "val", ")", ";", "return", "$", "this", ";", "}" ]
Passes data to Dwoo_Data object @see Dwoo_Data::assign() @param array|string $name @param mixed $val @return Dwoo_Adapters_ZendFramework_View
[ "Passes", "data", "to", "Dwoo_Data", "object" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/ZendFramework/View.php#L392-L396
Eresus/EresusCMS
src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/ZendFramework/View.php
Dwoo_Adapters_ZendFramework_View._run
public function _run() { echo $this->_engine->get( $this->getTemplateFile(func_get_arg(0)), $this->getDataProvider(), $this->getCompiler() ); }
php
public function _run() { echo $this->_engine->get( $this->getTemplateFile(func_get_arg(0)), $this->getDataProvider(), $this->getCompiler() ); }
[ "public", "function", "_run", "(", ")", "{", "echo", "$", "this", "->", "_engine", "->", "get", "(", "$", "this", "->", "getTemplateFile", "(", "func_get_arg", "(", "0", ")", ")", ",", "$", "this", "->", "getDataProvider", "(", ")", ",", "$", "this", "->", "getCompiler", "(", ")", ")", ";", "}" ]
Processes a view script and outputs it. Output is then passed through filters. @param string $name The script script name to process. @return string The script output.
[ "Processes", "a", "view", "script", "and", "outputs", "it", ".", "Output", "is", "then", "passed", "through", "filters", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/ZendFramework/View.php#L444-L451
surebert/surebert-framework
src/sb/FTP/Client.php
Client.login
public function login($uname, $pass, $passive = false) { if (!ftp_login($this->connection, $uname, $pass)) { throw new \Exception("Could not authenticate with credentials given."); } if ($passive) { \ftp_pasv($this->connection, true); } return true; }
php
public function login($uname, $pass, $passive = false) { if (!ftp_login($this->connection, $uname, $pass)) { throw new \Exception("Could not authenticate with credentials given."); } if ($passive) { \ftp_pasv($this->connection, true); } return true; }
[ "public", "function", "login", "(", "$", "uname", ",", "$", "pass", ",", "$", "passive", "=", "false", ")", "{", "if", "(", "!", "ftp_login", "(", "$", "this", "->", "connection", ",", "$", "uname", ",", "$", "pass", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not authenticate with credentials given.\"", ")", ";", "}", "if", "(", "$", "passive", ")", "{", "\\", "ftp_pasv", "(", "$", "this", "->", "connection", ",", "true", ")", ";", "}", "return", "true", ";", "}" ]
Login to a remote server with uname and pass based credentials @param string $uname The user name to login with @param string $pass The password to login with
[ "Login", "to", "a", "remote", "server", "with", "uname", "and", "pass", "based", "credentials" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L37-L48
surebert/surebert-framework
src/sb/FTP/Client.php
Client.get
public function get($remote_file, $local_file, $mode = null) { $mode = $mode ? $mode : FTP_ASCII; if (!@ftp_get($this->connection, $local_file, $remote_file, $mode)) { throw new \Exception("Could not get remote file:" . $remote_file); } return true; }
php
public function get($remote_file, $local_file, $mode = null) { $mode = $mode ? $mode : FTP_ASCII; if (!@ftp_get($this->connection, $local_file, $remote_file, $mode)) { throw new \Exception("Could not get remote file:" . $remote_file); } return true; }
[ "public", "function", "get", "(", "$", "remote_file", ",", "$", "local_file", ",", "$", "mode", "=", "null", ")", "{", "$", "mode", "=", "$", "mode", "?", "$", "mode", ":", "FTP_ASCII", ";", "if", "(", "!", "@", "ftp_get", "(", "$", "this", "->", "connection", ",", "$", "local_file", ",", "$", "remote_file", ",", "$", "mode", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not get remote file:\"", ".", "$", "remote_file", ")", ";", "}", "return", "true", ";", "}" ]
Get a file from the remote machine @param string $remote_file The path to the remote file to read @param string $local_file The path to the local file to write @param const $mode FTP_ASCII or FTP_BINARY default FTP_ASCII
[ "Get", "a", "file", "from", "the", "remote", "machine" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L57-L65
surebert/surebert-framework
src/sb/FTP/Client.php
Client.put
public function put($local_file, $remote_file, $mode = null) { $mode = $mode ? $mode : FTP_ASCII; if (!@ftp_put($this->connection, $remote_file, $local_file, $mode)) { throw new \Exception("Could not authenticate with credentials given."); } return true; }
php
public function put($local_file, $remote_file, $mode = null) { $mode = $mode ? $mode : FTP_ASCII; if (!@ftp_put($this->connection, $remote_file, $local_file, $mode)) { throw new \Exception("Could not authenticate with credentials given."); } return true; }
[ "public", "function", "put", "(", "$", "local_file", ",", "$", "remote_file", ",", "$", "mode", "=", "null", ")", "{", "$", "mode", "=", "$", "mode", "?", "$", "mode", ":", "FTP_ASCII", ";", "if", "(", "!", "@", "ftp_put", "(", "$", "this", "->", "connection", ",", "$", "remote_file", ",", "$", "local_file", ",", "$", "mode", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not authenticate with credentials given.\"", ")", ";", "}", "return", "true", ";", "}" ]
Put a file on the remote machine @param string $local_file The path to the local file to read @param string $remote_file The path to the remote file to write @param const $mode FTP_ASCII or FTP_BINARY default FTP_ASCII
[ "Put", "a", "file", "on", "the", "remote", "machine" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L73-L81
surebert/surebert-framework
src/sb/FTP/Client.php
Client.size
public function size($remote_file) { $size = @ftp_size($this->connection, $remote_file); if ($size && $size != -1) { return $size; } else { throw new \Exception("Could not get remote file size: " . $path); } }
php
public function size($remote_file) { $size = @ftp_size($this->connection, $remote_file); if ($size && $size != -1) { return $size; } else { throw new \Exception("Could not get remote file size: " . $path); } }
[ "public", "function", "size", "(", "$", "remote_file", ")", "{", "$", "size", "=", "@", "ftp_size", "(", "$", "this", "->", "connection", ",", "$", "remote_file", ")", ";", "if", "(", "$", "size", "&&", "$", "size", "!=", "-", "1", ")", "{", "return", "$", "size", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "\"Could not get remote file size: \"", ".", "$", "path", ")", ";", "}", "}" ]
Gets the size of a remote file @param string $remote_file path to remote file @return integer The size of the file in bytes
[ "Gets", "the", "size", "of", "a", "remote", "file" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L127-L135
surebert/surebert-framework
src/sb/FTP/Client.php
Client.chmod
public function chmod($remote_file, $mode) { $mode = octdec(str_pad($mode, 4, '0', STR_PAD_LEFT)); $mode = (int) $mode; if (!@ftp_chmod($this->connection, $mode, $remote_file) !== false) { throw new \Exception("Could not change remote file to mode: " . $mode); } return true; }
php
public function chmod($remote_file, $mode) { $mode = octdec(str_pad($mode, 4, '0', STR_PAD_LEFT)); $mode = (int) $mode; if (!@ftp_chmod($this->connection, $mode, $remote_file) !== false) { throw new \Exception("Could not change remote file to mode: " . $mode); } return true; }
[ "public", "function", "chmod", "(", "$", "remote_file", ",", "$", "mode", ")", "{", "$", "mode", "=", "octdec", "(", "str_pad", "(", "$", "mode", ",", "4", ",", "'0'", ",", "STR_PAD_LEFT", ")", ")", ";", "$", "mode", "=", "(", "int", ")", "$", "mode", ";", "if", "(", "!", "@", "ftp_chmod", "(", "$", "this", "->", "connection", ",", "$", "mode", ",", "$", "remote_file", ")", "!==", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not change remote file to mode: \"", ".", "$", "mode", ")", ";", "}", "return", "true", ";", "}" ]
Change the file mode of a remote file @param string $remote_file The path to the remote file @param integer $mode The file mode e.g. 0644, 0777 @return boolean
[ "Change", "the", "file", "mode", "of", "a", "remote", "file" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L143-L153
surebert/surebert-framework
src/sb/FTP/Client.php
Client.nlist
public function nlist($directory) { $list = ftp_nlist($this->connection, $directory); if (!$list) { throw new \Exception("Could list files in remote directory: " . $directory); } return $list; }
php
public function nlist($directory) { $list = ftp_nlist($this->connection, $directory); if (!$list) { throw new \Exception("Could list files in remote directory: " . $directory); } return $list; }
[ "public", "function", "nlist", "(", "$", "directory", ")", "{", "$", "list", "=", "ftp_nlist", "(", "$", "this", "->", "connection", ",", "$", "directory", ")", ";", "if", "(", "!", "$", "list", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could list files in remote directory: \"", ".", "$", "directory", ")", ";", "}", "return", "$", "list", ";", "}" ]
List files in remote directory @param string $directory The path @return array
[ "List", "files", "in", "remote", "directory" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L174-L182
surebert/surebert-framework
src/sb/FTP/Client.php
Client.rawlist
public function rawlist($directory) { $list = ftp_rawlist($this->connection, $directory); if (!$list) { throw new \Exception("Could raw list files in remote directory: " . $directory); } return $list; }
php
public function rawlist($directory) { $list = ftp_rawlist($this->connection, $directory); if (!$list) { throw new \Exception("Could raw list files in remote directory: " . $directory); } return $list; }
[ "public", "function", "rawlist", "(", "$", "directory", ")", "{", "$", "list", "=", "ftp_rawlist", "(", "$", "this", "->", "connection", ",", "$", "directory", ")", ";", "if", "(", "!", "$", "list", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could raw list files in remote directory: \"", ".", "$", "directory", ")", ";", "}", "return", "$", "list", ";", "}" ]
List files in remote directory @param string $directory The path @return array
[ "List", "files", "in", "remote", "directory" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/FTP/Client.php#L189-L197
webdevvie/pheanstalk-task-queue-bundle
Command/StopWorkerTenderCommand.php
StopWorkerTenderCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $processes = $this->findWorkerTenderProcessesForTube($this->tube); if (count($processes) == 0) { $output->writeln("<info>Found no processes</info>"); return; } $output->writeln('<info>Found ' . count($processes) . ' process(es)'); foreach ($processes as $process) { $output->writeln('<info>sending kill to:</info> ' . $process); exec("kill $process"); } $output->write('<info>Waiting on processes to stop</info> '); while (count($processes) > 0) { $processes = $this->findWorkerTenderProcessesForTube($this->tube); $output->write("."); sleep(1); } $output->writeln("Done!"); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $processes = $this->findWorkerTenderProcessesForTube($this->tube); if (count($processes) == 0) { $output->writeln("<info>Found no processes</info>"); return; } $output->writeln('<info>Found ' . count($processes) . ' process(es)'); foreach ($processes as $process) { $output->writeln('<info>sending kill to:</info> ' . $process); exec("kill $process"); } $output->write('<info>Waiting on processes to stop</info> '); while (count($processes) > 0) { $processes = $this->findWorkerTenderProcessesForTube($this->tube); $output->write("."); sleep(1); } $output->writeln("Done!"); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "initialiseWorker", "(", "$", "input", ",", "$", "output", ")", ";", "$", "processes", "=", "$", "this", "->", "findWorkerTenderProcessesForTube", "(", "$", "this", "->", "tube", ")", ";", "if", "(", "count", "(", "$", "processes", ")", "==", "0", ")", "{", "$", "output", "->", "writeln", "(", "\"<info>Found no processes</info>\"", ")", ";", "return", ";", "}", "$", "output", "->", "writeln", "(", "'<info>Found '", ".", "count", "(", "$", "processes", ")", ".", "' process(es)'", ")", ";", "foreach", "(", "$", "processes", "as", "$", "process", ")", "{", "$", "output", "->", "writeln", "(", "'<info>sending kill to:</info> '", ".", "$", "process", ")", ";", "exec", "(", "\"kill $process\"", ")", ";", "}", "$", "output", "->", "write", "(", "'<info>Waiting on processes to stop</info> '", ")", ";", "while", "(", "count", "(", "$", "processes", ")", ">", "0", ")", "{", "$", "processes", "=", "$", "this", "->", "findWorkerTenderProcessesForTube", "(", "$", "this", "->", "tube", ")", ";", "$", "output", "->", "write", "(", "\".\"", ")", ";", "sleep", "(", "1", ")", ";", "}", "$", "output", "->", "writeln", "(", "\"Done!\"", ")", ";", "}" ]
{@inheritDoc} @param InputInterface $input @param OutputInterface $output @return void @throws \InvalidArgumentException
[ "{", "@inheritDoc", "}" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/StopWorkerTenderCommand.php#L40-L61
webdevvie/pheanstalk-task-queue-bundle
Command/StopWorkerTenderCommand.php
StopWorkerTenderCommand.findWorkerTenderProcessesForTube
private function findWorkerTenderProcessesForTube($tube) { $processes = array(); $command = "ps ax "; $command .= "|grep php "; $command .= "|grep -v stop "; $command .= "|grep worker-tender "; if ($tube !== '') { $command .= "|grep " . escapeshellarg('use-tube=' . $tube); } $data = exec($command); $lines = explode("\n", $data); foreach ($lines as $line) { $line = trim($line); $parts = explode(" ", $line); if ($parts[0] === '') { continue; } $processes[] = intval($parts[0]); } return $processes; }
php
private function findWorkerTenderProcessesForTube($tube) { $processes = array(); $command = "ps ax "; $command .= "|grep php "; $command .= "|grep -v stop "; $command .= "|grep worker-tender "; if ($tube !== '') { $command .= "|grep " . escapeshellarg('use-tube=' . $tube); } $data = exec($command); $lines = explode("\n", $data); foreach ($lines as $line) { $line = trim($line); $parts = explode(" ", $line); if ($parts[0] === '') { continue; } $processes[] = intval($parts[0]); } return $processes; }
[ "private", "function", "findWorkerTenderProcessesForTube", "(", "$", "tube", ")", "{", "$", "processes", "=", "array", "(", ")", ";", "$", "command", "=", "\"ps ax \"", ";", "$", "command", ".=", "\"|grep php \"", ";", "$", "command", ".=", "\"|grep -v stop \"", ";", "$", "command", ".=", "\"|grep worker-tender \"", ";", "if", "(", "$", "tube", "!==", "''", ")", "{", "$", "command", ".=", "\"|grep \"", ".", "escapeshellarg", "(", "'use-tube='", ".", "$", "tube", ")", ";", "}", "$", "data", "=", "exec", "(", "$", "command", ")", ";", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "data", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "line", "=", "trim", "(", "$", "line", ")", ";", "$", "parts", "=", "explode", "(", "\" \"", ",", "$", "line", ")", ";", "if", "(", "$", "parts", "[", "0", "]", "===", "''", ")", "{", "continue", ";", "}", "$", "processes", "[", "]", "=", "intval", "(", "$", "parts", "[", "0", "]", ")", ";", "}", "return", "$", "processes", ";", "}" ]
Returns a list of processes that match the worker-tender @param string $tube @return array
[ "Returns", "a", "list", "of", "processes", "that", "match", "the", "worker", "-", "tender" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/StopWorkerTenderCommand.php#L69-L92
expectation-php/expect
src/factory/DefaultMatcherFactory.php
DefaultMatcherFactory.create
public function create($name, array $arguments = []) { $matcherClass = $this->container->get($name); if (count($arguments) <= 1) { $matcher = $matcherClass->newInstance($arguments); } else { $matcher = $matcherClass->newInstance([$arguments]); } return $matcher; }
php
public function create($name, array $arguments = []) { $matcherClass = $this->container->get($name); if (count($arguments) <= 1) { $matcher = $matcherClass->newInstance($arguments); } else { $matcher = $matcherClass->newInstance([$arguments]); } return $matcher; }
[ "public", "function", "create", "(", "$", "name", ",", "array", "$", "arguments", "=", "[", "]", ")", "{", "$", "matcherClass", "=", "$", "this", "->", "container", "->", "get", "(", "$", "name", ")", ";", "if", "(", "count", "(", "$", "arguments", ")", "<=", "1", ")", "{", "$", "matcher", "=", "$", "matcherClass", "->", "newInstance", "(", "$", "arguments", ")", ";", "}", "else", "{", "$", "matcher", "=", "$", "matcherClass", "->", "newInstance", "(", "[", "$", "arguments", "]", ")", ";", "}", "return", "$", "matcher", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/factory/DefaultMatcherFactory.php#L51-L62
sciactive/nymph-server
src/REST.php
REST.run
public function run($method, $action, $data) { $method = strtoupper($method); if (is_callable([$this, $method])) { return $this->$method($action, $data); } return $this->httpError(405, 'Method Not Allowed'); }
php
public function run($method, $action, $data) { $method = strtoupper($method); if (is_callable([$this, $method])) { return $this->$method($action, $data); } return $this->httpError(405, 'Method Not Allowed'); }
[ "public", "function", "run", "(", "$", "method", ",", "$", "action", ",", "$", "data", ")", "{", "$", "method", "=", "strtoupper", "(", "$", "method", ")", ";", "if", "(", "is_callable", "(", "[", "$", "this", ",", "$", "method", "]", ")", ")", "{", "return", "$", "this", "->", "$", "method", "(", "$", "action", ",", "$", "data", ")", ";", "}", "return", "$", "this", "->", "httpError", "(", "405", ",", "'Method Not Allowed'", ")", ";", "}" ]
Run the Nymph REST server process. Note that on failure, an HTTP error status code will be sent, usually along with a message body. @param string $method The HTTP method. @param string $action The Nymph action. @param string $data The JSON encoded data. @return bool True on success, false on failure.
[ "Run", "the", "Nymph", "REST", "server", "process", "." ]
train
https://github.com/sciactive/nymph-server/blob/3c18dbf45c2750d07c798e14534dba87387beeba/src/REST.php#L26-L32
sciactive/nymph-server
src/REST.php
REST.translateSelector
public static function translateSelector($className, $selector) { $restricted = []; if (isset($className::$searchRestrictedData)) { $restricted = $className::$searchRestrictedData; } // Filter clauses that are restricted for frontend searches. $filterClauses = function ($clause, $value) use ($restricted) { $unrestrictedClauses = ['guid', 'tag']; $scalarClauses = ['isset']; if (empty($restricted) || in_array($clause, $unrestrictedClauses)) { return $value; } if (in_array($clause, $scalarClauses)) { // Each entry is a property name. if (is_array($value)) { return array_values(array_diff($value, $restricted)); } else { return in_array($value, $restricted) ? null : $value; } } else { // Each entry is an array of property name, value. if (is_array($value[0])) { return array_values( array_filter( $value, function ($arr) use ($restricted) { return !in_array($arr[0], $restricted); } ) ); } else { return in_array($value[0], $restricted) ? null : $value; } } }; $newSel = []; foreach ($selector as $key => $val) { if ($key === 'type' || $key === 0) { $tmpArg = [$val]; $newSel = array_merge($tmpArg, $newSel); } elseif (is_numeric($key)) { if (isset($val['type']) || ( isset($val[0]) && in_array($val[0], ['&', '!&', '|', '!|']) )) { $tmpSel = self::translateSelector($className, $val); if ($tmpSel === false) { return false; } $newSel[] = $tmpSel; } else { foreach ($val as $k2 => $v2) { if (key_exists($k2, $newSel)) { return false; } $value = $filterClauses($k2, $v2); if (!empty($value)) { $newSel[$k2] = $value; } } } } else { $value = $filterClauses($key, $val); if (!empty($value)) { $newSel[$key] = $value; } } } if (!isset($newSel[0]) || !in_array($newSel[0], ['&', '!&', '|', '!|'])) { return false; } return $newSel; }
php
public static function translateSelector($className, $selector) { $restricted = []; if (isset($className::$searchRestrictedData)) { $restricted = $className::$searchRestrictedData; } // Filter clauses that are restricted for frontend searches. $filterClauses = function ($clause, $value) use ($restricted) { $unrestrictedClauses = ['guid', 'tag']; $scalarClauses = ['isset']; if (empty($restricted) || in_array($clause, $unrestrictedClauses)) { return $value; } if (in_array($clause, $scalarClauses)) { // Each entry is a property name. if (is_array($value)) { return array_values(array_diff($value, $restricted)); } else { return in_array($value, $restricted) ? null : $value; } } else { // Each entry is an array of property name, value. if (is_array($value[0])) { return array_values( array_filter( $value, function ($arr) use ($restricted) { return !in_array($arr[0], $restricted); } ) ); } else { return in_array($value[0], $restricted) ? null : $value; } } }; $newSel = []; foreach ($selector as $key => $val) { if ($key === 'type' || $key === 0) { $tmpArg = [$val]; $newSel = array_merge($tmpArg, $newSel); } elseif (is_numeric($key)) { if (isset($val['type']) || ( isset($val[0]) && in_array($val[0], ['&', '!&', '|', '!|']) )) { $tmpSel = self::translateSelector($className, $val); if ($tmpSel === false) { return false; } $newSel[] = $tmpSel; } else { foreach ($val as $k2 => $v2) { if (key_exists($k2, $newSel)) { return false; } $value = $filterClauses($k2, $v2); if (!empty($value)) { $newSel[$k2] = $value; } } } } else { $value = $filterClauses($key, $val); if (!empty($value)) { $newSel[$key] = $value; } } } if (!isset($newSel[0]) || !in_array($newSel[0], ['&', '!&', '|', '!|'])) { return false; } return $newSel; }
[ "public", "static", "function", "translateSelector", "(", "$", "className", ",", "$", "selector", ")", "{", "$", "restricted", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "className", "::", "$", "searchRestrictedData", ")", ")", "{", "$", "restricted", "=", "$", "className", "::", "$", "searchRestrictedData", ";", "}", "// Filter clauses that are restricted for frontend searches.", "$", "filterClauses", "=", "function", "(", "$", "clause", ",", "$", "value", ")", "use", "(", "$", "restricted", ")", "{", "$", "unrestrictedClauses", "=", "[", "'guid'", ",", "'tag'", "]", ";", "$", "scalarClauses", "=", "[", "'isset'", "]", ";", "if", "(", "empty", "(", "$", "restricted", ")", "||", "in_array", "(", "$", "clause", ",", "$", "unrestrictedClauses", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "in_array", "(", "$", "clause", ",", "$", "scalarClauses", ")", ")", "{", "// Each entry is a property name.", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "array_values", "(", "array_diff", "(", "$", "value", ",", "$", "restricted", ")", ")", ";", "}", "else", "{", "return", "in_array", "(", "$", "value", ",", "$", "restricted", ")", "?", "null", ":", "$", "value", ";", "}", "}", "else", "{", "// Each entry is an array of property name, value.", "if", "(", "is_array", "(", "$", "value", "[", "0", "]", ")", ")", "{", "return", "array_values", "(", "array_filter", "(", "$", "value", ",", "function", "(", "$", "arr", ")", "use", "(", "$", "restricted", ")", "{", "return", "!", "in_array", "(", "$", "arr", "[", "0", "]", ",", "$", "restricted", ")", ";", "}", ")", ")", ";", "}", "else", "{", "return", "in_array", "(", "$", "value", "[", "0", "]", ",", "$", "restricted", ")", "?", "null", ":", "$", "value", ";", "}", "}", "}", ";", "$", "newSel", "=", "[", "]", ";", "foreach", "(", "$", "selector", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "$", "key", "===", "'type'", "||", "$", "key", "===", "0", ")", "{", "$", "tmpArg", "=", "[", "$", "val", "]", ";", "$", "newSel", "=", "array_merge", "(", "$", "tmpArg", ",", "$", "newSel", ")", ";", "}", "elseif", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "if", "(", "isset", "(", "$", "val", "[", "'type'", "]", ")", "||", "(", "isset", "(", "$", "val", "[", "0", "]", ")", "&&", "in_array", "(", "$", "val", "[", "0", "]", ",", "[", "'&'", ",", "'!&'", ",", "'|'", ",", "'!|'", "]", ")", ")", ")", "{", "$", "tmpSel", "=", "self", "::", "translateSelector", "(", "$", "className", ",", "$", "val", ")", ";", "if", "(", "$", "tmpSel", "===", "false", ")", "{", "return", "false", ";", "}", "$", "newSel", "[", "]", "=", "$", "tmpSel", ";", "}", "else", "{", "foreach", "(", "$", "val", "as", "$", "k2", "=>", "$", "v2", ")", "{", "if", "(", "key_exists", "(", "$", "k2", ",", "$", "newSel", ")", ")", "{", "return", "false", ";", "}", "$", "value", "=", "$", "filterClauses", "(", "$", "k2", ",", "$", "v2", ")", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "newSel", "[", "$", "k2", "]", "=", "$", "value", ";", "}", "}", "}", "}", "else", "{", "$", "value", "=", "$", "filterClauses", "(", "$", "key", ",", "$", "val", ")", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "newSel", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "if", "(", "!", "isset", "(", "$", "newSel", "[", "0", "]", ")", "||", "!", "in_array", "(", "$", "newSel", "[", "0", "]", ",", "[", "'&'", ",", "'!&'", ",", "'|'", ",", "'!|'", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "newSel", ";", "}" ]
Translate - JS {"type": "&", "crit": "val", "1": {"type": "&", ...}, ...} - JS ["&", {"crit": "val"}, ["&", ...], ...] to PHP ["&", "crit" => "val", ["&", ...], ...] Also filter out clauses that use restricted properties.
[ "Translate", "-", "JS", "{", "type", ":", "&", "crit", ":", "val", "1", ":", "{", "type", ":", "&", "...", "}", "...", "}", "-", "JS", "[", "&", "{", "crit", ":", "val", "}", "[", "&", "...", "]", "...", "]", "to", "PHP", "[", "&", "crit", "=", ">", "val", "[", "&", "...", "]", "...", "]" ]
train
https://github.com/sciactive/nymph-server/blob/3c18dbf45c2750d07c798e14534dba87387beeba/src/REST.php#L337-L410
sciactive/nymph-server
src/REST.php
REST.httpError
protected function httpError($errorCode, $message, $exception = null) { header("HTTP/1.1 $errorCode $message", true, $errorCode); if ($exception) { echo json_encode([ 'textStatus' => "$errorCode $message", 'exception' => get_class($exception), 'code' => $exception->getCode(), 'message' => $exception->getMessage() ]); } else { echo json_encode(['textStatus' => "$errorCode $message"]); } return false; }
php
protected function httpError($errorCode, $message, $exception = null) { header("HTTP/1.1 $errorCode $message", true, $errorCode); if ($exception) { echo json_encode([ 'textStatus' => "$errorCode $message", 'exception' => get_class($exception), 'code' => $exception->getCode(), 'message' => $exception->getMessage() ]); } else { echo json_encode(['textStatus' => "$errorCode $message"]); } return false; }
[ "protected", "function", "httpError", "(", "$", "errorCode", ",", "$", "message", ",", "$", "exception", "=", "null", ")", "{", "header", "(", "\"HTTP/1.1 $errorCode $message\"", ",", "true", ",", "$", "errorCode", ")", ";", "if", "(", "$", "exception", ")", "{", "echo", "json_encode", "(", "[", "'textStatus'", "=>", "\"$errorCode $message\"", ",", "'exception'", "=>", "get_class", "(", "$", "exception", ")", ",", "'code'", "=>", "$", "exception", "->", "getCode", "(", ")", ",", "'message'", "=>", "$", "exception", "->", "getMessage", "(", ")", "]", ")", ";", "}", "else", "{", "echo", "json_encode", "(", "[", "'textStatus'", "=>", "\"$errorCode $message\"", "]", ")", ";", "}", "return", "false", ";", "}" ]
Return the request with an HTTP error response. @param int $errorCode The HTTP status code. @param string $message The message to place on the HTTP status header line. @param Exception $exception An optional exception object to report. @return boolean Always returns false. @access protected
[ "Return", "the", "request", "with", "an", "HTTP", "error", "response", "." ]
train
https://github.com/sciactive/nymph-server/blob/3c18dbf45c2750d07c798e14534dba87387beeba/src/REST.php#L457-L470
sciactive/nymph-server
src/REST.php
REST.referenceToEntity
private function referenceToEntity(&$item, $key) { if (is_array($item)) { if (isset($item[0]) && $item[0] === 'nymph_entity_reference') { $item = call_user_func([$item[2], 'factoryReference'], $item); } else { array_walk($item, [$this, 'referenceToEntity']); } } elseif (is_object($item) && !( ( is_a($item, '\Nymph\Entity') || is_a($item, '\SciActive\HookOverride') ) && is_callable([$item, 'toReference']) )) { // Only do this for non-entity objects. foreach ($item as &$curProperty) { $this->referenceToEntity($curProperty, null); } unset($curProperty); } }
php
private function referenceToEntity(&$item, $key) { if (is_array($item)) { if (isset($item[0]) && $item[0] === 'nymph_entity_reference') { $item = call_user_func([$item[2], 'factoryReference'], $item); } else { array_walk($item, [$this, 'referenceToEntity']); } } elseif (is_object($item) && !( ( is_a($item, '\Nymph\Entity') || is_a($item, '\SciActive\HookOverride') ) && is_callable([$item, 'toReference']) )) { // Only do this for non-entity objects. foreach ($item as &$curProperty) { $this->referenceToEntity($curProperty, null); } unset($curProperty); } }
[ "private", "function", "referenceToEntity", "(", "&", "$", "item", ",", "$", "key", ")", "{", "if", "(", "is_array", "(", "$", "item", ")", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "0", "]", ")", "&&", "$", "item", "[", "0", "]", "===", "'nymph_entity_reference'", ")", "{", "$", "item", "=", "call_user_func", "(", "[", "$", "item", "[", "2", "]", ",", "'factoryReference'", "]", ",", "$", "item", ")", ";", "}", "else", "{", "array_walk", "(", "$", "item", ",", "[", "$", "this", ",", "'referenceToEntity'", "]", ")", ";", "}", "}", "elseif", "(", "is_object", "(", "$", "item", ")", "&&", "!", "(", "(", "is_a", "(", "$", "item", ",", "'\\Nymph\\Entity'", ")", "||", "is_a", "(", "$", "item", ",", "'\\SciActive\\HookOverride'", ")", ")", "&&", "is_callable", "(", "[", "$", "item", ",", "'toReference'", "]", ")", ")", ")", "{", "// Only do this for non-entity objects.", "foreach", "(", "$", "item", "as", "&", "$", "curProperty", ")", "{", "$", "this", "->", "referenceToEntity", "(", "$", "curProperty", ",", "null", ")", ";", "}", "unset", "(", "$", "curProperty", ")", ";", "}", "}" ]
Check if an item is a reference, and if it is, convert it to an entity. This function will recurse into deeper arrays. @param mixed &$item The item to check. @param mixed $key Unused. @access private
[ "Check", "if", "an", "item", "is", "a", "reference", "and", "if", "it", "is", "convert", "it", "to", "an", "entity", "." ]
train
https://github.com/sciactive/nymph-server/blob/3c18dbf45c2750d07c798e14534dba87387beeba/src/REST.php#L481-L502
frodeborli/fubber-reactor
src/Host.php
Host.listen
public function listen($request, $response) { // $this->debug('Host::listen: path='.$request->getPath().'?'.http_build_query($request->getQuery())); $this->hits++; $path = '/'.ltrim($request->getPath(), '/'); $endpoint = NULL; if(isset($this->routes[$path])) { // Direct lookup $endpoint = $this->routes[$path]; } else { $endpointKey = NULL; if(isset($this->lookupCache[$path])) { $endpointKey = $this->lookupCache[$path]; // The item was found in the lookupCache, so we move it back to the end of the array (to avoid unshifting it too soon) - LRU algorithm if($this->lookupCacheCount == 1000) { unset($this->lookupCache[$path]); $this->lookupCache[$path] = $endpointKey; } $endpoint = $this->searchRoutes[$endpointKey][1]; } else { foreach($this->searchRoutes as $key => $route) { if(fnmatch($route[0], $path)) { $endpointKey = $key; break; } } if($endpointKey !== NULL) { // LRU algorithm $this->lookupCache[$path] = $endpointKey; // Added to the end of the array $this->lookupCacheCount++; while($this->lookupCacheCount-- > 1000) array_shift($this->lookupCache); // Remove something from the beginning of the array $endpoint = $this->searchRoutes[$endpointKey][1]; } } } if($endpoint) { // We identified an endpoint return $endpoint->listen($request, $response); } else { // We failed to find an endpoint, so we redirect to /errors/404 // This is not cached, because we don't want anybody to be able to fill the lookupCache with garbage return $this->respondError(404, $request, $response); } }
php
public function listen($request, $response) { // $this->debug('Host::listen: path='.$request->getPath().'?'.http_build_query($request->getQuery())); $this->hits++; $path = '/'.ltrim($request->getPath(), '/'); $endpoint = NULL; if(isset($this->routes[$path])) { // Direct lookup $endpoint = $this->routes[$path]; } else { $endpointKey = NULL; if(isset($this->lookupCache[$path])) { $endpointKey = $this->lookupCache[$path]; // The item was found in the lookupCache, so we move it back to the end of the array (to avoid unshifting it too soon) - LRU algorithm if($this->lookupCacheCount == 1000) { unset($this->lookupCache[$path]); $this->lookupCache[$path] = $endpointKey; } $endpoint = $this->searchRoutes[$endpointKey][1]; } else { foreach($this->searchRoutes as $key => $route) { if(fnmatch($route[0], $path)) { $endpointKey = $key; break; } } if($endpointKey !== NULL) { // LRU algorithm $this->lookupCache[$path] = $endpointKey; // Added to the end of the array $this->lookupCacheCount++; while($this->lookupCacheCount-- > 1000) array_shift($this->lookupCache); // Remove something from the beginning of the array $endpoint = $this->searchRoutes[$endpointKey][1]; } } } if($endpoint) { // We identified an endpoint return $endpoint->listen($request, $response); } else { // We failed to find an endpoint, so we redirect to /errors/404 // This is not cached, because we don't want anybody to be able to fill the lookupCache with garbage return $this->respondError(404, $request, $response); } }
[ "public", "function", "listen", "(", "$", "request", ",", "$", "response", ")", "{", "//\t\t$this->debug('Host::listen: path='.$request->getPath().'?'.http_build_query($request->getQuery()));", "$", "this", "->", "hits", "++", ";", "$", "path", "=", "'/'", ".", "ltrim", "(", "$", "request", "->", "getPath", "(", ")", ",", "'/'", ")", ";", "$", "endpoint", "=", "NULL", ";", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "$", "path", "]", ")", ")", "{", "// Direct lookup", "$", "endpoint", "=", "$", "this", "->", "routes", "[", "$", "path", "]", ";", "}", "else", "{", "$", "endpointKey", "=", "NULL", ";", "if", "(", "isset", "(", "$", "this", "->", "lookupCache", "[", "$", "path", "]", ")", ")", "{", "$", "endpointKey", "=", "$", "this", "->", "lookupCache", "[", "$", "path", "]", ";", "// The item was found in the lookupCache, so we move it back to the end of the array (to avoid unshifting it too soon) - LRU algorithm", "if", "(", "$", "this", "->", "lookupCacheCount", "==", "1000", ")", "{", "unset", "(", "$", "this", "->", "lookupCache", "[", "$", "path", "]", ")", ";", "$", "this", "->", "lookupCache", "[", "$", "path", "]", "=", "$", "endpointKey", ";", "}", "$", "endpoint", "=", "$", "this", "->", "searchRoutes", "[", "$", "endpointKey", "]", "[", "1", "]", ";", "}", "else", "{", "foreach", "(", "$", "this", "->", "searchRoutes", "as", "$", "key", "=>", "$", "route", ")", "{", "if", "(", "fnmatch", "(", "$", "route", "[", "0", "]", ",", "$", "path", ")", ")", "{", "$", "endpointKey", "=", "$", "key", ";", "break", ";", "}", "}", "if", "(", "$", "endpointKey", "!==", "NULL", ")", "{", "// LRU algorithm", "$", "this", "->", "lookupCache", "[", "$", "path", "]", "=", "$", "endpointKey", ";", "// Added to the end of the array", "$", "this", "->", "lookupCacheCount", "++", ";", "while", "(", "$", "this", "->", "lookupCacheCount", "--", ">", "1000", ")", "array_shift", "(", "$", "this", "->", "lookupCache", ")", ";", "// Remove something from the beginning of the array", "$", "endpoint", "=", "$", "this", "->", "searchRoutes", "[", "$", "endpointKey", "]", "[", "1", "]", ";", "}", "}", "}", "if", "(", "$", "endpoint", ")", "{", "// We identified an endpoint", "return", "$", "endpoint", "->", "listen", "(", "$", "request", ",", "$", "response", ")", ";", "}", "else", "{", "// We failed to find an endpoint, so we redirect to /errors/404", "// This is not cached, because we don't want anybody to be able to fill the lookupCache with garbage", "return", "$", "this", "->", "respondError", "(", "404", ",", "$", "request", ",", "$", "response", ")", ";", "}", "}" ]
Handle an incoming request, map it to the correct endpoint using routes and call the listen method on the endpoint
[ "Handle", "an", "incoming", "request", "map", "it", "to", "the", "correct", "endpoint", "using", "routes", "and", "call", "the", "listen", "method", "on", "the", "endpoint" ]
train
https://github.com/frodeborli/fubber-reactor/blob/3920f86a788c1a73360ebf6a215da15e097a1afa/src/Host.php#L156-L206
frodeborli/fubber-reactor
src/Host.php
Host.addRoute
public function addRoute($pattern, $endpoint) { if(is_object($endpoint) && $endpoint instanceof \Fubber\Reactor\EndpointInterface) { // All is fine and dandy } elseif (is_callable($endpoint)) { // Make a CallbackController return $this->addRoute($pattern, new CallbackController($endpoint)); } else { $this->notice('Host::addRoute(): Expects a callback or a controller'); return FALSE; } $count = substr_count($pattern, '*'); if ($count === 0) { // This is merely a direct route $this->extraRoutes[$pattern] = $this->routes[$pattern] = $endpoint; } else { // Add this route to the $this->searchRoutes and sort it again $this->extraRoutes[$pattern] = $endpoint; $this->searchRoutes[] = array($pattern, $endpoint); } }
php
public function addRoute($pattern, $endpoint) { if(is_object($endpoint) && $endpoint instanceof \Fubber\Reactor\EndpointInterface) { // All is fine and dandy } elseif (is_callable($endpoint)) { // Make a CallbackController return $this->addRoute($pattern, new CallbackController($endpoint)); } else { $this->notice('Host::addRoute(): Expects a callback or a controller'); return FALSE; } $count = substr_count($pattern, '*'); if ($count === 0) { // This is merely a direct route $this->extraRoutes[$pattern] = $this->routes[$pattern] = $endpoint; } else { // Add this route to the $this->searchRoutes and sort it again $this->extraRoutes[$pattern] = $endpoint; $this->searchRoutes[] = array($pattern, $endpoint); } }
[ "public", "function", "addRoute", "(", "$", "pattern", ",", "$", "endpoint", ")", "{", "if", "(", "is_object", "(", "$", "endpoint", ")", "&&", "$", "endpoint", "instanceof", "\\", "Fubber", "\\", "Reactor", "\\", "EndpointInterface", ")", "{", "// All is fine and dandy", "}", "elseif", "(", "is_callable", "(", "$", "endpoint", ")", ")", "{", "// Make a CallbackController", "return", "$", "this", "->", "addRoute", "(", "$", "pattern", ",", "new", "CallbackController", "(", "$", "endpoint", ")", ")", ";", "}", "else", "{", "$", "this", "->", "notice", "(", "'Host::addRoute(): Expects a callback or a controller'", ")", ";", "return", "FALSE", ";", "}", "$", "count", "=", "substr_count", "(", "$", "pattern", ",", "'*'", ")", ";", "if", "(", "$", "count", "===", "0", ")", "{", "// This is merely a direct route", "$", "this", "->", "extraRoutes", "[", "$", "pattern", "]", "=", "$", "this", "->", "routes", "[", "$", "pattern", "]", "=", "$", "endpoint", ";", "}", "else", "{", "// Add this route to the $this->searchRoutes and sort it again", "$", "this", "->", "extraRoutes", "[", "$", "pattern", "]", "=", "$", "endpoint", ";", "$", "this", "->", "searchRoutes", "[", "]", "=", "array", "(", "$", "pattern", ",", "$", "endpoint", ")", ";", "}", "}" ]
Add a routing rule to the routing table. The $endpoint must be either a callback accepting $request, $response, or a class that extends the \Fubber\Reactor\Controller.
[ "Add", "a", "routing", "rule", "to", "the", "routing", "table", ".", "The", "$endpoint", "must", "be", "either", "a", "callback", "accepting", "$request", "$response", "or", "a", "class", "that", "extends", "the", "\\", "Fubber", "\\", "Reactor", "\\", "Controller", "." ]
train
https://github.com/frodeborli/fubber-reactor/blob/3920f86a788c1a73360ebf6a215da15e097a1afa/src/Host.php#L223-L244
frodeborli/fubber-reactor
src/Host.php
Host.scanRoutes
protected function scanRoutes($root, $realRoot=NULL) { if($realRoot === NULL) $realRoot = $root; $result = array(); $all = glob($root.'/*'); /* */ foreach($all as $path) { if(!is_dir($path)) { // This is an endpoint $res = $this->createRouteFromFile($realRoot, $path); if($res) $result[] = $res; } else { $res = $this->scanRoutes($path, $realRoot); foreach($res as $route) $result[] = $route; } } return $result; }
php
protected function scanRoutes($root, $realRoot=NULL) { if($realRoot === NULL) $realRoot = $root; $result = array(); $all = glob($root.'/*'); /* */ foreach($all as $path) { if(!is_dir($path)) { // This is an endpoint $res = $this->createRouteFromFile($realRoot, $path); if($res) $result[] = $res; } else { $res = $this->scanRoutes($path, $realRoot); foreach($res as $route) $result[] = $route; } } return $result; }
[ "protected", "function", "scanRoutes", "(", "$", "root", ",", "$", "realRoot", "=", "NULL", ")", "{", "if", "(", "$", "realRoot", "===", "NULL", ")", "$", "realRoot", "=", "$", "root", ";", "$", "result", "=", "array", "(", ")", ";", "$", "all", "=", "glob", "(", "$", "root", ".", "'/*'", ")", ";", "/* */", "foreach", "(", "$", "all", "as", "$", "path", ")", "{", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "// This is an endpoint", "$", "res", "=", "$", "this", "->", "createRouteFromFile", "(", "$", "realRoot", ",", "$", "path", ")", ";", "if", "(", "$", "res", ")", "$", "result", "[", "]", "=", "$", "res", ";", "}", "else", "{", "$", "res", "=", "$", "this", "->", "scanRoutes", "(", "$", "path", ",", "$", "realRoot", ")", ";", "foreach", "(", "$", "res", "as", "$", "route", ")", "$", "result", "[", "]", "=", "$", "route", ";", "}", "}", "return", "$", "result", ";", "}" ]
Recursively find all routes within path
[ "Recursively", "find", "all", "routes", "within", "path" ]
train
https://github.com/frodeborli/fubber-reactor/blob/3920f86a788c1a73360ebf6a215da15e097a1afa/src/Host.php#L283-L301
surebert/surebert-framework
src/sb/PDO/Debugger.php
Debugger.s2o
public function s2o($sql, $params = null, $class_name = '', $prepare_and_store = 1) { try { return parent::s2o($sql, $params, $class_name, $prepare_and_store); } catch (\Exception $e) { throw(new \sb\PDO\Exception('CALLED: ' . __METHOD__ . "\nERROR RETURNED: " . print_r($e, 1))); } }
php
public function s2o($sql, $params = null, $class_name = '', $prepare_and_store = 1) { try { return parent::s2o($sql, $params, $class_name, $prepare_and_store); } catch (\Exception $e) { throw(new \sb\PDO\Exception('CALLED: ' . __METHOD__ . "\nERROR RETURNED: " . print_r($e, 1))); } }
[ "public", "function", "s2o", "(", "$", "sql", ",", "$", "params", "=", "null", ",", "$", "class_name", "=", "''", ",", "$", "prepare_and_store", "=", "1", ")", "{", "try", "{", "return", "parent", "::", "s2o", "(", "$", "sql", ",", "$", "params", ",", "$", "class_name", ",", "$", "prepare_and_store", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "(", "new", "\\", "sb", "\\", "PDO", "\\", "Exception", "(", "'CALLED: '", ".", "__METHOD__", ".", "\"\\nERROR RETURNED: \"", ".", "print_r", "(", "$", "e", ",", "1", ")", ")", ")", ";", "}", "}" ]
Additionally Logs the errors
[ "Additionally", "Logs", "the", "errors" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Debugger.php#L39-L47
bespoke-ws/blademanager
src/BladeManagerServiceProvider.php
BladeManagerServiceProvider.boot
public function boot() { // Register the custom directives $this->app->make('blade_directive_manager')->register(); // Register the views $viewPath = __DIR__ . '/Views'; $this->loadViewsFrom($viewPath, 'blade_manager'); $this->publishes([$viewPath => $this->app->resourcePath('views/vendor/' . 'blade_manager')]); }
php
public function boot() { // Register the custom directives $this->app->make('blade_directive_manager')->register(); // Register the views $viewPath = __DIR__ . '/Views'; $this->loadViewsFrom($viewPath, 'blade_manager'); $this->publishes([$viewPath => $this->app->resourcePath('views/vendor/' . 'blade_manager')]); }
[ "public", "function", "boot", "(", ")", "{", "// Register the custom directives", "$", "this", "->", "app", "->", "make", "(", "'blade_directive_manager'", ")", "->", "register", "(", ")", ";", "// Register the views", "$", "viewPath", "=", "__DIR__", ".", "'/Views'", ";", "$", "this", "->", "loadViewsFrom", "(", "$", "viewPath", ",", "'blade_manager'", ")", ";", "$", "this", "->", "publishes", "(", "[", "$", "viewPath", "=>", "$", "this", "->", "app", "->", "resourcePath", "(", "'views/vendor/'", ".", "'blade_manager'", ")", "]", ")", ";", "}" ]
Bootstrap any application services. @return void
[ "Bootstrap", "any", "application", "services", "." ]
train
https://github.com/bespoke-ws/blademanager/blob/4bf358bfbcdde953415f7bebba7db5b40aca8a4c/src/BladeManagerServiceProvider.php#L33-L42
fkooman/php-lib-http
src/fkooman/Http/Response.php
Response.setHeader
public function setHeader($keyName, $value) { $normalizedKeyName = self::normalizeHeaderKeyName($keyName); $this->headers[$normalizedKeyName] = $value; }
php
public function setHeader($keyName, $value) { $normalizedKeyName = self::normalizeHeaderKeyName($keyName); $this->headers[$normalizedKeyName] = $value; }
[ "public", "function", "setHeader", "(", "$", "keyName", ",", "$", "value", ")", "{", "$", "normalizedKeyName", "=", "self", "::", "normalizeHeaderKeyName", "(", "$", "keyName", ")", ";", "$", "this", "->", "headers", "[", "$", "normalizedKeyName", "]", "=", "$", "value", ";", "}" ]
Set a header. If it already exists the value is overwritten with the new one. @param string $keyName the name of the header @param string|int $value the value of the header
[ "Set", "a", "header", ".", "If", "it", "already", "exists", "the", "value", "is", "overwritten", "with", "the", "new", "one", "." ]
train
https://github.com/fkooman/php-lib-http/blob/94956a480459b7f6b880d61f21ef03e683deb995/src/fkooman/Http/Response.php#L124-L128
fkooman/php-lib-http
src/fkooman/Http/Response.php
Response.addHeader
public function addHeader($keyName, $value) { $normalizedKeyName = self::normalizeHeaderKeyName($keyName); if (array_key_exists($normalizedKeyName, $this->headers)) { $this->headers[$normalizedKeyName] = sprintf('%s, %s', $this->headers[$normalizedKeyName], $value); } else { $this->headers[$normalizedKeyName] = $value; } }
php
public function addHeader($keyName, $value) { $normalizedKeyName = self::normalizeHeaderKeyName($keyName); if (array_key_exists($normalizedKeyName, $this->headers)) { $this->headers[$normalizedKeyName] = sprintf('%s, %s', $this->headers[$normalizedKeyName], $value); } else { $this->headers[$normalizedKeyName] = $value; } }
[ "public", "function", "addHeader", "(", "$", "keyName", ",", "$", "value", ")", "{", "$", "normalizedKeyName", "=", "self", "::", "normalizeHeaderKeyName", "(", "$", "keyName", ")", ";", "if", "(", "array_key_exists", "(", "$", "normalizedKeyName", ",", "$", "this", "->", "headers", ")", ")", "{", "$", "this", "->", "headers", "[", "$", "normalizedKeyName", "]", "=", "sprintf", "(", "'%s, %s'", ",", "$", "this", "->", "headers", "[", "$", "normalizedKeyName", "]", ",", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "headers", "[", "$", "normalizedKeyName", "]", "=", "$", "value", ";", "}", "}" ]
Add a header. If it already exists the value is appended to the existing header using comma separation. NOTE: not all headers 'support' this. It is up to the developer to figure out if this is supported by the specific header by consulting the specification. @param string $keyName the name of the header @param string $value the value of the header
[ "Add", "a", "header", ".", "If", "it", "already", "exists", "the", "value", "is", "appended", "to", "the", "existing", "header", "using", "comma", "separation", ".", "NOTE", ":", "not", "all", "headers", "support", "this", ".", "It", "is", "up", "to", "the", "developer", "to", "figure", "out", "if", "this", "is", "supported", "by", "the", "specific", "header", "by", "consulting", "the", "specification", "." ]
train
https://github.com/fkooman/php-lib-http/blob/94956a480459b7f6b880d61f21ef03e683deb995/src/fkooman/Http/Response.php#L139-L147
fkooman/php-lib-http
src/fkooman/Http/Response.php
Response.send
public function send() { header( sprintf( 'HTTP/1.1 %s %s', $this->statusCode, self::codeToReason($this->statusCode) ) ); foreach ($this->headers as $k => $v) { header( sprintf('%s: %s', $k, $v) ); } echo $this->body; }
php
public function send() { header( sprintf( 'HTTP/1.1 %s %s', $this->statusCode, self::codeToReason($this->statusCode) ) ); foreach ($this->headers as $k => $v) { header( sprintf('%s: %s', $k, $v) ); } echo $this->body; }
[ "public", "function", "send", "(", ")", "{", "header", "(", "sprintf", "(", "'HTTP/1.1 %s %s'", ",", "$", "this", "->", "statusCode", ",", "self", "::", "codeToReason", "(", "$", "this", "->", "statusCode", ")", ")", ")", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "k", "=>", "$", "v", ")", "{", "header", "(", "sprintf", "(", "'%s: %s'", ",", "$", "k", ",", "$", "v", ")", ")", ";", "}", "echo", "$", "this", "->", "body", ";", "}" ]
Construct the response and send it out.
[ "Construct", "the", "response", "and", "send", "it", "out", "." ]
train
https://github.com/fkooman/php-lib-http/blob/94956a480459b7f6b880d61f21ef03e683deb995/src/fkooman/Http/Response.php#L152-L167
fkooman/php-lib-http
src/fkooman/Http/Response.php
Response.toArray
public function toArray() { $output = []; $output[] = sprintf( 'HTTP/1.1 %s %s', $this->statusCode, self::codeToReason($this->statusCode) ); foreach ($this->headers as $k => $v) { $output[] = sprintf('%s: %s', $k, $v); } $output[] = ''; $output[] = $this->body; return $output; }
php
public function toArray() { $output = []; $output[] = sprintf( 'HTTP/1.1 %s %s', $this->statusCode, self::codeToReason($this->statusCode) ); foreach ($this->headers as $k => $v) { $output[] = sprintf('%s: %s', $k, $v); } $output[] = ''; $output[] = $this->body; return $output; }
[ "public", "function", "toArray", "(", ")", "{", "$", "output", "=", "[", "]", ";", "$", "output", "[", "]", "=", "sprintf", "(", "'HTTP/1.1 %s %s'", ",", "$", "this", "->", "statusCode", ",", "self", "::", "codeToReason", "(", "$", "this", "->", "statusCode", ")", ")", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "output", "[", "]", "=", "sprintf", "(", "'%s: %s'", ",", "$", "k", ",", "$", "v", ")", ";", "}", "$", "output", "[", "]", "=", "''", ";", "$", "output", "[", "]", "=", "$", "this", "->", "body", ";", "return", "$", "output", ";", "}" ]
Convert the full response to array for the purpose of unit testing.
[ "Convert", "the", "full", "response", "to", "array", "for", "the", "purpose", "of", "unit", "testing", "." ]
train
https://github.com/fkooman/php-lib-http/blob/94956a480459b7f6b880d61f21ef03e683deb995/src/fkooman/Http/Response.php#L172-L187
ekuiter/feature-php
FeaturePhp/Renderer.php
Renderer.render
public function render($textOnly = false) { if ($textOnly) return $this->renderText(); $str = $this->getStyle(); $str .= "<table><tr><td valign='top'>"; $str .= $this->_render(false); $str .= "</td></tr></table>"; return $str; }
php
public function render($textOnly = false) { if ($textOnly) return $this->renderText(); $str = $this->getStyle(); $str .= "<table><tr><td valign='top'>"; $str .= $this->_render(false); $str .= "</td></tr></table>"; return $str; }
[ "public", "function", "render", "(", "$", "textOnly", "=", "false", ")", "{", "if", "(", "$", "textOnly", ")", "return", "$", "this", "->", "renderText", "(", ")", ";", "$", "str", "=", "$", "this", "->", "getStyle", "(", ")", ";", "$", "str", ".=", "\"<table><tr><td valign='top'>\"", ";", "$", "str", ".=", "$", "this", "->", "_render", "(", "false", ")", ";", "$", "str", ".=", "\"</td></tr></table>\"", ";", "return", "$", "str", ";", "}" ]
Returns the renderer's web page. @param bool $textOnly whether to render text or HTML @return string
[ "Returns", "the", "renderer", "s", "web", "page", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Renderer.php#L46-L55
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.isQueryAllowed
public function isQueryAllowed( ezcDbHandler $db, $query ) { if ( strstr($query, 'DROP COLUMN') || strstr($query, 'CHANGE') ) // detecting DROP COLUMN clause or field CHANGE clause { return false; } if ( substr( $query, 0, 10 ) == 'DROP TABLE' ) { $tableName = substr( $query, strlen( 'DROP TABLE ' ) ); $result = $db->query( "SELECT count(*) AS count FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type='table' AND tbl_name={$tableName}" )->fetchAll(); if ( $result[0]['count'] == 1 ) { return true; } else { return false; } } return true; }
php
public function isQueryAllowed( ezcDbHandler $db, $query ) { if ( strstr($query, 'DROP COLUMN') || strstr($query, 'CHANGE') ) // detecting DROP COLUMN clause or field CHANGE clause { return false; } if ( substr( $query, 0, 10 ) == 'DROP TABLE' ) { $tableName = substr( $query, strlen( 'DROP TABLE ' ) ); $result = $db->query( "SELECT count(*) AS count FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type='table' AND tbl_name={$tableName}" )->fetchAll(); if ( $result[0]['count'] == 1 ) { return true; } else { return false; } } return true; }
[ "public", "function", "isQueryAllowed", "(", "ezcDbHandler", "$", "db", ",", "$", "query", ")", "{", "if", "(", "strstr", "(", "$", "query", ",", "'DROP COLUMN'", ")", "||", "strstr", "(", "$", "query", ",", "'CHANGE'", ")", ")", "// detecting DROP COLUMN clause or field CHANGE clause ", "{", "return", "false", ";", "}", "if", "(", "substr", "(", "$", "query", ",", "0", ",", "10", ")", "==", "'DROP TABLE'", ")", "{", "$", "tableName", "=", "substr", "(", "$", "query", ",", "strlen", "(", "'DROP TABLE '", ")", ")", ";", "$", "result", "=", "$", "db", "->", "query", "(", "\"SELECT count(*) AS count FROM \n (SELECT * FROM sqlite_master UNION ALL \n SELECT * FROM sqlite_temp_master)\n WHERE type='table' AND tbl_name={$tableName}\"", ")", "->", "fetchAll", "(", ")", ";", "if", "(", "$", "result", "[", "0", "]", "[", "'count'", "]", "==", "1", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if certain query allowed. Perform testing if table exist for DROP TABLE query to avoid stoping execution while try to drop not existent table. @param ezcDbHandler $db @param string $query @return boolean false if query should not be executed.
[ "Checks", "if", "certain", "query", "allowed", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L59-L84
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.applyDiffToDb
public function applyDiffToDb( ezcDbHandler $db, ezcDbSchemaDiff $dbSchemaDiff ) { $db->beginTransaction(); foreach ( $this->convertDiffToDDL( $dbSchemaDiff ) as $query ) { if ( $this->isQueryAllowed( $db, $query ) ) { $db->exec( $query ); } else { // SQLite don't support SQL clause for removing columns // perform emulation for this if ( strstr( $query, 'DROP COLUMN' ) ) { $db->commit(); $db->beginTransaction(); try { preg_match ( "/ALTER TABLE (.*) DROP COLUMN (.*)/" , $query, $matches ); if ( !$matches ) { throw new ezcDbSchemaSqliteDropFieldException( "Can't fetch field for droping from SQL query: $query" ); } $tableName = trim( $matches[1], "'" ); $dropFieldName = trim( $matches[2], "'" ); $this->dropField( $db, $tableName , $dropFieldName ); } catch ( ezcDbSchemaSqliteDropFieldException $e ) { } $db->commit(); $db->beginTransaction(); } else if ( strstr( $query, 'CHANGE' ) ) // SQLite don't support SQL clause for changing columns // perform emulation for this { $db->commit(); $db->beginTransaction(); try { preg_match( "/ALTER TABLE (.*) CHANGE (.*?) (.*?) (.*)/" , $query, $matches ); $tableName = trim( $matches[1], "'" ); $changeFieldName = trim( $matches[2], "'" ); $changeFieldNewName = trim( $matches[3], "'" ); $changeFieldNewType = $matches[4]; $this->changeField( $db, $tableName, $changeFieldName, $changeFieldNewName, $changeFieldNewType ); } catch ( ezcDbSchemaSqliteDropFieldException $e ) { } $db->commit(); $db->beginTransaction(); } } } $db->commit(); }
php
public function applyDiffToDb( ezcDbHandler $db, ezcDbSchemaDiff $dbSchemaDiff ) { $db->beginTransaction(); foreach ( $this->convertDiffToDDL( $dbSchemaDiff ) as $query ) { if ( $this->isQueryAllowed( $db, $query ) ) { $db->exec( $query ); } else { // SQLite don't support SQL clause for removing columns // perform emulation for this if ( strstr( $query, 'DROP COLUMN' ) ) { $db->commit(); $db->beginTransaction(); try { preg_match ( "/ALTER TABLE (.*) DROP COLUMN (.*)/" , $query, $matches ); if ( !$matches ) { throw new ezcDbSchemaSqliteDropFieldException( "Can't fetch field for droping from SQL query: $query" ); } $tableName = trim( $matches[1], "'" ); $dropFieldName = trim( $matches[2], "'" ); $this->dropField( $db, $tableName , $dropFieldName ); } catch ( ezcDbSchemaSqliteDropFieldException $e ) { } $db->commit(); $db->beginTransaction(); } else if ( strstr( $query, 'CHANGE' ) ) // SQLite don't support SQL clause for changing columns // perform emulation for this { $db->commit(); $db->beginTransaction(); try { preg_match( "/ALTER TABLE (.*) CHANGE (.*?) (.*?) (.*)/" , $query, $matches ); $tableName = trim( $matches[1], "'" ); $changeFieldName = trim( $matches[2], "'" ); $changeFieldNewName = trim( $matches[3], "'" ); $changeFieldNewType = $matches[4]; $this->changeField( $db, $tableName, $changeFieldName, $changeFieldNewName, $changeFieldNewType ); } catch ( ezcDbSchemaSqliteDropFieldException $e ) { } $db->commit(); $db->beginTransaction(); } } } $db->commit(); }
[ "public", "function", "applyDiffToDb", "(", "ezcDbHandler", "$", "db", ",", "ezcDbSchemaDiff", "$", "dbSchemaDiff", ")", "{", "$", "db", "->", "beginTransaction", "(", ")", ";", "foreach", "(", "$", "this", "->", "convertDiffToDDL", "(", "$", "dbSchemaDiff", ")", "as", "$", "query", ")", "{", "if", "(", "$", "this", "->", "isQueryAllowed", "(", "$", "db", ",", "$", "query", ")", ")", "{", "$", "db", "->", "exec", "(", "$", "query", ")", ";", "}", "else", "{", "// SQLite don't support SQL clause for removing columns", "// perform emulation for this", "if", "(", "strstr", "(", "$", "query", ",", "'DROP COLUMN'", ")", ")", "{", "$", "db", "->", "commit", "(", ")", ";", "$", "db", "->", "beginTransaction", "(", ")", ";", "try", "{", "preg_match", "(", "\"/ALTER TABLE (.*) DROP COLUMN (.*)/\"", ",", "$", "query", ",", "$", "matches", ")", ";", "if", "(", "!", "$", "matches", ")", "{", "throw", "new", "ezcDbSchemaSqliteDropFieldException", "(", "\"Can't fetch field for droping from SQL query: $query\"", ")", ";", "}", "$", "tableName", "=", "trim", "(", "$", "matches", "[", "1", "]", ",", "\"'\"", ")", ";", "$", "dropFieldName", "=", "trim", "(", "$", "matches", "[", "2", "]", ",", "\"'\"", ")", ";", "$", "this", "->", "dropField", "(", "$", "db", ",", "$", "tableName", ",", "$", "dropFieldName", ")", ";", "}", "catch", "(", "ezcDbSchemaSqliteDropFieldException", "$", "e", ")", "{", "}", "$", "db", "->", "commit", "(", ")", ";", "$", "db", "->", "beginTransaction", "(", ")", ";", "}", "else", "if", "(", "strstr", "(", "$", "query", ",", "'CHANGE'", ")", ")", "// SQLite don't support SQL clause for changing columns ", "// perform emulation for this", "{", "$", "db", "->", "commit", "(", ")", ";", "$", "db", "->", "beginTransaction", "(", ")", ";", "try", "{", "preg_match", "(", "\"/ALTER TABLE (.*) CHANGE (.*?) (.*?) (.*)/\"", ",", "$", "query", ",", "$", "matches", ")", ";", "$", "tableName", "=", "trim", "(", "$", "matches", "[", "1", "]", ",", "\"'\"", ")", ";", "$", "changeFieldName", "=", "trim", "(", "$", "matches", "[", "2", "]", ",", "\"'\"", ")", ";", "$", "changeFieldNewName", "=", "trim", "(", "$", "matches", "[", "3", "]", ",", "\"'\"", ")", ";", "$", "changeFieldNewType", "=", "$", "matches", "[", "4", "]", ";", "$", "this", "->", "changeField", "(", "$", "db", ",", "$", "tableName", ",", "$", "changeFieldName", ",", "$", "changeFieldNewName", ",", "$", "changeFieldNewType", ")", ";", "}", "catch", "(", "ezcDbSchemaSqliteDropFieldException", "$", "e", ")", "{", "}", "$", "db", "->", "commit", "(", ")", ";", "$", "db", "->", "beginTransaction", "(", ")", ";", "}", "}", "}", "$", "db", "->", "commit", "(", ")", ";", "}" ]
Applies the differences defined in $dbSchemaDiff to the database referenced by $db. This method uses {@link convertDiffToDDL} to create SQL for the differences and then executes the returned SQL statements on the database handler $db. @todo check for failed transaction @param ezcDbHandler $db @param ezcDbSchemaDiff $dbSchemaDiff
[ "Applies", "the", "differences", "defined", "in", "$dbSchemaDiff", "to", "the", "database", "referenced", "by", "$db", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L109-L172
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.changeField
private function changeField( ezcDbHandler $db, $tableName, $changeFieldName, $changeFieldNewName, $changeFieldNewDefinition ) { $tmpTableName = $tableName.'_ezcbackup'; $resultArray = $db->query( "PRAGMA TABLE_INFO( '$tableName' )" ); $resultArray->setFetchMode( PDO::FETCH_NUM ); $fieldsDefinitions = array(); $fieldsList = array(); foreach ( $resultArray as $row ) { $fieldSql = array(); $fieldSql[] = $row[1]; // name if ( $row[1] == $changeFieldName ) { // will recreate changed field with new definition $fieldsDefinitions[] = "'$changeFieldNewName' $changeFieldNewDefinition"; $fieldsList[] = $fieldSql[0]; continue; } $fieldSql[] = $row[2]; // type if ( $row[3] == '99' ) { $fieldSql[] = 'NOT NULL'; } $fieldDefault = null; if ( $row[4] != '' ) { $fieldSql[]= "DEFAULT '{$row[4]}'"; } if ( $row[5] =='1' ) { $fieldSql[] = 'PRIMARY KEY AUTOINCREMENT'; } // FIXME: unsigned needs to be implemented $fieldUnsigned = false; $fieldsDefinitions[] = join ( ' ', $fieldSql ); $fieldsList[] = $fieldSql[0]; } if ( count( $fieldsDefinitions ) > 0 ) { $fields = join( ', ', $fieldsDefinitions ); $tmpTableCreateSql = "CREATE TEMPORARY TABLE '$tmpTableName'( $fields );"; $newTableCreateSql = "CREATE TABLE '$tableName'( $fields )" ; if ( count($fieldsList)>0 ) { $db->exec( $tmpTableCreateSql ); $db->exec( "INSERT INTO '$tmpTableName' SELECT ". join( ', ', $fieldsList )." FROM '$tableName';" ); $db->exec( "DROP TABLE '$tableName';" ); $db->exec( $newTableCreateSql ); $db->exec( "INSERT INTO '$tableName' SELECT ". join( ', ', $fieldsList )." FROM '$tmpTableName';" ); $db->exec( "DROP TABLE '$tmpTableName';" ); } else { // we had table with one column will drop table and recreate with changed column. $db->exec( "DROP TABLE '$tableName';" ); $newTableCreateSql = "CREATE TABLE '$tableName'( $changeFieldNewName $changeFieldNewDefinition )" ; $db->exec( $newTableCreateSql ); } } }
php
private function changeField( ezcDbHandler $db, $tableName, $changeFieldName, $changeFieldNewName, $changeFieldNewDefinition ) { $tmpTableName = $tableName.'_ezcbackup'; $resultArray = $db->query( "PRAGMA TABLE_INFO( '$tableName' )" ); $resultArray->setFetchMode( PDO::FETCH_NUM ); $fieldsDefinitions = array(); $fieldsList = array(); foreach ( $resultArray as $row ) { $fieldSql = array(); $fieldSql[] = $row[1]; // name if ( $row[1] == $changeFieldName ) { // will recreate changed field with new definition $fieldsDefinitions[] = "'$changeFieldNewName' $changeFieldNewDefinition"; $fieldsList[] = $fieldSql[0]; continue; } $fieldSql[] = $row[2]; // type if ( $row[3] == '99' ) { $fieldSql[] = 'NOT NULL'; } $fieldDefault = null; if ( $row[4] != '' ) { $fieldSql[]= "DEFAULT '{$row[4]}'"; } if ( $row[5] =='1' ) { $fieldSql[] = 'PRIMARY KEY AUTOINCREMENT'; } // FIXME: unsigned needs to be implemented $fieldUnsigned = false; $fieldsDefinitions[] = join ( ' ', $fieldSql ); $fieldsList[] = $fieldSql[0]; } if ( count( $fieldsDefinitions ) > 0 ) { $fields = join( ', ', $fieldsDefinitions ); $tmpTableCreateSql = "CREATE TEMPORARY TABLE '$tmpTableName'( $fields );"; $newTableCreateSql = "CREATE TABLE '$tableName'( $fields )" ; if ( count($fieldsList)>0 ) { $db->exec( $tmpTableCreateSql ); $db->exec( "INSERT INTO '$tmpTableName' SELECT ". join( ', ', $fieldsList )." FROM '$tableName';" ); $db->exec( "DROP TABLE '$tableName';" ); $db->exec( $newTableCreateSql ); $db->exec( "INSERT INTO '$tableName' SELECT ". join( ', ', $fieldsList )." FROM '$tmpTableName';" ); $db->exec( "DROP TABLE '$tmpTableName';" ); } else { // we had table with one column will drop table and recreate with changed column. $db->exec( "DROP TABLE '$tableName';" ); $newTableCreateSql = "CREATE TABLE '$tableName'( $changeFieldNewName $changeFieldNewDefinition )" ; $db->exec( $newTableCreateSql ); } } }
[ "private", "function", "changeField", "(", "ezcDbHandler", "$", "db", ",", "$", "tableName", ",", "$", "changeFieldName", ",", "$", "changeFieldNewName", ",", "$", "changeFieldNewDefinition", ")", "{", "$", "tmpTableName", "=", "$", "tableName", ".", "'_ezcbackup'", ";", "$", "resultArray", "=", "$", "db", "->", "query", "(", "\"PRAGMA TABLE_INFO( '$tableName' )\"", ")", ";", "$", "resultArray", "->", "setFetchMode", "(", "PDO", "::", "FETCH_NUM", ")", ";", "$", "fieldsDefinitions", "=", "array", "(", ")", ";", "$", "fieldsList", "=", "array", "(", ")", ";", "foreach", "(", "$", "resultArray", "as", "$", "row", ")", "{", "$", "fieldSql", "=", "array", "(", ")", ";", "$", "fieldSql", "[", "]", "=", "$", "row", "[", "1", "]", ";", "// name", "if", "(", "$", "row", "[", "1", "]", "==", "$", "changeFieldName", ")", "{", "// will recreate changed field with new definition", "$", "fieldsDefinitions", "[", "]", "=", "\"'$changeFieldNewName' $changeFieldNewDefinition\"", ";", "$", "fieldsList", "[", "]", "=", "$", "fieldSql", "[", "0", "]", ";", "continue", ";", "}", "$", "fieldSql", "[", "]", "=", "$", "row", "[", "2", "]", ";", "// type", "if", "(", "$", "row", "[", "3", "]", "==", "'99'", ")", "{", "$", "fieldSql", "[", "]", "=", "'NOT NULL'", ";", "}", "$", "fieldDefault", "=", "null", ";", "if", "(", "$", "row", "[", "4", "]", "!=", "''", ")", "{", "$", "fieldSql", "[", "]", "=", "\"DEFAULT '{$row[4]}'\"", ";", "}", "if", "(", "$", "row", "[", "5", "]", "==", "'1'", ")", "{", "$", "fieldSql", "[", "]", "=", "'PRIMARY KEY AUTOINCREMENT'", ";", "}", "// FIXME: unsigned needs to be implemented", "$", "fieldUnsigned", "=", "false", ";", "$", "fieldsDefinitions", "[", "]", "=", "join", "(", "' '", ",", "$", "fieldSql", ")", ";", "$", "fieldsList", "[", "]", "=", "$", "fieldSql", "[", "0", "]", ";", "}", "if", "(", "count", "(", "$", "fieldsDefinitions", ")", ">", "0", ")", "{", "$", "fields", "=", "join", "(", "', '", ",", "$", "fieldsDefinitions", ")", ";", "$", "tmpTableCreateSql", "=", "\"CREATE TEMPORARY TABLE '$tmpTableName'( $fields );\"", ";", "$", "newTableCreateSql", "=", "\"CREATE TABLE '$tableName'( $fields )\"", ";", "if", "(", "count", "(", "$", "fieldsList", ")", ">", "0", ")", "{", "$", "db", "->", "exec", "(", "$", "tmpTableCreateSql", ")", ";", "$", "db", "->", "exec", "(", "\"INSERT INTO '$tmpTableName' SELECT \"", ".", "join", "(", "', '", ",", "$", "fieldsList", ")", ".", "\" FROM '$tableName';\"", ")", ";", "$", "db", "->", "exec", "(", "\"DROP TABLE '$tableName';\"", ")", ";", "$", "db", "->", "exec", "(", "$", "newTableCreateSql", ")", ";", "$", "db", "->", "exec", "(", "\"INSERT INTO '$tableName' SELECT \"", ".", "join", "(", "', '", ",", "$", "fieldsList", ")", ".", "\" FROM '$tmpTableName';\"", ")", ";", "$", "db", "->", "exec", "(", "\"DROP TABLE '$tmpTableName';\"", ")", ";", "}", "else", "{", "// we had table with one column will drop table and recreate with changed column.", "$", "db", "->", "exec", "(", "\"DROP TABLE '$tableName';\"", ")", ";", "$", "newTableCreateSql", "=", "\"CREATE TABLE '$tableName'( $changeFieldNewName $changeFieldNewDefinition )\"", ";", "$", "db", "->", "exec", "(", "$", "newTableCreateSql", ")", ";", "}", "}", "}" ]
Performs changing field in SQLite table. (workaround for "ALTER TABLE table CHANGE field fieldDefinition" that not alowed in SQLite ). @param ezcDbHandler $db @param string $tableName @param string $changeFieldName @param string $changeFieldNewName @param string $changeFieldNewDefinition
[ "Performs", "changing", "field", "in", "SQLite", "table", ".", "(", "workaround", "for", "ALTER", "TABLE", "table", "CHANGE", "field", "fieldDefinition", "that", "not", "alowed", "in", "SQLite", ")", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L184-L253
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.dropField
private function dropField( $db, $tableName , $dropFieldName ) { $tmpTableName = $tableName.'_ezcbackup'; $resultArray = $db->query( "PRAGMA TABLE_INFO( $tableName )" ); $resultArray->setFetchMode( PDO::FETCH_NUM ); $fieldsDefinitions = array(); $fieldsList = array(); foreach ( $resultArray as $row ) { $fieldSql = array(); $fieldSql[] = "'{$row[1]}'"; // name if ( $row[1] == $dropFieldName ) { continue; // don't include droped fileld in temporary table } $fieldSql[] = $row[2]; // type if ( $row[3] == '99' ) { $fieldSql[] = 'NOT NULL'; } $fieldDefault = null; if ( $row[4] != '' ) { $fieldSql[]= "DEFAULT '{$row[4]}'"; } if ( $row[5] =='1' ) { $fieldSql[] = 'PRIMARY KEY AUTOINCREMENT'; } // FIXME: unsigned needs to be implemented $fieldUnsigned = false; $fieldsDefinitions[] = join ( ' ', $fieldSql ); $fieldsList[] = $fieldSql[0]; } $fields = join( ', ', $fieldsDefinitions ); $tmpTableCreateSql = "CREATE TEMPORARY TABLE '$tmpTableName'( $fields );"; $newTableCreateSql = "CREATE TABLE '$tableName'( $fields )" ; if ( count( $fieldsList ) > 0 ) { $db->exec( $tmpTableCreateSql ); $db->exec( "INSERT INTO '$tmpTableName' SELECT ". join( ', ', $fieldsList )." FROM '$tableName';" ); $db->exec( "DROP TABLE '$tableName';" ); $db->exec( $newTableCreateSql ); $db->exec( "INSERT INTO '$tableName' SELECT ". join( ', ', $fieldsList )." FROM '$tmpTableName';" ); $db->exec( "DROP TABLE '$tmpTableName';" ); } else { throw new ezcDbSchemaDropAllColumnsException( "Trying to delete all columns in table: $tableName" ); } }
php
private function dropField( $db, $tableName , $dropFieldName ) { $tmpTableName = $tableName.'_ezcbackup'; $resultArray = $db->query( "PRAGMA TABLE_INFO( $tableName )" ); $resultArray->setFetchMode( PDO::FETCH_NUM ); $fieldsDefinitions = array(); $fieldsList = array(); foreach ( $resultArray as $row ) { $fieldSql = array(); $fieldSql[] = "'{$row[1]}'"; // name if ( $row[1] == $dropFieldName ) { continue; // don't include droped fileld in temporary table } $fieldSql[] = $row[2]; // type if ( $row[3] == '99' ) { $fieldSql[] = 'NOT NULL'; } $fieldDefault = null; if ( $row[4] != '' ) { $fieldSql[]= "DEFAULT '{$row[4]}'"; } if ( $row[5] =='1' ) { $fieldSql[] = 'PRIMARY KEY AUTOINCREMENT'; } // FIXME: unsigned needs to be implemented $fieldUnsigned = false; $fieldsDefinitions[] = join ( ' ', $fieldSql ); $fieldsList[] = $fieldSql[0]; } $fields = join( ', ', $fieldsDefinitions ); $tmpTableCreateSql = "CREATE TEMPORARY TABLE '$tmpTableName'( $fields );"; $newTableCreateSql = "CREATE TABLE '$tableName'( $fields )" ; if ( count( $fieldsList ) > 0 ) { $db->exec( $tmpTableCreateSql ); $db->exec( "INSERT INTO '$tmpTableName' SELECT ". join( ', ', $fieldsList )." FROM '$tableName';" ); $db->exec( "DROP TABLE '$tableName';" ); $db->exec( $newTableCreateSql ); $db->exec( "INSERT INTO '$tableName' SELECT ". join( ', ', $fieldsList )." FROM '$tmpTableName';" ); $db->exec( "DROP TABLE '$tmpTableName';" ); } else { throw new ezcDbSchemaDropAllColumnsException( "Trying to delete all columns in table: $tableName" ); } }
[ "private", "function", "dropField", "(", "$", "db", ",", "$", "tableName", ",", "$", "dropFieldName", ")", "{", "$", "tmpTableName", "=", "$", "tableName", ".", "'_ezcbackup'", ";", "$", "resultArray", "=", "$", "db", "->", "query", "(", "\"PRAGMA TABLE_INFO( $tableName )\"", ")", ";", "$", "resultArray", "->", "setFetchMode", "(", "PDO", "::", "FETCH_NUM", ")", ";", "$", "fieldsDefinitions", "=", "array", "(", ")", ";", "$", "fieldsList", "=", "array", "(", ")", ";", "foreach", "(", "$", "resultArray", "as", "$", "row", ")", "{", "$", "fieldSql", "=", "array", "(", ")", ";", "$", "fieldSql", "[", "]", "=", "\"'{$row[1]}'\"", ";", "// name", "if", "(", "$", "row", "[", "1", "]", "==", "$", "dropFieldName", ")", "{", "continue", ";", "// don't include droped fileld in temporary table", "}", "$", "fieldSql", "[", "]", "=", "$", "row", "[", "2", "]", ";", "// type", "if", "(", "$", "row", "[", "3", "]", "==", "'99'", ")", "{", "$", "fieldSql", "[", "]", "=", "'NOT NULL'", ";", "}", "$", "fieldDefault", "=", "null", ";", "if", "(", "$", "row", "[", "4", "]", "!=", "''", ")", "{", "$", "fieldSql", "[", "]", "=", "\"DEFAULT '{$row[4]}'\"", ";", "}", "if", "(", "$", "row", "[", "5", "]", "==", "'1'", ")", "{", "$", "fieldSql", "[", "]", "=", "'PRIMARY KEY AUTOINCREMENT'", ";", "}", "// FIXME: unsigned needs to be implemented", "$", "fieldUnsigned", "=", "false", ";", "$", "fieldsDefinitions", "[", "]", "=", "join", "(", "' '", ",", "$", "fieldSql", ")", ";", "$", "fieldsList", "[", "]", "=", "$", "fieldSql", "[", "0", "]", ";", "}", "$", "fields", "=", "join", "(", "', '", ",", "$", "fieldsDefinitions", ")", ";", "$", "tmpTableCreateSql", "=", "\"CREATE TEMPORARY TABLE '$tmpTableName'( $fields );\"", ";", "$", "newTableCreateSql", "=", "\"CREATE TABLE '$tableName'( $fields )\"", ";", "if", "(", "count", "(", "$", "fieldsList", ")", ">", "0", ")", "{", "$", "db", "->", "exec", "(", "$", "tmpTableCreateSql", ")", ";", "$", "db", "->", "exec", "(", "\"INSERT INTO '$tmpTableName' SELECT \"", ".", "join", "(", "', '", ",", "$", "fieldsList", ")", ".", "\" FROM '$tableName';\"", ")", ";", "$", "db", "->", "exec", "(", "\"DROP TABLE '$tableName';\"", ")", ";", "$", "db", "->", "exec", "(", "$", "newTableCreateSql", ")", ";", "$", "db", "->", "exec", "(", "\"INSERT INTO '$tableName' SELECT \"", ".", "join", "(", "', '", ",", "$", "fieldsList", ")", ".", "\" FROM '$tmpTableName';\"", ")", ";", "$", "db", "->", "exec", "(", "\"DROP TABLE '$tmpTableName';\"", ")", ";", "}", "else", "{", "throw", "new", "ezcDbSchemaDropAllColumnsException", "(", "\"Trying to delete all columns in table: $tableName\"", ")", ";", "}", "}" ]
Performs droping field from SQLite table using temporary table (workaround for "ALTER TABLE table DROP field" that not alowed in SQLite ). @param ezcDbHandler $db @param string $tableName @param string $dropFieldName
[ "Performs", "droping", "field", "from", "SQLite", "table", "using", "temporary", "table", "(", "workaround", "for", "ALTER", "TABLE", "table", "DROP", "field", "that", "not", "alowed", "in", "SQLite", ")", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L263-L324
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.generateAddFieldSql
protected function generateAddFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition ) { if ( $fieldDefinition->notNull && $fieldDefinition->default == null ) { $fieldDefinition->default = $this->generateDefault( $fieldDefinition->type, 0 ); } $this->queries[] = "ALTER TABLE '$tableName' ADD " . $this->generateFieldSql( $fieldName, $fieldDefinition ); }
php
protected function generateAddFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition ) { if ( $fieldDefinition->notNull && $fieldDefinition->default == null ) { $fieldDefinition->default = $this->generateDefault( $fieldDefinition->type, 0 ); } $this->queries[] = "ALTER TABLE '$tableName' ADD " . $this->generateFieldSql( $fieldName, $fieldDefinition ); }
[ "protected", "function", "generateAddFieldSql", "(", "$", "tableName", ",", "$", "fieldName", ",", "ezcDbSchemaField", "$", "fieldDefinition", ")", "{", "if", "(", "$", "fieldDefinition", "->", "notNull", "&&", "$", "fieldDefinition", "->", "default", "==", "null", ")", "{", "$", "fieldDefinition", "->", "default", "=", "$", "this", "->", "generateDefault", "(", "$", "fieldDefinition", "->", "type", ",", "0", ")", ";", "}", "$", "this", "->", "queries", "[", "]", "=", "\"ALTER TABLE '$tableName' ADD \"", ".", "$", "this", "->", "generateFieldSql", "(", "$", "fieldName", ",", "$", "fieldDefinition", ")", ";", "}" ]
Adds a "alter table" query to add the field $fieldName to $tableName with the definition $fieldDefinition. @param string $tableName @param string $fieldName @param ezcDbSchemaField $fieldDefinition
[ "Adds", "a", "alter", "table", "query", "to", "add", "the", "field", "$fieldName", "to", "$tableName", "with", "the", "definition", "$fieldDefinition", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L467-L475
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.generateChangeFieldSql
protected function generateChangeFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition ) { $this->queries[] = "ALTER TABLE '$tableName' CHANGE '$fieldName' " . $this->generateFieldSql( $fieldName, $fieldDefinition ); }
php
protected function generateChangeFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition ) { $this->queries[] = "ALTER TABLE '$tableName' CHANGE '$fieldName' " . $this->generateFieldSql( $fieldName, $fieldDefinition ); }
[ "protected", "function", "generateChangeFieldSql", "(", "$", "tableName", ",", "$", "fieldName", ",", "ezcDbSchemaField", "$", "fieldDefinition", ")", "{", "$", "this", "->", "queries", "[", "]", "=", "\"ALTER TABLE '$tableName' CHANGE '$fieldName' \"", ".", "$", "this", "->", "generateFieldSql", "(", "$", "fieldName", ",", "$", "fieldDefinition", ")", ";", "}" ]
Adds a "alter table" query to change the field $fieldName to $tableName with the definition $fieldDefinition. @param string $tableName @param string $fieldName @param ezcDbSchemaField $fieldDefinition
[ "Adds", "a", "alter", "table", "query", "to", "change", "the", "field", "$fieldName", "to", "$tableName", "with", "the", "definition", "$fieldDefinition", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L484-L487
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.generateFieldSql
protected function generateFieldSql( $fieldName, ezcDbSchemaField $fieldDefinition ) { $sqlDefinition = "'$fieldName' "; $defList = array(); $type = $this->convertFromGenericType( $fieldDefinition ); $defList[] = $type; if ( $fieldDefinition->notNull ) { $defList[] = 'NOT NULL'; } if ( $fieldDefinition->autoIncrement ) { $defList[] = "PRIMARY KEY AUTOINCREMENT"; $this->context['skip_primary'] = true; } if ( !is_null( $fieldDefinition->default ) && !$fieldDefinition->autoIncrement ) { $default = $this->generateDefault( $fieldDefinition->type, $fieldDefinition->default ); $defList[] = "DEFAULT $default"; } $sqlDefinition .= join( ' ', $defList ); return $sqlDefinition; }
php
protected function generateFieldSql( $fieldName, ezcDbSchemaField $fieldDefinition ) { $sqlDefinition = "'$fieldName' "; $defList = array(); $type = $this->convertFromGenericType( $fieldDefinition ); $defList[] = $type; if ( $fieldDefinition->notNull ) { $defList[] = 'NOT NULL'; } if ( $fieldDefinition->autoIncrement ) { $defList[] = "PRIMARY KEY AUTOINCREMENT"; $this->context['skip_primary'] = true; } if ( !is_null( $fieldDefinition->default ) && !$fieldDefinition->autoIncrement ) { $default = $this->generateDefault( $fieldDefinition->type, $fieldDefinition->default ); $defList[] = "DEFAULT $default"; } $sqlDefinition .= join( ' ', $defList ); return $sqlDefinition; }
[ "protected", "function", "generateFieldSql", "(", "$", "fieldName", ",", "ezcDbSchemaField", "$", "fieldDefinition", ")", "{", "$", "sqlDefinition", "=", "\"'$fieldName' \"", ";", "$", "defList", "=", "array", "(", ")", ";", "$", "type", "=", "$", "this", "->", "convertFromGenericType", "(", "$", "fieldDefinition", ")", ";", "$", "defList", "[", "]", "=", "$", "type", ";", "if", "(", "$", "fieldDefinition", "->", "notNull", ")", "{", "$", "defList", "[", "]", "=", "'NOT NULL'", ";", "}", "if", "(", "$", "fieldDefinition", "->", "autoIncrement", ")", "{", "$", "defList", "[", "]", "=", "\"PRIMARY KEY AUTOINCREMENT\"", ";", "$", "this", "->", "context", "[", "'skip_primary'", "]", "=", "true", ";", "}", "if", "(", "!", "is_null", "(", "$", "fieldDefinition", "->", "default", ")", "&&", "!", "$", "fieldDefinition", "->", "autoIncrement", ")", "{", "$", "default", "=", "$", "this", "->", "generateDefault", "(", "$", "fieldDefinition", "->", "type", ",", "$", "fieldDefinition", "->", "default", ")", ";", "$", "defList", "[", "]", "=", "\"DEFAULT $default\"", ";", "}", "$", "sqlDefinition", ".=", "join", "(", "' '", ",", "$", "defList", ")", ";", "return", "$", "sqlDefinition", ";", "}" ]
Returns a column definition for $fieldName with definition $fieldDefinition. @param string $fieldName @param ezcDbSchemaField $fieldDefinition @return string
[ "Returns", "a", "column", "definition", "for", "$fieldName", "with", "definition", "$fieldDefinition", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L509-L537
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php
ezcDbSchemaSqliteWriter.generateAddIndexSql
protected function generateAddIndexSql( $tableName, $indexName, ezcDbSchemaIndex $indexDefinition ) { $sql = ""; if ( $indexDefinition->primary ) { if ( $this->context['skip_primary'] ) { return; } if ( $indexName == 'primary' ) { $indexName = $tableName.'_pri'; } $sql = "CREATE UNIQUE INDEX '$indexName' ON '$tableName'"; } else if ( $indexDefinition->unique ) { $sql = "CREATE UNIQUE INDEX '$indexName' ON '$tableName'"; } else { $sql = "CREATE INDEX '$indexName' ON '$tableName'"; } $sql .= " ( "; $indexFieldSql = array(); foreach ( $indexDefinition->indexFields as $indexFieldName => $dummy ) { $indexFieldSql[] = "'$indexFieldName'"; } $sql .= join( ', ', $indexFieldSql ) . " )"; $this->queries[] = $sql; }
php
protected function generateAddIndexSql( $tableName, $indexName, ezcDbSchemaIndex $indexDefinition ) { $sql = ""; if ( $indexDefinition->primary ) { if ( $this->context['skip_primary'] ) { return; } if ( $indexName == 'primary' ) { $indexName = $tableName.'_pri'; } $sql = "CREATE UNIQUE INDEX '$indexName' ON '$tableName'"; } else if ( $indexDefinition->unique ) { $sql = "CREATE UNIQUE INDEX '$indexName' ON '$tableName'"; } else { $sql = "CREATE INDEX '$indexName' ON '$tableName'"; } $sql .= " ( "; $indexFieldSql = array(); foreach ( $indexDefinition->indexFields as $indexFieldName => $dummy ) { $indexFieldSql[] = "'$indexFieldName'"; } $sql .= join( ', ', $indexFieldSql ) . " )"; $this->queries[] = $sql; }
[ "protected", "function", "generateAddIndexSql", "(", "$", "tableName", ",", "$", "indexName", ",", "ezcDbSchemaIndex", "$", "indexDefinition", ")", "{", "$", "sql", "=", "\"\"", ";", "if", "(", "$", "indexDefinition", "->", "primary", ")", "{", "if", "(", "$", "this", "->", "context", "[", "'skip_primary'", "]", ")", "{", "return", ";", "}", "if", "(", "$", "indexName", "==", "'primary'", ")", "{", "$", "indexName", "=", "$", "tableName", ".", "'_pri'", ";", "}", "$", "sql", "=", "\"CREATE UNIQUE INDEX '$indexName' ON '$tableName'\"", ";", "}", "else", "if", "(", "$", "indexDefinition", "->", "unique", ")", "{", "$", "sql", "=", "\"CREATE UNIQUE INDEX '$indexName' ON '$tableName'\"", ";", "}", "else", "{", "$", "sql", "=", "\"CREATE INDEX '$indexName' ON '$tableName'\"", ";", "}", "$", "sql", ".=", "\" ( \"", ";", "$", "indexFieldSql", "=", "array", "(", ")", ";", "foreach", "(", "$", "indexDefinition", "->", "indexFields", "as", "$", "indexFieldName", "=>", "$", "dummy", ")", "{", "$", "indexFieldSql", "[", "]", "=", "\"'$indexFieldName'\"", ";", "}", "$", "sql", ".=", "join", "(", "', '", ",", "$", "indexFieldSql", ")", ".", "\" )\"", ";", "$", "this", "->", "queries", "[", "]", "=", "$", "sql", ";", "}" ]
Adds a "create index" query to add the index $indexName to the table $tableName with definition $indexDefinition to the internal list of queries @param string $tableName @param string $indexName @param ezcDbSchemaIndex $indexDefinition
[ "Adds", "a", "create", "index", "query", "to", "add", "the", "index", "$indexName", "to", "the", "table", "$tableName", "with", "definition", "$indexDefinition", "to", "the", "internal", "list", "of", "queries" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/writer.php#L547-L581
spiral-modules/listing
source/Listing/Filters/ValueFilter.php
ValueFilter.isApplicable
public function isApplicable($value) { if (!is_scalar($value)) { return false; } switch ($this->type) { case self::TYPE_STRING: return is_string($value); case self::TYPE_INT: return is_numeric($value); case self::TYPE_FLOAT: return is_float($value) || is_numeric($value); } throw new FilterException("Invalid filter value type \"{$this->type}\""); }
php
public function isApplicable($value) { if (!is_scalar($value)) { return false; } switch ($this->type) { case self::TYPE_STRING: return is_string($value); case self::TYPE_INT: return is_numeric($value); case self::TYPE_FLOAT: return is_float($value) || is_numeric($value); } throw new FilterException("Invalid filter value type \"{$this->type}\""); }
[ "public", "function", "isApplicable", "(", "$", "value", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "self", "::", "TYPE_STRING", ":", "return", "is_string", "(", "$", "value", ")", ";", "case", "self", "::", "TYPE_INT", ":", "return", "is_numeric", "(", "$", "value", ")", ";", "case", "self", "::", "TYPE_FLOAT", ":", "return", "is_float", "(", "$", "value", ")", "||", "is_numeric", "(", "$", "value", ")", ";", "}", "throw", "new", "FilterException", "(", "\"Invalid filter value type \\\"{$this->type}\\\"\"", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral-modules/listing/blob/89abe8939ce91cbf61b51b99e93ce1e57c8af83c/source/Listing/Filters/ValueFilter.php#L58-L74
spiral-modules/listing
source/Listing/Filters/ValueFilter.php
ValueFilter.withValue
public function withValue($value) { if (!$this->isApplicable($value)) { throw new FilterException("Invalid filtering value, '" . gettype($value) . "' given"); } $filter = clone $this; $filter->value = $this->normalizeValue($value); return $filter; }
php
public function withValue($value) { if (!$this->isApplicable($value)) { throw new FilterException("Invalid filtering value, '" . gettype($value) . "' given"); } $filter = clone $this; $filter->value = $this->normalizeValue($value); return $filter; }
[ "public", "function", "withValue", "(", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "isApplicable", "(", "$", "value", ")", ")", "{", "throw", "new", "FilterException", "(", "\"Invalid filtering value, '\"", ".", "gettype", "(", "$", "value", ")", ".", "\"' given\"", ")", ";", "}", "$", "filter", "=", "clone", "$", "this", ";", "$", "filter", "->", "value", "=", "$", "this", "->", "normalizeValue", "(", "$", "value", ")", ";", "return", "$", "filter", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral-modules/listing/blob/89abe8939ce91cbf61b51b99e93ce1e57c8af83c/source/Listing/Filters/ValueFilter.php#L79-L89
spiral-modules/listing
source/Listing/Filters/ValueFilter.php
ValueFilter.normalizeValue
private function normalizeValue($value) { switch ($this->type) { case self::TYPE_STRING: return trim((string)$value); case self::TYPE_INT: return intval($value); case self::TYPE_FLOAT: return floatval($value); } throw new FilterException("Invalid filter value type \"{$this->type}\""); }
php
private function normalizeValue($value) { switch ($this->type) { case self::TYPE_STRING: return trim((string)$value); case self::TYPE_INT: return intval($value); case self::TYPE_FLOAT: return floatval($value); } throw new FilterException("Invalid filter value type \"{$this->type}\""); }
[ "private", "function", "normalizeValue", "(", "$", "value", ")", "{", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "self", "::", "TYPE_STRING", ":", "return", "trim", "(", "(", "string", ")", "$", "value", ")", ";", "case", "self", "::", "TYPE_INT", ":", "return", "intval", "(", "$", "value", ")", ";", "case", "self", "::", "TYPE_FLOAT", ":", "return", "floatval", "(", "$", "value", ")", ";", "}", "throw", "new", "FilterException", "(", "\"Invalid filter value type \\\"{$this->type}\\\"\"", ")", ";", "}" ]
Normalize input value @param mixed $value @return float|int|string
[ "Normalize", "input", "value" ]
train
https://github.com/spiral-modules/listing/blob/89abe8939ce91cbf61b51b99e93ce1e57c8af83c/source/Listing/Filters/ValueFilter.php#L116-L128
cirrusidentity/simplesamlphp-test-utils
src/Auth/MockAuthSource.php
MockAuthSource.getById
static public function getById(&$authSource, $authSourceId) { self::$authSourceMap[$authSourceId] = &$authSource; // php 5.6 can't seem to use the static map in the closure $map = &self::$authSourceMap; test::double('\SimpleSAML_Auth_Source', [ 'getById' => function & ($authSourceId, $class) use ($map) { $toRet = null; if (array_key_exists($authSourceId, $map)) { $toRet = &$map[$authSourceId]; } return $toRet; } ]); }
php
static public function getById(&$authSource, $authSourceId) { self::$authSourceMap[$authSourceId] = &$authSource; // php 5.6 can't seem to use the static map in the closure $map = &self::$authSourceMap; test::double('\SimpleSAML_Auth_Source', [ 'getById' => function & ($authSourceId, $class) use ($map) { $toRet = null; if (array_key_exists($authSourceId, $map)) { $toRet = &$map[$authSourceId]; } return $toRet; } ]); }
[ "static", "public", "function", "getById", "(", "&", "$", "authSource", ",", "$", "authSourceId", ")", "{", "self", "::", "$", "authSourceMap", "[", "$", "authSourceId", "]", "=", "&", "$", "authSource", ";", "// php 5.6 can't seem to use the static map in the closure", "$", "map", "=", "&", "self", "::", "$", "authSourceMap", ";", "test", "::", "double", "(", "'\\SimpleSAML_Auth_Source'", ",", "[", "'getById'", "=>", "function", "&", "(", "$", "authSourceId", ",", "$", "class", ")", "use", "(", "$", "map", ")", "{", "$", "toRet", "=", "null", ";", "if", "(", "array_key_exists", "(", "$", "authSourceId", ",", "$", "map", ")", ")", "{", "$", "toRet", "=", "&", "$", "map", "[", "$", "authSourceId", "]", ";", "}", "return", "$", "toRet", ";", "}", "]", ")", ";", "}" ]
Return $authSource when SSP tries to load $authSourceId @param \SimpleSAML_Auth_Source $authSource the auth source to return @param string $authSourceId The auth source ID for this $authSource
[ "Return", "$authSource", "when", "SSP", "tries", "to", "load", "$authSourceId" ]
train
https://github.com/cirrusidentity/simplesamlphp-test-utils/blob/79150efb8bca89c180b604dc1d6194f819ebe2b2/src/Auth/MockAuthSource.php#L27-L41
LCPHP/php-aliyun-oss
src/AliyunOSS.php
AliyunOSS.upload
public function upload($file , $path = 'default' , $object = null ){ $bucket = $this->config['bucket']; if (!$object){ $extArr = explode('.', $file); $ext = $extArr[count($extArr) - 1]; $object = md5( $file ) . '.' . $ext; } $object = $path . '/' . $object; try { $res = $this->ossClient->uploadFile($bucket, $object, $file); $result['url'] = isset($this->config['domain'] ) ? $this->config['domain'] . $object : $object ; return $result; } catch (OssException $e) { $this->error = $e->getMessage(); return false; } }
php
public function upload($file , $path = 'default' , $object = null ){ $bucket = $this->config['bucket']; if (!$object){ $extArr = explode('.', $file); $ext = $extArr[count($extArr) - 1]; $object = md5( $file ) . '.' . $ext; } $object = $path . '/' . $object; try { $res = $this->ossClient->uploadFile($bucket, $object, $file); $result['url'] = isset($this->config['domain'] ) ? $this->config['domain'] . $object : $object ; return $result; } catch (OssException $e) { $this->error = $e->getMessage(); return false; } }
[ "public", "function", "upload", "(", "$", "file", ",", "$", "path", "=", "'default'", ",", "$", "object", "=", "null", ")", "{", "$", "bucket", "=", "$", "this", "->", "config", "[", "'bucket'", "]", ";", "if", "(", "!", "$", "object", ")", "{", "$", "extArr", "=", "explode", "(", "'.'", ",", "$", "file", ")", ";", "$", "ext", "=", "$", "extArr", "[", "count", "(", "$", "extArr", ")", "-", "1", "]", ";", "$", "object", "=", "md5", "(", "$", "file", ")", ".", "'.'", ".", "$", "ext", ";", "}", "$", "object", "=", "$", "path", ".", "'/'", ".", "$", "object", ";", "try", "{", "$", "res", "=", "$", "this", "->", "ossClient", "->", "uploadFile", "(", "$", "bucket", ",", "$", "object", ",", "$", "file", ")", ";", "$", "result", "[", "'url'", "]", "=", "isset", "(", "$", "this", "->", "config", "[", "'domain'", "]", ")", "?", "$", "this", "->", "config", "[", "'domain'", "]", ".", "$", "object", ":", "$", "object", ";", "return", "$", "result", ";", "}", "catch", "(", "OssException", "$", "e", ")", "{", "$", "this", "->", "error", "=", "$", "e", "->", "getMessage", "(", ")", ";", "return", "false", ";", "}", "}" ]
上传 @param unknown $file 本地文件 @param unknown $path 上传文件夹 @param unknown $object 上传文件名
[ "上传" ]
train
https://github.com/LCPHP/php-aliyun-oss/blob/4ac2963ccc3ff1a66ee0e245b2f2c4f7f5b01bfd/src/AliyunOSS.php#L57-L79
phpcq/branch-alias-validation
src/Command/ValidateBranchAlias.php
ValidateBranchAlias.getTagFromBranch
protected function getTagFromBranch($branch) { $git = new GitRepository($this->input->getArgument('git-dir')); $tag = trim($git->describe()->tags()->always()->execute($branch)); $hash = trim($git->revParse()->short(false)->execute($branch)); return $hash !== $tag ? $tag : null; }
php
protected function getTagFromBranch($branch) { $git = new GitRepository($this->input->getArgument('git-dir')); $tag = trim($git->describe()->tags()->always()->execute($branch)); $hash = trim($git->revParse()->short(false)->execute($branch)); return $hash !== $tag ? $tag : null; }
[ "protected", "function", "getTagFromBranch", "(", "$", "branch", ")", "{", "$", "git", "=", "new", "GitRepository", "(", "$", "this", "->", "input", "->", "getArgument", "(", "'git-dir'", ")", ")", ";", "$", "tag", "=", "trim", "(", "$", "git", "->", "describe", "(", ")", "->", "tags", "(", ")", "->", "always", "(", ")", "->", "execute", "(", "$", "branch", ")", ")", ";", "$", "hash", "=", "trim", "(", "$", "git", "->", "revParse", "(", ")", "->", "short", "(", "false", ")", "->", "execute", "(", "$", "branch", ")", ")", ";", "return", "$", "hash", "!==", "$", "tag", "?", "$", "tag", ":", "null", ";", "}" ]
Retrieve the latest tag from a branch. @param string $branch The branch name to retrieve the tag from. @return null|string Returns null when no tag has been found, the tag name otherwise.
[ "Retrieve", "the", "latest", "tag", "from", "a", "branch", "." ]
train
https://github.com/phpcq/branch-alias-validation/blob/99ff083af418aad87a6da1331d3924c32137fc76/src/Command/ValidateBranchAlias.php#L86-L92
phpcq/branch-alias-validation
src/Command/ValidateBranchAlias.php
ValidateBranchAlias.validate
public function validate($tag, $alias) { $simpleAlias = preg_replace('~(\.x)?-dev~', '', $alias); $versionLevel = count(explode('.', $simpleAlias)); $reducedTag = preg_replace('~-.*$~', '', $tag); $reducedTag = implode('.', array_slice(explode('.', $reducedTag), 0, $versionLevel)); return version_compare($reducedTag, $simpleAlias, '<='); }
php
public function validate($tag, $alias) { $simpleAlias = preg_replace('~(\.x)?-dev~', '', $alias); $versionLevel = count(explode('.', $simpleAlias)); $reducedTag = preg_replace('~-.*$~', '', $tag); $reducedTag = implode('.', array_slice(explode('.', $reducedTag), 0, $versionLevel)); return version_compare($reducedTag, $simpleAlias, '<='); }
[ "public", "function", "validate", "(", "$", "tag", ",", "$", "alias", ")", "{", "$", "simpleAlias", "=", "preg_replace", "(", "'~(\\.x)?-dev~'", ",", "''", ",", "$", "alias", ")", ";", "$", "versionLevel", "=", "count", "(", "explode", "(", "'.'", ",", "$", "simpleAlias", ")", ")", ";", "$", "reducedTag", "=", "preg_replace", "(", "'~-.*$~'", ",", "''", ",", "$", "tag", ")", ";", "$", "reducedTag", "=", "implode", "(", "'.'", ",", "array_slice", "(", "explode", "(", "'.'", ",", "$", "reducedTag", ")", ",", "0", ",", "$", "versionLevel", ")", ")", ";", "return", "version_compare", "(", "$", "reducedTag", ",", "$", "simpleAlias", ",", "'<='", ")", ";", "}" ]
Validate the given branch. Returns true on success, the name of the offending tag on failure. @param string $tag The tag to check. @param string $alias The alias for the given branch. @return bool|string
[ "Validate", "the", "given", "branch", "." ]
train
https://github.com/phpcq/branch-alias-validation/blob/99ff083af418aad87a6da1331d3924c32137fc76/src/Command/ValidateBranchAlias.php#L105-L113
phpcq/branch-alias-validation
src/Command/ValidateBranchAlias.php
ValidateBranchAlias.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; $exitCode = 0; $git = new GitRepository($this->input->getArgument('git-dir')); $branches = $git->branch()->listBranches()->getNames(); $composer = json_decode(file_get_contents($input->getArgument('git-dir') . '/composer.json'), true); if (!isset($composer['extra']['branch-alias'])) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln('<info>No branch aliases found, skipping test.</info>'); } return 0; } foreach ($composer['extra']['branch-alias'] as $branch => $alias) { $simpleBranch = $this->simplifyBranch($branch); if (!in_array($simpleBranch, $branches)) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln( sprintf( '<info>Skipping non existing branch %s(%s)</info>', $branch, $alias ) ); } continue; } $tag = $this->getTagFromBranch($simpleBranch); // No tag yet, therefore definately before any version. if ($tag === null) { $output->writeln( sprintf( '<comment>Branch alias %s(%s) has not been tagged yet.</comment>', $branch, $alias ) ); } elseif (!$this->validate($tag, $alias)) { $output->writeln( sprintf( '<error>The branch alias %s(%s) is behind the latest branch tag %s!</error>', $branch, $alias, $tag ) ); $exitCode = 1; } else { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln( sprintf( '<info>Branch alias %s(%s) is ahead of the latest branch tag.</info>', $branch, $alias ) ); } } } return $exitCode; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; $exitCode = 0; $git = new GitRepository($this->input->getArgument('git-dir')); $branches = $git->branch()->listBranches()->getNames(); $composer = json_decode(file_get_contents($input->getArgument('git-dir') . '/composer.json'), true); if (!isset($composer['extra']['branch-alias'])) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln('<info>No branch aliases found, skipping test.</info>'); } return 0; } foreach ($composer['extra']['branch-alias'] as $branch => $alias) { $simpleBranch = $this->simplifyBranch($branch); if (!in_array($simpleBranch, $branches)) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln( sprintf( '<info>Skipping non existing branch %s(%s)</info>', $branch, $alias ) ); } continue; } $tag = $this->getTagFromBranch($simpleBranch); // No tag yet, therefore definately before any version. if ($tag === null) { $output->writeln( sprintf( '<comment>Branch alias %s(%s) has not been tagged yet.</comment>', $branch, $alias ) ); } elseif (!$this->validate($tag, $alias)) { $output->writeln( sprintf( '<error>The branch alias %s(%s) is behind the latest branch tag %s!</error>', $branch, $alias, $tag ) ); $exitCode = 1; } else { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln( sprintf( '<info>Branch alias %s(%s) is ahead of the latest branch tag.</info>', $branch, $alias ) ); } } } return $exitCode; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "input", "=", "$", "input", ";", "$", "this", "->", "output", "=", "$", "output", ";", "$", "exitCode", "=", "0", ";", "$", "git", "=", "new", "GitRepository", "(", "$", "this", "->", "input", "->", "getArgument", "(", "'git-dir'", ")", ")", ";", "$", "branches", "=", "$", "git", "->", "branch", "(", ")", "->", "listBranches", "(", ")", "->", "getNames", "(", ")", ";", "$", "composer", "=", "json_decode", "(", "file_get_contents", "(", "$", "input", "->", "getArgument", "(", "'git-dir'", ")", ".", "'/composer.json'", ")", ",", "true", ")", ";", "if", "(", "!", "isset", "(", "$", "composer", "[", "'extra'", "]", "[", "'branch-alias'", "]", ")", ")", "{", "if", "(", "OutputInterface", "::", "VERBOSITY_VERBOSE", "<=", "$", "output", "->", "getVerbosity", "(", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>No branch aliases found, skipping test.</info>'", ")", ";", "}", "return", "0", ";", "}", "foreach", "(", "$", "composer", "[", "'extra'", "]", "[", "'branch-alias'", "]", "as", "$", "branch", "=>", "$", "alias", ")", "{", "$", "simpleBranch", "=", "$", "this", "->", "simplifyBranch", "(", "$", "branch", ")", ";", "if", "(", "!", "in_array", "(", "$", "simpleBranch", ",", "$", "branches", ")", ")", "{", "if", "(", "OutputInterface", "::", "VERBOSITY_VERBOSE", "<=", "$", "output", "->", "getVerbosity", "(", ")", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'<info>Skipping non existing branch %s(%s)</info>'", ",", "$", "branch", ",", "$", "alias", ")", ")", ";", "}", "continue", ";", "}", "$", "tag", "=", "$", "this", "->", "getTagFromBranch", "(", "$", "simpleBranch", ")", ";", "// No tag yet, therefore definately before any version.", "if", "(", "$", "tag", "===", "null", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'<comment>Branch alias %s(%s) has not been tagged yet.</comment>'", ",", "$", "branch", ",", "$", "alias", ")", ")", ";", "}", "elseif", "(", "!", "$", "this", "->", "validate", "(", "$", "tag", ",", "$", "alias", ")", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'<error>The branch alias %s(%s) is behind the latest branch tag %s!</error>'", ",", "$", "branch", ",", "$", "alias", ",", "$", "tag", ")", ")", ";", "$", "exitCode", "=", "1", ";", "}", "else", "{", "if", "(", "OutputInterface", "::", "VERBOSITY_VERBOSE", "<=", "$", "output", "->", "getVerbosity", "(", ")", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'<info>Branch alias %s(%s) is ahead of the latest branch tag.</info>'", ",", "$", "branch", ",", "$", "alias", ")", ")", ";", "}", "}", "}", "return", "$", "exitCode", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phpcq/branch-alias-validation/blob/99ff083af418aad87a6da1331d3924c32137fc76/src/Command/ValidateBranchAlias.php#L118-L184
inhere/php-librarys
src/Traits/PathAliasTrait.php
PathAliasTrait.alias
public static function alias($path, $value = null) { // get path by alias if (\is_string($path) && !$value) { // don't use alias if ($path[0] !== '@') { return $path; } $sep = '/'; $path = str_replace(['/', '\\'], $sep, $path); // only a alias. e.g. @project if (!strpos($path, $sep)) { return self::$aliases[$path] ?? $path; } // have other partial. e.g: @project/temp/logs $realPath = $path; list($alias, $other) = explode($sep, $path, 2); if (isset(self::$aliases[$alias])) { $realPath = self::$aliases[$alias] . $sep . $other; } return $realPath; } if ($path && $value && \is_string($path) && \is_string($value)) { $path = [$path => $value]; } // custom set path's alias. e.g: Slim::alias([ 'alias' => 'path' ]); if (\is_array($path)) { /** * @var string $alias * @var string $realPath */ foreach ($path as $alias => $realPath) { // 1th char must is '@' if ($alias[0] !== '@') { continue; } self::$aliases[$alias] = self::alias($realPath); } } return true; }
php
public static function alias($path, $value = null) { // get path by alias if (\is_string($path) && !$value) { // don't use alias if ($path[0] !== '@') { return $path; } $sep = '/'; $path = str_replace(['/', '\\'], $sep, $path); // only a alias. e.g. @project if (!strpos($path, $sep)) { return self::$aliases[$path] ?? $path; } // have other partial. e.g: @project/temp/logs $realPath = $path; list($alias, $other) = explode($sep, $path, 2); if (isset(self::$aliases[$alias])) { $realPath = self::$aliases[$alias] . $sep . $other; } return $realPath; } if ($path && $value && \is_string($path) && \is_string($value)) { $path = [$path => $value]; } // custom set path's alias. e.g: Slim::alias([ 'alias' => 'path' ]); if (\is_array($path)) { /** * @var string $alias * @var string $realPath */ foreach ($path as $alias => $realPath) { // 1th char must is '@' if ($alias[0] !== '@') { continue; } self::$aliases[$alias] = self::alias($realPath); } } return true; }
[ "public", "static", "function", "alias", "(", "$", "path", ",", "$", "value", "=", "null", ")", "{", "// get path by alias", "if", "(", "\\", "is_string", "(", "$", "path", ")", "&&", "!", "$", "value", ")", "{", "// don't use alias", "if", "(", "$", "path", "[", "0", "]", "!==", "'@'", ")", "{", "return", "$", "path", ";", "}", "$", "sep", "=", "'/'", ";", "$", "path", "=", "str_replace", "(", "[", "'/'", ",", "'\\\\'", "]", ",", "$", "sep", ",", "$", "path", ")", ";", "// only a alias. e.g. @project", "if", "(", "!", "strpos", "(", "$", "path", ",", "$", "sep", ")", ")", "{", "return", "self", "::", "$", "aliases", "[", "$", "path", "]", "??", "$", "path", ";", "}", "// have other partial. e.g: @project/temp/logs", "$", "realPath", "=", "$", "path", ";", "list", "(", "$", "alias", ",", "$", "other", ")", "=", "explode", "(", "$", "sep", ",", "$", "path", ",", "2", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "aliases", "[", "$", "alias", "]", ")", ")", "{", "$", "realPath", "=", "self", "::", "$", "aliases", "[", "$", "alias", "]", ".", "$", "sep", ".", "$", "other", ";", "}", "return", "$", "realPath", ";", "}", "if", "(", "$", "path", "&&", "$", "value", "&&", "\\", "is_string", "(", "$", "path", ")", "&&", "\\", "is_string", "(", "$", "value", ")", ")", "{", "$", "path", "=", "[", "$", "path", "=>", "$", "value", "]", ";", "}", "// custom set path's alias. e.g: Slim::alias([ 'alias' => 'path' ]);", "if", "(", "\\", "is_array", "(", "$", "path", ")", ")", "{", "/**\n * @var string $alias\n * @var string $realPath\n */", "foreach", "(", "$", "path", "as", "$", "alias", "=>", "$", "realPath", ")", "{", "// 1th char must is '@'", "if", "(", "$", "alias", "[", "0", "]", "!==", "'@'", ")", "{", "continue", ";", "}", "self", "::", "$", "aliases", "[", "$", "alias", "]", "=", "self", "::", "alias", "(", "$", "realPath", ")", ";", "}", "}", "return", "true", ";", "}" ]
set/get path alias @param array|string $path @param string|null $value @return bool|string
[ "set", "/", "get", "path", "alias" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/PathAliasTrait.php#L26-L75
odiaseo/pagebuilder
src/PageBuilder/Model/SettingModel.php
SettingModel.getSettingList
public function getSettingList(Site $site) { $settingList = []; $items = $this->getSettingBySiteId($site->getId()); /** @var $setting \PageBuilder\Entity\Setting */ foreach ($items as $setting) { $code = $setting->getSettingKey()->getCode(); $value = $setting->getSettingValue() ?: $setting->getSettingKey()->getDefaultValue(); $settingList[$code] = $value; } $locale = $site->getLocale() ?: 'en_GB'; $settingList = array_merge($settingList, \Locale::parseLocale($locale)); $settingList['locale'] = $locale; return $settingList; }
php
public function getSettingList(Site $site) { $settingList = []; $items = $this->getSettingBySiteId($site->getId()); /** @var $setting \PageBuilder\Entity\Setting */ foreach ($items as $setting) { $code = $setting->getSettingKey()->getCode(); $value = $setting->getSettingValue() ?: $setting->getSettingKey()->getDefaultValue(); $settingList[$code] = $value; } $locale = $site->getLocale() ?: 'en_GB'; $settingList = array_merge($settingList, \Locale::parseLocale($locale)); $settingList['locale'] = $locale; return $settingList; }
[ "public", "function", "getSettingList", "(", "Site", "$", "site", ")", "{", "$", "settingList", "=", "[", "]", ";", "$", "items", "=", "$", "this", "->", "getSettingBySiteId", "(", "$", "site", "->", "getId", "(", ")", ")", ";", "/** @var $setting \\PageBuilder\\Entity\\Setting */", "foreach", "(", "$", "items", "as", "$", "setting", ")", "{", "$", "code", "=", "$", "setting", "->", "getSettingKey", "(", ")", "->", "getCode", "(", ")", ";", "$", "value", "=", "$", "setting", "->", "getSettingValue", "(", ")", "?", ":", "$", "setting", "->", "getSettingKey", "(", ")", "->", "getDefaultValue", "(", ")", ";", "$", "settingList", "[", "$", "code", "]", "=", "$", "value", ";", "}", "$", "locale", "=", "$", "site", "->", "getLocale", "(", ")", "?", ":", "'en_GB'", ";", "$", "settingList", "=", "array_merge", "(", "$", "settingList", ",", "\\", "Locale", "::", "parseLocale", "(", "$", "locale", ")", ")", ";", "$", "settingList", "[", "'locale'", "]", "=", "$", "locale", ";", "return", "$", "settingList", ";", "}" ]
@param $site @return array
[ "@param", "$site" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/SettingModel.php#L20-L36
odiaseo/pagebuilder
src/PageBuilder/Model/SettingModel.php
SettingModel.getSettingBySiteId
public function getSettingBySiteId($siteId) { /** @var $query QueryBuilder */ $params = ['dataSource' => $siteId]; $qb = $this->getFindByQueryBuilder($params, null, 'e', ['id','settingValue']); $qb->addSelect('partial k.{id,code,defaultValue}') ->innerJoin('e.settingKey', 'k'); return $qb->getQuery()->getResult(); }
php
public function getSettingBySiteId($siteId) { /** @var $query QueryBuilder */ $params = ['dataSource' => $siteId]; $qb = $this->getFindByQueryBuilder($params, null, 'e', ['id','settingValue']); $qb->addSelect('partial k.{id,code,defaultValue}') ->innerJoin('e.settingKey', 'k'); return $qb->getQuery()->getResult(); }
[ "public", "function", "getSettingBySiteId", "(", "$", "siteId", ")", "{", "/** @var $query QueryBuilder */", "$", "params", "=", "[", "'dataSource'", "=>", "$", "siteId", "]", ";", "$", "qb", "=", "$", "this", "->", "getFindByQueryBuilder", "(", "$", "params", ",", "null", ",", "'e'", ",", "[", "'id'", ",", "'settingValue'", "]", ")", ";", "$", "qb", "->", "addSelect", "(", "'partial k.{id,code,defaultValue}'", ")", "->", "innerJoin", "(", "'e.settingKey'", ",", "'k'", ")", ";", "return", "$", "qb", "->", "getQuery", "(", ")", "->", "getResult", "(", ")", ";", "}" ]
@param $siteId @return array
[ "@param", "$siteId" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/SettingModel.php#L43-L52
odiaseo/pagebuilder
src/PageBuilder/Model/SettingModel.php
SettingModel.getSettingByKey
public function getSettingByKey($settingKeyId, array $params) { /** @var $query QueryBuilder */ $params['settingKey'] = $settingKeyId; $qb = $this->getFindByQueryBuilder($params, null, 'e'); return $qb->getQuery()->getOneOrNullResult(); }
php
public function getSettingByKey($settingKeyId, array $params) { /** @var $query QueryBuilder */ $params['settingKey'] = $settingKeyId; $qb = $this->getFindByQueryBuilder($params, null, 'e'); return $qb->getQuery()->getOneOrNullResult(); }
[ "public", "function", "getSettingByKey", "(", "$", "settingKeyId", ",", "array", "$", "params", ")", "{", "/** @var $query QueryBuilder */", "$", "params", "[", "'settingKey'", "]", "=", "$", "settingKeyId", ";", "$", "qb", "=", "$", "this", "->", "getFindByQueryBuilder", "(", "$", "params", ",", "null", ",", "'e'", ")", ";", "return", "$", "qb", "->", "getQuery", "(", ")", "->", "getOneOrNullResult", "(", ")", ";", "}" ]
@param $settingKeyId @param array $params @return Setting
[ "@param", "$settingKeyId", "@param", "array", "$params" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/SettingModel.php#L60-L68
tttptd/laravel-responder
src/Traits/ConvertsParameters.php
ConvertsParameters.getConvertedParameters
protected function getConvertedParameters():array { $parameters = $this->all(); $parameters = $this->castBooleans($parameters); $parameters = $this->convertToSnakeCase($parameters); if (method_exists($this, 'convertParameters')) { $parameters = $this->convertParameters($parameters); } return $parameters; }
php
protected function getConvertedParameters():array { $parameters = $this->all(); $parameters = $this->castBooleans($parameters); $parameters = $this->convertToSnakeCase($parameters); if (method_exists($this, 'convertParameters')) { $parameters = $this->convertParameters($parameters); } return $parameters; }
[ "protected", "function", "getConvertedParameters", "(", ")", ":", "array", "{", "$", "parameters", "=", "$", "this", "->", "all", "(", ")", ";", "$", "parameters", "=", "$", "this", "->", "castBooleans", "(", "$", "parameters", ")", ";", "$", "parameters", "=", "$", "this", "->", "convertToSnakeCase", "(", "$", "parameters", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "'convertParameters'", ")", ")", "{", "$", "parameters", "=", "$", "this", "->", "convertParameters", "(", "$", "parameters", ")", ";", "}", "return", "$", "parameters", ";", "}" ]
Cast and convert parameters. @return array
[ "Cast", "and", "convert", "parameters", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Traits/ConvertsParameters.php#L62-L73
tttptd/laravel-responder
src/Traits/ConvertsParameters.php
ConvertsParameters.castBooleans
protected function castBooleans($input):array { if ($this->castToBooleanIsDisabled()) { return []; } $casted = []; foreach ($input as $key => $value) { $casted[$key] = $this->castValueToBoolean($value); } return $casted; }
php
protected function castBooleans($input):array { if ($this->castToBooleanIsDisabled()) { return []; } $casted = []; foreach ($input as $key => $value) { $casted[$key] = $this->castValueToBoolean($value); } return $casted; }
[ "protected", "function", "castBooleans", "(", "$", "input", ")", ":", "array", "{", "if", "(", "$", "this", "->", "castToBooleanIsDisabled", "(", ")", ")", "{", "return", "[", "]", ";", "}", "$", "casted", "=", "[", "]", ";", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "casted", "[", "$", "key", "]", "=", "$", "this", "->", "castValueToBoolean", "(", "$", "value", ")", ";", "}", "return", "$", "casted", ";", "}" ]
Cast all string booleans to real boolean values. @param mixed $input @return array
[ "Cast", "all", "string", "booleans", "to", "real", "boolean", "values", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Traits/ConvertsParameters.php#L88-L101
tttptd/laravel-responder
src/Traits/ConvertsParameters.php
ConvertsParameters.convertToSnakeCase
protected function convertToSnakeCase($input) { if ($this->convertToSnakeCaseIsDisabled()) { return; } if (is_null($input)) { return null; } elseif (is_array($input)) { return $this->convertArrayToSnakeCase($input); } return snake_case($input); }
php
protected function convertToSnakeCase($input) { if ($this->convertToSnakeCaseIsDisabled()) { return; } if (is_null($input)) { return null; } elseif (is_array($input)) { return $this->convertArrayToSnakeCase($input); } return snake_case($input); }
[ "protected", "function", "convertToSnakeCase", "(", "$", "input", ")", "{", "if", "(", "$", "this", "->", "convertToSnakeCaseIsDisabled", "(", ")", ")", "{", "return", ";", "}", "if", "(", "is_null", "(", "$", "input", ")", ")", "{", "return", "null", ";", "}", "elseif", "(", "is_array", "(", "$", "input", ")", ")", "{", "return", "$", "this", "->", "convertArrayToSnakeCase", "(", "$", "input", ")", ";", "}", "return", "snake_case", "(", "$", "input", ")", ";", "}" ]
Convert a string or array to snake case. @param mixed $input @return mixed
[ "Convert", "a", "string", "or", "array", "to", "snake", "case", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Traits/ConvertsParameters.php#L134-L147
tttptd/laravel-responder
src/Traits/ConvertsParameters.php
ConvertsParameters.convertArrayToSnakeCase
protected function convertArrayToSnakeCase(array $input):array { $converted = []; foreach ($input as $key => $value) { $converted[snake_case($key)] = $value; } return $converted; }
php
protected function convertArrayToSnakeCase(array $input):array { $converted = []; foreach ($input as $key => $value) { $converted[snake_case($key)] = $value; } return $converted; }
[ "protected", "function", "convertArrayToSnakeCase", "(", "array", "$", "input", ")", ":", "array", "{", "$", "converted", "=", "[", "]", ";", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "converted", "[", "snake_case", "(", "$", "key", ")", "]", "=", "$", "value", ";", "}", "return", "$", "converted", ";", "}" ]
Convert all keys of an array to snake case. @param array $input @return array
[ "Convert", "all", "keys", "of", "an", "array", "to", "snake", "case", "." ]
train
https://github.com/tttptd/laravel-responder/blob/0e4a32701f0de755c1f1af458045829e1bd6caf6/src/Traits/ConvertsParameters.php#L165-L174
WellCommerce/StandardEditionBundle
DataFixtures/ORM/LoadLocaleData.php
LoadLocaleData.load
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } $locale = new Locale(); $locale->setCode($this->container->getParameter('locale')); $locale->setEnabled(true); $locale->setCurrency($this->getReference('currency_USD')); $manager->persist($locale); $manager->flush(); }
php
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } $locale = new Locale(); $locale->setCode($this->container->getParameter('locale')); $locale->setEnabled(true); $locale->setCurrency($this->getReference('currency_USD')); $manager->persist($locale); $manager->flush(); }
[ "public", "function", "load", "(", "ObjectManager", "$", "manager", ")", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "return", ";", "}", "$", "locale", "=", "new", "Locale", "(", ")", ";", "$", "locale", "->", "setCode", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'locale'", ")", ")", ";", "$", "locale", "->", "setEnabled", "(", "true", ")", ";", "$", "locale", "->", "setCurrency", "(", "$", "this", "->", "getReference", "(", "'currency_USD'", ")", ")", ";", "$", "manager", "->", "persist", "(", "$", "locale", ")", ";", "$", "manager", "->", "flush", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/WellCommerce/StandardEditionBundle/blob/6367bd20bbb6bde37c710a6ba87ae72b5f05f61e/DataFixtures/ORM/LoadLocaleData.php#L29-L41
ajgarlag/AjglSessionConcurrency
src/Http/Session/Registry/SessionRegistry.php
SessionRegistry.refreshLastUsed
public function refreshLastUsed($sessionId, $lastUsed = null) { if ($sessionInformation = $this->getSessionInformation($sessionId)) { if ($sessionInformation->getLastUsed() !== $lastUsed) { $sessionInformation->refreshLastUsed($lastUsed); $this->saveSessionInformation($sessionInformation); } } }
php
public function refreshLastUsed($sessionId, $lastUsed = null) { if ($sessionInformation = $this->getSessionInformation($sessionId)) { if ($sessionInformation->getLastUsed() !== $lastUsed) { $sessionInformation->refreshLastUsed($lastUsed); $this->saveSessionInformation($sessionInformation); } } }
[ "public", "function", "refreshLastUsed", "(", "$", "sessionId", ",", "$", "lastUsed", "=", "null", ")", "{", "if", "(", "$", "sessionInformation", "=", "$", "this", "->", "getSessionInformation", "(", "$", "sessionId", ")", ")", "{", "if", "(", "$", "sessionInformation", "->", "getLastUsed", "(", ")", "!==", "$", "lastUsed", ")", "{", "$", "sessionInformation", "->", "refreshLastUsed", "(", "$", "lastUsed", ")", ";", "$", "this", "->", "saveSessionInformation", "(", "$", "sessionInformation", ")", ";", "}", "}", "}" ]
Updates the given sessionId so its last request time is equal to the present date and time. @param string $sessionId the session identifier key. @param int|null $lastUsed the last request timestamp
[ "Updates", "the", "given", "sessionId", "so", "its", "last", "request", "time", "is", "equal", "to", "the", "present", "date", "and", "time", "." ]
train
https://github.com/ajgarlag/AjglSessionConcurrency/blob/daa3b1ff3ad4951947f7192e12b2496555e135fb/src/Http/Session/Registry/SessionRegistry.php#L64-L72
ajgarlag/AjglSessionConcurrency
src/Http/Session/Registry/SessionRegistry.php
SessionRegistry.expireNow
public function expireNow($sessionId) { if ($sessionInformation = $this->getSessionInformation($sessionId)) { $sessionInformation->expireNow(); $this->saveSessionInformation($sessionInformation); } }
php
public function expireNow($sessionId) { if ($sessionInformation = $this->getSessionInformation($sessionId)) { $sessionInformation->expireNow(); $this->saveSessionInformation($sessionInformation); } }
[ "public", "function", "expireNow", "(", "$", "sessionId", ")", "{", "if", "(", "$", "sessionInformation", "=", "$", "this", "->", "getSessionInformation", "(", "$", "sessionId", ")", ")", "{", "$", "sessionInformation", "->", "expireNow", "(", ")", ";", "$", "this", "->", "saveSessionInformation", "(", "$", "sessionInformation", ")", ";", "}", "}" ]
Expires the given sessionId. @param string $sessionId the session identifier key.
[ "Expires", "the", "given", "sessionId", "." ]
train
https://github.com/ajgarlag/AjglSessionConcurrency/blob/daa3b1ff3ad4951947f7192e12b2496555e135fb/src/Http/Session/Registry/SessionRegistry.php#L79-L85
ajgarlag/AjglSessionConcurrency
src/Http/Session/Registry/SessionRegistry.php
SessionRegistry.registerNewSession
public function registerNewSession($sessionId, $username, $lastUsed = null) { $sessionInformation = new SessionInformation($sessionId, $username, $lastUsed ?: time()); $this->saveSessionInformation($sessionInformation); }
php
public function registerNewSession($sessionId, $username, $lastUsed = null) { $sessionInformation = new SessionInformation($sessionId, $username, $lastUsed ?: time()); $this->saveSessionInformation($sessionInformation); }
[ "public", "function", "registerNewSession", "(", "$", "sessionId", ",", "$", "username", ",", "$", "lastUsed", "=", "null", ")", "{", "$", "sessionInformation", "=", "new", "SessionInformation", "(", "$", "sessionId", ",", "$", "username", ",", "$", "lastUsed", "?", ":", "time", "(", ")", ")", ";", "$", "this", "->", "saveSessionInformation", "(", "$", "sessionInformation", ")", ";", "}" ]
Registers a new session for the given user. @param string $sessionId the session identifier key. @param string $username the given user. @param int $lastUsed
[ "Registers", "a", "new", "session", "for", "the", "given", "user", "." ]
train
https://github.com/ajgarlag/AjglSessionConcurrency/blob/daa3b1ff3ad4951947f7192e12b2496555e135fb/src/Http/Session/Registry/SessionRegistry.php#L94-L99
ajgarlag/AjglSessionConcurrency
src/Http/Session/Registry/SessionRegistry.php
SessionRegistry.collectGarbage
public function collectGarbage($maxLifetime = null) { $maxLifetime = $maxLifetime ?: ini_get('session.gc_maxlifetime'); $this->sessionRegistryStorage->collectGarbage($maxLifetime); }
php
public function collectGarbage($maxLifetime = null) { $maxLifetime = $maxLifetime ?: ini_get('session.gc_maxlifetime'); $this->sessionRegistryStorage->collectGarbage($maxLifetime); }
[ "public", "function", "collectGarbage", "(", "$", "maxLifetime", "=", "null", ")", "{", "$", "maxLifetime", "=", "$", "maxLifetime", "?", ":", "ini_get", "(", "'session.gc_maxlifetime'", ")", ";", "$", "this", "->", "sessionRegistryStorage", "->", "collectGarbage", "(", "$", "maxLifetime", ")", ";", "}" ]
Removes sessions information which last used timestamp is older than the given lifetime. @param int $maxLifetime
[ "Removes", "sessions", "information", "which", "last", "used", "timestamp", "is", "older", "than", "the", "given", "lifetime", "." ]
train
https://github.com/ajgarlag/AjglSessionConcurrency/blob/daa3b1ff3ad4951947f7192e12b2496555e135fb/src/Http/Session/Registry/SessionRegistry.php#L117-L121
DevGroup-ru/yii2-users-module
src/models/RegistrationForm.php
RegistrationForm.register
public function register() { if (!$this->validate()) { return false; } /** @var User $user */ $user = Yii::createObject(ModelMapHelper::User()); $user->setAttributes($this->attributes); $result = $user->register(); if ($user->hasErrors()) { foreach ($user->errors as $attribute => $errors) { foreach ($errors as $error) { $this->addError($attribute, $error); } } } return $result; }
php
public function register() { if (!$this->validate()) { return false; } /** @var User $user */ $user = Yii::createObject(ModelMapHelper::User()); $user->setAttributes($this->attributes); $result = $user->register(); if ($user->hasErrors()) { foreach ($user->errors as $attribute => $errors) { foreach ($errors as $error) { $this->addError($attribute, $error); } } } return $result; }
[ "public", "function", "register", "(", ")", "{", "if", "(", "!", "$", "this", "->", "validate", "(", ")", ")", "{", "return", "false", ";", "}", "/** @var User $user */", "$", "user", "=", "Yii", "::", "createObject", "(", "ModelMapHelper", "::", "User", "(", ")", ")", ";", "$", "user", "->", "setAttributes", "(", "$", "this", "->", "attributes", ")", ";", "$", "result", "=", "$", "user", "->", "register", "(", ")", ";", "if", "(", "$", "user", "->", "hasErrors", "(", ")", ")", "{", "foreach", "(", "$", "user", "->", "errors", "as", "$", "attribute", "=>", "$", "errors", ")", "{", "foreach", "(", "$", "errors", "as", "$", "error", ")", "{", "$", "this", "->", "addError", "(", "$", "attribute", ",", "$", "error", ")", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Performs registration of user. Returns User object on success or false on failure. @return bool|User @throws \yii\base\InvalidConfigException
[ "Performs", "registration", "of", "user", ".", "Returns", "User", "object", "on", "success", "or", "false", "on", "failure", "." ]
train
https://github.com/DevGroup-ru/yii2-users-module/blob/ff0103dc55c3462627ccc704c33e70c96053f750/src/models/RegistrationForm.php#L64-L85
mekras/atompub
src/Element/Workspace.php
Workspace.getCollections
public function getCollections() { return $this->getCachedProperty( 'collections', function () { $result = []; /** @var \DOMNodeList $items */ // No REQUIRED — no exception. $items = $this->query('app:collection'); foreach ($items as $item) { $result[] = $this->getExtensions()->parseElement($this, $item); } return $result; } ); }
php
public function getCollections() { return $this->getCachedProperty( 'collections', function () { $result = []; /** @var \DOMNodeList $items */ // No REQUIRED — no exception. $items = $this->query('app:collection'); foreach ($items as $item) { $result[] = $this->getExtensions()->parseElement($this, $item); } return $result; } ); }
[ "public", "function", "getCollections", "(", ")", "{", "return", "$", "this", "->", "getCachedProperty", "(", "'collections'", ",", "function", "(", ")", "{", "$", "result", "=", "[", "]", ";", "/** @var \\DOMNodeList $items */", "// No REQUIRED — no exception.", "$", "items", "=", "$", "this", "->", "query", "(", "'app:collection'", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "result", "[", "]", "=", "$", "this", "->", "getExtensions", "(", ")", "->", "parseElement", "(", "$", "this", ",", "$", "item", ")", ";", "}", "return", "$", "result", ";", "}", ")", ";", "}" ]
Return collections. @return Collection[] @since 1.0
[ "Return", "collections", "." ]
train
https://github.com/mekras/atompub/blob/cfc9aab97cff7a822b720e1dd84ef16733183dbb/src/Element/Workspace.php#L30-L46
mekras/atompub
src/Element/Workspace.php
Workspace.addCollection
public function addCollection($title) { $collections = $this->getCollections(); /** @var Collection $collection */ $collection = $this->getExtensions()->createElement($this, 'app:collection'); $collection->addTitle($title); $collections[] = $collection; $this->setCachedProperty('collections', $collections); return $collection; }
php
public function addCollection($title) { $collections = $this->getCollections(); /** @var Collection $collection */ $collection = $this->getExtensions()->createElement($this, 'app:collection'); $collection->addTitle($title); $collections[] = $collection; $this->setCachedProperty('collections', $collections); return $collection; }
[ "public", "function", "addCollection", "(", "$", "title", ")", "{", "$", "collections", "=", "$", "this", "->", "getCollections", "(", ")", ";", "/** @var Collection $collection */", "$", "collection", "=", "$", "this", "->", "getExtensions", "(", ")", "->", "createElement", "(", "$", "this", ",", "'app:collection'", ")", ";", "$", "collection", "->", "addTitle", "(", "$", "title", ")", ";", "$", "collections", "[", "]", "=", "$", "collection", ";", "$", "this", "->", "setCachedProperty", "(", "'collections'", ",", "$", "collections", ")", ";", "return", "$", "collection", ";", "}" ]
Add new Collection @param string $title @return Collection @since 1.0
[ "Add", "new", "Collection" ]
train
https://github.com/mekras/atompub/blob/cfc9aab97cff7a822b720e1dd84ef16733183dbb/src/Element/Workspace.php#L57-L69
i-lateral/silverstripe-modeladminplus
src/GridFieldDateFinder.php
GridFieldDateFinder.convertDateFields
public function convertDateFields() { $grid_field = $this->getGridField(); $config = $grid_field->getConfig(); $db = Config::inst()->get($grid_field->getModelClass(), "db"); $dates = self::config()->date_fields; $fields = $this->findDateFields(); // First setup columns foreach ($config->getComponents() as $component) { $class = get_class($component); $is_header = ($component instanceof GridFieldSortableHeader); $is_columns = ClassInfo::classImplements( $class, GridField_ColumnProvider::class ); // If we are working with a set of data columns, look for // date/datetime columns if ($is_columns && method_exists($component, "getDisplayFields")) { $display_fields = $component->getDisplayFields($grid_field); foreach ($fields as $field) { $display_fields = $this->changeKeys( $field["Sort"], $field["Column"], $display_fields ); } $component->setDisplayFields($display_fields); } // If we are working with sortable headers, look for // date/datetime columns if ($is_header && count($component->getFieldSorting()) == 0) { $sort_fields = []; foreach ($fields as $field) { $sort_fields[$field["Column"]] = $field["Sort"]; } $component->setFieldSorting($sort_fields); } } $this->setGridField($grid_field); return $this; }
php
public function convertDateFields() { $grid_field = $this->getGridField(); $config = $grid_field->getConfig(); $db = Config::inst()->get($grid_field->getModelClass(), "db"); $dates = self::config()->date_fields; $fields = $this->findDateFields(); // First setup columns foreach ($config->getComponents() as $component) { $class = get_class($component); $is_header = ($component instanceof GridFieldSortableHeader); $is_columns = ClassInfo::classImplements( $class, GridField_ColumnProvider::class ); // If we are working with a set of data columns, look for // date/datetime columns if ($is_columns && method_exists($component, "getDisplayFields")) { $display_fields = $component->getDisplayFields($grid_field); foreach ($fields as $field) { $display_fields = $this->changeKeys( $field["Sort"], $field["Column"], $display_fields ); } $component->setDisplayFields($display_fields); } // If we are working with sortable headers, look for // date/datetime columns if ($is_header && count($component->getFieldSorting()) == 0) { $sort_fields = []; foreach ($fields as $field) { $sort_fields[$field["Column"]] = $field["Sort"]; } $component->setFieldSorting($sort_fields); } } $this->setGridField($grid_field); return $this; }
[ "public", "function", "convertDateFields", "(", ")", "{", "$", "grid_field", "=", "$", "this", "->", "getGridField", "(", ")", ";", "$", "config", "=", "$", "grid_field", "->", "getConfig", "(", ")", ";", "$", "db", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "grid_field", "->", "getModelClass", "(", ")", ",", "\"db\"", ")", ";", "$", "dates", "=", "self", "::", "config", "(", ")", "->", "date_fields", ";", "$", "fields", "=", "$", "this", "->", "findDateFields", "(", ")", ";", "// First setup columns", "foreach", "(", "$", "config", "->", "getComponents", "(", ")", "as", "$", "component", ")", "{", "$", "class", "=", "get_class", "(", "$", "component", ")", ";", "$", "is_header", "=", "(", "$", "component", "instanceof", "GridFieldSortableHeader", ")", ";", "$", "is_columns", "=", "ClassInfo", "::", "classImplements", "(", "$", "class", ",", "GridField_ColumnProvider", "::", "class", ")", ";", "// If we are working with a set of data columns, look for", "// date/datetime columns", "if", "(", "$", "is_columns", "&&", "method_exists", "(", "$", "component", ",", "\"getDisplayFields\"", ")", ")", "{", "$", "display_fields", "=", "$", "component", "->", "getDisplayFields", "(", "$", "grid_field", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "display_fields", "=", "$", "this", "->", "changeKeys", "(", "$", "field", "[", "\"Sort\"", "]", ",", "$", "field", "[", "\"Column\"", "]", ",", "$", "display_fields", ")", ";", "}", "$", "component", "->", "setDisplayFields", "(", "$", "display_fields", ")", ";", "}", "// If we are working with sortable headers, look for", "// date/datetime columns", "if", "(", "$", "is_header", "&&", "count", "(", "$", "component", "->", "getFieldSorting", "(", ")", ")", "==", "0", ")", "{", "$", "sort_fields", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "sort_fields", "[", "$", "field", "[", "\"Column\"", "]", "]", "=", "$", "field", "[", "\"Sort\"", "]", ";", "}", "$", "component", "->", "setFieldSorting", "(", "$", "sort_fields", ")", ";", "}", "}", "$", "this", "->", "setGridField", "(", "$", "grid_field", ")", ";", "return", "$", "this", ";", "}" ]
Get any date fields from the passed list and convert to .Nice format. @param GridField $field GridField want to convert @return self
[ "Get", "any", "date", "fields", "from", "the", "passed", "list", "and", "convert", "to", ".", "Nice", "format", "." ]
train
https://github.com/i-lateral/silverstripe-modeladminplus/blob/c5209d9610cdb36ddc7b9231fad342df7e75ffc0/src/GridFieldDateFinder.php#L59-L104
i-lateral/silverstripe-modeladminplus
src/GridFieldDateFinder.php
GridFieldDateFinder.findDateFields
public function findDateFields() { $grid_field = $this->getGridField(); $config = $grid_field->getConfig(); $class = $grid_field->getModelClass(); $obj = $class::singleton(); $fields = []; // First setup columns foreach ($config->getComponents() as $component) { // If we are working with a set of data columns, look for // date/datetime columns if ($this->isColumnProvider($component) && method_exists($component, "getDisplayFields")) { foreach ($component->getDisplayFields($grid_field) as $k => $v) { $field = $obj->dbObject($k); if (isset($field) && $field instanceof DBDate) { $fields[] = [ "Title" => $v, "Column" => $k . $this->getDateType(), "Sort" => $k ]; } } } } return $fields; }
php
public function findDateFields() { $grid_field = $this->getGridField(); $config = $grid_field->getConfig(); $class = $grid_field->getModelClass(); $obj = $class::singleton(); $fields = []; // First setup columns foreach ($config->getComponents() as $component) { // If we are working with a set of data columns, look for // date/datetime columns if ($this->isColumnProvider($component) && method_exists($component, "getDisplayFields")) { foreach ($component->getDisplayFields($grid_field) as $k => $v) { $field = $obj->dbObject($k); if (isset($field) && $field instanceof DBDate) { $fields[] = [ "Title" => $v, "Column" => $k . $this->getDateType(), "Sort" => $k ]; } } } } return $fields; }
[ "public", "function", "findDateFields", "(", ")", "{", "$", "grid_field", "=", "$", "this", "->", "getGridField", "(", ")", ";", "$", "config", "=", "$", "grid_field", "->", "getConfig", "(", ")", ";", "$", "class", "=", "$", "grid_field", "->", "getModelClass", "(", ")", ";", "$", "obj", "=", "$", "class", "::", "singleton", "(", ")", ";", "$", "fields", "=", "[", "]", ";", "// First setup columns", "foreach", "(", "$", "config", "->", "getComponents", "(", ")", "as", "$", "component", ")", "{", "// If we are working with a set of data columns, look for", "// date/datetime columns", "if", "(", "$", "this", "->", "isColumnProvider", "(", "$", "component", ")", "&&", "method_exists", "(", "$", "component", ",", "\"getDisplayFields\"", ")", ")", "{", "foreach", "(", "$", "component", "->", "getDisplayFields", "(", "$", "grid_field", ")", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "field", "=", "$", "obj", "->", "dbObject", "(", "$", "k", ")", ";", "if", "(", "isset", "(", "$", "field", ")", "&&", "$", "field", "instanceof", "DBDate", ")", "{", "$", "fields", "[", "]", "=", "[", "\"Title\"", "=>", "$", "v", ",", "\"Column\"", "=>", "$", "k", ".", "$", "this", "->", "getDateType", "(", ")", ",", "\"Sort\"", "=>", "$", "k", "]", ";", "}", "}", "}", "}", "return", "$", "fields", ";", "}" ]
Create an array of fields, titles and values that we use to setup sortable fields in the following format: - Title (the human readable name of the column) - Column (the actual field used to display data) - Sort (DB the column used to sort the data) @return array
[ "Create", "an", "array", "of", "fields", "titles", "and", "values", "that", "we", "use", "to", "setup", "sortable", "fields", "in", "the", "following", "format", ":" ]
train
https://github.com/i-lateral/silverstripe-modeladminplus/blob/c5209d9610cdb36ddc7b9231fad342df7e75ffc0/src/GridFieldDateFinder.php#L116-L143
i-lateral/silverstripe-modeladminplus
src/GridFieldDateFinder.php
GridFieldDateFinder.changeKeys
public function changeKeys($original, $new, &$array) { foreach ($array as $k => $v) { $res[$k === $original ? $new : $k] = $v; } return $res; }
php
public function changeKeys($original, $new, &$array) { foreach ($array as $k => $v) { $res[$k === $original ? $new : $k] = $v; } return $res; }
[ "public", "function", "changeKeys", "(", "$", "original", ",", "$", "new", ",", "&", "$", "array", ")", "{", "foreach", "(", "$", "array", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "res", "[", "$", "k", "===", "$", "original", "?", "$", "new", ":", "$", "k", "]", "=", "$", "v", ";", "}", "return", "$", "res", ";", "}" ]
Change the array keys on the provided array to the provided alternative (thanks to: https://stackoverflow.com/a/14227644/4161644) @param string $original Original key @param string $new New key @param array $array Haystack array @return array
[ "Change", "the", "array", "keys", "on", "the", "provided", "array", "to", "the", "provided", "alternative", "(", "thanks", "to", ":", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "14227644", "/", "4161644", ")" ]
train
https://github.com/i-lateral/silverstripe-modeladminplus/blob/c5209d9610cdb36ddc7b9231fad342df7e75ffc0/src/GridFieldDateFinder.php#L170-L176
mikebarlow/html-helper
src/Helpers/Form.php
Form.open
public function open($method, $action = '', $attr = array()) { // check if they wish to send a file // default to post method and add the enctype needed to send files $method = strtolower($method); if ($method === 'file') { $method = 'post'; $attr['enctype'] = 'multipart/form-data'; } if (! in_array($method, array('post', 'get'))) { $method = 'post'; } $attr['method'] = $method; $attr['action'] = $action; return $this->Html->tag('form', $attr); }
php
public function open($method, $action = '', $attr = array()) { // check if they wish to send a file // default to post method and add the enctype needed to send files $method = strtolower($method); if ($method === 'file') { $method = 'post'; $attr['enctype'] = 'multipart/form-data'; } if (! in_array($method, array('post', 'get'))) { $method = 'post'; } $attr['method'] = $method; $attr['action'] = $action; return $this->Html->tag('form', $attr); }
[ "public", "function", "open", "(", "$", "method", ",", "$", "action", "=", "''", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "// check if they wish to send a file", "// default to post method and add the enctype needed to send files", "$", "method", "=", "strtolower", "(", "$", "method", ")", ";", "if", "(", "$", "method", "===", "'file'", ")", "{", "$", "method", "=", "'post'", ";", "$", "attr", "[", "'enctype'", "]", "=", "'multipart/form-data'", ";", "}", "if", "(", "!", "in_array", "(", "$", "method", ",", "array", "(", "'post'", ",", "'get'", ")", ")", ")", "{", "$", "method", "=", "'post'", ";", "}", "$", "attr", "[", "'method'", "]", "=", "$", "method", ";", "$", "attr", "[", "'action'", "]", "=", "$", "action", ";", "return", "$", "this", "->", "Html", "->", "tag", "(", "'form'", ",", "$", "attr", ")", ";", "}" ]
open a form @param string Type of form, get / post / file (adds as post and adds enctype) etc... @param string Action for the form @param array Array of extra params @return string
[ "open", "a", "form" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L57-L75
mikebarlow/html-helper
src/Helpers/Form.php
Form.hidden
public function hidden($name, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array('type' => 'hidden', 'wrapper' => false) ) ); }
php
public function hidden($name, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array('type' => 'hidden', 'wrapper' => false) ) ); }
[ "public", "function", "hidden", "(", "$", "name", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "false", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'hidden'", ",", "'wrapper'", "=>", "false", ")", ")", ")", ";", "}" ]
shortcut for hidden input field @param string input name (dot notation for multi-dimensional array) @param array input attributes @return string
[ "shortcut", "for", "hidden", "input", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L106-L116
mikebarlow/html-helper
src/Helpers/Form.php
Form.password
public function password($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'password') ) ); }
php
public function password($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'password') ) ); }
[ "public", "function", "password", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'password'", ")", ")", ")", ";", "}" ]
shortcut for password field @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array input attributes @return string
[ "shortcut", "for", "password", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L126-L136
mikebarlow/html-helper
src/Helpers/Form.php
Form.textarea
public function textarea($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'textarea') ) ); }
php
public function textarea($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'textarea') ) ); }
[ "public", "function", "textarea", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'textarea'", ")", ")", ")", ";", "}" ]
shortcut for textarea field @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array input attributes @return string
[ "shortcut", "for", "textarea", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L146-L156
mikebarlow/html-helper
src/Helpers/Form.php
Form.file
public function file($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'file') ) ); }
php
public function file($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'file') ) ); }
[ "public", "function", "file", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'file'", ")", ")", ")", ";", "}" ]
shortcut for file field @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array input attributes @return string
[ "shortcut", "for", "file", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L166-L176
mikebarlow/html-helper
src/Helpers/Form.php
Form.checkbox
public function checkbox($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'checkbox') ) ); }
php
public function checkbox($name, $label, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array('type' => 'checkbox') ) ); }
[ "public", "function", "checkbox", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'checkbox'", ")", ")", ")", ";", "}" ]
shortcut for checkbox field @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array input attributes @return string
[ "shortcut", "for", "checkbox", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L186-L196
mikebarlow/html-helper
src/Helpers/Form.php
Form.submit
public function submit($name, $label, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array( 'type' => 'submit', 'value' => $label ) ) ); }
php
public function submit($name, $label, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array( 'type' => 'submit', 'value' => $label ) ) ); }
[ "public", "function", "submit", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "false", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'submit'", ",", "'value'", "=>", "$", "label", ")", ")", ")", ";", "}" ]
generate a submit input @param string dot notation form for input - will match with Input handler and prefill if found @param string label for form, pass false to not show label @param array array of extra options for the input @return string form element
[ "generate", "a", "submit", "input" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L206-L219
mikebarlow/html-helper
src/Helpers/Form.php
Form.button
public function button($name, $label, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array( 'type' => 'button', 'value' => $label ) ) ); }
php
public function button($name, $label, $attr = array()) { return $this->input( $name, false, array_merge( $attr, array( 'type' => 'button', 'value' => $label ) ) ); }
[ "public", "function", "button", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "false", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'button'", ",", "'value'", "=>", "$", "label", ")", ")", ")", ";", "}" ]
generate a button input @param string dot notation form for input - will match with Input handler and prefill if found @param string label for form, pass false to not show label @param array array of extra options for the input @return string form element
[ "generate", "a", "button", "input" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L229-L242
mikebarlow/html-helper
src/Helpers/Form.php
Form.select
public function select($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'select', 'options' => $options ) ) ); }
php
public function select($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'select', 'options' => $options ) ) ); }
[ "public", "function", "select", "(", "$", "name", ",", "$", "label", ",", "$", "options", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'select'", ",", "'options'", "=>", "$", "options", ")", ")", ")", ";", "}" ]
generate a select @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array Select Options @param array input attributes @return string
[ "generate", "a", "select" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L253-L266
mikebarlow/html-helper
src/Helpers/Form.php
Form.radio
public function radio($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'radio', 'options' => $options ) ) ); }
php
public function radio($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'radio', 'options' => $options ) ) ); }
[ "public", "function", "radio", "(", "$", "name", ",", "$", "label", ",", "$", "options", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'radio'", ",", "'options'", "=>", "$", "options", ")", ")", ")", ";", "}" ]
generate a group of radio buttons @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array radio Options @param array input attributes @return string
[ "generate", "a", "group", "of", "radio", "buttons" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L277-L290
mikebarlow/html-helper
src/Helpers/Form.php
Form.multiselect
public function multiselect($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'select', 'options' => $options, 'multiple' ) ) ); }
php
public function multiselect($name, $label, $options, $attr = array()) { return $this->input( $name, $label, array_merge( $attr, array( 'type' => 'select', 'options' => $options, 'multiple' ) ) ); }
[ "public", "function", "multiselect", "(", "$", "name", ",", "$", "label", ",", "$", "options", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "input", "(", "$", "name", ",", "$", "label", ",", "array_merge", "(", "$", "attr", ",", "array", "(", "'type'", "=>", "'select'", ",", "'options'", "=>", "$", "options", ",", "'multiple'", ")", ")", ")", ";", "}" ]
generate a select @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array Select Options @param array input attributes @return string
[ "generate", "a", "select" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L301-L315
mikebarlow/html-helper
src/Helpers/Form.php
Form.input
public function input($name, $label, $attr = array()) { // generate an id if none exists if (empty($attr['id'])) { $attr['id'] = $this->transformNameForID($name); } // build the label if ($label !== false) { $labelAttr = []; if (is_array($label)) { $labelAttr = $label; $label = (! empty($label['value'])) ? $label['value'] : $name; unset($labelAttr['value']); } $labelAttr['for'] = $attr['id']; $label = $this->label($label, $labelAttr); } else { $label = ''; } // remove any wrapper attributes // these will be dealt with later $wrapper = array(); if (isset($attr['wrapper'])) { $wrapper = $attr['wrapper']; unset($attr['wrapper']); } // any before / between / after set // $attr passed by reference $injects = $this->getInjects($attr); // generate the actual field if (empty($attr['type'])) { $attr['type'] = 'text'; } $field = $this->generateField( $name, $attr ); // build the contents for the wrapper $contents = $this->buildField($attr['type'], $label, $field, $injects); // check if they actually want a wrapper if (isset($wrapper) && $wrapper === false) { return $contents; } // build up the wrapper info // should return the tag and attributes array $wrapperInfo = $this->getWrapper($wrapper, $attr); // return the final wrapper tag with the contents return $this->Html->tag( $wrapperInfo['tag'], $wrapperInfo['attr'], $contents, true ); }
php
public function input($name, $label, $attr = array()) { // generate an id if none exists if (empty($attr['id'])) { $attr['id'] = $this->transformNameForID($name); } // build the label if ($label !== false) { $labelAttr = []; if (is_array($label)) { $labelAttr = $label; $label = (! empty($label['value'])) ? $label['value'] : $name; unset($labelAttr['value']); } $labelAttr['for'] = $attr['id']; $label = $this->label($label, $labelAttr); } else { $label = ''; } // remove any wrapper attributes // these will be dealt with later $wrapper = array(); if (isset($attr['wrapper'])) { $wrapper = $attr['wrapper']; unset($attr['wrapper']); } // any before / between / after set // $attr passed by reference $injects = $this->getInjects($attr); // generate the actual field if (empty($attr['type'])) { $attr['type'] = 'text'; } $field = $this->generateField( $name, $attr ); // build the contents for the wrapper $contents = $this->buildField($attr['type'], $label, $field, $injects); // check if they actually want a wrapper if (isset($wrapper) && $wrapper === false) { return $contents; } // build up the wrapper info // should return the tag and attributes array $wrapperInfo = $this->getWrapper($wrapper, $attr); // return the final wrapper tag with the contents return $this->Html->tag( $wrapperInfo['tag'], $wrapperInfo['attr'], $contents, true ); }
[ "public", "function", "input", "(", "$", "name", ",", "$", "label", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "// generate an id if none exists", "if", "(", "empty", "(", "$", "attr", "[", "'id'", "]", ")", ")", "{", "$", "attr", "[", "'id'", "]", "=", "$", "this", "->", "transformNameForID", "(", "$", "name", ")", ";", "}", "// build the label", "if", "(", "$", "label", "!==", "false", ")", "{", "$", "labelAttr", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "label", ")", ")", "{", "$", "labelAttr", "=", "$", "label", ";", "$", "label", "=", "(", "!", "empty", "(", "$", "label", "[", "'value'", "]", ")", ")", "?", "$", "label", "[", "'value'", "]", ":", "$", "name", ";", "unset", "(", "$", "labelAttr", "[", "'value'", "]", ")", ";", "}", "$", "labelAttr", "[", "'for'", "]", "=", "$", "attr", "[", "'id'", "]", ";", "$", "label", "=", "$", "this", "->", "label", "(", "$", "label", ",", "$", "labelAttr", ")", ";", "}", "else", "{", "$", "label", "=", "''", ";", "}", "// remove any wrapper attributes", "// these will be dealt with later", "$", "wrapper", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "attr", "[", "'wrapper'", "]", ")", ")", "{", "$", "wrapper", "=", "$", "attr", "[", "'wrapper'", "]", ";", "unset", "(", "$", "attr", "[", "'wrapper'", "]", ")", ";", "}", "// any before / between / after set", "// $attr passed by reference", "$", "injects", "=", "$", "this", "->", "getInjects", "(", "$", "attr", ")", ";", "// generate the actual field", "if", "(", "empty", "(", "$", "attr", "[", "'type'", "]", ")", ")", "{", "$", "attr", "[", "'type'", "]", "=", "'text'", ";", "}", "$", "field", "=", "$", "this", "->", "generateField", "(", "$", "name", ",", "$", "attr", ")", ";", "// build the contents for the wrapper", "$", "contents", "=", "$", "this", "->", "buildField", "(", "$", "attr", "[", "'type'", "]", ",", "$", "label", ",", "$", "field", ",", "$", "injects", ")", ";", "// check if they actually want a wrapper", "if", "(", "isset", "(", "$", "wrapper", ")", "&&", "$", "wrapper", "===", "false", ")", "{", "return", "$", "contents", ";", "}", "// build up the wrapper info", "// should return the tag and attributes array", "$", "wrapperInfo", "=", "$", "this", "->", "getWrapper", "(", "$", "wrapper", ",", "$", "attr", ")", ";", "// return the final wrapper tag with the contents", "return", "$", "this", "->", "Html", "->", "tag", "(", "$", "wrapperInfo", "[", "'tag'", "]", ",", "$", "wrapperInfo", "[", "'attr'", "]", ",", "$", "contents", ",", "true", ")", ";", "}" ]
generate a complete input with wrapped div and label @param string input name (dot notation for multi-dimensional array) @param string|array Label string or array of label value and attributes @param array input attributes @return string
[ "generate", "a", "complete", "input", "with", "wrapped", "div", "and", "label" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L325-L388
mikebarlow/html-helper
src/Helpers/Form.php
Form.buildField
public function buildField($type, $label, $field, $injects) { $format = $this->orderFormat['default']; if (isset($this->orderFormat[$type])) { $format = $this->orderFormat[$type]; } $output = ''; foreach ($format as $item) { if ($item == 'label') { $output .= $label; } elseif ($item == 'field') { $output .= $field; } elseif (isset($injects[$item])) { $output .= $injects[$item]; } } return $output; }
php
public function buildField($type, $label, $field, $injects) { $format = $this->orderFormat['default']; if (isset($this->orderFormat[$type])) { $format = $this->orderFormat[$type]; } $output = ''; foreach ($format as $item) { if ($item == 'label') { $output .= $label; } elseif ($item == 'field') { $output .= $field; } elseif (isset($injects[$item])) { $output .= $injects[$item]; } } return $output; }
[ "public", "function", "buildField", "(", "$", "type", ",", "$", "label", ",", "$", "field", ",", "$", "injects", ")", "{", "$", "format", "=", "$", "this", "->", "orderFormat", "[", "'default'", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "orderFormat", "[", "$", "type", "]", ")", ")", "{", "$", "format", "=", "$", "this", "->", "orderFormat", "[", "$", "type", "]", ";", "}", "$", "output", "=", "''", ";", "foreach", "(", "$", "format", "as", "$", "item", ")", "{", "if", "(", "$", "item", "==", "'label'", ")", "{", "$", "output", ".=", "$", "label", ";", "}", "elseif", "(", "$", "item", "==", "'field'", ")", "{", "$", "output", ".=", "$", "field", ";", "}", "elseif", "(", "isset", "(", "$", "injects", "[", "$", "item", "]", ")", ")", "{", "$", "output", ".=", "$", "injects", "[", "$", "item", "]", ";", "}", "}", "return", "$", "output", ";", "}" ]
build the label / field / injects format slightly different for checkboxs @param string the field type @param string label tag / empty string @param string field tag @param array array of the before / between / after injects @return string
[ "build", "the", "label", "/", "field", "/", "injects", "format", "slightly", "different", "for", "checkboxs" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L400-L420
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateField
public function generateField($name, $attr = array()) { $tag = 'input'; if (in_array($attr['type'], $this->customGenerate)) { $tag = $attr['type']; } $attr['name'] = $this->transformName($name); $attr = $this->getData($name, $attr); if ($tag !== 'input') { $generate = 'generate' . ucfirst(strtolower($tag)) . 'Field'; return $this->{$generate}($attr); } else { return $this->Html->tag('input', $attr); } }
php
public function generateField($name, $attr = array()) { $tag = 'input'; if (in_array($attr['type'], $this->customGenerate)) { $tag = $attr['type']; } $attr['name'] = $this->transformName($name); $attr = $this->getData($name, $attr); if ($tag !== 'input') { $generate = 'generate' . ucfirst(strtolower($tag)) . 'Field'; return $this->{$generate}($attr); } else { return $this->Html->tag('input', $attr); } }
[ "public", "function", "generateField", "(", "$", "name", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "$", "tag", "=", "'input'", ";", "if", "(", "in_array", "(", "$", "attr", "[", "'type'", "]", ",", "$", "this", "->", "customGenerate", ")", ")", "{", "$", "tag", "=", "$", "attr", "[", "'type'", "]", ";", "}", "$", "attr", "[", "'name'", "]", "=", "$", "this", "->", "transformName", "(", "$", "name", ")", ";", "$", "attr", "=", "$", "this", "->", "getData", "(", "$", "name", ",", "$", "attr", ")", ";", "if", "(", "$", "tag", "!==", "'input'", ")", "{", "$", "generate", "=", "'generate'", ".", "ucfirst", "(", "strtolower", "(", "$", "tag", ")", ")", ".", "'Field'", ";", "return", "$", "this", "->", "{", "$", "generate", "}", "(", "$", "attr", ")", ";", "}", "else", "{", "return", "$", "this", "->", "Html", "->", "tag", "(", "'input'", ",", "$", "attr", ")", ";", "}", "}" ]
generate a field @param string The type of input field to create @param array Array of attributes for the tag @return string
[ "generate", "a", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L429-L446
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateRadioField
public function generateRadioField($attr) { if (empty($attr['name'])) { return ''; } $out = ''; $options = array(); if (! empty($attr['options'])) { $options = $attr['options']; } if (isset($attr['checked'])) { $checkedItem = $attr['checked']; } unset($attr['options'], $attr['checked']); foreach ($options as $value => $label) { $id = $attr['id'] . '_' . $value; $optionsAttr = array('id' => $id, 'value' => $value); if (isset($checkedItem) && $checkedItem == $value) { $optionsAttr[] = 'checked'; } $input = $this->Html->tag( 'input', array_merge( $attr, $optionsAttr ) ); $label = $this->Html->tag( 'label', array('for' => $id), $label, true ); $out .= $this->Html->tag( 'div', array( 'class' => 'radio-item' ), $input . $label, true ); } return $out; }
php
public function generateRadioField($attr) { if (empty($attr['name'])) { return ''; } $out = ''; $options = array(); if (! empty($attr['options'])) { $options = $attr['options']; } if (isset($attr['checked'])) { $checkedItem = $attr['checked']; } unset($attr['options'], $attr['checked']); foreach ($options as $value => $label) { $id = $attr['id'] . '_' . $value; $optionsAttr = array('id' => $id, 'value' => $value); if (isset($checkedItem) && $checkedItem == $value) { $optionsAttr[] = 'checked'; } $input = $this->Html->tag( 'input', array_merge( $attr, $optionsAttr ) ); $label = $this->Html->tag( 'label', array('for' => $id), $label, true ); $out .= $this->Html->tag( 'div', array( 'class' => 'radio-item' ), $input . $label, true ); } return $out; }
[ "public", "function", "generateRadioField", "(", "$", "attr", ")", "{", "if", "(", "empty", "(", "$", "attr", "[", "'name'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "out", "=", "''", ";", "$", "options", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'options'", "]", ")", ")", "{", "$", "options", "=", "$", "attr", "[", "'options'", "]", ";", "}", "if", "(", "isset", "(", "$", "attr", "[", "'checked'", "]", ")", ")", "{", "$", "checkedItem", "=", "$", "attr", "[", "'checked'", "]", ";", "}", "unset", "(", "$", "attr", "[", "'options'", "]", ",", "$", "attr", "[", "'checked'", "]", ")", ";", "foreach", "(", "$", "options", "as", "$", "value", "=>", "$", "label", ")", "{", "$", "id", "=", "$", "attr", "[", "'id'", "]", ".", "'_'", ".", "$", "value", ";", "$", "optionsAttr", "=", "array", "(", "'id'", "=>", "$", "id", ",", "'value'", "=>", "$", "value", ")", ";", "if", "(", "isset", "(", "$", "checkedItem", ")", "&&", "$", "checkedItem", "==", "$", "value", ")", "{", "$", "optionsAttr", "[", "]", "=", "'checked'", ";", "}", "$", "input", "=", "$", "this", "->", "Html", "->", "tag", "(", "'input'", ",", "array_merge", "(", "$", "attr", ",", "$", "optionsAttr", ")", ")", ";", "$", "label", "=", "$", "this", "->", "Html", "->", "tag", "(", "'label'", ",", "array", "(", "'for'", "=>", "$", "id", ")", ",", "$", "label", ",", "true", ")", ";", "$", "out", ".=", "$", "this", "->", "Html", "->", "tag", "(", "'div'", ",", "array", "(", "'class'", "=>", "'radio-item'", ")", ",", "$", "input", ".", "$", "label", ",", "true", ")", ";", "}", "return", "$", "out", ";", "}" ]
generate a selection of radio buttons @param array array of attributes @return string
[ "generate", "a", "selection", "of", "radio", "buttons" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L454-L506
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateCheckboxField
public function generateCheckboxField($attr) { if (empty($attr['name'])) { return ''; } $out = ''; if ((isset($attr['hiddenCheckbox']) && $attr['hiddenCheckbox']) || ! isset($attr['hiddenCheckbox'])) { $out .= $this->input( $attr['name'], false, array( 'type' => 'hidden', 'wrapper' => false, 'id' => '_' . $attr['id'], 'value' => 0 ) ); } unset($attr['hiddenCheckbox']); if (! isset($attr['value'])) { $attr['value'] = 1; } $out .= $this->Html->tag('input', $attr); return $out; }
php
public function generateCheckboxField($attr) { if (empty($attr['name'])) { return ''; } $out = ''; if ((isset($attr['hiddenCheckbox']) && $attr['hiddenCheckbox']) || ! isset($attr['hiddenCheckbox'])) { $out .= $this->input( $attr['name'], false, array( 'type' => 'hidden', 'wrapper' => false, 'id' => '_' . $attr['id'], 'value' => 0 ) ); } unset($attr['hiddenCheckbox']); if (! isset($attr['value'])) { $attr['value'] = 1; } $out .= $this->Html->tag('input', $attr); return $out; }
[ "public", "function", "generateCheckboxField", "(", "$", "attr", ")", "{", "if", "(", "empty", "(", "$", "attr", "[", "'name'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "out", "=", "''", ";", "if", "(", "(", "isset", "(", "$", "attr", "[", "'hiddenCheckbox'", "]", ")", "&&", "$", "attr", "[", "'hiddenCheckbox'", "]", ")", "||", "!", "isset", "(", "$", "attr", "[", "'hiddenCheckbox'", "]", ")", ")", "{", "$", "out", ".=", "$", "this", "->", "input", "(", "$", "attr", "[", "'name'", "]", ",", "false", ",", "array", "(", "'type'", "=>", "'hidden'", ",", "'wrapper'", "=>", "false", ",", "'id'", "=>", "'_'", ".", "$", "attr", "[", "'id'", "]", ",", "'value'", "=>", "0", ")", ")", ";", "}", "unset", "(", "$", "attr", "[", "'hiddenCheckbox'", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "attr", "[", "'value'", "]", ")", ")", "{", "$", "attr", "[", "'value'", "]", "=", "1", ";", "}", "$", "out", ".=", "$", "this", "->", "Html", "->", "tag", "(", "'input'", ",", "$", "attr", ")", ";", "return", "$", "out", ";", "}" ]
generate a checkbox @param array array of attributes @return string
[ "generate", "a", "checkbox" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L514-L542
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateTextareaField
public function generateTextareaField($attr) { if (empty($attr['name'])) { return ''; } $contents = ''; if (! empty($attr['value'])) { $contents = $attr['value']; } unset($attr['type'], $attr['value']); return $this->Html->tag('textarea', $attr, $contents, true); }
php
public function generateTextareaField($attr) { if (empty($attr['name'])) { return ''; } $contents = ''; if (! empty($attr['value'])) { $contents = $attr['value']; } unset($attr['type'], $attr['value']); return $this->Html->tag('textarea', $attr, $contents, true); }
[ "public", "function", "generateTextareaField", "(", "$", "attr", ")", "{", "if", "(", "empty", "(", "$", "attr", "[", "'name'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "contents", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'value'", "]", ")", ")", "{", "$", "contents", "=", "$", "attr", "[", "'value'", "]", ";", "}", "unset", "(", "$", "attr", "[", "'type'", "]", ",", "$", "attr", "[", "'value'", "]", ")", ";", "return", "$", "this", "->", "Html", "->", "tag", "(", "'textarea'", ",", "$", "attr", ",", "$", "contents", ",", "true", ")", ";", "}" ]
generate a textarea @param array array of attributes @return string
[ "generate", "a", "textarea" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L550-L563
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateButtonField
public function generateButtonField($attr) { $value = 'Submit'; if (! empty($attr['value'])) { $value = $attr['value']; } unset($attr['value'], $attr['type']); return $this->Html->tag('button', $attr, $value, true); }
php
public function generateButtonField($attr) { $value = 'Submit'; if (! empty($attr['value'])) { $value = $attr['value']; } unset($attr['value'], $attr['type']); return $this->Html->tag('button', $attr, $value, true); }
[ "public", "function", "generateButtonField", "(", "$", "attr", ")", "{", "$", "value", "=", "'Submit'", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'value'", "]", ")", ")", "{", "$", "value", "=", "$", "attr", "[", "'value'", "]", ";", "}", "unset", "(", "$", "attr", "[", "'value'", "]", ",", "$", "attr", "[", "'type'", "]", ")", ";", "return", "$", "this", "->", "Html", "->", "tag", "(", "'button'", ",", "$", "attr", ",", "$", "value", ",", "true", ")", ";", "}" ]
generate a button @param array array of attributes @return string
[ "generate", "a", "button" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L571-L581
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateSelectField
public function generateSelectField($attr) { if (empty($attr['name'])) { return ''; } $options = array(); if (! empty($attr['options'])) { $options = $attr['options']; } $options = $this->generateSelectOptions($options, $attr); unset($attr['options'], $attr['type'], $attr['selected']); return $this->Html->tag('select', $attr, $options, true); }
php
public function generateSelectField($attr) { if (empty($attr['name'])) { return ''; } $options = array(); if (! empty($attr['options'])) { $options = $attr['options']; } $options = $this->generateSelectOptions($options, $attr); unset($attr['options'], $attr['type'], $attr['selected']); return $this->Html->tag('select', $attr, $options, true); }
[ "public", "function", "generateSelectField", "(", "$", "attr", ")", "{", "if", "(", "empty", "(", "$", "attr", "[", "'name'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "options", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'options'", "]", ")", ")", "{", "$", "options", "=", "$", "attr", "[", "'options'", "]", ";", "}", "$", "options", "=", "$", "this", "->", "generateSelectOptions", "(", "$", "options", ",", "$", "attr", ")", ";", "unset", "(", "$", "attr", "[", "'options'", "]", ",", "$", "attr", "[", "'type'", "]", ",", "$", "attr", "[", "'selected'", "]", ")", ";", "return", "$", "this", "->", "Html", "->", "tag", "(", "'select'", ",", "$", "attr", ",", "$", "options", ",", "true", ")", ";", "}" ]
generate a select field @param array array of attributes @return string
[ "generate", "a", "select", "field" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L589-L605
mikebarlow/html-helper
src/Helpers/Form.php
Form.generateSelectOptions
public function generateSelectOptions($options, $attr) { $return = ''; foreach ($options as $key => $value) { if (is_array($value)) { $subArray = $this->generateSelectOptions($value, $attr); $return .= $this->Html->tag( 'optgroup', array( 'label' => $key ), $subArray, true ); } else { $optionsAttr = array('value' => $key); if (isset($attr['selected']) && $attr['selected'] == $key) { $optionsAttr[] = 'selected'; } $return .= $this->Html->tag( 'option', $optionsAttr, $value, true ); } } return $return; }
php
public function generateSelectOptions($options, $attr) { $return = ''; foreach ($options as $key => $value) { if (is_array($value)) { $subArray = $this->generateSelectOptions($value, $attr); $return .= $this->Html->tag( 'optgroup', array( 'label' => $key ), $subArray, true ); } else { $optionsAttr = array('value' => $key); if (isset($attr['selected']) && $attr['selected'] == $key) { $optionsAttr[] = 'selected'; } $return .= $this->Html->tag( 'option', $optionsAttr, $value, true ); } } return $return; }
[ "public", "function", "generateSelectOptions", "(", "$", "options", ",", "$", "attr", ")", "{", "$", "return", "=", "''", ";", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "subArray", "=", "$", "this", "->", "generateSelectOptions", "(", "$", "value", ",", "$", "attr", ")", ";", "$", "return", ".=", "$", "this", "->", "Html", "->", "tag", "(", "'optgroup'", ",", "array", "(", "'label'", "=>", "$", "key", ")", ",", "$", "subArray", ",", "true", ")", ";", "}", "else", "{", "$", "optionsAttr", "=", "array", "(", "'value'", "=>", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "attr", "[", "'selected'", "]", ")", "&&", "$", "attr", "[", "'selected'", "]", "==", "$", "key", ")", "{", "$", "optionsAttr", "[", "]", "=", "'selected'", ";", "}", "$", "return", ".=", "$", "this", "->", "Html", "->", "tag", "(", "'option'", ",", "$", "optionsAttr", ",", "$", "value", ",", "true", ")", ";", "}", "}", "return", "$", "return", ";", "}" ]
generate the options for a select box @param array array of options @param array array of attributes @return string
[ "generate", "the", "options", "for", "a", "select", "box" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L625-L658
mikebarlow/html-helper
src/Helpers/Form.php
Form.transformName
public function transformName($name) { if (strpos($name, '.') !== false) { $bits = explode('.', $name, 2); $bits['1'] = '[' . str_replace('.', '][', $bits['1']) . ']'; return implode('', $bits); } else { return $name; } }
php
public function transformName($name) { if (strpos($name, '.') !== false) { $bits = explode('.', $name, 2); $bits['1'] = '[' . str_replace('.', '][', $bits['1']) . ']'; return implode('', $bits); } else { return $name; } }
[ "public", "function", "transformName", "(", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'.'", ")", "!==", "false", ")", "{", "$", "bits", "=", "explode", "(", "'.'", ",", "$", "name", ",", "2", ")", ";", "$", "bits", "[", "'1'", "]", "=", "'['", ".", "str_replace", "(", "'.'", ",", "']['", ",", "$", "bits", "[", "'1'", "]", ")", ".", "']'", ";", "return", "implode", "(", "''", ",", "$", "bits", ")", ";", "}", "else", "{", "return", "$", "name", ";", "}", "}" ]
transform the dot notation name into proper name @param string Dot notation input name @return string transformed name for input
[ "transform", "the", "dot", "notation", "name", "into", "proper", "name" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L666-L675
mikebarlow/html-helper
src/Helpers/Form.php
Form.transformNameForID
public function transformNameForID($name) { $bits = explode('.', $name); array_walk( $bits, function (&$value, $key) { $value = ucfirst(strtolower($value)); } ); return implode('', $bits); }
php
public function transformNameForID($name) { $bits = explode('.', $name); array_walk( $bits, function (&$value, $key) { $value = ucfirst(strtolower($value)); } ); return implode('', $bits); }
[ "public", "function", "transformNameForID", "(", "$", "name", ")", "{", "$", "bits", "=", "explode", "(", "'.'", ",", "$", "name", ")", ";", "array_walk", "(", "$", "bits", ",", "function", "(", "&", "$", "value", ",", "$", "key", ")", "{", "$", "value", "=", "ucfirst", "(", "strtolower", "(", "$", "value", ")", ")", ";", "}", ")", ";", "return", "implode", "(", "''", ",", "$", "bits", ")", ";", "}" ]
transform the dot notation name into a name for input ID if no ID was passed @param string Dot notation input name @return string transformed name for input ID
[ "transform", "the", "dot", "notation", "name", "into", "a", "name", "for", "input", "ID", "if", "no", "ID", "was", "passed" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L684-L694
mikebarlow/html-helper
src/Helpers/Form.php
Form.getInjects
public function getInjects(&$attr) { $inject = array( 'before' => '', 'between' => '', 'after' => '' ); if (! empty($attr['before'])) { $inject['before'] = $attr['before']; unset($attr['before']); } if (! empty($attr['between'])) { $inject['between'] = $attr['between']; unset($attr['between']); } if (! empty($attr['after'])) { $inject['after'] = $attr['after']; unset($attr['after']); } return $inject; }
php
public function getInjects(&$attr) { $inject = array( 'before' => '', 'between' => '', 'after' => '' ); if (! empty($attr['before'])) { $inject['before'] = $attr['before']; unset($attr['before']); } if (! empty($attr['between'])) { $inject['between'] = $attr['between']; unset($attr['between']); } if (! empty($attr['after'])) { $inject['after'] = $attr['after']; unset($attr['after']); } return $inject; }
[ "public", "function", "getInjects", "(", "&", "$", "attr", ")", "{", "$", "inject", "=", "array", "(", "'before'", "=>", "''", ",", "'between'", "=>", "''", ",", "'after'", "=>", "''", ")", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'before'", "]", ")", ")", "{", "$", "inject", "[", "'before'", "]", "=", "$", "attr", "[", "'before'", "]", ";", "unset", "(", "$", "attr", "[", "'before'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "attr", "[", "'between'", "]", ")", ")", "{", "$", "inject", "[", "'between'", "]", "=", "$", "attr", "[", "'between'", "]", ";", "unset", "(", "$", "attr", "[", "'between'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "attr", "[", "'after'", "]", ")", ")", "{", "$", "inject", "[", "'after'", "]", "=", "$", "attr", "[", "'after'", "]", ";", "unset", "(", "$", "attr", "[", "'after'", "]", ")", ";", "}", "return", "$", "inject", ";", "}" ]
get injections from the attributes allows data to be entered before, between, after @param array attributes array (Passed by reference) @return array
[ "get", "injections", "from", "the", "attributes", "allows", "data", "to", "be", "entered", "before", "between", "after" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L703-L727
mikebarlow/html-helper
src/Helpers/Form.php
Form.getWrapper
public function getWrapper($wrapper, $attr) { $type = ''; if (! empty($attr['type'])) { $type = ' ' . $attr['type']; if ((isset($attr['type']) && $attr['type'] == 'select') && in_array('multiple', $attr)) { $type .= ' multiselect'; } } $defaults = array( 'tag' => 'div', 'class' => 'input' . $type ); $wrapperAttr = array_merge( $defaults, $wrapper ); // double check for the presence of a tag element $tag = $wrapperAttr['tag']; unset($wrapperAttr['tag']); return array( 'tag' => $tag, 'attr' => $wrapperAttr ); }
php
public function getWrapper($wrapper, $attr) { $type = ''; if (! empty($attr['type'])) { $type = ' ' . $attr['type']; if ((isset($attr['type']) && $attr['type'] == 'select') && in_array('multiple', $attr)) { $type .= ' multiselect'; } } $defaults = array( 'tag' => 'div', 'class' => 'input' . $type ); $wrapperAttr = array_merge( $defaults, $wrapper ); // double check for the presence of a tag element $tag = $wrapperAttr['tag']; unset($wrapperAttr['tag']); return array( 'tag' => $tag, 'attr' => $wrapperAttr ); }
[ "public", "function", "getWrapper", "(", "$", "wrapper", ",", "$", "attr", ")", "{", "$", "type", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "attr", "[", "'type'", "]", ")", ")", "{", "$", "type", "=", "' '", ".", "$", "attr", "[", "'type'", "]", ";", "if", "(", "(", "isset", "(", "$", "attr", "[", "'type'", "]", ")", "&&", "$", "attr", "[", "'type'", "]", "==", "'select'", ")", "&&", "in_array", "(", "'multiple'", ",", "$", "attr", ")", ")", "{", "$", "type", ".=", "' multiselect'", ";", "}", "}", "$", "defaults", "=", "array", "(", "'tag'", "=>", "'div'", ",", "'class'", "=>", "'input'", ".", "$", "type", ")", ";", "$", "wrapperAttr", "=", "array_merge", "(", "$", "defaults", ",", "$", "wrapper", ")", ";", "// double check for the presence of a tag element", "$", "tag", "=", "$", "wrapperAttr", "[", "'tag'", "]", ";", "unset", "(", "$", "wrapperAttr", "[", "'tag'", "]", ")", ";", "return", "array", "(", "'tag'", "=>", "$", "tag", ",", "'attr'", "=>", "$", "wrapperAttr", ")", ";", "}" ]
given any user defined wrapper instructions build the wrapper data @param array Array of any passed wrapper info @param array Array of the inputs attributes @return array two element array of tag / attr
[ "given", "any", "user", "defined", "wrapper", "instructions", "build", "the", "wrapper", "data" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L737-L766
mikebarlow/html-helper
src/Helpers/Form.php
Form.getData
public function getData($name, $attr) { if (empty($name)) { return $attr; } $value = $this->Data->getValue($name); if ($value !== null) { $isCheckbox = (isset($attr['type']) && $attr['type'] == 'checkbox'); $isRadio = (isset($attr['type']) && $attr['type'] == 'radio'); $isSelect = (isset($attr['type']) && $attr['type'] == 'select'); if ($isCheckbox) { $attr[] = 'checked'; } elseif ($isRadio) { $attr['checked'] = $value; } elseif ($isSelect) { $attr['selected'] = $value; } else { $attr['value'] = $value; } } return $attr; }
php
public function getData($name, $attr) { if (empty($name)) { return $attr; } $value = $this->Data->getValue($name); if ($value !== null) { $isCheckbox = (isset($attr['type']) && $attr['type'] == 'checkbox'); $isRadio = (isset($attr['type']) && $attr['type'] == 'radio'); $isSelect = (isset($attr['type']) && $attr['type'] == 'select'); if ($isCheckbox) { $attr[] = 'checked'; } elseif ($isRadio) { $attr['checked'] = $value; } elseif ($isSelect) { $attr['selected'] = $value; } else { $attr['value'] = $value; } } return $attr; }
[ "public", "function", "getData", "(", "$", "name", ",", "$", "attr", ")", "{", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "$", "attr", ";", "}", "$", "value", "=", "$", "this", "->", "Data", "->", "getValue", "(", "$", "name", ")", ";", "if", "(", "$", "value", "!==", "null", ")", "{", "$", "isCheckbox", "=", "(", "isset", "(", "$", "attr", "[", "'type'", "]", ")", "&&", "$", "attr", "[", "'type'", "]", "==", "'checkbox'", ")", ";", "$", "isRadio", "=", "(", "isset", "(", "$", "attr", "[", "'type'", "]", ")", "&&", "$", "attr", "[", "'type'", "]", "==", "'radio'", ")", ";", "$", "isSelect", "=", "(", "isset", "(", "$", "attr", "[", "'type'", "]", ")", "&&", "$", "attr", "[", "'type'", "]", "==", "'select'", ")", ";", "if", "(", "$", "isCheckbox", ")", "{", "$", "attr", "[", "]", "=", "'checked'", ";", "}", "elseif", "(", "$", "isRadio", ")", "{", "$", "attr", "[", "'checked'", "]", "=", "$", "value", ";", "}", "elseif", "(", "$", "isSelect", ")", "{", "$", "attr", "[", "'selected'", "]", "=", "$", "value", ";", "}", "else", "{", "$", "attr", "[", "'value'", "]", "=", "$", "value", ";", "}", "}", "return", "$", "attr", ";", "}" ]
use the Data interface and find any post data @param string input name (dot notation for multi-dimensional array) @param array Array of attributes for the tag @return array Return the attribute array with added post data
[ "use", "the", "Data", "interface", "and", "find", "any", "post", "data" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L775-L800
mikebarlow/html-helper
src/Helpers/Form.php
Form.setData
public function setData($Data) { if (! is_object($Data) || ! $Data instanceof Data) { throw new \InvalidArgumentException( 'The Data Interface must be a valid Data Object' ); } $this->Data = $Data; return true; }
php
public function setData($Data) { if (! is_object($Data) || ! $Data instanceof Data) { throw new \InvalidArgumentException( 'The Data Interface must be a valid Data Object' ); } $this->Data = $Data; return true; }
[ "public", "function", "setData", "(", "$", "Data", ")", "{", "if", "(", "!", "is_object", "(", "$", "Data", ")", "||", "!", "$", "Data", "instanceof", "Data", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The Data Interface must be a valid Data Object'", ")", ";", "}", "$", "this", "->", "Data", "=", "$", "Data", ";", "return", "true", ";", "}" ]
check and set the form data interface @param Object Instance of an Data Interface @return bool @throws \InvalidArgumentException
[ "check", "and", "set", "the", "form", "data", "interface" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L809-L819
mikebarlow/html-helper
src/Helpers/Form.php
Form.setHtml
public function setHtml($Html) { if (! is_object($Html) || ! $Html instanceof HtmlObject) { throw new \InvalidArgumentException( 'The HTML Object must be a valid HTML Object' ); } $this->Html = $Html; return true; }
php
public function setHtml($Html) { if (! is_object($Html) || ! $Html instanceof HtmlObject) { throw new \InvalidArgumentException( 'The HTML Object must be a valid HTML Object' ); } $this->Html = $Html; return true; }
[ "public", "function", "setHtml", "(", "$", "Html", ")", "{", "if", "(", "!", "is_object", "(", "$", "Html", ")", "||", "!", "$", "Html", "instanceof", "HtmlObject", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The HTML Object must be a valid HTML Object'", ")", ";", "}", "$", "this", "->", "Html", "=", "$", "Html", ";", "return", "true", ";", "}" ]
check and set the HTML Object @param Object Instance of an Html @return bool @throws \InvalidArgumentException
[ "check", "and", "set", "the", "HTML", "Object" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Helpers/Form.php#L838-L848
technote-space/wordpress-plugin-base
src/classes/models/lib/mail.php
Mail.send
public function send( $to, $subject, $body, $text = false ) { if ( $this->_is_sending || empty( $to ) || empty( $subject ) || ( empty( $body ) && empty( $text ) ) ) { return false; } $subject = str_replace( [ "\r\n", "\r", "\n" ], '', $subject ); $this->remove_special_space( $subject ); $this->remove_special_space( $body ); if ( ! is_array( $body ) ) { $body = [ 'text/html' => $body ]; } if ( ! empty( $text ) ) { $this->remove_special_space( $text ); $body['text/plain'] = $text; } $cssToInlineStyles = new CssToInlineStyles; $messages = []; $content_type = 'text/html'; foreach ( $body as $type => $message ) { is_array( $message ) and $message = reset( $messages ); if ( 'text/html' === $type ) { $message = $this->get_view( 'common/mail', [ 'subject' => $subject, 'body' => $message ] ); $message = $cssToInlineStyles->convert( $message ); $message = preg_replace( '/<\s*style.*?>[\s\S]*<\s*\/style\s*>/', '', $message ); } elseif ( 'text/plain' !== $type ) { continue; } $messages[ $type ] = $message; $content_type = $type; } if ( empty( $messages ) ) { return false; } if ( count( $messages ) > 1 ) { $content_type = 'multipart/alternative'; } // このチケットがマージされたら以下の処理は不要 // https://core.trac.wordpress.org/ticket/15448 add_action( 'phpmailer_init', $set_phpmailer = function ( $phpmailer ) use ( &$set_phpmailer, $messages, $content_type ) { /** @var \PHPMailer $phpmailer */ remove_action( 'phpmailer_init', $set_phpmailer ); $phpmailer->Body = ''; $phpmailer->AltBody = ''; foreach ( $messages as $type => $message ) { if ( 'text/html' === $type ) { $phpmailer->Body = $message; } elseif ( 'text/plain' === $type ) { $phpmailer->AltBody = $message; } } $phpmailer->ContentType = $content_type; } ); // suppress error if ( ! isset( $_SERVER['SERVER_NAME'] ) ) { $_SERVER['SERVER_NAME'] = ''; } // is sending $this->_is_sending = true; $result = wp_mail( $to, $subject, reset( $messages ) ); $this->_is_sending = false; return $result; }
php
public function send( $to, $subject, $body, $text = false ) { if ( $this->_is_sending || empty( $to ) || empty( $subject ) || ( empty( $body ) && empty( $text ) ) ) { return false; } $subject = str_replace( [ "\r\n", "\r", "\n" ], '', $subject ); $this->remove_special_space( $subject ); $this->remove_special_space( $body ); if ( ! is_array( $body ) ) { $body = [ 'text/html' => $body ]; } if ( ! empty( $text ) ) { $this->remove_special_space( $text ); $body['text/plain'] = $text; } $cssToInlineStyles = new CssToInlineStyles; $messages = []; $content_type = 'text/html'; foreach ( $body as $type => $message ) { is_array( $message ) and $message = reset( $messages ); if ( 'text/html' === $type ) { $message = $this->get_view( 'common/mail', [ 'subject' => $subject, 'body' => $message ] ); $message = $cssToInlineStyles->convert( $message ); $message = preg_replace( '/<\s*style.*?>[\s\S]*<\s*\/style\s*>/', '', $message ); } elseif ( 'text/plain' !== $type ) { continue; } $messages[ $type ] = $message; $content_type = $type; } if ( empty( $messages ) ) { return false; } if ( count( $messages ) > 1 ) { $content_type = 'multipart/alternative'; } // このチケットがマージされたら以下の処理は不要 // https://core.trac.wordpress.org/ticket/15448 add_action( 'phpmailer_init', $set_phpmailer = function ( $phpmailer ) use ( &$set_phpmailer, $messages, $content_type ) { /** @var \PHPMailer $phpmailer */ remove_action( 'phpmailer_init', $set_phpmailer ); $phpmailer->Body = ''; $phpmailer->AltBody = ''; foreach ( $messages as $type => $message ) { if ( 'text/html' === $type ) { $phpmailer->Body = $message; } elseif ( 'text/plain' === $type ) { $phpmailer->AltBody = $message; } } $phpmailer->ContentType = $content_type; } ); // suppress error if ( ! isset( $_SERVER['SERVER_NAME'] ) ) { $_SERVER['SERVER_NAME'] = ''; } // is sending $this->_is_sending = true; $result = wp_mail( $to, $subject, reset( $messages ) ); $this->_is_sending = false; return $result; }
[ "public", "function", "send", "(", "$", "to", ",", "$", "subject", ",", "$", "body", ",", "$", "text", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_is_sending", "||", "empty", "(", "$", "to", ")", "||", "empty", "(", "$", "subject", ")", "||", "(", "empty", "(", "$", "body", ")", "&&", "empty", "(", "$", "text", ")", ")", ")", "{", "return", "false", ";", "}", "$", "subject", "=", "str_replace", "(", "[", "\"\\r\\n\"", ",", "\"\\r\"", ",", "\"\\n\"", "]", ",", "''", ",", "$", "subject", ")", ";", "$", "this", "->", "remove_special_space", "(", "$", "subject", ")", ";", "$", "this", "->", "remove_special_space", "(", "$", "body", ")", ";", "if", "(", "!", "is_array", "(", "$", "body", ")", ")", "{", "$", "body", "=", "[", "'text/html'", "=>", "$", "body", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "text", ")", ")", "{", "$", "this", "->", "remove_special_space", "(", "$", "text", ")", ";", "$", "body", "[", "'text/plain'", "]", "=", "$", "text", ";", "}", "$", "cssToInlineStyles", "=", "new", "CssToInlineStyles", ";", "$", "messages", "=", "[", "]", ";", "$", "content_type", "=", "'text/html'", ";", "foreach", "(", "$", "body", "as", "$", "type", "=>", "$", "message", ")", "{", "is_array", "(", "$", "message", ")", "and", "$", "message", "=", "reset", "(", "$", "messages", ")", ";", "if", "(", "'text/html'", "===", "$", "type", ")", "{", "$", "message", "=", "$", "this", "->", "get_view", "(", "'common/mail'", ",", "[", "'subject'", "=>", "$", "subject", ",", "'body'", "=>", "$", "message", "]", ")", ";", "$", "message", "=", "$", "cssToInlineStyles", "->", "convert", "(", "$", "message", ")", ";", "$", "message", "=", "preg_replace", "(", "'/<\\s*style.*?>[\\s\\S]*<\\s*\\/style\\s*>/'", ",", "''", ",", "$", "message", ")", ";", "}", "elseif", "(", "'text/plain'", "!==", "$", "type", ")", "{", "continue", ";", "}", "$", "messages", "[", "$", "type", "]", "=", "$", "message", ";", "$", "content_type", "=", "$", "type", ";", "}", "if", "(", "empty", "(", "$", "messages", ")", ")", "{", "return", "false", ";", "}", "if", "(", "count", "(", "$", "messages", ")", ">", "1", ")", "{", "$", "content_type", "=", "'multipart/alternative'", ";", "}", "// このチケットがマージされたら以下の処理は不要\r", "// https://core.trac.wordpress.org/ticket/15448\r", "add_action", "(", "'phpmailer_init'", ",", "$", "set_phpmailer", "=", "function", "(", "$", "phpmailer", ")", "use", "(", "&", "$", "set_phpmailer", ",", "$", "messages", ",", "$", "content_type", ")", "{", "/** @var \\PHPMailer $phpmailer */", "remove_action", "(", "'phpmailer_init'", ",", "$", "set_phpmailer", ")", ";", "$", "phpmailer", "->", "Body", "=", "''", ";", "$", "phpmailer", "->", "AltBody", "=", "''", ";", "foreach", "(", "$", "messages", "as", "$", "type", "=>", "$", "message", ")", "{", "if", "(", "'text/html'", "===", "$", "type", ")", "{", "$", "phpmailer", "->", "Body", "=", "$", "message", ";", "}", "elseif", "(", "'text/plain'", "===", "$", "type", ")", "{", "$", "phpmailer", "->", "AltBody", "=", "$", "message", ";", "}", "}", "$", "phpmailer", "->", "ContentType", "=", "$", "content_type", ";", "}", ")", ";", "// suppress error\r", "if", "(", "!", "isset", "(", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ")", ")", "{", "$", "_SERVER", "[", "'SERVER_NAME'", "]", "=", "''", ";", "}", "// is sending\r", "$", "this", "->", "_is_sending", "=", "true", ";", "$", "result", "=", "wp_mail", "(", "$", "to", ",", "$", "subject", ",", "reset", "(", "$", "messages", ")", ")", ";", "$", "this", "->", "_is_sending", "=", "false", ";", "return", "$", "result", ";", "}" ]
@param string $to @param string $subject @param string|array $body @param string|false $text @return bool
[ "@param", "string", "$to", "@param", "string", "$subject", "@param", "string|array", "$body", "@param", "string|false", "$text" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/mail.php#L42-L113
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Twig/Writer/Twig.php
Twig.addExtensionsFromTemplateConfiguration
protected function addExtensionsFromTemplateConfiguration( Transformation $transformation, ProjectDescriptor $project, \Twig_Environment $twigEnvironment ) { $isDebug = $transformation->getParameter('twig-debug') ? $transformation->getParameter('twig-debug')->getValue() : false; if ($isDebug == 'true') { $twigEnvironment->enableDebug(); $twigEnvironment->enableAutoReload(); $twigEnvironment->addExtension(new \Twig_Extension_Debug()); } /** @var Template\Parameter $extension */ foreach ($transformation->getParametersWithKey('twig-extension') as $extension) { $extensionValue = $extension->getValue(); if (!class_exists($extensionValue)) { throw new \InvalidArgumentException('Unknown twig extension: ' . $extensionValue); } // to support 'normal' Twig extensions we check the interface to determine what instantiation to do. $implementsInterface = in_array( 'phpDocumentor\Plugin\Twig\ExtensionInterface', class_implements($extensionValue) ); $twigEnvironment->addExtension( $implementsInterface ? new $extensionValue($project, $transformation) : new $extensionValue() ); } }
php
protected function addExtensionsFromTemplateConfiguration( Transformation $transformation, ProjectDescriptor $project, \Twig_Environment $twigEnvironment ) { $isDebug = $transformation->getParameter('twig-debug') ? $transformation->getParameter('twig-debug')->getValue() : false; if ($isDebug == 'true') { $twigEnvironment->enableDebug(); $twigEnvironment->enableAutoReload(); $twigEnvironment->addExtension(new \Twig_Extension_Debug()); } /** @var Template\Parameter $extension */ foreach ($transformation->getParametersWithKey('twig-extension') as $extension) { $extensionValue = $extension->getValue(); if (!class_exists($extensionValue)) { throw new \InvalidArgumentException('Unknown twig extension: ' . $extensionValue); } // to support 'normal' Twig extensions we check the interface to determine what instantiation to do. $implementsInterface = in_array( 'phpDocumentor\Plugin\Twig\ExtensionInterface', class_implements($extensionValue) ); $twigEnvironment->addExtension( $implementsInterface ? new $extensionValue($project, $transformation) : new $extensionValue() ); } }
[ "protected", "function", "addExtensionsFromTemplateConfiguration", "(", "Transformation", "$", "transformation", ",", "ProjectDescriptor", "$", "project", ",", "\\", "Twig_Environment", "$", "twigEnvironment", ")", "{", "$", "isDebug", "=", "$", "transformation", "->", "getParameter", "(", "'twig-debug'", ")", "?", "$", "transformation", "->", "getParameter", "(", "'twig-debug'", ")", "->", "getValue", "(", ")", ":", "false", ";", "if", "(", "$", "isDebug", "==", "'true'", ")", "{", "$", "twigEnvironment", "->", "enableDebug", "(", ")", ";", "$", "twigEnvironment", "->", "enableAutoReload", "(", ")", ";", "$", "twigEnvironment", "->", "addExtension", "(", "new", "\\", "Twig_Extension_Debug", "(", ")", ")", ";", "}", "/** @var Template\\Parameter $extension */", "foreach", "(", "$", "transformation", "->", "getParametersWithKey", "(", "'twig-extension'", ")", "as", "$", "extension", ")", "{", "$", "extensionValue", "=", "$", "extension", "->", "getValue", "(", ")", ";", "if", "(", "!", "class_exists", "(", "$", "extensionValue", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown twig extension: '", ".", "$", "extensionValue", ")", ";", "}", "// to support 'normal' Twig extensions we check the interface to determine what instantiation to do.", "$", "implementsInterface", "=", "in_array", "(", "'phpDocumentor\\Plugin\\Twig\\ExtensionInterface'", ",", "class_implements", "(", "$", "extensionValue", ")", ")", ";", "$", "twigEnvironment", "->", "addExtension", "(", "$", "implementsInterface", "?", "new", "$", "extensionValue", "(", "$", "project", ",", "$", "transformation", ")", ":", "new", "$", "extensionValue", "(", ")", ")", ";", "}", "}" ]
Tries to add any custom extensions that have been defined in the template or the transformation's configuration. This method will read the `twig-extension` parameter of the transformation (which inherits the template's parameter set) and try to add those extensions to the environment. @param Transformation $transformation @param ProjectDescriptor $project @param \Twig_Environment $twigEnvironment @throws \InvalidArgumentException if a twig-extension should be loaded but it could not be found. @return void
[ "Tries", "to", "add", "any", "custom", "extensions", "that", "have", "been", "defined", "in", "the", "template", "or", "the", "transformation", "s", "configuration", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Twig/Writer/Twig.php#L199-L230
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Twig/Writer/Twig.php
Twig.getDestinationPath
protected function getDestinationPath($node, Transformation $transformation) { $writer = $this; if (!$node) { throw new \UnexpectedValueException( 'The transformation node in the twig writer is not expected to be false or null' ); } if (!$transformation->getArtifact()) { $rule = $this->routers->match($node); if (!$rule) { throw new \InvalidArgumentException( 'No matching routing rule could be found for the given node, please provide an artifact location, ' . 'encountered: ' . ($node === null ? 'NULL' : get_class($node)) ); } $rule = new ForFileProxy($rule); $url = $rule->generate($node); if ($url === false || $url[0] !== DIRECTORY_SEPARATOR) { return false; } $path = $transformation->getTransformer()->getTarget() . str_replace('/', DIRECTORY_SEPARATOR, $url); } else { $path = $transformation->getTransformer()->getTarget() . DIRECTORY_SEPARATOR . $transformation->getArtifact(); } $finder = new Pathfinder(); $destination = preg_replace_callback( '/{{([^}]+)}}/', // explicitly do not use the unicode modifier; this breaks windows function ($query) use ($node, $writer, $finder) { // strip any surrounding \ or / $filepart = trim((string) current($finder->find($node, $query[1])), '\\/'); // make it windows proof if (extension_loaded('iconv')) { $filepart = iconv('UTF-8', 'ASCII//TRANSLIT', $filepart); } $filepart = strpos($filepart, '/') !== false ? implode('/', array_map('urlencode', explode('/', $filepart))) : implode('\\', array_map('urlencode', explode('\\', $filepart))); return $filepart; }, $path ); // replace any \ with the directory separator to be compatible with the // current filesystem and allow the next file_exists to do its work $destination = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $destination); // create directory if it does not exist yet if (!file_exists(dirname($destination))) { mkdir(dirname($destination), 0777, true); } return $destination; }
php
protected function getDestinationPath($node, Transformation $transformation) { $writer = $this; if (!$node) { throw new \UnexpectedValueException( 'The transformation node in the twig writer is not expected to be false or null' ); } if (!$transformation->getArtifact()) { $rule = $this->routers->match($node); if (!$rule) { throw new \InvalidArgumentException( 'No matching routing rule could be found for the given node, please provide an artifact location, ' . 'encountered: ' . ($node === null ? 'NULL' : get_class($node)) ); } $rule = new ForFileProxy($rule); $url = $rule->generate($node); if ($url === false || $url[0] !== DIRECTORY_SEPARATOR) { return false; } $path = $transformation->getTransformer()->getTarget() . str_replace('/', DIRECTORY_SEPARATOR, $url); } else { $path = $transformation->getTransformer()->getTarget() . DIRECTORY_SEPARATOR . $transformation->getArtifact(); } $finder = new Pathfinder(); $destination = preg_replace_callback( '/{{([^}]+)}}/', // explicitly do not use the unicode modifier; this breaks windows function ($query) use ($node, $writer, $finder) { // strip any surrounding \ or / $filepart = trim((string) current($finder->find($node, $query[1])), '\\/'); // make it windows proof if (extension_loaded('iconv')) { $filepart = iconv('UTF-8', 'ASCII//TRANSLIT', $filepart); } $filepart = strpos($filepart, '/') !== false ? implode('/', array_map('urlencode', explode('/', $filepart))) : implode('\\', array_map('urlencode', explode('\\', $filepart))); return $filepart; }, $path ); // replace any \ with the directory separator to be compatible with the // current filesystem and allow the next file_exists to do its work $destination = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $destination); // create directory if it does not exist yet if (!file_exists(dirname($destination))) { mkdir(dirname($destination), 0777, true); } return $destination; }
[ "protected", "function", "getDestinationPath", "(", "$", "node", ",", "Transformation", "$", "transformation", ")", "{", "$", "writer", "=", "$", "this", ";", "if", "(", "!", "$", "node", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'The transformation node in the twig writer is not expected to be false or null'", ")", ";", "}", "if", "(", "!", "$", "transformation", "->", "getArtifact", "(", ")", ")", "{", "$", "rule", "=", "$", "this", "->", "routers", "->", "match", "(", "$", "node", ")", ";", "if", "(", "!", "$", "rule", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'No matching routing rule could be found for the given node, please provide an artifact location, '", ".", "'encountered: '", ".", "(", "$", "node", "===", "null", "?", "'NULL'", ":", "get_class", "(", "$", "node", ")", ")", ")", ";", "}", "$", "rule", "=", "new", "ForFileProxy", "(", "$", "rule", ")", ";", "$", "url", "=", "$", "rule", "->", "generate", "(", "$", "node", ")", ";", "if", "(", "$", "url", "===", "false", "||", "$", "url", "[", "0", "]", "!==", "DIRECTORY_SEPARATOR", ")", "{", "return", "false", ";", "}", "$", "path", "=", "$", "transformation", "->", "getTransformer", "(", ")", "->", "getTarget", "(", ")", ".", "str_replace", "(", "'/'", ",", "DIRECTORY_SEPARATOR", ",", "$", "url", ")", ";", "}", "else", "{", "$", "path", "=", "$", "transformation", "->", "getTransformer", "(", ")", "->", "getTarget", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "transformation", "->", "getArtifact", "(", ")", ";", "}", "$", "finder", "=", "new", "Pathfinder", "(", ")", ";", "$", "destination", "=", "preg_replace_callback", "(", "'/{{([^}]+)}}/'", ",", "// explicitly do not use the unicode modifier; this breaks windows", "function", "(", "$", "query", ")", "use", "(", "$", "node", ",", "$", "writer", ",", "$", "finder", ")", "{", "// strip any surrounding \\ or /", "$", "filepart", "=", "trim", "(", "(", "string", ")", "current", "(", "$", "finder", "->", "find", "(", "$", "node", ",", "$", "query", "[", "1", "]", ")", ")", ",", "'\\\\/'", ")", ";", "// make it windows proof", "if", "(", "extension_loaded", "(", "'iconv'", ")", ")", "{", "$", "filepart", "=", "iconv", "(", "'UTF-8'", ",", "'ASCII//TRANSLIT'", ",", "$", "filepart", ")", ";", "}", "$", "filepart", "=", "strpos", "(", "$", "filepart", ",", "'/'", ")", "!==", "false", "?", "implode", "(", "'/'", ",", "array_map", "(", "'urlencode'", ",", "explode", "(", "'/'", ",", "$", "filepart", ")", ")", ")", ":", "implode", "(", "'\\\\'", ",", "array_map", "(", "'urlencode'", ",", "explode", "(", "'\\\\'", ",", "$", "filepart", ")", ")", ")", ";", "return", "$", "filepart", ";", "}", ",", "$", "path", ")", ";", "// replace any \\ with the directory separator to be compatible with the", "// current filesystem and allow the next file_exists to do its work", "$", "destination", "=", "str_replace", "(", "array", "(", "'/'", ",", "'\\\\'", ")", ",", "DIRECTORY_SEPARATOR", ",", "$", "destination", ")", ";", "// create directory if it does not exist yet", "if", "(", "!", "file_exists", "(", "dirname", "(", "$", "destination", ")", ")", ")", "{", "mkdir", "(", "dirname", "(", "$", "destination", ")", ",", "0777", ",", "true", ")", ";", "}", "return", "$", "destination", ";", "}" ]
Uses the currently selected node and transformation to assemble the destination path for the file. The Twig writer accepts the use of a Query to be able to generate output for multiple objects using the same template. The given node is the result of such a query, or if no query given the selected element, and the transformation contains the destination file. Since it is important to be able to generate a unique name per element can the user provide a template variable in the name of the file. Such a template variable always resides between double braces and tries to take the node value of a given query string. Example: An artifact stating `classes/{{name}}.html` will try to find the node 'name' as a child of the given $node and use that value instead. @param DescriptorAbstract $node @param Transformation $transformation @throws \InvalidArgumentException if no artifact is provided and no routing rule matches. @throws \UnexpectedValueException if the provided node does not contain anything. @return string|false returns the destination location or false if generation should be aborted.
[ "Uses", "the", "currently", "selected", "node", "and", "transformation", "to", "assemble", "the", "destination", "path", "for", "the", "file", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Twig/Writer/Twig.php#L259-L319
digipolisgent/robo-digipolis-package-drupal8
src/ThemesCompileDrupal8.php
ThemesCompileDrupal8.run
public function run() { $themes = empty($this->themes) ? $this->getConfig()->get('digipolis.themes.drupal8', false) : $this->themes; if (!$themes) { return \Robo\Result::success($this); } $collection = $this->collectionBuilder(); foreach ($this->getThemePaths(array_keys($themes)) as $themeName => $path) { $themeSettings = isset($themes[$themeName]) ? $themes[$themeName] : []; if (is_string($themeSettings)) { // Backward compatibility. $themeSettings = ['command' => $themeSettings]; } $themeSettings = array_merge( ['command' => 'build', 'sourcedir' => 'source'], $themeSettings ); $dir = $path; if ($themeSettings['sourcedir'] && is_dir($path . '/' . $themeSettings['sourcedir'])) { $dir = $path . '/' . $themeSettings['sourcedir']; } $collection->addTask( $this->taskThemeCompile( $dir, $themeSettings['command'] ) ); } return $collection->run(); }
php
public function run() { $themes = empty($this->themes) ? $this->getConfig()->get('digipolis.themes.drupal8', false) : $this->themes; if (!$themes) { return \Robo\Result::success($this); } $collection = $this->collectionBuilder(); foreach ($this->getThemePaths(array_keys($themes)) as $themeName => $path) { $themeSettings = isset($themes[$themeName]) ? $themes[$themeName] : []; if (is_string($themeSettings)) { // Backward compatibility. $themeSettings = ['command' => $themeSettings]; } $themeSettings = array_merge( ['command' => 'build', 'sourcedir' => 'source'], $themeSettings ); $dir = $path; if ($themeSettings['sourcedir'] && is_dir($path . '/' . $themeSettings['sourcedir'])) { $dir = $path . '/' . $themeSettings['sourcedir']; } $collection->addTask( $this->taskThemeCompile( $dir, $themeSettings['command'] ) ); } return $collection->run(); }
[ "public", "function", "run", "(", ")", "{", "$", "themes", "=", "empty", "(", "$", "this", "->", "themes", ")", "?", "$", "this", "->", "getConfig", "(", ")", "->", "get", "(", "'digipolis.themes.drupal8'", ",", "false", ")", ":", "$", "this", "->", "themes", ";", "if", "(", "!", "$", "themes", ")", "{", "return", "\\", "Robo", "\\", "Result", "::", "success", "(", "$", "this", ")", ";", "}", "$", "collection", "=", "$", "this", "->", "collectionBuilder", "(", ")", ";", "foreach", "(", "$", "this", "->", "getThemePaths", "(", "array_keys", "(", "$", "themes", ")", ")", "as", "$", "themeName", "=>", "$", "path", ")", "{", "$", "themeSettings", "=", "isset", "(", "$", "themes", "[", "$", "themeName", "]", ")", "?", "$", "themes", "[", "$", "themeName", "]", ":", "[", "]", ";", "if", "(", "is_string", "(", "$", "themeSettings", ")", ")", "{", "// Backward compatibility.", "$", "themeSettings", "=", "[", "'command'", "=>", "$", "themeSettings", "]", ";", "}", "$", "themeSettings", "=", "array_merge", "(", "[", "'command'", "=>", "'build'", ",", "'sourcedir'", "=>", "'source'", "]", ",", "$", "themeSettings", ")", ";", "$", "dir", "=", "$", "path", ";", "if", "(", "$", "themeSettings", "[", "'sourcedir'", "]", "&&", "is_dir", "(", "$", "path", ".", "'/'", ".", "$", "themeSettings", "[", "'sourcedir'", "]", ")", ")", "{", "$", "dir", "=", "$", "path", ".", "'/'", ".", "$", "themeSettings", "[", "'sourcedir'", "]", ";", "}", "$", "collection", "->", "addTask", "(", "$", "this", "->", "taskThemeCompile", "(", "$", "dir", ",", "$", "themeSettings", "[", "'command'", "]", ")", ")", ";", "}", "return", "$", "collection", "->", "run", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/digipolisgent/robo-digipolis-package-drupal8/blob/dc03ae0f68d56a027291e9574ff7aa433c27690a/src/ThemesCompileDrupal8.php#L99-L132
WScore/Validation
src/Filter/Sanitizers.php
Sanitizers.filter_sanitize
public function filter_sanitize($v, $p) { $option = Helper::arrGet($this->sanitizes, $p, $p); $v->setValue(filter_var($v->getValue(), $option)); if ($p === 'int') { if ((int)$v->getValue() !== (int)(float)$v->getValue()) { $v->setValue(''); } } }
php
public function filter_sanitize($v, $p) { $option = Helper::arrGet($this->sanitizes, $p, $p); $v->setValue(filter_var($v->getValue(), $option)); if ($p === 'int') { if ((int)$v->getValue() !== (int)(float)$v->getValue()) { $v->setValue(''); } } }
[ "public", "function", "filter_sanitize", "(", "$", "v", ",", "$", "p", ")", "{", "$", "option", "=", "Helper", "::", "arrGet", "(", "$", "this", "->", "sanitizes", ",", "$", "p", ",", "$", "p", ")", ";", "$", "v", "->", "setValue", "(", "filter_var", "(", "$", "v", "->", "getValue", "(", ")", ",", "$", "option", ")", ")", ";", "if", "(", "$", "p", "===", "'int'", ")", "{", "if", "(", "(", "int", ")", "$", "v", "->", "getValue", "(", ")", "!==", "(", "int", ")", "(", "float", ")", "$", "v", "->", "getValue", "(", ")", ")", "{", "$", "v", "->", "setValue", "(", "''", ")", ";", "}", "}", "}" ]
sanitize the value using filter_var. @param ValueTO $v @param $p
[ "sanitize", "the", "value", "using", "filter_var", "." ]
train
https://github.com/WScore/Validation/blob/25c0dca37d624bb0bb22f8e79ba54db2f69e0950/src/Filter/Sanitizers.php#L49-L58
WScore/Validation
src/Filter/Sanitizers.php
Sanitizers.filter_datetime
public function filter_datetime($v, $p) { if (is_bool($p) && $p) { $p = 'Y-m-d H:i:s'; } $dt = \date_create_from_format($p, $v->getValue()); if (!$dt) { $v->setValue(null); $v->setError(__METHOD__, $p); return; } $v->setValue($dt->format($p)); }
php
public function filter_datetime($v, $p) { if (is_bool($p) && $p) { $p = 'Y-m-d H:i:s'; } $dt = \date_create_from_format($p, $v->getValue()); if (!$dt) { $v->setValue(null); $v->setError(__METHOD__, $p); return; } $v->setValue($dt->format($p)); }
[ "public", "function", "filter_datetime", "(", "$", "v", ",", "$", "p", ")", "{", "if", "(", "is_bool", "(", "$", "p", ")", "&&", "$", "p", ")", "{", "$", "p", "=", "'Y-m-d H:i:s'", ";", "}", "$", "dt", "=", "\\", "date_create_from_format", "(", "$", "p", ",", "$", "v", "->", "getValue", "(", ")", ")", ";", "if", "(", "!", "$", "dt", ")", "{", "$", "v", "->", "setValue", "(", "null", ")", ";", "$", "v", "->", "setError", "(", "__METHOD__", ",", "$", "p", ")", ";", "return", ";", "}", "$", "v", "->", "setValue", "(", "$", "dt", "->", "format", "(", "$", "p", ")", ")", ";", "}" ]
check for valid date-time input string. @param ValueTO $v @param bool|string $p
[ "check", "for", "valid", "date", "-", "time", "input", "string", "." ]
train
https://github.com/WScore/Validation/blob/25c0dca37d624bb0bb22f8e79ba54db2f69e0950/src/Filter/Sanitizers.php#L66-L78
WScore/Validation
src/Filter/Sanitizers.php
Sanitizers.filter_default
public function filter_default($v, $p) { $val = $v->getValue(); if (!$val && "" == "{$val}") { // no value. set default... $v->setValue($p); } }
php
public function filter_default($v, $p) { $val = $v->getValue(); if (!$val && "" == "{$val}") { // no value. set default... $v->setValue($p); } }
[ "public", "function", "filter_default", "(", "$", "v", ",", "$", "p", ")", "{", "$", "val", "=", "$", "v", "->", "getValue", "(", ")", ";", "if", "(", "!", "$", "val", "&&", "\"\"", "==", "\"{$val}\"", ")", "{", "// no value. set default...", "$", "v", "->", "setValue", "(", "$", "p", ")", ";", "}", "}" ]
if the value is empty (false, null, empty string, or empty array), the default value of $p is used for the value. @param ValueTO $v @param $p
[ "if", "the", "value", "is", "empty", "(", "false", "null", "empty", "string", "or", "empty", "array", ")", "the", "default", "value", "of", "$p", "is", "used", "for", "the", "value", "." ]
train
https://github.com/WScore/Validation/blob/25c0dca37d624bb0bb22f8e79ba54db2f69e0950/src/Filter/Sanitizers.php#L139-L145
ttreeagency/Taxonomy
Classes/Command/TaxonomyCommandController.php
TaxonomyCommandController.showMappingCommand
public function showMappingCommand(string $node) { foreach ($this->contentDimensionCombinator->getAllAllowedCombinations() as $dimensions) { $context = $this->createContentContext('live', $dimensions); $siteNode = $context->getNodeByIdentifier($node); $taxonomyNodes = (new FlowQuery([$siteNode]))->find('[instanceof Ttree.Taxonomy:Document.Taxonomy]')->get(); $settings = []; /** @var NodeInterface $taxonomyNode */ foreach ($taxonomyNodes as $taxonomyNode) { $this->outputLine(); $this->outputLine('Show mapping for <b>%s</b> (%s)', [$taxonomyNode->getLabel(), $taxonomyNode->getContextPath()]); $settings = $this->managedVocabulary->build($taxonomyNode); foreach (Arrays::getValueByPath($settings, 'analysis.analyzer') as $analyzerName => $analyzerConfiguration) { $this->outputLine(); $this->outputLine('+ Analyzer <info>%s</info>', [$analyzerName]); $this->outputLine(' Tokenizer <info>%s</info>', [$analyzerConfiguration['tokenizer']]); $this->outputLine(' Filter <info>%s</info>', [\implode(', ', $analyzerConfiguration['filter'])]); } foreach (Arrays::getValueByPath($settings, 'analysis.filter') as $filterName => $filterConfiguration) { $this->outputLine(); $this->outputLine('+ Filter <info>%s</info>', [$analyzerName]); $this->outputLine(' Type <info>%s</info>', [$filterConfiguration['type']]); if ($filterConfiguration['type'] === 'synonym') { $this->outputLine(' Synonyms <info>%d</info>', [count($filterConfiguration['synonyms'])]); } } } } }
php
public function showMappingCommand(string $node) { foreach ($this->contentDimensionCombinator->getAllAllowedCombinations() as $dimensions) { $context = $this->createContentContext('live', $dimensions); $siteNode = $context->getNodeByIdentifier($node); $taxonomyNodes = (new FlowQuery([$siteNode]))->find('[instanceof Ttree.Taxonomy:Document.Taxonomy]')->get(); $settings = []; /** @var NodeInterface $taxonomyNode */ foreach ($taxonomyNodes as $taxonomyNode) { $this->outputLine(); $this->outputLine('Show mapping for <b>%s</b> (%s)', [$taxonomyNode->getLabel(), $taxonomyNode->getContextPath()]); $settings = $this->managedVocabulary->build($taxonomyNode); foreach (Arrays::getValueByPath($settings, 'analysis.analyzer') as $analyzerName => $analyzerConfiguration) { $this->outputLine(); $this->outputLine('+ Analyzer <info>%s</info>', [$analyzerName]); $this->outputLine(' Tokenizer <info>%s</info>', [$analyzerConfiguration['tokenizer']]); $this->outputLine(' Filter <info>%s</info>', [\implode(', ', $analyzerConfiguration['filter'])]); } foreach (Arrays::getValueByPath($settings, 'analysis.filter') as $filterName => $filterConfiguration) { $this->outputLine(); $this->outputLine('+ Filter <info>%s</info>', [$analyzerName]); $this->outputLine(' Type <info>%s</info>', [$filterConfiguration['type']]); if ($filterConfiguration['type'] === 'synonym') { $this->outputLine(' Synonyms <info>%d</info>', [count($filterConfiguration['synonyms'])]); } } } } }
[ "public", "function", "showMappingCommand", "(", "string", "$", "node", ")", "{", "foreach", "(", "$", "this", "->", "contentDimensionCombinator", "->", "getAllAllowedCombinations", "(", ")", "as", "$", "dimensions", ")", "{", "$", "context", "=", "$", "this", "->", "createContentContext", "(", "'live'", ",", "$", "dimensions", ")", ";", "$", "siteNode", "=", "$", "context", "->", "getNodeByIdentifier", "(", "$", "node", ")", ";", "$", "taxonomyNodes", "=", "(", "new", "FlowQuery", "(", "[", "$", "siteNode", "]", ")", ")", "->", "find", "(", "'[instanceof Ttree.Taxonomy:Document.Taxonomy]'", ")", "->", "get", "(", ")", ";", "$", "settings", "=", "[", "]", ";", "/** @var NodeInterface $taxonomyNode */", "foreach", "(", "$", "taxonomyNodes", "as", "$", "taxonomyNode", ")", "{", "$", "this", "->", "outputLine", "(", ")", ";", "$", "this", "->", "outputLine", "(", "'Show mapping for <b>%s</b> (%s)'", ",", "[", "$", "taxonomyNode", "->", "getLabel", "(", ")", ",", "$", "taxonomyNode", "->", "getContextPath", "(", ")", "]", ")", ";", "$", "settings", "=", "$", "this", "->", "managedVocabulary", "->", "build", "(", "$", "taxonomyNode", ")", ";", "foreach", "(", "Arrays", "::", "getValueByPath", "(", "$", "settings", ",", "'analysis.analyzer'", ")", "as", "$", "analyzerName", "=>", "$", "analyzerConfiguration", ")", "{", "$", "this", "->", "outputLine", "(", ")", ";", "$", "this", "->", "outputLine", "(", "'+ Analyzer <info>%s</info>'", ",", "[", "$", "analyzerName", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' Tokenizer <info>%s</info>'", ",", "[", "$", "analyzerConfiguration", "[", "'tokenizer'", "]", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' Filter <info>%s</info>'", ",", "[", "\\", "implode", "(", "', '", ",", "$", "analyzerConfiguration", "[", "'filter'", "]", ")", "]", ")", ";", "}", "foreach", "(", "Arrays", "::", "getValueByPath", "(", "$", "settings", ",", "'analysis.filter'", ")", "as", "$", "filterName", "=>", "$", "filterConfiguration", ")", "{", "$", "this", "->", "outputLine", "(", ")", ";", "$", "this", "->", "outputLine", "(", "'+ Filter <info>%s</info>'", ",", "[", "$", "analyzerName", "]", ")", ";", "$", "this", "->", "outputLine", "(", "' Type <info>%s</info>'", ",", "[", "$", "filterConfiguration", "[", "'type'", "]", "]", ")", ";", "if", "(", "$", "filterConfiguration", "[", "'type'", "]", "===", "'synonym'", ")", "{", "$", "this", "->", "outputLine", "(", "' Synonyms <info>%d</info>'", ",", "[", "count", "(", "$", "filterConfiguration", "[", "'synonyms'", "]", ")", "]", ")", ";", "}", "}", "}", "}", "}" ]
Show ElasticSearch filters and analyzers
[ "Show", "ElasticSearch", "filters", "and", "analyzers" ]
train
https://github.com/ttreeagency/Taxonomy/blob/9e94e2863a722bbdb1dcbdc34afbda1e1e10b4c9/Classes/Command/TaxonomyCommandController.php#L37-L65
qlake/framework
src/Qlake/Database/Grammar/Grammar.php
Grammar.compileWheres
public function compileWheres(Query $query) { $wheres = $query->wheres; $sql = []; foreach ($wheres as $where) { if ($where instanceof Expression) { switch ($where->type) { case 'raw': $sql[] = $this->compileRawWhere($where); break; case 'disjunct': $sql[] = $this->compileBasicWhere($where); break; case 'builder': $query = Query::$self->newQuery(); call_user_func($where->clause, $query); $sql[] = '(' . substr($this->compileWheres($query), 6) . ')'; break; default: # code... break; } } elseif (($operator = $where) instanceof Operator) { $sql[] = $operator->getType(); } } return 'WHERE ' . implode(' ', $sql); }
php
public function compileWheres(Query $query) { $wheres = $query->wheres; $sql = []; foreach ($wheres as $where) { if ($where instanceof Expression) { switch ($where->type) { case 'raw': $sql[] = $this->compileRawWhere($where); break; case 'disjunct': $sql[] = $this->compileBasicWhere($where); break; case 'builder': $query = Query::$self->newQuery(); call_user_func($where->clause, $query); $sql[] = '(' . substr($this->compileWheres($query), 6) . ')'; break; default: # code... break; } } elseif (($operator = $where) instanceof Operator) { $sql[] = $operator->getType(); } } return 'WHERE ' . implode(' ', $sql); }
[ "public", "function", "compileWheres", "(", "Query", "$", "query", ")", "{", "$", "wheres", "=", "$", "query", "->", "wheres", ";", "$", "sql", "=", "[", "]", ";", "foreach", "(", "$", "wheres", "as", "$", "where", ")", "{", "if", "(", "$", "where", "instanceof", "Expression", ")", "{", "switch", "(", "$", "where", "->", "type", ")", "{", "case", "'raw'", ":", "$", "sql", "[", "]", "=", "$", "this", "->", "compileRawWhere", "(", "$", "where", ")", ";", "break", ";", "case", "'disjunct'", ":", "$", "sql", "[", "]", "=", "$", "this", "->", "compileBasicWhere", "(", "$", "where", ")", ";", "break", ";", "case", "'builder'", ":", "$", "query", "=", "Query", "::", "$", "self", "->", "newQuery", "(", ")", ";", "call_user_func", "(", "$", "where", "->", "clause", ",", "$", "query", ")", ";", "$", "sql", "[", "]", "=", "'('", ".", "substr", "(", "$", "this", "->", "compileWheres", "(", "$", "query", ")", ",", "6", ")", ".", "')'", ";", "break", ";", "default", ":", "# code...", "break", ";", "}", "}", "elseif", "(", "(", "$", "operator", "=", "$", "where", ")", "instanceof", "Operator", ")", "{", "$", "sql", "[", "]", "=", "$", "operator", "->", "getType", "(", ")", ";", "}", "}", "return", "'WHERE '", ".", "implode", "(", "' '", ",", "$", "sql", ")", ";", "}" ]
/*public function compileBuilderConditionalExpression(Expression $expression) { $query = Query::$self->newQuery(); call_user_func($expression->clause, $query); $sql[] = '(' . $this->compileExpressions($query) . ')'; }
[ "/", "*", "public", "function", "compileBuilderConditionalExpression", "(", "Expression", "$expression", ")", "{", "$query", "=", "Query", "::", "$self", "-", ">", "newQuery", "()", ";" ]
train
https://github.com/qlake/framework/blob/0b7bad459ae0721bc5cdd141344f9dfc1acee28a/src/Qlake/Database/Grammar/Grammar.php#L293-L339
verdet23/SphinxSearchBundle
Command/SearchSphinxIndexerShowCommand.php
SearchSphinxIndexerShowCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { /** @var $indexer \Verdet\SphinxSearchBundle\Services\Indexer\Indexer */ $indexer = $this->getContainer()->get('search.sphinxsearch.indexer'); $indexes = $indexer->getIndexes(); if (count($indexes)) { $output->writeln("\n <info>==</info> Indexes:\n"); foreach ($indexes as $index) { $output->writeln(' <comment>>></comment> ' . $index); } } else { $output->writeln('<error>Indexes not configured</error>'); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { /** @var $indexer \Verdet\SphinxSearchBundle\Services\Indexer\Indexer */ $indexer = $this->getContainer()->get('search.sphinxsearch.indexer'); $indexes = $indexer->getIndexes(); if (count($indexes)) { $output->writeln("\n <info>==</info> Indexes:\n"); foreach ($indexes as $index) { $output->writeln(' <comment>>></comment> ' . $index); } } else { $output->writeln('<error>Indexes not configured</error>'); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "/** @var $indexer \\Verdet\\SphinxSearchBundle\\Services\\Indexer\\Indexer */", "$", "indexer", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'search.sphinxsearch.indexer'", ")", ";", "$", "indexes", "=", "$", "indexer", "->", "getIndexes", "(", ")", ";", "if", "(", "count", "(", "$", "indexes", ")", ")", "{", "$", "output", "->", "writeln", "(", "\"\\n <info>==</info> Indexes:\\n\"", ")", ";", "foreach", "(", "$", "indexes", "as", "$", "index", ")", "{", "$", "output", "->", "writeln", "(", "' <comment>>></comment> '", ".", "$", "index", ")", ";", "}", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<error>Indexes not configured</error>'", ")", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Command/SearchSphinxIndexerShowCommand.php#L34-L51
creolab/resources
src/Item.php
Item.toArray
public function toArray() { $this->data = $this->transformer->transformBack($this->data); return $this->data; }
php
public function toArray() { $this->data = $this->transformer->transformBack($this->data); return $this->data; }
[ "public", "function", "toArray", "(", ")", "{", "$", "this", "->", "data", "=", "$", "this", "->", "transformer", "->", "transformBack", "(", "$", "this", "->", "data", ")", ";", "return", "$", "this", "->", "data", ";", "}" ]
Return array representation of item @return array
[ "Return", "array", "representation", "of", "item" ]
train
https://github.com/creolab/resources/blob/6e1bdd266aa373f6dafd2408b230f7d2fa05a637/src/Item.php#L68-L73
php-comp/lite-database
src/ConfigAndEventAwareTrait.php
ConfigAndEventAwareTrait.setConfig
public function setConfig(array $config, $merge = true) { $this->config = $merge ? \array_merge($this->config, $config) : $config; return $this; }
php
public function setConfig(array $config, $merge = true) { $this->config = $merge ? \array_merge($this->config, $config) : $config; return $this; }
[ "public", "function", "setConfig", "(", "array", "$", "config", ",", "$", "merge", "=", "true", ")", "{", "$", "this", "->", "config", "=", "$", "merge", "?", "\\", "array_merge", "(", "$", "this", "->", "config", ",", "$", "config", ")", ":", "$", "config", ";", "return", "$", "this", ";", "}" ]
Method to set property config @param array $config @param bool $merge @return static Return self to support chaining.
[ "Method", "to", "set", "property", "config" ]
train
https://github.com/php-comp/lite-database/blob/af5f73cb89e0e6cd24dd464f7a48fb5088eaafca/src/ConfigAndEventAwareTrait.php#L133-L138