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
Lansoweb/LosBase
src/LosBase/Service/Uuid.php
Uuid.generateVersion
private static function generateVersion($namespace, $name, $version) { if (!self::isValid($namespace)) { return false; } $nhex = str_replace(array('-', '{', '}'), '', $namespace); $nstr = ''; $len = strlen($nhex); for ($i = 0; $i < $len; $i += 2) { $nstr .= chr(hexdec($nhex[$i].$nhex[$i + 1])); } if ($version == 3) { $hash = md5($nstr.$name); $digit = 0x3000; } else { $hash = sha1($nstr.$name); $digit = 0x5000; } return sprintf('%08s-%04s-%04x-%04x-%12s', substr($hash, 0, 8), substr($hash, 8, 4), (hexdec(substr($hash, 12, 4)) & 0x0fff) | $digit, (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, substr($hash, 20, 12) ); }
php
private static function generateVersion($namespace, $name, $version) { if (!self::isValid($namespace)) { return false; } $nhex = str_replace(array('-', '{', '}'), '', $namespace); $nstr = ''; $len = strlen($nhex); for ($i = 0; $i < $len; $i += 2) { $nstr .= chr(hexdec($nhex[$i].$nhex[$i + 1])); } if ($version == 3) { $hash = md5($nstr.$name); $digit = 0x3000; } else { $hash = sha1($nstr.$name); $digit = 0x5000; } return sprintf('%08s-%04s-%04x-%04x-%12s', substr($hash, 0, 8), substr($hash, 8, 4), (hexdec(substr($hash, 12, 4)) & 0x0fff) | $digit, (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, substr($hash, 20, 12) ); }
[ "private", "static", "function", "generateVersion", "(", "$", "namespace", ",", "$", "name", ",", "$", "version", ")", "{", "if", "(", "!", "self", "::", "isValid", "(", "$", "namespace", ")", ")", "{", "return", "false", ";", "}", "$", "nhex", "=", "str_replace", "(", "array", "(", "'-'", ",", "'{'", ",", "'}'", ")", ",", "''", ",", "$", "namespace", ")", ";", "$", "nstr", "=", "''", ";", "$", "len", "=", "strlen", "(", "$", "nhex", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "$", "i", "+=", "2", ")", "{", "$", "nstr", ".=", "chr", "(", "hexdec", "(", "$", "nhex", "[", "$", "i", "]", ".", "$", "nhex", "[", "$", "i", "+", "1", "]", ")", ")", ";", "}", "if", "(", "$", "version", "==", "3", ")", "{", "$", "hash", "=", "md5", "(", "$", "nstr", ".", "$", "name", ")", ";", "$", "digit", "=", "0x3000", ";", "}", "else", "{", "$", "hash", "=", "sha1", "(", "$", "nstr", ".", "$", "name", ")", ";", "$", "digit", "=", "0x5000", ";", "}", "return", "sprintf", "(", "'%08s-%04s-%04x-%04x-%12s'", ",", "substr", "(", "$", "hash", ",", "0", ",", "8", ")", ",", "substr", "(", "$", "hash", ",", "8", ",", "4", ")", ",", "(", "hexdec", "(", "substr", "(", "$", "hash", ",", "12", ",", "4", ")", ")", "&", "0x0fff", ")", "|", "$", "digit", ",", "(", "hexdec", "(", "substr", "(", "$", "hash", ",", "16", ",", "4", ")", ")", "&", "0x3fff", ")", "|", "0x8000", ",", "substr", "(", "$", "hash", ",", "20", ",", "12", ")", ")", ";", "}" ]
Generates v3 or v5 UUIDs. @param string $namespace @param string $name @param int $version @return bool|string
[ "Generates", "v3", "or", "v5", "UUIDs", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Service/Uuid.php#L30-L59
webtown-php/KunstmaanExtensionBundle
src/User/UserUpdater.php
UserUpdater.getChanged
public function getChanged(UserUpdater $update) { $changed = []; $ref = new \ReflectionClass($this); foreach ($ref->getProperties() as $prop) { $method = 'get' . ucfirst($prop->getName()); $newVal = $update->$method(); if ($this->$method() != $newVal) { $changed[$prop->getName()] = $newVal; } } return $changed; }
php
public function getChanged(UserUpdater $update) { $changed = []; $ref = new \ReflectionClass($this); foreach ($ref->getProperties() as $prop) { $method = 'get' . ucfirst($prop->getName()); $newVal = $update->$method(); if ($this->$method() != $newVal) { $changed[$prop->getName()] = $newVal; } } return $changed; }
[ "public", "function", "getChanged", "(", "UserUpdater", "$", "update", ")", "{", "$", "changed", "=", "[", "]", ";", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "this", ")", ";", "foreach", "(", "$", "ref", "->", "getProperties", "(", ")", "as", "$", "prop", ")", "{", "$", "method", "=", "'get'", ".", "ucfirst", "(", "$", "prop", "->", "getName", "(", ")", ")", ";", "$", "newVal", "=", "$", "update", "->", "$", "method", "(", ")", ";", "if", "(", "$", "this", "->", "$", "method", "(", ")", "!=", "$", "newVal", ")", "{", "$", "changed", "[", "$", "prop", "->", "getName", "(", ")", "]", "=", "$", "newVal", ";", "}", "}", "return", "$", "changed", ";", "}" ]
@param UserUpdater $update @return array
[ "@param", "UserUpdater", "$update" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/User/UserUpdater.php#L98-L111
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/File/Exists.php
Zend_Validate_File_Exists.addDirectory
public function addDirectory($directory) { $directories = $this->getDirectory(true); if (is_string($directory)) { $directory = explode(',', $directory); } else if (!is_array($directory)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } foreach ($directory as $content) { if (empty($content) || !is_string($content)) { continue; } $directories[] = trim($content); } $directories = array_unique($directories); // Sanity check to ensure no empty values foreach ($directories as $key => $dir) { if (empty($dir)) { unset($directories[$key]); } } $this->_directory = implode(',', $directories); return $this; }
php
public function addDirectory($directory) { $directories = $this->getDirectory(true); if (is_string($directory)) { $directory = explode(',', $directory); } else if (!is_array($directory)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception ('Invalid options to validator provided'); } foreach ($directory as $content) { if (empty($content) || !is_string($content)) { continue; } $directories[] = trim($content); } $directories = array_unique($directories); // Sanity check to ensure no empty values foreach ($directories as $key => $dir) { if (empty($dir)) { unset($directories[$key]); } } $this->_directory = implode(',', $directories); return $this; }
[ "public", "function", "addDirectory", "(", "$", "directory", ")", "{", "$", "directories", "=", "$", "this", "->", "getDirectory", "(", "true", ")", ";", "if", "(", "is_string", "(", "$", "directory", ")", ")", "{", "$", "directory", "=", "explode", "(", "','", ",", "$", "directory", ")", ";", "}", "else", "if", "(", "!", "is_array", "(", "$", "directory", ")", ")", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'Invalid options to validator provided'", ")", ";", "}", "foreach", "(", "$", "directory", "as", "$", "content", ")", "{", "if", "(", "empty", "(", "$", "content", ")", "||", "!", "is_string", "(", "$", "content", ")", ")", "{", "continue", ";", "}", "$", "directories", "[", "]", "=", "trim", "(", "$", "content", ")", ";", "}", "$", "directories", "=", "array_unique", "(", "$", "directories", ")", ";", "// Sanity check to ensure no empty values", "foreach", "(", "$", "directories", "as", "$", "key", "=>", "$", "dir", ")", "{", "if", "(", "empty", "(", "$", "dir", ")", ")", "{", "unset", "(", "$", "directories", "[", "$", "key", "]", ")", ";", "}", "}", "$", "this", "->", "_directory", "=", "implode", "(", "','", ",", "$", "directories", ")", ";", "return", "$", "this", ";", "}" ]
Adds the file directory which will be checked @param string|array $directory The directory to add for validation @return Zend_Validate_File_Extension Provides a fluent interface
[ "Adds", "the", "file", "directory", "which", "will", "be", "checked" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/File/Exists.php#L118-L148
atkrad/data-tables
src/DataSource/JsArray.php
JsArray.initialize
public function initialize(Table $table) { $this->table = $table; $this->table->setData($this->getData()); }
php
public function initialize(Table $table) { $this->table = $table; $this->table->setData($this->getData()); }
[ "public", "function", "initialize", "(", "Table", "$", "table", ")", "{", "$", "this", "->", "table", "=", "$", "table", ";", "$", "this", "->", "table", "->", "setData", "(", "$", "this", "->", "getData", "(", ")", ")", ";", "}" ]
Initialize data source @param Table $table Table object @return void
[ "Initialize", "data", "source" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/JsArray.php#L47-L51
atkrad/data-tables
src/DataSource/JsArray.php
JsArray.getData
protected function getData() { $data = []; foreach ($this->data as $dataValue) { $row = []; foreach ($this->table->getColumns() as $column) { if ($column instanceof ColumnInterface) { $row[$column->getData()] = $column->getContent($dataValue); continue; } if (is_callable($column->getFormatter())) { $row[$column->getData()] = call_user_func_array( $column->getFormatter(), [ $dataValue[$column->getData()], $dataValue ] ); } else { $row[$column->getData()] = (string)$dataValue[$column->getData()]; } } $data[] = $row; } return $data; }
php
protected function getData() { $data = []; foreach ($this->data as $dataValue) { $row = []; foreach ($this->table->getColumns() as $column) { if ($column instanceof ColumnInterface) { $row[$column->getData()] = $column->getContent($dataValue); continue; } if (is_callable($column->getFormatter())) { $row[$column->getData()] = call_user_func_array( $column->getFormatter(), [ $dataValue[$column->getData()], $dataValue ] ); } else { $row[$column->getData()] = (string)$dataValue[$column->getData()]; } } $data[] = $row; } return $data; }
[ "protected", "function", "getData", "(", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "dataValue", ")", "{", "$", "row", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "table", "->", "getColumns", "(", ")", "as", "$", "column", ")", "{", "if", "(", "$", "column", "instanceof", "ColumnInterface", ")", "{", "$", "row", "[", "$", "column", "->", "getData", "(", ")", "]", "=", "$", "column", "->", "getContent", "(", "$", "dataValue", ")", ";", "continue", ";", "}", "if", "(", "is_callable", "(", "$", "column", "->", "getFormatter", "(", ")", ")", ")", "{", "$", "row", "[", "$", "column", "->", "getData", "(", ")", "]", "=", "call_user_func_array", "(", "$", "column", "->", "getFormatter", "(", ")", ",", "[", "$", "dataValue", "[", "$", "column", "->", "getData", "(", ")", "]", ",", "$", "dataValue", "]", ")", ";", "}", "else", "{", "$", "row", "[", "$", "column", "->", "getData", "(", ")", "]", "=", "(", "string", ")", "$", "dataValue", "[", "$", "column", "->", "getData", "(", ")", "]", ";", "}", "}", "$", "data", "[", "]", "=", "$", "row", ";", "}", "return", "$", "data", ";", "}" ]
Get data @return array
[ "Get", "data" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/DataSource/JsArray.php#L58-L85
limenet/deploy
src/limenet/Deploy/Deploy.php
Deploy.updateCode
protected function updateCode() : array { $output = []; $returnValue = 0; $updateMaster = 'ls'; // dummy if ($this->getBranch() !== 'master') { $updateMaster = ' git checkout master && git pull && git checkout '.$this->getBranch().' '; } $commands = [ 'git reset --hard HEAD', 'git pull', $updateMaster, 'composer install --no-dev', 'yarn install --production', ]; foreach ($commands as $command) { exec('cd '.$this->getBasepath().' && '.$command, $output, $returnValue); } return [ 'output' => $output, 'returnValue' => $returnValue, ]; }
php
protected function updateCode() : array { $output = []; $returnValue = 0; $updateMaster = 'ls'; // dummy if ($this->getBranch() !== 'master') { $updateMaster = ' git checkout master && git pull && git checkout '.$this->getBranch().' '; } $commands = [ 'git reset --hard HEAD', 'git pull', $updateMaster, 'composer install --no-dev', 'yarn install --production', ]; foreach ($commands as $command) { exec('cd '.$this->getBasepath().' && '.$command, $output, $returnValue); } return [ 'output' => $output, 'returnValue' => $returnValue, ]; }
[ "protected", "function", "updateCode", "(", ")", ":", "array", "{", "$", "output", "=", "[", "]", ";", "$", "returnValue", "=", "0", ";", "$", "updateMaster", "=", "'ls'", ";", "// dummy", "if", "(", "$", "this", "->", "getBranch", "(", ")", "!==", "'master'", ")", "{", "$", "updateMaster", "=", "' git checkout master && git pull && git checkout '", ".", "$", "this", "->", "getBranch", "(", ")", ".", "' '", ";", "}", "$", "commands", "=", "[", "'git reset --hard HEAD'", ",", "'git pull'", ",", "$", "updateMaster", ",", "'composer install --no-dev'", ",", "'yarn install --production'", ",", "]", ";", "foreach", "(", "$", "commands", "as", "$", "command", ")", "{", "exec", "(", "'cd '", ".", "$", "this", "->", "getBasepath", "(", ")", ".", "' && '", ".", "$", "command", ",", "$", "output", ",", "$", "returnValue", ")", ";", "}", "return", "[", "'output'", "=>", "$", "output", ",", "'returnValue'", "=>", "$", "returnValue", ",", "]", ";", "}" ]
Executes the actual deployment commands. @return array
[ "Executes", "the", "actual", "deployment", "commands", "." ]
train
https://github.com/limenet/deploy/blob/7c403b69f3221fd159c528f7a6a59f481765a2da/src/limenet/Deploy/Deploy.php#L178-L205
webforge-labs/psc-cms
lib/Psc/URL/Request.php
Request.init
public function init() { curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); // gibt die Value zurück curl_setopt($this->ch, CURLOPT_URL, $this->url); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects curl_setopt($this->ch, CURLOPT_COOKIEJAR, (string) $this->cookieJar); curl_setopt($this->ch, CURLOPT_COOKIEFILE, (string) $this->cookieJar); curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE); $headers = array(); $headers[] = 'Expect:'; // prevents expect-100 automatisch zu senden (ka) foreach ($this->httpHeaders as $name => $value) { $headers[] = $name.': '.$value; } $this->setOption(CURLOPT_HTTPHEADER, $headers); $this->initData(); $this->init = TRUE; return $this; }
php
public function init() { curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); // gibt die Value zurück curl_setopt($this->ch, CURLOPT_URL, $this->url); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects curl_setopt($this->ch, CURLOPT_COOKIEJAR, (string) $this->cookieJar); curl_setopt($this->ch, CURLOPT_COOKIEFILE, (string) $this->cookieJar); curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE); $headers = array(); $headers[] = 'Expect:'; // prevents expect-100 automatisch zu senden (ka) foreach ($this->httpHeaders as $name => $value) { $headers[] = $name.': '.$value; } $this->setOption(CURLOPT_HTTPHEADER, $headers); $this->initData(); $this->init = TRUE; return $this; }
[ "public", "function", "init", "(", ")", "{", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "1", ")", ";", "// gibt die Value zurück", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLOPT_URL", ",", "$", "this", "->", "url", ")", ";", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "1", ")", ";", "// follow redirects", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLOPT_COOKIEJAR", ",", "(", "string", ")", "$", "this", "->", "cookieJar", ")", ";", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLOPT_COOKIEFILE", ",", "(", "string", ")", "$", "this", "->", "cookieJar", ")", ";", "curl_setopt", "(", "$", "this", "->", "ch", ",", "CURLINFO_HEADER_OUT", ",", "TRUE", ")", ";", "$", "headers", "=", "array", "(", ")", ";", "$", "headers", "[", "]", "=", "'Expect:'", ";", "// prevents expect-100 automatisch zu senden (ka) ", "foreach", "(", "$", "this", "->", "httpHeaders", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "headers", "[", "]", "=", "$", "name", ".", "': '", ".", "$", "value", ";", "}", "$", "this", "->", "setOption", "(", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "$", "this", "->", "initData", "(", ")", ";", "$", "this", "->", "init", "=", "TRUE", ";", "return", "$", "this", ";", "}" ]
/* set allet
[ "/", "*", "set", "allet" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/URL/Request.php#L100-L119
periaptio/empress-generator
src/Syntax/AddForeignKeysToTable.php
AddForeignKeysToTable.getItem
protected function getItem($foreignKey) { $value = $foreignKey['field']; if (! empty($foreignKey['name'])) { $value .= "', '". $foreignKey['name']; } $output = sprintf( "\$table->foreign('%s')->references('%s')->on('%s')", $value, $foreignKey['references'], $foreignKey['on'] ); if ($foreignKey['onUpdate']) { $output .= sprintf("->onUpdate('%s')", $foreignKey['onUpdate']); } if ($foreignKey['onDelete']) { $output .= sprintf("->onDelete('%s')", $foreignKey['onDelete']); } if (isset($foreignKey['decorators'])) { $output .= $this->addDecorators($foreignKey['decorators']); } return $output . ';'; }
php
protected function getItem($foreignKey) { $value = $foreignKey['field']; if (! empty($foreignKey['name'])) { $value .= "', '". $foreignKey['name']; } $output = sprintf( "\$table->foreign('%s')->references('%s')->on('%s')", $value, $foreignKey['references'], $foreignKey['on'] ); if ($foreignKey['onUpdate']) { $output .= sprintf("->onUpdate('%s')", $foreignKey['onUpdate']); } if ($foreignKey['onDelete']) { $output .= sprintf("->onDelete('%s')", $foreignKey['onDelete']); } if (isset($foreignKey['decorators'])) { $output .= $this->addDecorators($foreignKey['decorators']); } return $output . ';'; }
[ "protected", "function", "getItem", "(", "$", "foreignKey", ")", "{", "$", "value", "=", "$", "foreignKey", "[", "'field'", "]", ";", "if", "(", "!", "empty", "(", "$", "foreignKey", "[", "'name'", "]", ")", ")", "{", "$", "value", ".=", "\"', '\"", ".", "$", "foreignKey", "[", "'name'", "]", ";", "}", "$", "output", "=", "sprintf", "(", "\"\\$table->foreign('%s')->references('%s')->on('%s')\"", ",", "$", "value", ",", "$", "foreignKey", "[", "'references'", "]", ",", "$", "foreignKey", "[", "'on'", "]", ")", ";", "if", "(", "$", "foreignKey", "[", "'onUpdate'", "]", ")", "{", "$", "output", ".=", "sprintf", "(", "\"->onUpdate('%s')\"", ",", "$", "foreignKey", "[", "'onUpdate'", "]", ")", ";", "}", "if", "(", "$", "foreignKey", "[", "'onDelete'", "]", ")", "{", "$", "output", ".=", "sprintf", "(", "\"->onDelete('%s')\"", ",", "$", "foreignKey", "[", "'onDelete'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "foreignKey", "[", "'decorators'", "]", ")", ")", "{", "$", "output", ".=", "$", "this", "->", "addDecorators", "(", "$", "foreignKey", "[", "'decorators'", "]", ")", ";", "}", "return", "$", "output", ".", "';'", ";", "}" ]
Return string for adding a foreign key @param array $foreignKey @return string
[ "Return", "string", "for", "adding", "a", "foreign", "key" ]
train
https://github.com/periaptio/empress-generator/blob/749fb4b12755819e9c97377ebfb446ee0822168a/src/Syntax/AddForeignKeysToTable.php#L16-L38
jinexus-framework/jinexus-mvc
src/Application/AbstractApplication.php
AbstractApplication.dispatchAction
public function dispatchAction($controller) { $action = $this->matchRoute[key($this->matchRoute)]['action'] . 'Action'; $viewModel = $controller->$action(); if ($viewModel instanceof ViewModel) { $this->view->setVariables($viewModel->getVariables()); } }
php
public function dispatchAction($controller) { $action = $this->matchRoute[key($this->matchRoute)]['action'] . 'Action'; $viewModel = $controller->$action(); if ($viewModel instanceof ViewModel) { $this->view->setVariables($viewModel->getVariables()); } }
[ "public", "function", "dispatchAction", "(", "$", "controller", ")", "{", "$", "action", "=", "$", "this", "->", "matchRoute", "[", "key", "(", "$", "this", "->", "matchRoute", ")", "]", "[", "'action'", "]", ".", "'Action'", ";", "$", "viewModel", "=", "$", "controller", "->", "$", "action", "(", ")", ";", "if", "(", "$", "viewModel", "instanceof", "ViewModel", ")", "{", "$", "this", "->", "view", "->", "setVariables", "(", "$", "viewModel", "->", "getVariables", "(", ")", ")", ";", "}", "}" ]
Dispatch Action @param $controller
[ "Dispatch", "Action" ]
train
https://github.com/jinexus-framework/jinexus-mvc/blob/63937fecea4bc927b1ac9669fee5cf50278d28d3/src/Application/AbstractApplication.php#L116-L125
jinexus-framework/jinexus-mvc
src/Application/AbstractApplication.php
AbstractApplication.error
public static function error($number, $string, $file, $line) { throw new \ErrorException($string, 0, $number, $file, $line); }
php
public static function error($number, $string, $file, $line) { throw new \ErrorException($string, 0, $number, $file, $line); }
[ "public", "static", "function", "error", "(", "$", "number", ",", "$", "string", ",", "$", "file", ",", "$", "line", ")", "{", "throw", "new", "\\", "ErrorException", "(", "$", "string", ",", "0", ",", "$", "number", ",", "$", "file", ",", "$", "line", ")", ";", "}" ]
Convert errors to \ErrorException instances @param int $number @param string $string @param string $file @param int $line @throws \ErrorException
[ "Convert", "errors", "to", "\\", "ErrorException", "instances" ]
train
https://github.com/jinexus-framework/jinexus-mvc/blob/63937fecea4bc927b1ac9669fee5cf50278d28d3/src/Application/AbstractApplication.php#L156-L159
jinexus-framework/jinexus-mvc
src/Application/AbstractApplication.php
AbstractApplication.renderView
public function renderView() { $viewManager = $this->config->get('view_manager'); try { $this->view->render($viewManager['template_map']['layout/layout']); } catch (Exception $e) { throw new \RuntimeException($e->getMessage()); } }
php
public function renderView() { $viewManager = $this->config->get('view_manager'); try { $this->view->render($viewManager['template_map']['layout/layout']); } catch (Exception $e) { throw new \RuntimeException($e->getMessage()); } }
[ "public", "function", "renderView", "(", ")", "{", "$", "viewManager", "=", "$", "this", "->", "config", "->", "get", "(", "'view_manager'", ")", ";", "try", "{", "$", "this", "->", "view", "->", "render", "(", "$", "viewManager", "[", "'template_map'", "]", "[", "'layout/layout'", "]", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Render View
[ "Render", "View" ]
train
https://github.com/jinexus-framework/jinexus-mvc/blob/63937fecea4bc927b1ac9669fee5cf50278d28d3/src/Application/AbstractApplication.php#L252-L261
jinexus-framework/jinexus-mvc
src/Application/AbstractApplication.php
AbstractApplication.run
public function run() { $this->view = $this->dispatchView(); if (! $this->matchRoute) { header('HTTP/1.0 404 Not Found'); header('Status: 404 Not Found'); $this->renderView(); exit(); } $controller = $this->dispatchController(); $this->dispatchAction($controller); $this->renderView(); }
php
public function run() { $this->view = $this->dispatchView(); if (! $this->matchRoute) { header('HTTP/1.0 404 Not Found'); header('Status: 404 Not Found'); $this->renderView(); exit(); } $controller = $this->dispatchController(); $this->dispatchAction($controller); $this->renderView(); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "view", "=", "$", "this", "->", "dispatchView", "(", ")", ";", "if", "(", "!", "$", "this", "->", "matchRoute", ")", "{", "header", "(", "'HTTP/1.0 404 Not Found'", ")", ";", "header", "(", "'Status: 404 Not Found'", ")", ";", "$", "this", "->", "renderView", "(", ")", ";", "exit", "(", ")", ";", "}", "$", "controller", "=", "$", "this", "->", "dispatchController", "(", ")", ";", "$", "this", "->", "dispatchAction", "(", "$", "controller", ")", ";", "$", "this", "->", "renderView", "(", ")", ";", "}" ]
Run Application
[ "Run", "Application" ]
train
https://github.com/jinexus-framework/jinexus-mvc/blob/63937fecea4bc927b1ac9669fee5cf50278d28d3/src/Application/AbstractApplication.php#L266-L280
ClanCats/Core
src/classes/CCTheme.php
CCTheme.create
public static function create( $file = null, $data = null, $encode = false ) { $view = parent::create( static::view_namespace().'::'.$file, $data, $encode ); // set the asset holder path \CCAsset::holder( 'theme' )->path = static::public_namespace(); // set the vendor path \CCAsset::holder( 'vendor' )->path = 'assets/vendor/'; // you may ask why not just return the parent::create(bla bla.. directly? // i actually wanted to do something with that var view. So if you'r still // able to read this i completly forgot it. return $view; }
php
public static function create( $file = null, $data = null, $encode = false ) { $view = parent::create( static::view_namespace().'::'.$file, $data, $encode ); // set the asset holder path \CCAsset::holder( 'theme' )->path = static::public_namespace(); // set the vendor path \CCAsset::holder( 'vendor' )->path = 'assets/vendor/'; // you may ask why not just return the parent::create(bla bla.. directly? // i actually wanted to do something with that var view. So if you'r still // able to read this i completly forgot it. return $view; }
[ "public", "static", "function", "create", "(", "$", "file", "=", "null", ",", "$", "data", "=", "null", ",", "$", "encode", "=", "false", ")", "{", "$", "view", "=", "parent", "::", "create", "(", "static", "::", "view_namespace", "(", ")", ".", "'::'", ".", "$", "file", ",", "$", "data", ",", "$", "encode", ")", ";", "// set the asset holder path", "\\", "CCAsset", "::", "holder", "(", "'theme'", ")", "->", "path", "=", "static", "::", "public_namespace", "(", ")", ";", "// set the vendor path", "\\", "CCAsset", "::", "holder", "(", "'vendor'", ")", "->", "path", "=", "'assets/vendor/'", ";", "// you may ask why not just return the parent::create(bla bla.. directly?", "// i actually wanted to do something with that var view. So if you'r still", "// able to read this i completly forgot it.", "return", "$", "view", ";", "}" ]
theme creator returns a new view instance @param string $file @param array $data @param bool $encode @return CCView
[ "theme", "creator", "returns", "a", "new", "view", "instance" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCTheme.php#L47-L61
ClanCats/Core
src/classes/CCTheme.php
CCTheme.view
public function view( $file = null, $data = null, $encode = false ) { if ( \CCView::exists( $view = static::view_namespace().'::'.$file ) ) { return \CCView::create( $view, $data, $encode ); } return \CCView::create( $file, $data, $encode ); }
php
public function view( $file = null, $data = null, $encode = false ) { if ( \CCView::exists( $view = static::view_namespace().'::'.$file ) ) { return \CCView::create( $view, $data, $encode ); } return \CCView::create( $file, $data, $encode ); }
[ "public", "function", "view", "(", "$", "file", "=", "null", ",", "$", "data", "=", "null", ",", "$", "encode", "=", "false", ")", "{", "if", "(", "\\", "CCView", "::", "exists", "(", "$", "view", "=", "static", "::", "view_namespace", "(", ")", ".", "'::'", ".", "$", "file", ")", ")", "{", "return", "\\", "CCView", "::", "create", "(", "$", "view", ",", "$", "data", ",", "$", "encode", ")", ";", "}", "return", "\\", "CCView", "::", "create", "(", "$", "file", ",", "$", "data", ",", "$", "encode", ")", ";", "}" ]
Creates a new view based on the current theme If the view cannot be found in the theme it's going to use the app::views @param string $file @param array $data @param bool $encode @return CCView
[ "Creates", "a", "new", "view", "based", "on", "the", "current", "theme", "If", "the", "view", "cannot", "be", "found", "in", "the", "theme", "it", "s", "going", "to", "use", "the", "app", "::", "views" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCTheme.php#L72-L80
Lansoweb/LosBase
src/LosBase/InputFilter/Factory.php
Factory.createInputString
public function createInputString($nome, $required = true, $min = 1, $max = 128, $filters = null, $validators = null) { if (null === $filters) { $filters = [ ['name' => 'StripTags'], ['name' => 'StringTrim'], ]; } if (null === $validators) { $validators = [ [ 'name' => 'StringLength', 'options' => [ 'encoding' => 'UTF-8', 'min' => $min, 'max' => $max, ], ], ]; } return $this->createInput([ 'name' => $nome, 'required' => $required, 'filters' => $filters, 'validators' => $validators, ]); }
php
public function createInputString($nome, $required = true, $min = 1, $max = 128, $filters = null, $validators = null) { if (null === $filters) { $filters = [ ['name' => 'StripTags'], ['name' => 'StringTrim'], ]; } if (null === $validators) { $validators = [ [ 'name' => 'StringLength', 'options' => [ 'encoding' => 'UTF-8', 'min' => $min, 'max' => $max, ], ], ]; } return $this->createInput([ 'name' => $nome, 'required' => $required, 'filters' => $filters, 'validators' => $validators, ]); }
[ "public", "function", "createInputString", "(", "$", "nome", ",", "$", "required", "=", "true", ",", "$", "min", "=", "1", ",", "$", "max", "=", "128", ",", "$", "filters", "=", "null", ",", "$", "validators", "=", "null", ")", "{", "if", "(", "null", "===", "$", "filters", ")", "{", "$", "filters", "=", "[", "[", "'name'", "=>", "'StripTags'", "]", ",", "[", "'name'", "=>", "'StringTrim'", "]", ",", "]", ";", "}", "if", "(", "null", "===", "$", "validators", ")", "{", "$", "validators", "=", "[", "[", "'name'", "=>", "'StringLength'", ",", "'options'", "=>", "[", "'encoding'", "=>", "'UTF-8'", ",", "'min'", "=>", "$", "min", ",", "'max'", "=>", "$", "max", ",", "]", ",", "]", ",", "]", ";", "}", "return", "$", "this", "->", "createInput", "(", "[", "'name'", "=>", "$", "nome", ",", "'required'", "=>", "$", "required", ",", "'filters'", "=>", "$", "filters", ",", "'validators'", "=>", "$", "validators", ",", "]", ")", ";", "}" ]
Cria um filtro padrão para strings. @param string $nome @param bool $required @param int $min @param int $max @param array $filters @param array $validators @return Ambigous <\Zend\InputFilter\InputInterface, \Zend\InputFilter\InputFilterInterface>
[ "Cria", "um", "filtro", "padrão", "para", "strings", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/InputFilter/Factory.php#L61-L88
simple-php-mvc/simple-php-mvc
src/MVC/Server/Response.php
Response._parse
protected function _parse($response) { $defaults = array( 'body' => '', 'headers' => array('Content-Type: text/html; charset=utf-8'), 'status' => 200 ); if ( is_array($response) ) { $response += $defaults; } elseif ( is_string($response) ) { $defaults['body'] = $response; $response = $defaults; } else { throw new \LogicException('Response can\'t be NULL.'); } return $response; }
php
protected function _parse($response) { $defaults = array( 'body' => '', 'headers' => array('Content-Type: text/html; charset=utf-8'), 'status' => 200 ); if ( is_array($response) ) { $response += $defaults; } elseif ( is_string($response) ) { $defaults['body'] = $response; $response = $defaults; } else { throw new \LogicException('Response can\'t be NULL.'); } return $response; }
[ "protected", "function", "_parse", "(", "$", "response", ")", "{", "$", "defaults", "=", "array", "(", "'body'", "=>", "''", ",", "'headers'", "=>", "array", "(", "'Content-Type: text/html; charset=utf-8'", ")", ",", "'status'", "=>", "200", ")", ";", "if", "(", "is_array", "(", "$", "response", ")", ")", "{", "$", "response", "+=", "$", "defaults", ";", "}", "elseif", "(", "is_string", "(", "$", "response", ")", ")", "{", "$", "defaults", "[", "'body'", "]", "=", "$", "response", ";", "$", "response", "=", "$", "defaults", ";", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "'Response can\\'t be NULL.'", ")", ";", "}", "return", "$", "response", ";", "}" ]
Parses a response. @access protected @param mixed $response The response to be parsed. Can be an array containing 'body', 'headers', and/or 'status' keys, or a string which will be used as the body of the response. Note that the headers must be well-formed HTTP headers, and the status must be an integer (i.e., the one associated with the HTTP status code). @return array
[ "Parses", "a", "response", "." ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Server/Response.php#L107-L123
simple-php-mvc/simple-php-mvc
src/MVC/Server/Response.php
Response.render
public function render($response, $status = null) { $response = $this->_parse($response); if (!is_null($status)) { $status = $this->_convert_status($status); } elseif (!is_null($response['status'])) { $status = $this->_convert_status($response['status']); } else { $status = $this->_convert_status(500); } if (!headers_sent()) { if (!strpos(PHP_SAPI, 'cgi')) { header($status); } foreach ( $response['headers'] as $header ) { header($header, false); } } $buffer_size = $this->_config['buffer_size']; $length = strlen($response['body']); for ( $i = 0; $i < $length; $i += $buffer_size ) { echo substr($response['body'], $i, $buffer_size); } }
php
public function render($response, $status = null) { $response = $this->_parse($response); if (!is_null($status)) { $status = $this->_convert_status($status); } elseif (!is_null($response['status'])) { $status = $this->_convert_status($response['status']); } else { $status = $this->_convert_status(500); } if (!headers_sent()) { if (!strpos(PHP_SAPI, 'cgi')) { header($status); } foreach ( $response['headers'] as $header ) { header($header, false); } } $buffer_size = $this->_config['buffer_size']; $length = strlen($response['body']); for ( $i = 0; $i < $length; $i += $buffer_size ) { echo substr($response['body'], $i, $buffer_size); } }
[ "public", "function", "render", "(", "$", "response", ",", "$", "status", "=", "null", ")", "{", "$", "response", "=", "$", "this", "->", "_parse", "(", "$", "response", ")", ";", "if", "(", "!", "is_null", "(", "$", "status", ")", ")", "{", "$", "status", "=", "$", "this", "->", "_convert_status", "(", "$", "status", ")", ";", "}", "elseif", "(", "!", "is_null", "(", "$", "response", "[", "'status'", "]", ")", ")", "{", "$", "status", "=", "$", "this", "->", "_convert_status", "(", "$", "response", "[", "'status'", "]", ")", ";", "}", "else", "{", "$", "status", "=", "$", "this", "->", "_convert_status", "(", "500", ")", ";", "}", "if", "(", "!", "headers_sent", "(", ")", ")", "{", "if", "(", "!", "strpos", "(", "PHP_SAPI", ",", "'cgi'", ")", ")", "{", "header", "(", "$", "status", ")", ";", "}", "foreach", "(", "$", "response", "[", "'headers'", "]", "as", "$", "header", ")", "{", "header", "(", "$", "header", ",", "false", ")", ";", "}", "}", "$", "buffer_size", "=", "$", "this", "->", "_config", "[", "'buffer_size'", "]", ";", "$", "length", "=", "strlen", "(", "$", "response", "[", "'body'", "]", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "+=", "$", "buffer_size", ")", "{", "echo", "substr", "(", "$", "response", "[", "'body'", "]", ",", "$", "i", ",", "$", "buffer_size", ")", ";", "}", "}" ]
Renders a response. @access public @param mixed $response The response to be rendered. Can be an array containing 'body', 'headers', and/or 'status' keys, or a string which will be used as the body of the response. Note that the headers must be well-formed HTTP headers, and the status must be an integer (i.e., the one associated with the HTTP status code). The response body is chunked according to the buffer_size set in the constructor. @param int $status The status of the response @return void
[ "Renders", "a", "response", "." ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Server/Response.php#L160-L186
gerritdrost/phenum
src/GerritDrost/Lib/Enum/Enum.php
Enum.byName
public static final function byName($enumName) { $instances = self::getInstances(get_called_class()); return isset($instances[$enumName]) ? $instances[$enumName] : null; }
php
public static final function byName($enumName) { $instances = self::getInstances(get_called_class()); return isset($instances[$enumName]) ? $instances[$enumName] : null; }
[ "public", "static", "final", "function", "byName", "(", "$", "enumName", ")", "{", "$", "instances", "=", "self", "::", "getInstances", "(", "get_called_class", "(", ")", ")", ";", "return", "isset", "(", "$", "instances", "[", "$", "enumName", "]", ")", "?", "$", "instances", "[", "$", "enumName", "]", ":", "null", ";", "}" ]
Returns the enum value instance representing the provided const name or null when the const name is not present in the enum. @param string $enumName @return Enum
[ "Returns", "the", "enum", "value", "instance", "representing", "the", "provided", "const", "name", "or", "null", "when", "the", "const", "name", "is", "not", "present", "in", "the", "enum", "." ]
train
https://github.com/gerritdrost/phenum/blob/935ba4911d0591dea9a2c94a1c1ab5babeec92cb/src/GerritDrost/Lib/Enum/Enum.php#L79-L86
gerritdrost/phenum
src/GerritDrost/Lib/Enum/Enum.php
Enum.getInstance
private final static function getInstance($fqcn, $name) { $instances = self::getInstances($fqcn); if (!isset($instances[$name])) { return null; } else { return $instances[$name]; } }
php
private final static function getInstance($fqcn, $name) { $instances = self::getInstances($fqcn); if (!isset($instances[$name])) { return null; } else { return $instances[$name]; } }
[ "private", "final", "static", "function", "getInstance", "(", "$", "fqcn", ",", "$", "name", ")", "{", "$", "instances", "=", "self", "::", "getInstances", "(", "$", "fqcn", ")", ";", "if", "(", "!", "isset", "(", "$", "instances", "[", "$", "name", "]", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "$", "instances", "[", "$", "name", "]", ";", "}", "}" ]
Returns the value singleton for the provided fqcn/name combination or null when the fqcn/name combo is invalid @param string $fqcn FQCN of the enum @param string $name Name of the constant @return static|null
[ "Returns", "the", "value", "singleton", "for", "the", "provided", "fqcn", "/", "name", "combination", "or", "null", "when", "the", "fqcn", "/", "name", "combo", "is", "invalid" ]
train
https://github.com/gerritdrost/phenum/blob/935ba4911d0591dea9a2c94a1c1ab5babeec92cb/src/GerritDrost/Lib/Enum/Enum.php#L123-L132
gerritdrost/phenum
src/GerritDrost/Lib/Enum/Enum.php
Enum.&
private final static function &getInstances($fqcn) { if (!isset(self::$instances[$fqcn])) { self::loadClass($fqcn); } return self::$instances[$fqcn]; }
php
private final static function &getInstances($fqcn) { if (!isset(self::$instances[$fqcn])) { self::loadClass($fqcn); } return self::$instances[$fqcn]; }
[ "private", "final", "static", "function", "&", "getInstances", "(", "$", "fqcn", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "instances", "[", "$", "fqcn", "]", ")", ")", "{", "self", "::", "loadClass", "(", "$", "fqcn", ")", ";", "}", "return", "self", "::", "$", "instances", "[", "$", "fqcn", "]", ";", "}" ]
Returns the array of all value singletons of one Enum class @param string $fqcn FQCN of the enum @return Enum[]
[ "Returns", "the", "array", "of", "all", "value", "singletons", "of", "one", "Enum", "class" ]
train
https://github.com/gerritdrost/phenum/blob/935ba4911d0591dea9a2c94a1c1ab5babeec92cb/src/GerritDrost/Lib/Enum/Enum.php#L141-L148
gerritdrost/phenum
src/GerritDrost/Lib/Enum/Enum.php
Enum.loadClass
private final static function loadClass($fqcn) { $reflectionClass = new ReflectionClass($fqcn); $constants = $reflectionClass->getConstants(); foreach ($constants as $name => $value) { $instance = new $fqcn($fqcn, $name, $value); /* @var $instance Enum */ if (is_callable([$instance, '__initEnum'])) { $instance->__initEnum(); } $instanceConstructorName = '__' . $name; if (is_callable([$instance, $instanceConstructorName])) { $instance->$instanceConstructorName(); } if (!isset(self::$instances[$fqcn])) { self::$instances[$fqcn] = []; } self::$instances[$fqcn][$name] = $instance; } }
php
private final static function loadClass($fqcn) { $reflectionClass = new ReflectionClass($fqcn); $constants = $reflectionClass->getConstants(); foreach ($constants as $name => $value) { $instance = new $fqcn($fqcn, $name, $value); /* @var $instance Enum */ if (is_callable([$instance, '__initEnum'])) { $instance->__initEnum(); } $instanceConstructorName = '__' . $name; if (is_callable([$instance, $instanceConstructorName])) { $instance->$instanceConstructorName(); } if (!isset(self::$instances[$fqcn])) { self::$instances[$fqcn] = []; } self::$instances[$fqcn][$name] = $instance; } }
[ "private", "final", "static", "function", "loadClass", "(", "$", "fqcn", ")", "{", "$", "reflectionClass", "=", "new", "ReflectionClass", "(", "$", "fqcn", ")", ";", "$", "constants", "=", "$", "reflectionClass", "->", "getConstants", "(", ")", ";", "foreach", "(", "$", "constants", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "instance", "=", "new", "$", "fqcn", "(", "$", "fqcn", ",", "$", "name", ",", "$", "value", ")", ";", "/* @var $instance Enum */", "if", "(", "is_callable", "(", "[", "$", "instance", ",", "'__initEnum'", "]", ")", ")", "{", "$", "instance", "->", "__initEnum", "(", ")", ";", "}", "$", "instanceConstructorName", "=", "'__'", ".", "$", "name", ";", "if", "(", "is_callable", "(", "[", "$", "instance", ",", "$", "instanceConstructorName", "]", ")", ")", "{", "$", "instance", "->", "$", "instanceConstructorName", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "self", "::", "$", "instances", "[", "$", "fqcn", "]", ")", ")", "{", "self", "::", "$", "instances", "[", "$", "fqcn", "]", "=", "[", "]", ";", "}", "self", "::", "$", "instances", "[", "$", "fqcn", "]", "[", "$", "name", "]", "=", "$", "instance", ";", "}", "}" ]
Uses reflection to load and cache all value singletons of the class represented by the fqcn. @param string $fqcn FQCN of the enum
[ "Uses", "reflection", "to", "load", "and", "cache", "all", "value", "singletons", "of", "the", "class", "represented", "by", "the", "fqcn", "." ]
train
https://github.com/gerritdrost/phenum/blob/935ba4911d0591dea9a2c94a1c1ab5babeec92cb/src/GerritDrost/Lib/Enum/Enum.php#L155-L179
1HappyPlace/phpunit-colors
src/PHPUnitColors/Display.php
Display.warning
public static function warning($text, $newline = true) { // echo the string surrounded with the escape coding to // display a warning $text = self::WARNING . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
php
public static function warning($text, $newline = true) { // echo the string surrounded with the escape coding to // display a warning $text = self::WARNING . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
[ "public", "static", "function", "warning", "(", "$", "text", ",", "$", "newline", "=", "true", ")", "{", "// echo the string surrounded with the escape coding to", "// display a warning", "$", "text", "=", "self", "::", "WARNING", ".", "$", "text", ".", "self", "::", "CLEAR", ";", "// if a carriage return was desired, send it out", "$", "text", ".=", "$", "newline", "?", "\"\\n\"", ":", "\"\"", ";", "// return the escaped text", "return", "$", "text", ";", "}" ]
Display the text with a red background and white foreground and end it with the newline character (if desired) @param mixed $text - the text of the message @param boolean $newline - whether to append a new line @return string - the escaped sequence and the optional newline
[ "Display", "the", "text", "with", "a", "red", "background", "and", "white", "foreground", "and", "end", "it", "with", "the", "newline", "character", "(", "if", "desired", ")" ]
train
https://github.com/1HappyPlace/phpunit-colors/blob/05d40d2a2feb8b95e7e845c86afb93fa54bd5f18/src/PHPUnitColors/Display.php#L52-L64
1HappyPlace/phpunit-colors
src/PHPUnitColors/Display.php
Display.caution
public static function caution($text, $newline = true) { // echo the string surrounded with the escape coding to // display a cautionary message $text = self::CAUTION . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
php
public static function caution($text, $newline = true) { // echo the string surrounded with the escape coding to // display a cautionary message $text = self::CAUTION . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
[ "public", "static", "function", "caution", "(", "$", "text", ",", "$", "newline", "=", "true", ")", "{", "// echo the string surrounded with the escape coding to", "// display a cautionary message", "$", "text", "=", "self", "::", "CAUTION", ".", "$", "text", ".", "self", "::", "CLEAR", ";", "// if a carriage return was desired, send it out", "$", "text", ".=", "$", "newline", "?", "\"\\n\"", ":", "\"\"", ";", "// return the escaped text", "return", "$", "text", ";", "}" ]
Display the text with a yellow background and black foreground and end it with the newline character (if desired) @param mixed $text - the text of the message @param boolean $newline - whether to append a new line @return string - the escaped sequence and the optional newline
[ "Display", "the", "text", "with", "a", "yellow", "background", "and", "black", "foreground", "and", "end", "it", "with", "the", "newline", "character", "(", "if", "desired", ")" ]
train
https://github.com/1HappyPlace/phpunit-colors/blob/05d40d2a2feb8b95e7e845c86afb93fa54bd5f18/src/PHPUnitColors/Display.php#L75-L86
1HappyPlace/phpunit-colors
src/PHPUnitColors/Display.php
Display.OK
public static function OK($text, $newline = true) { // echo the string surrounded with the escape coding to // display a positive message $text = self::OK . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
php
public static function OK($text, $newline = true) { // echo the string surrounded with the escape coding to // display a positive message $text = self::OK . $text . self::CLEAR; // if a carriage return was desired, send it out $text .= $newline ? "\n" : ""; // return the escaped text return $text; }
[ "public", "static", "function", "OK", "(", "$", "text", ",", "$", "newline", "=", "true", ")", "{", "// echo the string surrounded with the escape coding to", "// display a positive message", "$", "text", "=", "self", "::", "OK", ".", "$", "text", ".", "self", "::", "CLEAR", ";", "// if a carriage return was desired, send it out", "$", "text", ".=", "$", "newline", "?", "\"\\n\"", ":", "\"\"", ";", "// return the escaped text", "return", "$", "text", ";", "}" ]
Display the text with a green background and black foreground and end it with the newline character (if desired) @param mixed $text - the text of the message @param boolean $newline - whether to append a new line @return string - the escaped sequence and the optional newline
[ "Display", "the", "text", "with", "a", "green", "background", "and", "black", "foreground", "and", "end", "it", "with", "the", "newline", "character", "(", "if", "desired", ")" ]
train
https://github.com/1HappyPlace/phpunit-colors/blob/05d40d2a2feb8b95e7e845c86afb93fa54bd5f18/src/PHPUnitColors/Display.php#L97-L108
inpsyde/inpsyde-filter
src/WordPress/SanitizeTitle.php
SanitizeTitle.filter
public function filter( $value ) { if ( ! is_string( $value ) || empty( $value ) ) { do_action( 'inpsyde.filter.error', 'The given value is not string or empty.', [ 'method' => __METHOD__, 'value' => $value ] ); return $value; } $fallback = (string) $this->options[ 'fallback' ]; $context = (string) $this->options[ 'context' ]; return sanitize_title( $value, $fallback, $context ); }
php
public function filter( $value ) { if ( ! is_string( $value ) || empty( $value ) ) { do_action( 'inpsyde.filter.error', 'The given value is not string or empty.', [ 'method' => __METHOD__, 'value' => $value ] ); return $value; } $fallback = (string) $this->options[ 'fallback' ]; $context = (string) $this->options[ 'context' ]; return sanitize_title( $value, $fallback, $context ); }
[ "public", "function", "filter", "(", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "||", "empty", "(", "$", "value", ")", ")", "{", "do_action", "(", "'inpsyde.filter.error'", ",", "'The given value is not string or empty.'", ",", "[", "'method'", "=>", "__METHOD__", ",", "'value'", "=>", "$", "value", "]", ")", ";", "return", "$", "value", ";", "}", "$", "fallback", "=", "(", "string", ")", "$", "this", "->", "options", "[", "'fallback'", "]", ";", "$", "context", "=", "(", "string", ")", "$", "this", "->", "options", "[", "'context'", "]", ";", "return", "sanitize_title", "(", "$", "value", ",", "$", "fallback", ",", "$", "context", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/inpsyde/inpsyde-filter/blob/777a6208ea4dfbeed89e6d0712a35dc25eab498b/src/WordPress/SanitizeTitle.php#L25-L37
phpmob/changmin
src/PhpMob/WidgetBundle/DependencyInjection/PhpMobWidgetExtension.php
PhpMobWidgetExtension.load
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $container->setParameter('phpmob.widgets', $config['widgets']); // auto register // simple widget without register twig service // can set or not set the service, if set can with or without `twig.extension` tag foreach (array_keys($config['widgets']) as $class) { $def = new Definition(); $hasDefinition = false; foreach ($container->getDefinitions() as $definition) { if ($definition->getClass() === $class) { $def = $definition; $hasDefinition = true; break; } } if (!$hasDefinition) { $container->setDefinition($class, $def); } $def->setClass($class)->addTag('twig.extension'); } }
php
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $container->setParameter('phpmob.widgets', $config['widgets']); // auto register // simple widget without register twig service // can set or not set the service, if set can with or without `twig.extension` tag foreach (array_keys($config['widgets']) as $class) { $def = new Definition(); $hasDefinition = false; foreach ($container->getDefinitions() as $definition) { if ($definition->getClass() === $class) { $def = $definition; $hasDefinition = true; break; } } if (!$hasDefinition) { $container->setDefinition($class, $def); } $def->setClass($class)->addTag('twig.extension'); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "config", "=", "$", "this", "->", "processConfiguration", "(", "new", "Configuration", "(", ")", ",", "$", "configs", ")", ";", "$", "loader", "=", "new", "Loader", "\\", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "loader", "->", "load", "(", "'services.xml'", ")", ";", "$", "container", "->", "setParameter", "(", "'phpmob.widgets'", ",", "$", "config", "[", "'widgets'", "]", ")", ";", "// auto register", "// simple widget without register twig service", "// can set or not set the service, if set can with or without `twig.extension` tag", "foreach", "(", "array_keys", "(", "$", "config", "[", "'widgets'", "]", ")", "as", "$", "class", ")", "{", "$", "def", "=", "new", "Definition", "(", ")", ";", "$", "hasDefinition", "=", "false", ";", "foreach", "(", "$", "container", "->", "getDefinitions", "(", ")", "as", "$", "definition", ")", "{", "if", "(", "$", "definition", "->", "getClass", "(", ")", "===", "$", "class", ")", "{", "$", "def", "=", "$", "definition", ";", "$", "hasDefinition", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "hasDefinition", ")", "{", "$", "container", "->", "setDefinition", "(", "$", "class", ",", "$", "def", ")", ";", "}", "$", "def", "->", "setClass", "(", "$", "class", ")", "->", "addTag", "(", "'twig.extension'", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/WidgetBundle/DependencyInjection/PhpMobWidgetExtension.php#L38-L67
redaigbaria/oauth2
src/Grant/AbstractGrant.php
AbstractGrant.validateScopes
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) { $scopesList = explode($this->server->getScopeDelimiter(), $scopeParam); for ($i = 0; $i < count($scopesList); $i++) { $scopesList[$i] = trim($scopesList[$i]); if ($scopesList[$i] === '') { unset($scopesList[$i]); // Remove any junk scopes } } if ( $this->server->scopeParamRequired() === true && $this->server->getDefaultScope() === null && count($scopesList) === 0 ) { throw new Exception\InvalidRequestException('scope'); } elseif (count($scopesList) === 0 && $this->server->getDefaultScope() !== null) { if (is_array($this->server->getDefaultScope())) { $scopesList = $this->server->getDefaultScope(); } else { $scopesList = [0 => $this->server->getDefaultScope()]; } } $scopes = []; foreach ($scopesList as $scopeItem) { $scope = $this->server->getScopeStorage()->get( $scopeItem, $this->getIdentifier(), $client->getId() ); if (($scope instanceof ScopeEntity) === false) { throw new Exception\InvalidScopeException($scopeItem, $redirectUri); } $scopes[$scope->getId()] = $scope; } return $scopes; }
php
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) { $scopesList = explode($this->server->getScopeDelimiter(), $scopeParam); for ($i = 0; $i < count($scopesList); $i++) { $scopesList[$i] = trim($scopesList[$i]); if ($scopesList[$i] === '') { unset($scopesList[$i]); // Remove any junk scopes } } if ( $this->server->scopeParamRequired() === true && $this->server->getDefaultScope() === null && count($scopesList) === 0 ) { throw new Exception\InvalidRequestException('scope'); } elseif (count($scopesList) === 0 && $this->server->getDefaultScope() !== null) { if (is_array($this->server->getDefaultScope())) { $scopesList = $this->server->getDefaultScope(); } else { $scopesList = [0 => $this->server->getDefaultScope()]; } } $scopes = []; foreach ($scopesList as $scopeItem) { $scope = $this->server->getScopeStorage()->get( $scopeItem, $this->getIdentifier(), $client->getId() ); if (($scope instanceof ScopeEntity) === false) { throw new Exception\InvalidScopeException($scopeItem, $redirectUri); } $scopes[$scope->getId()] = $scope; } return $scopes; }
[ "public", "function", "validateScopes", "(", "$", "scopeParam", "=", "''", ",", "ClientEntity", "$", "client", ",", "$", "redirectUri", "=", "null", ")", "{", "$", "scopesList", "=", "explode", "(", "$", "this", "->", "server", "->", "getScopeDelimiter", "(", ")", ",", "$", "scopeParam", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "scopesList", ")", ";", "$", "i", "++", ")", "{", "$", "scopesList", "[", "$", "i", "]", "=", "trim", "(", "$", "scopesList", "[", "$", "i", "]", ")", ";", "if", "(", "$", "scopesList", "[", "$", "i", "]", "===", "''", ")", "{", "unset", "(", "$", "scopesList", "[", "$", "i", "]", ")", ";", "// Remove any junk scopes", "}", "}", "if", "(", "$", "this", "->", "server", "->", "scopeParamRequired", "(", ")", "===", "true", "&&", "$", "this", "->", "server", "->", "getDefaultScope", "(", ")", "===", "null", "&&", "count", "(", "$", "scopesList", ")", "===", "0", ")", "{", "throw", "new", "Exception", "\\", "InvalidRequestException", "(", "'scope'", ")", ";", "}", "elseif", "(", "count", "(", "$", "scopesList", ")", "===", "0", "&&", "$", "this", "->", "server", "->", "getDefaultScope", "(", ")", "!==", "null", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "server", "->", "getDefaultScope", "(", ")", ")", ")", "{", "$", "scopesList", "=", "$", "this", "->", "server", "->", "getDefaultScope", "(", ")", ";", "}", "else", "{", "$", "scopesList", "=", "[", "0", "=>", "$", "this", "->", "server", "->", "getDefaultScope", "(", ")", "]", ";", "}", "}", "$", "scopes", "=", "[", "]", ";", "foreach", "(", "$", "scopesList", "as", "$", "scopeItem", ")", "{", "$", "scope", "=", "$", "this", "->", "server", "->", "getScopeStorage", "(", ")", "->", "get", "(", "$", "scopeItem", ",", "$", "this", "->", "getIdentifier", "(", ")", ",", "$", "client", "->", "getId", "(", ")", ")", ";", "if", "(", "(", "$", "scope", "instanceof", "ScopeEntity", ")", "===", "false", ")", "{", "throw", "new", "Exception", "\\", "InvalidScopeException", "(", "$", "scopeItem", ",", "$", "redirectUri", ")", ";", "}", "$", "scopes", "[", "$", "scope", "->", "getId", "(", ")", "]", "=", "$", "scope", ";", "}", "return", "$", "scopes", ";", "}" ]
Given a list of scopes, validate them and return an array of Scope entities @param string $scopeParam A string of scopes (e.g. "profile email birthday") @param \League\OAuth2\Server\Entity\ClientEntity $client Client entity @param string|null $redirectUri The redirect URI to return the user to @return \League\OAuth2\Server\Entity\ScopeEntity[] @throws \League\OAuth2\Server\Exception\InvalidScopeException If scope is invalid, or no scopes passed when required @throws
[ "Given", "a", "list", "of", "scopes", "validate", "them", "and", "return", "an", "array", "of", "Scope", "entities" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Grant/AbstractGrant.php#L135-L177
redaigbaria/oauth2
src/Grant/AbstractGrant.php
AbstractGrant.formatScopes
protected function formatScopes($unformated = []) { $scopes = []; foreach ($unformated as $scope) { if ($scope instanceof ScopeEntity) { $scopes[$scope->getId()] = $scope; } } return $scopes; }
php
protected function formatScopes($unformated = []) { $scopes = []; foreach ($unformated as $scope) { if ($scope instanceof ScopeEntity) { $scopes[$scope->getId()] = $scope; } } return $scopes; }
[ "protected", "function", "formatScopes", "(", "$", "unformated", "=", "[", "]", ")", "{", "$", "scopes", "=", "[", "]", ";", "foreach", "(", "$", "unformated", "as", "$", "scope", ")", "{", "if", "(", "$", "scope", "instanceof", "ScopeEntity", ")", "{", "$", "scopes", "[", "$", "scope", "->", "getId", "(", ")", "]", "=", "$", "scope", ";", "}", "}", "return", "$", "scopes", ";", "}" ]
Format the local scopes array @param \League\OAuth2\Server\Entity\ScopeEntity[] @return array
[ "Format", "the", "local", "scopes", "array" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Grant/AbstractGrant.php#L186-L196
yuncms/framework
src/user/models/UserBizRule.php
UserBizRule.classExists
public function classExists() { if (!class_exists($this->className)) { $message = Yii::t('yuncms', "Unknown class '{class}'", ['class' => $this->className]); $this->addError('className', $message); return; } if (!is_subclass_of($this->className, Rule::class)) { $message = Yii::t('yuncms', "'{class}' must extend from 'yii\\rbac\\Rule' or its child class", [ 'class' => $this->className]); $this->addError('className', $message); } }
php
public function classExists() { if (!class_exists($this->className)) { $message = Yii::t('yuncms', "Unknown class '{class}'", ['class' => $this->className]); $this->addError('className', $message); return; } if (!is_subclass_of($this->className, Rule::class)) { $message = Yii::t('yuncms', "'{class}' must extend from 'yii\\rbac\\Rule' or its child class", [ 'class' => $this->className]); $this->addError('className', $message); } }
[ "public", "function", "classExists", "(", ")", "{", "if", "(", "!", "class_exists", "(", "$", "this", "->", "className", ")", ")", "{", "$", "message", "=", "Yii", "::", "t", "(", "'yuncms'", ",", "\"Unknown class '{class}'\"", ",", "[", "'class'", "=>", "$", "this", "->", "className", "]", ")", ";", "$", "this", "->", "addError", "(", "'className'", ",", "$", "message", ")", ";", "return", ";", "}", "if", "(", "!", "is_subclass_of", "(", "$", "this", "->", "className", ",", "Rule", "::", "class", ")", ")", "{", "$", "message", "=", "Yii", "::", "t", "(", "'yuncms'", ",", "\"'{class}' must extend from 'yii\\\\rbac\\\\Rule' or its child class\"", ",", "[", "'class'", "=>", "$", "this", "->", "className", "]", ")", ";", "$", "this", "->", "addError", "(", "'className'", ",", "$", "message", ")", ";", "}", "}" ]
Validate class exists
[ "Validate", "class", "exists" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/UserBizRule.php#L72-L84
yuncms/framework
src/user/models/UserBizRule.php
UserBizRule.find
public static function find($id) { $item = UserRBACHelper::getAuthManager()->getRule($id); if ($item !== null) { return new static($item); } return null; }
php
public static function find($id) { $item = UserRBACHelper::getAuthManager()->getRule($id); if ($item !== null) { return new static($item); } return null; }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "item", "=", "UserRBACHelper", "::", "getAuthManager", "(", ")", "->", "getRule", "(", "$", "id", ")", ";", "if", "(", "$", "item", "!==", "null", ")", "{", "return", "new", "static", "(", "$", "item", ")", ";", "}", "return", "null", ";", "}" ]
Find model by id @param int $id @return null|static @throws \yii\base\InvalidConfigException
[ "Find", "model", "by", "id" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/UserBizRule.php#L112-L120
yuncms/framework
src/user/models/UserBizRule.php
UserBizRule.save
public function save() { if ($this->validate()) { $class = $this->className; if ($this->_item === null) { $this->_item = new $class(); $isNew = true; } else { $isNew = false; $oldName = $this->_item->name; } $this->_item->name = $this->name; if ($isNew) { UserRBACHelper::getAuthManager()->add($this->_item); } else { UserRBACHelper::getAuthManager()->update($oldName, $this->_item); } return true; } else { return false; } }
php
public function save() { if ($this->validate()) { $class = $this->className; if ($this->_item === null) { $this->_item = new $class(); $isNew = true; } else { $isNew = false; $oldName = $this->_item->name; } $this->_item->name = $this->name; if ($isNew) { UserRBACHelper::getAuthManager()->add($this->_item); } else { UserRBACHelper::getAuthManager()->update($oldName, $this->_item); } return true; } else { return false; } }
[ "public", "function", "save", "(", ")", "{", "if", "(", "$", "this", "->", "validate", "(", ")", ")", "{", "$", "class", "=", "$", "this", "->", "className", ";", "if", "(", "$", "this", "->", "_item", "===", "null", ")", "{", "$", "this", "->", "_item", "=", "new", "$", "class", "(", ")", ";", "$", "isNew", "=", "true", ";", "}", "else", "{", "$", "isNew", "=", "false", ";", "$", "oldName", "=", "$", "this", "->", "_item", "->", "name", ";", "}", "$", "this", "->", "_item", "->", "name", "=", "$", "this", "->", "name", ";", "if", "(", "$", "isNew", ")", "{", "UserRBACHelper", "::", "getAuthManager", "(", ")", "->", "add", "(", "$", "this", "->", "_item", ")", ";", "}", "else", "{", "UserRBACHelper", "::", "getAuthManager", "(", ")", "->", "update", "(", "$", "oldName", ",", "$", "this", "->", "_item", ")", ";", "}", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Save model to authManager @return boolean @throws \Exception
[ "Save", "model", "to", "authManager" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/UserBizRule.php#L127-L150
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php
BaseSystemSettingsQuery.create
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof SystemSettingsQuery) { return $criteria; } $query = new SystemSettingsQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
php
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof SystemSettingsQuery) { return $criteria; } $query = new SystemSettingsQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
[ "public", "static", "function", "create", "(", "$", "modelAlias", "=", "null", ",", "$", "criteria", "=", "null", ")", "{", "if", "(", "$", "criteria", "instanceof", "SystemSettingsQuery", ")", "{", "return", "$", "criteria", ";", "}", "$", "query", "=", "new", "SystemSettingsQuery", "(", "null", ",", "null", ",", "$", "modelAlias", ")", ";", "if", "(", "$", "criteria", "instanceof", "Criteria", ")", "{", "$", "query", "->", "mergeWith", "(", "$", "criteria", ")", ";", "}", "return", "$", "query", ";", "}" ]
Returns a new SystemSettingsQuery object. @param string $modelAlias The alias of a model in the query @param SystemSettingsQuery|Criteria $criteria Optional Criteria to build the query from @return SystemSettingsQuery
[ "Returns", "a", "new", "SystemSettingsQuery", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php#L68-L80
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php
BaseSystemSettingsQuery.filterByKey
public function filterByKey($key = null, $comparison = null) { if (null === $comparison) { if (is_array($key)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $key)) { $key = str_replace('*', '%', $key); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(SystemSettingsPeer::KEY, $key, $comparison); }
php
public function filterByKey($key = null, $comparison = null) { if (null === $comparison) { if (is_array($key)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $key)) { $key = str_replace('*', '%', $key); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(SystemSettingsPeer::KEY, $key, $comparison); }
[ "public", "function", "filterByKey", "(", "$", "key", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "key", ")", ")", "{", "$", "key", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "key", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "SystemSettingsPeer", "::", "KEY", ",", "$", "key", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the key column Example usage: <code> $query->filterByKey('fooValue'); // WHERE key = 'fooValue' $query->filterByKey('%fooValue%'); // WHERE key LIKE '%fooValue%' </code> @param string $key The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return SystemSettingsQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "key", "column" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php#L290-L302
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php
BaseSystemSettingsQuery.prune
public function prune($systemSettings = null) { if ($systemSettings) { $this->addUsingAlias(SystemSettingsPeer::ID, $systemSettings->getId(), Criteria::NOT_EQUAL); } return $this; }
php
public function prune($systemSettings = null) { if ($systemSettings) { $this->addUsingAlias(SystemSettingsPeer::ID, $systemSettings->getId(), Criteria::NOT_EQUAL); } return $this; }
[ "public", "function", "prune", "(", "$", "systemSettings", "=", "null", ")", "{", "if", "(", "$", "systemSettings", ")", "{", "$", "this", "->", "addUsingAlias", "(", "SystemSettingsPeer", "::", "ID", ",", "$", "systemSettings", "->", "getId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param SystemSettings $systemSettings Object to remove from the list of results @return SystemSettingsQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseSystemSettingsQuery.php#L340-L347
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.buildUrl
public function buildUrl() { $url = $this->getApiUrl(); if ($endpoint = $this->getEndpoint()) { $url .= $endpoint; } if ($id = $this->getId()) { $url .= '/'.$id; } $parameters = []; if ($include = $this->getInclude()) { if (is_array($include)) { $include = implode(',', $include); } $parameters['include'] = $include; } if ($filters = $this->getFilters()) { if (!empty($filters)) { $parameters['filter'] = $filters; } } if ($pageSize = $this->getPageSize()) { if (!empty($pageSize)) { $parameters['page'] = ['size' => $pageSize]; } } if ($sort = $this->getSort()) { if (!empty($sort)) { $parameters['sort'] = $sort; } } if ($parameters) { $url .= '?'.http_build_query($parameters); } return $url; }
php
public function buildUrl() { $url = $this->getApiUrl(); if ($endpoint = $this->getEndpoint()) { $url .= $endpoint; } if ($id = $this->getId()) { $url .= '/'.$id; } $parameters = []; if ($include = $this->getInclude()) { if (is_array($include)) { $include = implode(',', $include); } $parameters['include'] = $include; } if ($filters = $this->getFilters()) { if (!empty($filters)) { $parameters['filter'] = $filters; } } if ($pageSize = $this->getPageSize()) { if (!empty($pageSize)) { $parameters['page'] = ['size' => $pageSize]; } } if ($sort = $this->getSort()) { if (!empty($sort)) { $parameters['sort'] = $sort; } } if ($parameters) { $url .= '?'.http_build_query($parameters); } return $url; }
[ "public", "function", "buildUrl", "(", ")", "{", "$", "url", "=", "$", "this", "->", "getApiUrl", "(", ")", ";", "if", "(", "$", "endpoint", "=", "$", "this", "->", "getEndpoint", "(", ")", ")", "{", "$", "url", ".=", "$", "endpoint", ";", "}", "if", "(", "$", "id", "=", "$", "this", "->", "getId", "(", ")", ")", "{", "$", "url", ".=", "'/'", ".", "$", "id", ";", "}", "$", "parameters", "=", "[", "]", ";", "if", "(", "$", "include", "=", "$", "this", "->", "getInclude", "(", ")", ")", "{", "if", "(", "is_array", "(", "$", "include", ")", ")", "{", "$", "include", "=", "implode", "(", "','", ",", "$", "include", ")", ";", "}", "$", "parameters", "[", "'include'", "]", "=", "$", "include", ";", "}", "if", "(", "$", "filters", "=", "$", "this", "->", "getFilters", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "filters", ")", ")", "{", "$", "parameters", "[", "'filter'", "]", "=", "$", "filters", ";", "}", "}", "if", "(", "$", "pageSize", "=", "$", "this", "->", "getPageSize", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "pageSize", ")", ")", "{", "$", "parameters", "[", "'page'", "]", "=", "[", "'size'", "=>", "$", "pageSize", "]", ";", "}", "}", "if", "(", "$", "sort", "=", "$", "this", "->", "getSort", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "sort", ")", ")", "{", "$", "parameters", "[", "'sort'", "]", "=", "$", "sort", ";", "}", "}", "if", "(", "$", "parameters", ")", "{", "$", "url", ".=", "'?'", ".", "http_build_query", "(", "$", "parameters", ")", ";", "}", "return", "$", "url", ";", "}" ]
Build api call url. @return string
[ "Build", "api", "call", "url", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L207-L242
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.httpGetRequest
public function httpGetRequest($url) { // Check for cache hit. if ($this->useCache()) { $cache = $this->getCache(); if ($response = $cache->get($url)) { return $response; } } if (empty($this->client)) { $this->client = new Client(['verify' => false]); } $this->response = $this->client->request( 'GET', $url, ['headers' => $this->getHeaders()] ); $response = json_decode($this->response->getBody()); if (!empty($cache)) { $cache->put($url, $response, $this->getCacheTtl()); } return $response; }
php
public function httpGetRequest($url) { // Check for cache hit. if ($this->useCache()) { $cache = $this->getCache(); if ($response = $cache->get($url)) { return $response; } } if (empty($this->client)) { $this->client = new Client(['verify' => false]); } $this->response = $this->client->request( 'GET', $url, ['headers' => $this->getHeaders()] ); $response = json_decode($this->response->getBody()); if (!empty($cache)) { $cache->put($url, $response, $this->getCacheTtl()); } return $response; }
[ "public", "function", "httpGetRequest", "(", "$", "url", ")", "{", "// Check for cache hit.", "if", "(", "$", "this", "->", "useCache", "(", ")", ")", "{", "$", "cache", "=", "$", "this", "->", "getCache", "(", ")", ";", "if", "(", "$", "response", "=", "$", "cache", "->", "get", "(", "$", "url", ")", ")", "{", "return", "$", "response", ";", "}", "}", "if", "(", "empty", "(", "$", "this", "->", "client", ")", ")", "{", "$", "this", "->", "client", "=", "new", "Client", "(", "[", "'verify'", "=>", "false", "]", ")", ";", "}", "$", "this", "->", "response", "=", "$", "this", "->", "client", "->", "request", "(", "'GET'", ",", "$", "url", ",", "[", "'headers'", "=>", "$", "this", "->", "getHeaders", "(", ")", "]", ")", ";", "$", "response", "=", "json_decode", "(", "$", "this", "->", "response", "->", "getBody", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "cache", ")", ")", "{", "$", "cache", "->", "put", "(", "$", "url", ",", "$", "response", ",", "$", "this", "->", "getCacheTtl", "(", ")", ")", ";", "}", "return", "$", "response", ";", "}" ]
Make a GET request and respond with json decoded to array. @param string $url @return array
[ "Make", "a", "GET", "request", "and", "respond", "with", "json", "decoded", "to", "array", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L265-L292
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.httpPostRequest
public function httpPostRequest($url, $parameters) { if (empty($this->client)) { $this->client = new Client(['verify' => false]); } $this->response = $this->client->request( 'POST', $url, [ 'headers' => $this->getHeaders(), 'json' => $parameters ] ); $response = json_decode($this->response->getBody()); return $response; }
php
public function httpPostRequest($url, $parameters) { if (empty($this->client)) { $this->client = new Client(['verify' => false]); } $this->response = $this->client->request( 'POST', $url, [ 'headers' => $this->getHeaders(), 'json' => $parameters ] ); $response = json_decode($this->response->getBody()); return $response; }
[ "public", "function", "httpPostRequest", "(", "$", "url", ",", "$", "parameters", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "client", ")", ")", "{", "$", "this", "->", "client", "=", "new", "Client", "(", "[", "'verify'", "=>", "false", "]", ")", ";", "}", "$", "this", "->", "response", "=", "$", "this", "->", "client", "->", "request", "(", "'POST'", ",", "$", "url", ",", "[", "'headers'", "=>", "$", "this", "->", "getHeaders", "(", ")", ",", "'json'", "=>", "$", "parameters", "]", ")", ";", "$", "response", "=", "json_decode", "(", "$", "this", "->", "response", "->", "getBody", "(", ")", ")", ";", "return", "$", "response", ";", "}" ]
Make a POST request and respond with json decoded to array. @param string $url @param array $url @return array
[ "Make", "a", "POST", "request", "and", "respond", "with", "json", "decoded", "to", "array", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L301-L318
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.get
public function get($fields = null) { if (!empty($fields)) { $this->fields($fields); } return $this->httpGetRequest($this->buildUrl()); }
php
public function get($fields = null) { if (!empty($fields)) { $this->fields($fields); } return $this->httpGetRequest($this->buildUrl()); }
[ "public", "function", "get", "(", "$", "fields", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "fields", ")", ")", "{", "$", "this", "->", "fields", "(", "$", "fields", ")", ";", "}", "return", "$", "this", "->", "httpGetRequest", "(", "$", "this", "->", "buildUrl", "(", ")", ")", ";", "}" ]
Call get request. @param array|null $fields @return object
[ "Call", "get", "request", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L350-L357
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.first
public function first() { $response = $this->httpGetRequest($this->buildUrl()); if (empty($response->data[0])) { return false; } return $response->data[0]; }
php
public function first() { $response = $this->httpGetRequest($this->buildUrl()); if (empty($response->data[0])) { return false; } return $response->data[0]; }
[ "public", "function", "first", "(", ")", "{", "$", "response", "=", "$", "this", "->", "httpGetRequest", "(", "$", "this", "->", "buildUrl", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "response", "->", "data", "[", "0", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "response", "->", "data", "[", "0", "]", ";", "}" ]
Get first item from get response. @return stdClass|false
[ "Get", "first", "item", "from", "get", "response", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L364-L373
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.flush
public function flush() { $this->filters = []; $this->include = null; $this->id = null; $this->endpoint = null; $this->sort = null; $this->fields = null; $this->pageSize = null; $this->response = null; }
php
public function flush() { $this->filters = []; $this->include = null; $this->id = null; $this->endpoint = null; $this->sort = null; $this->fields = null; $this->pageSize = null; $this->response = null; }
[ "public", "function", "flush", "(", ")", "{", "$", "this", "->", "filters", "=", "[", "]", ";", "$", "this", "->", "include", "=", "null", ";", "$", "this", "->", "id", "=", "null", ";", "$", "this", "->", "endpoint", "=", "null", ";", "$", "this", "->", "sort", "=", "null", ";", "$", "this", "->", "fields", "=", "null", ";", "$", "this", "->", "pageSize", "=", "null", ";", "$", "this", "->", "response", "=", "null", ";", "}" ]
Unset all call parameters. @return void
[ "Unset", "all", "call", "parameters", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L522-L532
monthly-cloud/monthly-sdk-php
src/Builder.php
Builder.useCache
public function useCache($caching = null) { if (is_null($caching)) { return ($this->useCache && $this->getCache()); } $this->useCache = (bool) $caching; return $this; }
php
public function useCache($caching = null) { if (is_null($caching)) { return ($this->useCache && $this->getCache()); } $this->useCache = (bool) $caching; return $this; }
[ "public", "function", "useCache", "(", "$", "caching", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "caching", ")", ")", "{", "return", "(", "$", "this", "->", "useCache", "&&", "$", "this", "->", "getCache", "(", ")", ")", ";", "}", "$", "this", "->", "useCache", "=", "(", "bool", ")", "$", "caching", ";", "return", "$", "this", ";", "}" ]
Check if cache can be used in this request, or set caching for request. Apply only to get requests. @param bool|null $caching @return self|bool
[ "Check", "if", "cache", "can", "be", "used", "in", "this", "request", "or", "set", "caching", "for", "request", "." ]
train
https://github.com/monthly-cloud/monthly-sdk-php/blob/88b9d2bb346344495346a42043108627f648a793/src/Builder.php#L542-L551
rayrutjes/domain-foundation
src/UnitOfWork/DefaultUnitOfWorkEventRegistrationCallback.php
DefaultUnitOfWorkEventRegistrationCallback.onEventRegistration
public function onEventRegistration(Event $event) { $this->unitOfWork->publishEvent($event, $this->eventBus); return $this->unitOfWork->invokeEventRegistrationListeners($event); }
php
public function onEventRegistration(Event $event) { $this->unitOfWork->publishEvent($event, $this->eventBus); return $this->unitOfWork->invokeEventRegistrationListeners($event); }
[ "public", "function", "onEventRegistration", "(", "Event", "$", "event", ")", "{", "$", "this", "->", "unitOfWork", "->", "publishEvent", "(", "$", "event", ",", "$", "this", "->", "eventBus", ")", ";", "return", "$", "this", "->", "unitOfWork", "->", "invokeEventRegistrationListeners", "(", "$", "event", ")", ";", "}" ]
@param Event $event @return Event
[ "@param", "Event", "$event" ]
train
https://github.com/rayrutjes/domain-foundation/blob/2bce7cd6a6612f718e70e3176589c1abf39d1a3e/src/UnitOfWork/DefaultUnitOfWorkEventRegistrationCallback.php#L36-L41
dms-org/package.blog
src/Cms/BlogArticleCommentModule.php
BlogArticleCommentModule.defineCrudModule
protected function defineCrudModule(CrudModuleDefinition $module) { $module->name('articles'); $module->labelObjects()->fromProperty(BlogArticleComment::AUTHOR_NAME); $module->crudForm(function (CrudFormDefinition $form) { $form->section('Details', [ $form->field( Field::create('author_name', 'Author Name')->string()->required() )->bindToProperty(BlogArticleComment::AUTHOR_NAME), // $form->field( Field::create('author_email', 'Author Email')->email()->required() )->bindToProperty(BlogArticleComment::AUTHOR_EMAIL), // $form->field( Field::create('comment', 'Comment')->string()->required()->multiline() )->bindToProperty(BlogArticleComment::CONTENT), ]); $form->onSubmit(function (BlogArticleComment $comment) { $comment->article = $this->blogArticle; }); if ($form->isCreateForm()) { $form->onSubmit(function (BlogArticleComment $comment) { $comment->getMetadata(); $comment->postedAt = new DateTime($this->clock->utcNow()); }); } else { $form->continueSection([ $form->field( Field::create('posted_at', 'Posted At')->dateTime()->required()->readonly() )->bindToProperty(BlogArticleComment::POSTED_AT), ]); } }); $module->removeAction()->deleteFromDataSource(); $module->summaryTable(function (SummaryTableDefinition $table) { $table->mapProperty(BlogArticleComment::AUTHOR_NAME)->to( Field::create('author_name', 'Author Name')->string()); $table->mapProperty(BlogArticleComment::AUTHOR_EMAIL)->to( Field::create('author_email', 'Author Email')->email()); $table->mapProperty(BlogArticleComment::CONTENT)->to(Field::create('comment', 'Comment')->string()); $table->view('all', 'All') ->asDefault() ->loadAll(); }); }
php
protected function defineCrudModule(CrudModuleDefinition $module) { $module->name('articles'); $module->labelObjects()->fromProperty(BlogArticleComment::AUTHOR_NAME); $module->crudForm(function (CrudFormDefinition $form) { $form->section('Details', [ $form->field( Field::create('author_name', 'Author Name')->string()->required() )->bindToProperty(BlogArticleComment::AUTHOR_NAME), // $form->field( Field::create('author_email', 'Author Email')->email()->required() )->bindToProperty(BlogArticleComment::AUTHOR_EMAIL), // $form->field( Field::create('comment', 'Comment')->string()->required()->multiline() )->bindToProperty(BlogArticleComment::CONTENT), ]); $form->onSubmit(function (BlogArticleComment $comment) { $comment->article = $this->blogArticle; }); if ($form->isCreateForm()) { $form->onSubmit(function (BlogArticleComment $comment) { $comment->getMetadata(); $comment->postedAt = new DateTime($this->clock->utcNow()); }); } else { $form->continueSection([ $form->field( Field::create('posted_at', 'Posted At')->dateTime()->required()->readonly() )->bindToProperty(BlogArticleComment::POSTED_AT), ]); } }); $module->removeAction()->deleteFromDataSource(); $module->summaryTable(function (SummaryTableDefinition $table) { $table->mapProperty(BlogArticleComment::AUTHOR_NAME)->to( Field::create('author_name', 'Author Name')->string()); $table->mapProperty(BlogArticleComment::AUTHOR_EMAIL)->to( Field::create('author_email', 'Author Email')->email()); $table->mapProperty(BlogArticleComment::CONTENT)->to(Field::create('comment', 'Comment')->string()); $table->view('all', 'All') ->asDefault() ->loadAll(); }); }
[ "protected", "function", "defineCrudModule", "(", "CrudModuleDefinition", "$", "module", ")", "{", "$", "module", "->", "name", "(", "'articles'", ")", ";", "$", "module", "->", "labelObjects", "(", ")", "->", "fromProperty", "(", "BlogArticleComment", "::", "AUTHOR_NAME", ")", ";", "$", "module", "->", "crudForm", "(", "function", "(", "CrudFormDefinition", "$", "form", ")", "{", "$", "form", "->", "section", "(", "'Details'", ",", "[", "$", "form", "->", "field", "(", "Field", "::", "create", "(", "'author_name'", ",", "'Author Name'", ")", "->", "string", "(", ")", "->", "required", "(", ")", ")", "->", "bindToProperty", "(", "BlogArticleComment", "::", "AUTHOR_NAME", ")", ",", "//", "$", "form", "->", "field", "(", "Field", "::", "create", "(", "'author_email'", ",", "'Author Email'", ")", "->", "email", "(", ")", "->", "required", "(", ")", ")", "->", "bindToProperty", "(", "BlogArticleComment", "::", "AUTHOR_EMAIL", ")", ",", "//", "$", "form", "->", "field", "(", "Field", "::", "create", "(", "'comment'", ",", "'Comment'", ")", "->", "string", "(", ")", "->", "required", "(", ")", "->", "multiline", "(", ")", ")", "->", "bindToProperty", "(", "BlogArticleComment", "::", "CONTENT", ")", ",", "]", ")", ";", "$", "form", "->", "onSubmit", "(", "function", "(", "BlogArticleComment", "$", "comment", ")", "{", "$", "comment", "->", "article", "=", "$", "this", "->", "blogArticle", ";", "}", ")", ";", "if", "(", "$", "form", "->", "isCreateForm", "(", ")", ")", "{", "$", "form", "->", "onSubmit", "(", "function", "(", "BlogArticleComment", "$", "comment", ")", "{", "$", "comment", "->", "getMetadata", "(", ")", ";", "$", "comment", "->", "postedAt", "=", "new", "DateTime", "(", "$", "this", "->", "clock", "->", "utcNow", "(", ")", ")", ";", "}", ")", ";", "}", "else", "{", "$", "form", "->", "continueSection", "(", "[", "$", "form", "->", "field", "(", "Field", "::", "create", "(", "'posted_at'", ",", "'Posted At'", ")", "->", "dateTime", "(", ")", "->", "required", "(", ")", "->", "readonly", "(", ")", ")", "->", "bindToProperty", "(", "BlogArticleComment", "::", "POSTED_AT", ")", ",", "]", ")", ";", "}", "}", ")", ";", "$", "module", "->", "removeAction", "(", ")", "->", "deleteFromDataSource", "(", ")", ";", "$", "module", "->", "summaryTable", "(", "function", "(", "SummaryTableDefinition", "$", "table", ")", "{", "$", "table", "->", "mapProperty", "(", "BlogArticleComment", "::", "AUTHOR_NAME", ")", "->", "to", "(", "Field", "::", "create", "(", "'author_name'", ",", "'Author Name'", ")", "->", "string", "(", ")", ")", ";", "$", "table", "->", "mapProperty", "(", "BlogArticleComment", "::", "AUTHOR_EMAIL", ")", "->", "to", "(", "Field", "::", "create", "(", "'author_email'", ",", "'Author Email'", ")", "->", "email", "(", ")", ")", ";", "$", "table", "->", "mapProperty", "(", "BlogArticleComment", "::", "CONTENT", ")", "->", "to", "(", "Field", "::", "create", "(", "'comment'", ",", "'Comment'", ")", "->", "string", "(", ")", ")", ";", "$", "table", "->", "view", "(", "'all'", ",", "'All'", ")", "->", "asDefault", "(", ")", "->", "loadAll", "(", ")", ";", "}", ")", ";", "}" ]
Defines the structure of this module. @param CrudModuleDefinition $module
[ "Defines", "the", "structure", "of", "this", "module", "." ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Cms/BlogArticleCommentModule.php#L70-L120
npbtrac/yii2-enpii-cms
components/giix/model/Generator.php
Generator.generateHints
public function generateHints($table) { $hints = []; foreach ($table->columns as $column) { if (!empty($column->comment)) { $hints[$column->name] = $column->comment; } else { } } return $hints; }
php
public function generateHints($table) { $hints = []; foreach ($table->columns as $column) { if (!empty($column->comment)) { $hints[$column->name] = $column->comment; } else { } } return $hints; }
[ "public", "function", "generateHints", "(", "$", "table", ")", "{", "$", "hints", "=", "[", "]", ";", "foreach", "(", "$", "table", "->", "columns", "as", "$", "column", ")", "{", "if", "(", "!", "empty", "(", "$", "column", "->", "comment", ")", ")", "{", "$", "hints", "[", "$", "column", "->", "name", "]", "=", "$", "column", "->", "comment", ";", "}", "else", "{", "}", "}", "return", "$", "hints", ";", "}" ]
Generates the attribute labels for the specified table. @param \yii\db\TableSchema $table the table schema @return array the generated attribute labels (name => label)
[ "Generates", "the", "attribute", "labels", "for", "the", "specified", "table", "." ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/components/giix/model/Generator.php#L269-L280
npbtrac/yii2-enpii-cms
components/giix/model/Generator.php
Generator.generateRelationName
protected function generateRelationName($relations, $table, $key, $multiple) { if (!empty($key) && substr_compare($key, 'id', -2, 2, true) === 0 && strcasecmp($key, 'id')) { $key = rtrim(substr($key, 0, -2), '_'); } if ($multiple) { $key = Inflector::pluralize($key); } $name = $rawName = Inflector::id2camel($key, '_'); $i = 0; while (isset($table->columns[lcfirst($name)])) { $name = $rawName . ($i++); } while (isset($relations[$table->fullName][$name])) { $name = $rawName . ($i++); } return $name; }
php
protected function generateRelationName($relations, $table, $key, $multiple) { if (!empty($key) && substr_compare($key, 'id', -2, 2, true) === 0 && strcasecmp($key, 'id')) { $key = rtrim(substr($key, 0, -2), '_'); } if ($multiple) { $key = Inflector::pluralize($key); } $name = $rawName = Inflector::id2camel($key, '_'); $i = 0; while (isset($table->columns[lcfirst($name)])) { $name = $rawName . ($i++); } while (isset($relations[$table->fullName][$name])) { $name = $rawName . ($i++); } return $name; }
[ "protected", "function", "generateRelationName", "(", "$", "relations", ",", "$", "table", ",", "$", "key", ",", "$", "multiple", ")", "{", "if", "(", "!", "empty", "(", "$", "key", ")", "&&", "substr_compare", "(", "$", "key", ",", "'id'", ",", "-", "2", ",", "2", ",", "true", ")", "===", "0", "&&", "strcasecmp", "(", "$", "key", ",", "'id'", ")", ")", "{", "$", "key", "=", "rtrim", "(", "substr", "(", "$", "key", ",", "0", ",", "-", "2", ")", ",", "'_'", ")", ";", "}", "if", "(", "$", "multiple", ")", "{", "$", "key", "=", "Inflector", "::", "pluralize", "(", "$", "key", ")", ";", "}", "$", "name", "=", "$", "rawName", "=", "Inflector", "::", "id2camel", "(", "$", "key", ",", "'_'", ")", ";", "$", "i", "=", "0", ";", "while", "(", "isset", "(", "$", "table", "->", "columns", "[", "lcfirst", "(", "$", "name", ")", "]", ")", ")", "{", "$", "name", "=", "$", "rawName", ".", "(", "$", "i", "++", ")", ";", "}", "while", "(", "isset", "(", "$", "relations", "[", "$", "table", "->", "fullName", "]", "[", "$", "name", "]", ")", ")", "{", "$", "name", "=", "$", "rawName", ".", "(", "$", "i", "++", ")", ";", "}", "return", "$", "name", ";", "}" ]
Generate a relation name for the specified table and a base name. @param array $relations the relations being generated currently. @param \yii\db\TableSchema $table the table schema @param string $key a base name that the relation name may be generated from @param boolean $multiple whether this is a has-many relation @return string the relation name
[ "Generate", "a", "relation", "name", "for", "the", "specified", "table", "and", "a", "base", "name", "." ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/components/giix/model/Generator.php#L536-L554
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.resetJsonResult
protected function resetJsonResult() { $this->jsonResult['skipped'] = false; $this->jsonResult['pass'] = false; $this->jsonResult['failure'] = false; $this->jsonResult['error'] = false; $this->jsonResult['unknown'] = false; }
php
protected function resetJsonResult() { $this->jsonResult['skipped'] = false; $this->jsonResult['pass'] = false; $this->jsonResult['failure'] = false; $this->jsonResult['error'] = false; $this->jsonResult['unknown'] = false; }
[ "protected", "function", "resetJsonResult", "(", ")", "{", "$", "this", "->", "jsonResult", "[", "'skipped'", "]", "=", "false", ";", "$", "this", "->", "jsonResult", "[", "'pass'", "]", "=", "false", ";", "$", "this", "->", "jsonResult", "[", "'failure'", "]", "=", "false", ";", "$", "this", "->", "jsonResult", "[", "'error'", "]", "=", "false", ";", "$", "this", "->", "jsonResult", "[", "'unknown'", "]", "=", "false", ";", "}" ]
initializer for json result set in write progress method
[ "initializer", "for", "json", "result", "set", "in", "write", "progress", "method" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L139-L146
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.setIndent
protected function setIndent($count, $char = ' ') { $outChar = null; for ($i = 1; $i <= $count; $i++) { $outChar .= $char; } return $outChar; }
php
protected function setIndent($count, $char = ' ') { $outChar = null; for ($i = 1; $i <= $count; $i++) { $outChar .= $char; } return $outChar; }
[ "protected", "function", "setIndent", "(", "$", "count", ",", "$", "char", "=", "' '", ")", "{", "$", "outChar", "=", "null", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "$", "count", ";", "$", "i", "++", ")", "{", "$", "outChar", ".=", "$", "char", ";", "}", "return", "$", "outChar", ";", "}" ]
@codeCoverageIgnore @param int $count @param string $char @return null|string
[ "@codeCoverageIgnore" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L173-L181
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.getScanFailPassStatistic
protected function getScanFailPassStatistic(CoverFishResult $coverFishResult) { $errorPercent = round($coverFishResult->getTestCount() / 100 * $coverFishResult->getFailureCount(), 2); $passPercent = 100 - $errorPercent; $errorStatistic = '%s %% failure rate%s%s %% pass rate%s'; $errorStatistic = sprintf($errorStatistic, $errorPercent, PHP_EOL, $passPercent, PHP_EOL ); $scanResultMacro = '%s'; $scanResult = sprintf($scanResultMacro, (false === $this->preventAnsiColors) ? Color::tplRedColor($errorStatistic) : $errorStatistic ); return $scanResult; }
php
protected function getScanFailPassStatistic(CoverFishResult $coverFishResult) { $errorPercent = round($coverFishResult->getTestCount() / 100 * $coverFishResult->getFailureCount(), 2); $passPercent = 100 - $errorPercent; $errorStatistic = '%s %% failure rate%s%s %% pass rate%s'; $errorStatistic = sprintf($errorStatistic, $errorPercent, PHP_EOL, $passPercent, PHP_EOL ); $scanResultMacro = '%s'; $scanResult = sprintf($scanResultMacro, (false === $this->preventAnsiColors) ? Color::tplRedColor($errorStatistic) : $errorStatistic ); return $scanResult; }
[ "protected", "function", "getScanFailPassStatistic", "(", "CoverFishResult", "$", "coverFishResult", ")", "{", "$", "errorPercent", "=", "round", "(", "$", "coverFishResult", "->", "getTestCount", "(", ")", "/", "100", "*", "$", "coverFishResult", "->", "getFailureCount", "(", ")", ",", "2", ")", ";", "$", "passPercent", "=", "100", "-", "$", "errorPercent", ";", "$", "errorStatistic", "=", "'%s %% failure rate%s%s %% pass rate%s'", ";", "$", "errorStatistic", "=", "sprintf", "(", "$", "errorStatistic", ",", "$", "errorPercent", ",", "PHP_EOL", ",", "$", "passPercent", ",", "PHP_EOL", ")", ";", "$", "scanResultMacro", "=", "'%s'", ";", "$", "scanResult", "=", "sprintf", "(", "$", "scanResultMacro", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "tplRedColor", "(", "$", "errorStatistic", ")", ":", "$", "errorStatistic", ")", ";", "return", "$", "scanResult", ";", "}" ]
@codeCoverageIgnore @param CoverFishResult $coverFishResult @return string
[ "@codeCoverageIgnore" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L190-L210
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.getFileResultTemplate
private function getFileResultTemplate($colorCode, $statusMinimal, $statusDetailed, $streamMessage = null) { $output = ($this->outputLevel > 1) ? $statusDetailed : $statusMinimal; return sprintf('%s%s %s%s%s', ($this->outputLevel > 1) ? PHP_EOL : null , ($this->outputLevel > 1) ? '=>' : null , (false === $this->preventAnsiColors) ? Color::setColor($colorCode, $output) : $output , ($this->outputLevel > 1) ? PHP_EOL : null , $streamMessage ); }
php
private function getFileResultTemplate($colorCode, $statusMinimal, $statusDetailed, $streamMessage = null) { $output = ($this->outputLevel > 1) ? $statusDetailed : $statusMinimal; return sprintf('%s%s %s%s%s', ($this->outputLevel > 1) ? PHP_EOL : null , ($this->outputLevel > 1) ? '=>' : null , (false === $this->preventAnsiColors) ? Color::setColor($colorCode, $output) : $output , ($this->outputLevel > 1) ? PHP_EOL : null , $streamMessage ); }
[ "private", "function", "getFileResultTemplate", "(", "$", "colorCode", ",", "$", "statusMinimal", ",", "$", "statusDetailed", ",", "$", "streamMessage", "=", "null", ")", "{", "$", "output", "=", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "$", "statusDetailed", ":", "$", "statusMinimal", ";", "return", "sprintf", "(", "'%s%s %s%s%s'", ",", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "PHP_EOL", ":", "null", ",", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "'=>'", ":", "null", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "setColor", "(", "$", "colorCode", ",", "$", "output", ")", ":", "$", "output", ",", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "PHP_EOL", ":", "null", ",", "$", "streamMessage", ")", ";", "}" ]
@param string $colorCode @param string $statusMinimal @param string $statusDetailed @param null|string $streamMessage @return string @throws \Exception
[ "@param", "string", "$colorCode", "@param", "string", "$statusMinimal", "@param", "string", "$statusDetailed", "@param", "null|string", "$streamMessage" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L222-L247
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.writeFileResult
protected function writeFileResult($status, $message) { $output = null; if (0 === $this->outputLevel) { return null; } switch ($status) { case self::FILE_FAILURE: $output = $this->getFileResultTemplate('bg_red_fg_white', 'FAIL', 'file/test FAILURE', $message); break; case self::FILE_PASS: $output = $this->getFileResultTemplate('green', 'OK', 'file/test OK', $message); break; default: break; } $this->writeLine($output); }
php
protected function writeFileResult($status, $message) { $output = null; if (0 === $this->outputLevel) { return null; } switch ($status) { case self::FILE_FAILURE: $output = $this->getFileResultTemplate('bg_red_fg_white', 'FAIL', 'file/test FAILURE', $message); break; case self::FILE_PASS: $output = $this->getFileResultTemplate('green', 'OK', 'file/test OK', $message); break; default: break; } $this->writeLine($output); }
[ "protected", "function", "writeFileResult", "(", "$", "status", ",", "$", "message", ")", "{", "$", "output", "=", "null", ";", "if", "(", "0", "===", "$", "this", "->", "outputLevel", ")", "{", "return", "null", ";", "}", "switch", "(", "$", "status", ")", "{", "case", "self", "::", "FILE_FAILURE", ":", "$", "output", "=", "$", "this", "->", "getFileResultTemplate", "(", "'bg_red_fg_white'", ",", "'FAIL'", ",", "'file/test FAILURE'", ",", "$", "message", ")", ";", "break", ";", "case", "self", "::", "FILE_PASS", ":", "$", "output", "=", "$", "this", "->", "getFileResultTemplate", "(", "'green'", ",", "'OK'", ",", "'file/test OK'", ",", "$", "message", ")", ";", "break", ";", "default", ":", "break", ";", "}", "$", "this", "->", "writeLine", "(", "$", "output", ")", ";", "}" ]
main progress output rendering function @param int $status @param string $message @return null
[ "main", "progress", "output", "rendering", "function" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L257-L278
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.getProgressTemplate
private function getProgressTemplate($colorCode, $charMinimal, $charDetailed) { $output = ($this->outputLevel > 1) ? $charDetailed // detailed output required? : $charMinimal // otherwise "normal" progress output will be provided ; return (false === $this->preventAnsiColors) ? $output = Color::setColor($colorCode, $output) : $output; }
php
private function getProgressTemplate($colorCode, $charMinimal, $charDetailed) { $output = ($this->outputLevel > 1) ? $charDetailed // detailed output required? : $charMinimal // otherwise "normal" progress output will be provided ; return (false === $this->preventAnsiColors) ? $output = Color::setColor($colorCode, $output) : $output; }
[ "private", "function", "getProgressTemplate", "(", "$", "colorCode", ",", "$", "charMinimal", ",", "$", "charDetailed", ")", "{", "$", "output", "=", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "$", "charDetailed", "// detailed output required?", ":", "$", "charMinimal", "// otherwise \"normal\" progress output will be provided", ";", "return", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "$", "output", "=", "Color", "::", "setColor", "(", "$", "colorCode", ",", "$", "output", ")", ":", "$", "output", ";", "}" ]
@param string $colorCode @param string $charMinimal @param string $charDetailed @return string @throws \Exception
[ "@param", "string", "$colorCode", "@param", "string", "$charMinimal", "@param", "string", "$charDetailed" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L289-L299
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.writeProgress
protected function writeProgress($status) { $this->resetJsonResult(); switch ($status) { case self::MACRO_SKIPPED: $this->jsonResult['skipped'] = true; $output = $this->getProgressTemplate('green', '_', 'S'); break; case self::MACRO_PASS: $this->jsonResult['pass'] = true; $output = $this->getProgressTemplate('green', '.', '+'); break; case self::MACRO_FAILURE: $this->jsonResult['failure'] = true; $output = $this->getProgressTemplate('bg_red_fg_yellow', 'f', 'F'); break; case self::MACRO_ERROR: $this->jsonResult['error'] = true; $output = $this->getProgressTemplate('bg_red_fg_white', 'e', 'E'); break; case self::MACRO_WARNING: $this->jsonResult['warning'] = true; $output = $this->getProgressTemplate('bg_yellow_fg_black', 'w', 'W'); break; default: $this->jsonResult['unknown'] = true; $output = $output = $this->getProgressTemplate('bg_yellow_fg_black', '?', '?'); break; } $this->write($output); }
php
protected function writeProgress($status) { $this->resetJsonResult(); switch ($status) { case self::MACRO_SKIPPED: $this->jsonResult['skipped'] = true; $output = $this->getProgressTemplate('green', '_', 'S'); break; case self::MACRO_PASS: $this->jsonResult['pass'] = true; $output = $this->getProgressTemplate('green', '.', '+'); break; case self::MACRO_FAILURE: $this->jsonResult['failure'] = true; $output = $this->getProgressTemplate('bg_red_fg_yellow', 'f', 'F'); break; case self::MACRO_ERROR: $this->jsonResult['error'] = true; $output = $this->getProgressTemplate('bg_red_fg_white', 'e', 'E'); break; case self::MACRO_WARNING: $this->jsonResult['warning'] = true; $output = $this->getProgressTemplate('bg_yellow_fg_black', 'w', 'W'); break; default: $this->jsonResult['unknown'] = true; $output = $output = $this->getProgressTemplate('bg_yellow_fg_black', '?', '?'); break; } $this->write($output); }
[ "protected", "function", "writeProgress", "(", "$", "status", ")", "{", "$", "this", "->", "resetJsonResult", "(", ")", ";", "switch", "(", "$", "status", ")", "{", "case", "self", "::", "MACRO_SKIPPED", ":", "$", "this", "->", "jsonResult", "[", "'skipped'", "]", "=", "true", ";", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'green'", ",", "'_'", ",", "'S'", ")", ";", "break", ";", "case", "self", "::", "MACRO_PASS", ":", "$", "this", "->", "jsonResult", "[", "'pass'", "]", "=", "true", ";", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'green'", ",", "'.'", ",", "'+'", ")", ";", "break", ";", "case", "self", "::", "MACRO_FAILURE", ":", "$", "this", "->", "jsonResult", "[", "'failure'", "]", "=", "true", ";", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'bg_red_fg_yellow'", ",", "'f'", ",", "'F'", ")", ";", "break", ";", "case", "self", "::", "MACRO_ERROR", ":", "$", "this", "->", "jsonResult", "[", "'error'", "]", "=", "true", ";", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'bg_red_fg_white'", ",", "'e'", ",", "'E'", ")", ";", "break", ";", "case", "self", "::", "MACRO_WARNING", ":", "$", "this", "->", "jsonResult", "[", "'warning'", "]", "=", "true", ";", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'bg_yellow_fg_black'", ",", "'w'", ",", "'W'", ")", ";", "break", ";", "default", ":", "$", "this", "->", "jsonResult", "[", "'unknown'", "]", "=", "true", ";", "$", "output", "=", "$", "output", "=", "$", "this", "->", "getProgressTemplate", "(", "'bg_yellow_fg_black'", ",", "'?'", ",", "'?'", ")", ";", "break", ";", "}", "$", "this", "->", "write", "(", "$", "output", ")", ";", "}" ]
main progress output rendering function @param int $status @return null
[ "main", "progress", "output", "rendering", "function" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L308-L351
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.writeScanPassStatistic
protected function writeScanPassStatistic(CoverFishResult $coverFishResult) { $passStatistic = '%s file(s) and %s method(s) scanned, scan succeeded, no problems found.%s'; $passStatistic = sprintf($passStatistic, $coverFishResult->getFileCount(), $coverFishResult->getTestCount(), PHP_EOL ); $scanResultMacro = '%s%s%s'; $scanResult = sprintf($scanResultMacro, ($this->outputLevel === 0) ? PHP_EOL : null, PHP_EOL, (false === $this->preventAnsiColors) ? Color::tplGreenColor($passStatistic) : $passStatistic ); $this->write($scanResult); }
php
protected function writeScanPassStatistic(CoverFishResult $coverFishResult) { $passStatistic = '%s file(s) and %s method(s) scanned, scan succeeded, no problems found.%s'; $passStatistic = sprintf($passStatistic, $coverFishResult->getFileCount(), $coverFishResult->getTestCount(), PHP_EOL ); $scanResultMacro = '%s%s%s'; $scanResult = sprintf($scanResultMacro, ($this->outputLevel === 0) ? PHP_EOL : null, PHP_EOL, (false === $this->preventAnsiColors) ? Color::tplGreenColor($passStatistic) : $passStatistic ); $this->write($scanResult); }
[ "protected", "function", "writeScanPassStatistic", "(", "CoverFishResult", "$", "coverFishResult", ")", "{", "$", "passStatistic", "=", "'%s file(s) and %s method(s) scanned, scan succeeded, no problems found.%s'", ";", "$", "passStatistic", "=", "sprintf", "(", "$", "passStatistic", ",", "$", "coverFishResult", "->", "getFileCount", "(", ")", ",", "$", "coverFishResult", "->", "getTestCount", "(", ")", ",", "PHP_EOL", ")", ";", "$", "scanResultMacro", "=", "'%s%s%s'", ";", "$", "scanResult", "=", "sprintf", "(", "$", "scanResultMacro", ",", "(", "$", "this", "->", "outputLevel", "===", "0", ")", "?", "PHP_EOL", ":", "null", ",", "PHP_EOL", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "tplGreenColor", "(", "$", "passStatistic", ")", ":", "$", "passStatistic", ")", ";", "$", "this", "->", "write", "(", "$", "scanResult", ")", ";", "}" ]
write scan pass results @param CoverFishResult $coverFishResult
[ "write", "scan", "pass", "results" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L358-L379
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.writeScanFailStatistic
protected function writeScanFailStatistic(CoverFishResult $coverFishResult) { $errorStatistic = '%s file(s) and %s method(s) scanned, coverage failed: %s cover annotation problem(s) found!%s'; $errorStatistic = sprintf($errorStatistic, $coverFishResult->getFileCount(), $coverFishResult->getTestCount(), $coverFishResult->getFailureCount(), PHP_EOL ); $scanResultMacro = '%s%s%s%s'; $scanResult = sprintf($scanResultMacro, ($this->outputLevel === 0) ? PHP_EOL : null, PHP_EOL, (false === $this->preventAnsiColors) ? Color::tplRedColor($errorStatistic) : $errorStatistic, $this->getScanFailPassStatistic($coverFishResult) ); $this->write($scanResult); throw new CoverFishFailExit(); }
php
protected function writeScanFailStatistic(CoverFishResult $coverFishResult) { $errorStatistic = '%s file(s) and %s method(s) scanned, coverage failed: %s cover annotation problem(s) found!%s'; $errorStatistic = sprintf($errorStatistic, $coverFishResult->getFileCount(), $coverFishResult->getTestCount(), $coverFishResult->getFailureCount(), PHP_EOL ); $scanResultMacro = '%s%s%s%s'; $scanResult = sprintf($scanResultMacro, ($this->outputLevel === 0) ? PHP_EOL : null, PHP_EOL, (false === $this->preventAnsiColors) ? Color::tplRedColor($errorStatistic) : $errorStatistic, $this->getScanFailPassStatistic($coverFishResult) ); $this->write($scanResult); throw new CoverFishFailExit(); }
[ "protected", "function", "writeScanFailStatistic", "(", "CoverFishResult", "$", "coverFishResult", ")", "{", "$", "errorStatistic", "=", "'%s file(s) and %s method(s) scanned, coverage failed: %s cover annotation problem(s) found!%s'", ";", "$", "errorStatistic", "=", "sprintf", "(", "$", "errorStatistic", ",", "$", "coverFishResult", "->", "getFileCount", "(", ")", ",", "$", "coverFishResult", "->", "getTestCount", "(", ")", ",", "$", "coverFishResult", "->", "getFailureCount", "(", ")", ",", "PHP_EOL", ")", ";", "$", "scanResultMacro", "=", "'%s%s%s%s'", ";", "$", "scanResult", "=", "sprintf", "(", "$", "scanResultMacro", ",", "(", "$", "this", "->", "outputLevel", "===", "0", ")", "?", "PHP_EOL", ":", "null", ",", "PHP_EOL", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "tplRedColor", "(", "$", "errorStatistic", ")", ":", "$", "errorStatistic", ",", "$", "this", "->", "getScanFailPassStatistic", "(", "$", "coverFishResult", ")", ")", ";", "$", "this", "->", "write", "(", "$", "scanResult", ")", ";", "throw", "new", "CoverFishFailExit", "(", ")", ";", "}" ]
write scan fail result @param CoverFishResult $coverFishResult @throws CoverFishFailExit
[ "write", "scan", "fail", "result" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L388-L413
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.writeFileName
protected function writeFileName(CoverFishPHPUnitFile $coverFishUnitFile) { if (true === $this->outputFormatJson || 0 === $this->outputLevel) { return null; } $file = $this->coverFishHelper->getFileNameFromPath($coverFishUnitFile->getFile()); $fileNameLine = sprintf('%s%s%s', (false === $this->preventAnsiColors) ? Color::tplNormalColor(($this->outputLevel > 1) ? 'scan file ' : null) : 'scan file ' , (false === $this->preventAnsiColors) ? Color::tplYellowColor($file) : $file , ($this->outputLevel > 1) ? PHP_EOL : ' ' ); $this->write($fileNameLine); }
php
protected function writeFileName(CoverFishPHPUnitFile $coverFishUnitFile) { if (true === $this->outputFormatJson || 0 === $this->outputLevel) { return null; } $file = $this->coverFishHelper->getFileNameFromPath($coverFishUnitFile->getFile()); $fileNameLine = sprintf('%s%s%s', (false === $this->preventAnsiColors) ? Color::tplNormalColor(($this->outputLevel > 1) ? 'scan file ' : null) : 'scan file ' , (false === $this->preventAnsiColors) ? Color::tplYellowColor($file) : $file , ($this->outputLevel > 1) ? PHP_EOL : ' ' ); $this->write($fileNameLine); }
[ "protected", "function", "writeFileName", "(", "CoverFishPHPUnitFile", "$", "coverFishUnitFile", ")", "{", "if", "(", "true", "===", "$", "this", "->", "outputFormatJson", "||", "0", "===", "$", "this", "->", "outputLevel", ")", "{", "return", "null", ";", "}", "$", "file", "=", "$", "this", "->", "coverFishHelper", "->", "getFileNameFromPath", "(", "$", "coverFishUnitFile", "->", "getFile", "(", ")", ")", ";", "$", "fileNameLine", "=", "sprintf", "(", "'%s%s%s'", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "tplNormalColor", "(", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "'scan file '", ":", "null", ")", ":", "'scan file '", ",", "(", "false", "===", "$", "this", "->", "preventAnsiColors", ")", "?", "Color", "::", "tplYellowColor", "(", "$", "file", ")", ":", "$", "file", ",", "(", "$", "this", "->", "outputLevel", ">", "1", ")", "?", "PHP_EOL", ":", "' '", ")", ";", "$", "this", "->", "write", "(", "$", "fileNameLine", ")", ";", "}" ]
@param CoverFishPHPUnitFile $coverFishUnitFile @return null
[ "@param", "CoverFishPHPUnitFile", "$coverFishUnitFile" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L420-L440
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php
BaseCoverFishOutput.outputResult
protected function outputResult(CoverFishResult $coverFishResult) { if (false === $this->outputFormatJson) { if ($coverFishResult->getFailureCount() > 0) { $this->writeScanFailStatistic($coverFishResult); } else { $this->writeScanPassStatistic($coverFishResult); } return null; } if (true === $this->preventEcho) { return json_encode($this->jsonResults); } $this->output->write(json_encode($this->jsonResults)); return null; }
php
protected function outputResult(CoverFishResult $coverFishResult) { if (false === $this->outputFormatJson) { if ($coverFishResult->getFailureCount() > 0) { $this->writeScanFailStatistic($coverFishResult); } else { $this->writeScanPassStatistic($coverFishResult); } return null; } if (true === $this->preventEcho) { return json_encode($this->jsonResults); } $this->output->write(json_encode($this->jsonResults)); return null; }
[ "protected", "function", "outputResult", "(", "CoverFishResult", "$", "coverFishResult", ")", "{", "if", "(", "false", "===", "$", "this", "->", "outputFormatJson", ")", "{", "if", "(", "$", "coverFishResult", "->", "getFailureCount", "(", ")", ">", "0", ")", "{", "$", "this", "->", "writeScanFailStatistic", "(", "$", "coverFishResult", ")", ";", "}", "else", "{", "$", "this", "->", "writeScanPassStatistic", "(", "$", "coverFishResult", ")", ";", "}", "return", "null", ";", "}", "if", "(", "true", "===", "$", "this", "->", "preventEcho", ")", "{", "return", "json_encode", "(", "$", "this", "->", "jsonResults", ")", ";", "}", "$", "this", "->", "output", "->", "write", "(", "json_encode", "(", "$", "this", "->", "jsonResults", ")", ")", ";", "return", "null", ";", "}" ]
handle scanner output by default/parametric output format settings @param CoverFishResult $coverFishResult @return null @throws CoverFishFailExit
[ "handle", "scanner", "output", "by", "default", "/", "parametric", "output", "format", "settings" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Common/Base/BaseCoverFishOutput.php#L451-L471
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__groupBy
protected static function __groupBy(callable $keyGen, array $list) : array { return self::foldl(function ($group, $element) use ($keyGen) { $group[$keyGen($element)][] = $element; return $group; }, [], $list); }
php
protected static function __groupBy(callable $keyGen, array $list) : array { return self::foldl(function ($group, $element) use ($keyGen) { $group[$keyGen($element)][] = $element; return $group; }, [], $list); }
[ "protected", "static", "function", "__groupBy", "(", "callable", "$", "keyGen", ",", "array", "$", "list", ")", ":", "array", "{", "return", "self", "::", "foldl", "(", "function", "(", "$", "group", ",", "$", "element", ")", "use", "(", "$", "keyGen", ")", "{", "$", "group", "[", "$", "keyGen", "(", "$", "element", ")", "]", "[", "]", "=", "$", "element", ";", "return", "$", "group", ";", "}", ",", "[", "]", ",", "$", "list", ")", ";", "}" ]
Group By Given a function that turns an element into a string, map over a list of elements and return a multi-dimensional array with elements grouped together by their key generator. @example $testCase = [1, 2, 3, 4, 5, 6, 7]; $keyGen = function($a) { return ($a <= 3) ? 'small' : 'big'; }; Arrays::groupBy($keyGen, $testCase); // ['small' => [1, 2, 3], 'big' => [4, 5, 6, 7]] @param callable|\Closure $keyGen Key generating function @param array $list List to group @return array Multidimensional array of grouped elements @internal param $ (a -> String) -> [a] -> [[a]]
[ "Group", "By" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L88-L94
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__index
protected static function __index($i, array $list) { /** * isset is much faster at the common case (non-null values) * but it falls down when the value is null, so we fallback to * array_key_exists (slower). */ if (!isset($list[$i]) && !array_key_exists($i, $list)) { throw new IndexOutOfBoundsException("'index' function tried to access non-existent index '$i'"); } return $list[$i]; }
php
protected static function __index($i, array $list) { /** * isset is much faster at the common case (non-null values) * but it falls down when the value is null, so we fallback to * array_key_exists (slower). */ if (!isset($list[$i]) && !array_key_exists($i, $list)) { throw new IndexOutOfBoundsException("'index' function tried to access non-existent index '$i'"); } return $list[$i]; }
[ "protected", "static", "function", "__index", "(", "$", "i", ",", "array", "$", "list", ")", "{", "/**\n * isset is much faster at the common case (non-null values)\n * but it falls down when the value is null, so we fallback to\n * array_key_exists (slower).\n */", "if", "(", "!", "isset", "(", "$", "list", "[", "$", "i", "]", ")", "&&", "!", "array_key_exists", "(", "$", "i", ",", "$", "list", ")", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"'index' function tried to access non-existent index '$i'\"", ")", ";", "}", "return", "$", "list", "[", "$", "i", "]", ";", "}" ]
List Index Returns the element of a list at the given index. Throws an exception if the given index does not exist in the list. @example Arrays::index(0, [1, 2, 3]); // 1 @example Arrays::index('foo', ['bar' => 1, 'foo' => 2]); // 2 @example Arrays::index('baz', [1, 2, 3]); // Exception thrown @type Int -> [a] -> a @throws \Vector\Core\Exception\IndexOutOfBoundsException if the requested index does not exist @param Int $i Index to get @param array $list List to get index from @return Mixed Item from $list and index $i
[ "List", "Index" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L316-L328
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__first
protected static function __first(callable $f, array $arr) { foreach ($arr as $a) { if ($f($a) === true) { return $a; } } throw new ElementNotFoundException(); }
php
protected static function __first(callable $f, array $arr) { foreach ($arr as $a) { if ($f($a) === true) { return $a; } } throw new ElementNotFoundException(); }
[ "protected", "static", "function", "__first", "(", "callable", "$", "f", ",", "array", "$", "arr", ")", "{", "foreach", "(", "$", "arr", "as", "$", "a", ")", "{", "if", "(", "$", "f", "(", "$", "a", ")", "===", "true", ")", "{", "return", "$", "a", ";", "}", "}", "throw", "new", "ElementNotFoundException", "(", ")", ";", "}" ]
First Element w/ Test @param callable $f @param array $arr @return mixed @throws ElementNotFoundException @internal param $ (a -> Bool) -> [a] -> a
[ "First", "Element", "w", "/", "Test" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L368-L377
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__zipWith
protected static function __zipWith(callable $f, array $a, array $b) : array { $result = []; while (($ai = array_shift($a)) !== null && ($bi = array_shift($b)) !== null) { $result[] = $f($ai, $bi); } return $result; }
php
protected static function __zipWith(callable $f, array $a, array $b) : array { $result = []; while (($ai = array_shift($a)) !== null && ($bi = array_shift($b)) !== null) { $result[] = $f($ai, $bi); } return $result; }
[ "protected", "static", "function", "__zipWith", "(", "callable", "$", "f", ",", "array", "$", "a", ",", "array", "$", "b", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "while", "(", "(", "$", "ai", "=", "array_shift", "(", "$", "a", ")", ")", "!==", "null", "&&", "(", "$", "bi", "=", "array_shift", "(", "$", "b", ")", ")", "!==", "null", ")", "{", "$", "result", "[", "]", "=", "$", "f", "(", "$", "ai", ",", "$", "bi", ")", ";", "}", "return", "$", "result", ";", "}" ]
Custom Array Zip Given two arrays a and b, and some combinator f, combine the arrays using the combinator f(ai, bi) into a new array c. If a and b are not the same length, the resultant array will always be the same length as the shorter array, i.e. the zip stops when it runs out of pairs. @example $combinator = function($a, $b) { return $a + $b; }; Arrays::zipWith($combinator, [1, 2, 3], [0, 8, -1]); // [1, 10, 2] @example $combinator = function($a, $b) { return $a - $b; }; Arrays::zipWith($combinator, [0], [1, 2, 3]); // [-1] @type (a -> b -> c) -> [a] -> [b] -> [c] @param Callable $f The function used to combine $a and $b @param array $a The first array to use in the combinator @param array $b The second array to use in the combinator @return array The result of calling f with each element of a and b in series
[ "Custom", "Array", "Zip" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L522-L531
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__zip
protected static function __zip(array $a, array $b) : array { return self::zipWith( function ($a, $b) { return [$a, $b]; }, $a, $b ); }
php
protected static function __zip(array $a, array $b) : array { return self::zipWith( function ($a, $b) { return [$a, $b]; }, $a, $b ); }
[ "protected", "static", "function", "__zip", "(", "array", "$", "a", ",", "array", "$", "b", ")", ":", "array", "{", "return", "self", "::", "zipWith", "(", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "[", "$", "a", ",", "$", "b", "]", ";", "}", ",", "$", "a", ",", "$", "b", ")", ";", "}" ]
Array Zip Given two arrays a and b, return a new array where each element is a tuple of a and b. If a and b are not the same length, the resultant array will always be the same length as the shorter array. @example Arrays::zip([1, 2, 3], ['a', 'b', 'c']); // [[1, 'a'], [2, 'b'], [3, 'c']] @type [a] -> [b] -> [(a, b)] @param array $a The first array to use when zipping @param array $b The second array to use when zipping @return array Array of tuples from a and b combined
[ "Array", "Zip" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L548-L557
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__bifurcate
protected static function __bifurcate(callable $test, array $arr) : array { $resPass = []; $resFail = []; foreach ($arr as $element) { if ($test($element)) { $resPass[] = $element; } else { $resFail[] = $element; } } return [$resPass, $resFail]; }
php
protected static function __bifurcate(callable $test, array $arr) : array { $resPass = []; $resFail = []; foreach ($arr as $element) { if ($test($element)) { $resPass[] = $element; } else { $resFail[] = $element; } } return [$resPass, $resFail]; }
[ "protected", "static", "function", "__bifurcate", "(", "callable", "$", "test", ",", "array", "$", "arr", ")", ":", "array", "{", "$", "resPass", "=", "[", "]", ";", "$", "resFail", "=", "[", "]", ";", "foreach", "(", "$", "arr", "as", "$", "element", ")", "{", "if", "(", "$", "test", "(", "$", "element", ")", ")", "{", "$", "resPass", "[", "]", "=", "$", "element", ";", "}", "else", "{", "$", "resFail", "[", "]", "=", "$", "element", ";", "}", "}", "return", "[", "$", "resPass", ",", "$", "resFail", "]", ";", "}" ]
Array Bifurcation Given an array and some filtering test that returns a boolean, return two arrays - one array of elements that pass the test, and another array of elements that don't. Similar to filter, but returns the elements that fail as well. @example Arrays::bifurcate($isEven, [1, 2, 3, 4, 5]); // [[2, 4], [1, 3, 5]] @type (a -> Bool) -> [a] -> ([a], [a]) @param callable $test Test to use when bifurcating the array @param array $arr Array to split apart @return array An array with two elements; the first is the list that passed the test, and the second element is the list that failed the test
[ "Array", "Bifurcation" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L576-L590
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__dropWhile
protected static function __dropWhile(callable $predicate, array $list) : array { foreach ($list as $item) { if ($predicate($item)) { array_shift($list); } else { break; } } return $list; }
php
protected static function __dropWhile(callable $predicate, array $list) : array { foreach ($list as $item) { if ($predicate($item)) { array_shift($list); } else { break; } } return $list; }
[ "protected", "static", "function", "__dropWhile", "(", "callable", "$", "predicate", ",", "array", "$", "list", ")", ":", "array", "{", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "if", "(", "$", "predicate", "(", "$", "item", ")", ")", "{", "array_shift", "(", "$", "list", ")", ";", "}", "else", "{", "break", ";", "}", "}", "return", "$", "list", ";", "}" ]
Drop Elements with Predicate Given some function that returns true or false, drop elements from an array starting at the front, testing each element along the way, until that function returns false. Return the array without all of those elements. @example $greaterThanOne = function($n) { return $n > 1; }; Arrays::dropWhile($greaterThanOne, [2, 4, 6, 1, 2, 3]); // [1, 2, 3] @type (a -> Bool) -> [a] -> [a] @param callable $predicate Function to use for testing @param array $list List to drop from @return array List with elements removed from the front
[ "Drop", "Elements", "with", "Predicate" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L632-L643
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__takeWhile
protected static function __takeWhile(callable $predicate, array $list) : array { $result = []; foreach ($list as $item) { if ($predicate($item)) { $result[] = $item; } else { break; } } return $result; }
php
protected static function __takeWhile(callable $predicate, array $list) : array { $result = []; foreach ($list as $item) { if ($predicate($item)) { $result[] = $item; } else { break; } } return $result; }
[ "protected", "static", "function", "__takeWhile", "(", "callable", "$", "predicate", ",", "array", "$", "list", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "if", "(", "$", "predicate", "(", "$", "item", ")", ")", "{", "$", "result", "[", "]", "=", "$", "item", ";", "}", "else", "{", "break", ";", "}", "}", "return", "$", "result", ";", "}" ]
Take Elements with Predicate Given some function that returns true or false, return the first elements of the array that all pass the test, until the test fails. @example $greaterThanOne = function($n) { return $n > 1; }; Arrays::takeWhile($greaterThanOne, [5, 5, 5, 1, 5, 5]); // [5, 5, 5] @type (a -> Bool) -> [a] -> [a] @param callable $predicate Function to use for testing each element @param array $list List to take elements from @return array First elements of list that all pass the $predicate
[ "Take", "Elements", "with", "Predicate" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L681-L694
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__flatten
protected static function __flatten(array $list) : array { $iter = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($list)); $flat = []; foreach ($iter as $item) { $flat[] = $item; } return $flat; }
php
protected static function __flatten(array $list) : array { $iter = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($list)); $flat = []; foreach ($iter as $item) { $flat[] = $item; } return $flat; }
[ "protected", "static", "function", "__flatten", "(", "array", "$", "list", ")", ":", "array", "{", "$", "iter", "=", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveArrayIterator", "(", "$", "list", ")", ")", ";", "$", "flat", "=", "[", "]", ";", "foreach", "(", "$", "iter", "as", "$", "item", ")", "{", "$", "flat", "[", "]", "=", "$", "item", ";", "}", "return", "$", "flat", ";", "}" ]
Array Flatten Flattens a nested array structure into a single-dimensional array. Can handle arrays of arbitrary dimension. @example Arrays::flatten([1, [2], [[[3, 4, [5]]]]]); // [1, 2, 3, 4, 5] @type [a] -> [b] @param array $list Nested array to flatten @return array Result of flattening $list into a 1-dimensional list
[ "Array", "Flatten" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L728-L738
joseph-walker/vector
src/Lib/Arrays.php
Arrays.__replicate
protected static function __replicate(int $n, $item) : array { $result = []; for ($i = 0; $i < $n; $i++) { $result[] = $item; } return $result; }
php
protected static function __replicate(int $n, $item) : array { $result = []; for ($i = 0; $i < $n; $i++) { $result[] = $item; } return $result; }
[ "protected", "static", "function", "__replicate", "(", "int", "$", "n", ",", "$", "item", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "result", "[", "]", "=", "$", "item", ";", "}", "return", "$", "result", ";", "}" ]
Replicate Item Given some integer n and an item to repeat, repeat that item and place the results into an array of length n. @example Arrays::replicate(5, 'foo'); // ['foo', 'foo', 'foo', 'foo', 'foo'] @type Int -> a -> [a] @param int $n Times to repeat some item @param mixed $item Item to repeat @return array Array with $n items
[ "Replicate", "Item" ]
train
https://github.com/joseph-walker/vector/blob/e349aa2e9e0535b1993f9fffc0476e7fd8e113fc/src/Lib/Arrays.php#L778-L787
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.getAuthority
public function getAuthority() { $userInfo = $this->getUserInfo(); return rtrim(($userInfo ? $userInfo . '@' : '') . $this->host . (!$this->isStandardPort($this->scheme, $this->port) ? ':' . $this->port : ''), ':'); }
php
public function getAuthority() { $userInfo = $this->getUserInfo(); return rtrim(($userInfo ? $userInfo . '@' : '') . $this->host . (!$this->isStandardPort($this->scheme, $this->port) ? ':' . $this->port : ''), ':'); }
[ "public", "function", "getAuthority", "(", ")", "{", "$", "userInfo", "=", "$", "this", "->", "getUserInfo", "(", ")", ";", "return", "rtrim", "(", "(", "$", "userInfo", "?", "$", "userInfo", ".", "'@'", ":", "''", ")", ".", "$", "this", "->", "host", ".", "(", "!", "$", "this", "->", "isStandardPort", "(", "$", "this", "->", "scheme", ",", "$", "this", "->", "port", ")", "?", "':'", ".", "$", "this", "->", "port", ":", "''", ")", ",", "':'", ")", ";", "}" ]
{@inheritdoc} @see https://tools.ietf.org/html/rfc3986#section-3.2 @return string The URI authority, in "[user-info@]host[:port]" format.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L102-L110
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.withScheme
public function withScheme($scheme) { $scheme = str_replace('://', '', strtolower((string)$scheme)); if (!empty($scheme) && !array_key_exists($scheme, $this->schemes)) { throw new InvalidArgumentException('Invalid scheme provided.'); } return $this->_clone('scheme', $scheme); }
php
public function withScheme($scheme) { $scheme = str_replace('://', '', strtolower((string)$scheme)); if (!empty($scheme) && !array_key_exists($scheme, $this->schemes)) { throw new InvalidArgumentException('Invalid scheme provided.'); } return $this->_clone('scheme', $scheme); }
[ "public", "function", "withScheme", "(", "$", "scheme", ")", "{", "$", "scheme", "=", "str_replace", "(", "'://'", ",", "''", ",", "strtolower", "(", "(", "string", ")", "$", "scheme", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "scheme", ")", "&&", "!", "array_key_exists", "(", "$", "scheme", ",", "$", "this", "->", "schemes", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid scheme provided.'", ")", ";", "}", "return", "$", "this", "->", "_clone", "(", "'scheme'", ",", "$", "scheme", ")", ";", "}" ]
{@inheritdoc} @param string $scheme The scheme to use with the new instance. @return self A new instance with the specified scheme. @throws \InvalidArgumentException for invalid or unsupported schemes.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L187-L196
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.withUserInfo
public function withUserInfo($user, $password = null) { $userInfo = implode(':', [$user, $password]); return $this->_clone('userInfo', rtrim($userInfo, ':')); }
php
public function withUserInfo($user, $password = null) { $userInfo = implode(':', [$user, $password]); return $this->_clone('userInfo', rtrim($userInfo, ':')); }
[ "public", "function", "withUserInfo", "(", "$", "user", ",", "$", "password", "=", "null", ")", "{", "$", "userInfo", "=", "implode", "(", "':'", ",", "[", "$", "user", ",", "$", "password", "]", ")", ";", "return", "$", "this", "->", "_clone", "(", "'userInfo'", ",", "rtrim", "(", "$", "userInfo", ",", "':'", ")", ")", ";", "}" ]
{@inheritdoc} @param string $user The user name to use for authority. @param null|string $password The password associated with $user. @return self A new instance with the specified user information.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L205-L210
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.withPort
public function withPort($port) { if ($port === null) { return $this->_clone('port', null); } if ($port < 1 || $port > 65535) { throw new InvalidArgumentException('Invalid port specified'); } return $this->_clone('port', (int)$port); }
php
public function withPort($port) { if ($port === null) { return $this->_clone('port', null); } if ($port < 1 || $port > 65535) { throw new InvalidArgumentException('Invalid port specified'); } return $this->_clone('port', (int)$port); }
[ "public", "function", "withPort", "(", "$", "port", ")", "{", "if", "(", "$", "port", "===", "null", ")", "{", "return", "$", "this", "->", "_clone", "(", "'port'", ",", "null", ")", ";", "}", "if", "(", "$", "port", "<", "1", "||", "$", "port", ">", "65535", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid port specified'", ")", ";", "}", "return", "$", "this", "->", "_clone", "(", "'port'", ",", "(", "int", ")", "$", "port", ")", ";", "}" ]
{@inheritdoc} @param null|int $port The port to use with the new instance; a null value removes the port information. @return self A new instance with the specified port. @throws InvalidArgumentException for invalid ports.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L231-L242
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.withPath
public function withPath($path) { if (!is_string($path) || strpos($path, '#') !== false || strpos($path, '?') !== false) { throw new \InvalidArgumentException('Path must be a string and cannot contain a fragment or query string'); } if (!empty($path) && '/' !== substr($path, 0, 1)) { $path = '/' . $path; } return $this->_clone('path', $this->filterPath($path)); }
php
public function withPath($path) { if (!is_string($path) || strpos($path, '#') !== false || strpos($path, '?') !== false) { throw new \InvalidArgumentException('Path must be a string and cannot contain a fragment or query string'); } if (!empty($path) && '/' !== substr($path, 0, 1)) { $path = '/' . $path; } return $this->_clone('path', $this->filterPath($path)); }
[ "public", "function", "withPath", "(", "$", "path", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", "||", "strpos", "(", "$", "path", ",", "'#'", ")", "!==", "false", "||", "strpos", "(", "$", "path", ",", "'?'", ")", "!==", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Path must be a string and cannot contain a fragment or query string'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "path", ")", "&&", "'/'", "!==", "substr", "(", "$", "path", ",", "0", ",", "1", ")", ")", "{", "$", "path", "=", "'/'", ".", "$", "path", ";", "}", "return", "$", "this", "->", "_clone", "(", "'path'", ",", "$", "this", "->", "filterPath", "(", "$", "path", ")", ")", ";", "}" ]
{@inheritdoc} @param string $path The path to use with the new instance. @return self A new instance with the specified path. @throws \InvalidArgumentException for invalid paths.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L251-L262
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.withFragment
public function withFragment($fragment) { if (strpos($fragment, '#') === 0) { $fragment = substr($fragment, 1); } return $this->_clone('fragment', $this->filter($fragment)); }
php
public function withFragment($fragment) { if (strpos($fragment, '#') === 0) { $fragment = substr($fragment, 1); } return $this->_clone('fragment', $this->filter($fragment)); }
[ "public", "function", "withFragment", "(", "$", "fragment", ")", "{", "if", "(", "strpos", "(", "$", "fragment", ",", "'#'", ")", "===", "0", ")", "{", "$", "fragment", "=", "substr", "(", "$", "fragment", ",", "1", ")", ";", "}", "return", "$", "this", "->", "_clone", "(", "'fragment'", ",", "$", "this", "->", "filter", "(", "$", "fragment", ")", ")", ";", "}" ]
{@inheritdoc} @param string $fragment The fragment to use with the new instance. @return self A new instance with the specified fragment.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L282-L289
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.filter
protected function filter($query) { $decoded = rawurldecode($query); if ($decoded === $query) { // Query string or fragment is already decoded, encode return str_replace(['%3D', '%26'], ['=', '&'], rawurlencode($query)); } return $query; }
php
protected function filter($query) { $decoded = rawurldecode($query); if ($decoded === $query) { // Query string or fragment is already decoded, encode return str_replace(['%3D', '%26'], ['=', '&'], rawurlencode($query)); } return $query; }
[ "protected", "function", "filter", "(", "$", "query", ")", "{", "$", "decoded", "=", "rawurldecode", "(", "$", "query", ")", ";", "if", "(", "$", "decoded", "===", "$", "query", ")", "{", "// Query string or fragment is already decoded, encode", "return", "str_replace", "(", "[", "'%3D'", ",", "'%26'", "]", ",", "[", "'='", ",", "'&'", "]", ",", "rawurlencode", "(", "$", "query", ")", ")", ";", "}", "return", "$", "query", ";", "}" ]
Filters the query string or fragment of a URI. @param string $query The raw uri query string. @return string The percent-encoded query string.
[ "Filters", "the", "query", "string", "or", "fragment", "of", "a", "URI", "." ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L337-L347
fyuze/framework
src/Fyuze/Http/Message/Uri.php
Uri.filterPath
protected function filterPath($path) { $decoded = rawurldecode($path); if ($decoded === $path) { // Url is already decoded, encode return str_replace('%2F', '/', rawurlencode($path)); } return $path; }
php
protected function filterPath($path) { $decoded = rawurldecode($path); if ($decoded === $path) { // Url is already decoded, encode return str_replace('%2F', '/', rawurlencode($path)); } return $path; }
[ "protected", "function", "filterPath", "(", "$", "path", ")", "{", "$", "decoded", "=", "rawurldecode", "(", "$", "path", ")", ";", "if", "(", "$", "decoded", "===", "$", "path", ")", "{", "// Url is already decoded, encode", "return", "str_replace", "(", "'%2F'", ",", "'/'", ",", "rawurlencode", "(", "$", "path", ")", ")", ";", "}", "return", "$", "path", ";", "}" ]
Filter Uri path. This method percent-encodes all reserved characters in the provided path string. This method will NOT double-encode characters that are already percent-encoded. @param string $path The raw uri path. @return string The RFC 3986 percent-encoded uri path. @link http://www.faqs.org/rfcs/rfc3986.html
[ "Filter", "Uri", "path", "." ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Uri.php#L361-L371
alanpich/slender
src/Core/View.php
View.render
protected function render($template, array $data = array()) { // Resolve and verify template file $templatePathname = $this->resolveTemplate($template); if (!is_file($templatePathname)) { throw new \RuntimeException("Cannot render template `$templatePathname` because the template does not exist. Make sure your view's template directory is correct."); } // Render template with view variables into a temporary output buffer $this->replace($data); extract($this->all()); ob_start(); require $templatePathname; // Return temporary output buffer content, destroy output buffer return ob_get_clean(); }
php
protected function render($template, array $data = array()) { // Resolve and verify template file $templatePathname = $this->resolveTemplate($template); if (!is_file($templatePathname)) { throw new \RuntimeException("Cannot render template `$templatePathname` because the template does not exist. Make sure your view's template directory is correct."); } // Render template with view variables into a temporary output buffer $this->replace($data); extract($this->all()); ob_start(); require $templatePathname; // Return temporary output buffer content, destroy output buffer return ob_get_clean(); }
[ "protected", "function", "render", "(", "$", "template", ",", "array", "$", "data", "=", "array", "(", ")", ")", "{", "// Resolve and verify template file", "$", "templatePathname", "=", "$", "this", "->", "resolveTemplate", "(", "$", "template", ")", ";", "if", "(", "!", "is_file", "(", "$", "templatePathname", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Cannot render template `$templatePathname` because the template does not exist. Make sure your view's template directory is correct.\"", ")", ";", "}", "// Render template with view variables into a temporary output buffer", "$", "this", "->", "replace", "(", "$", "data", ")", ";", "extract", "(", "$", "this", "->", "all", "(", ")", ")", ";", "ob_start", "(", ")", ";", "require", "$", "templatePathname", ";", "// Return temporary output buffer content, destroy output buffer", "return", "ob_get_clean", "(", ")", ";", "}" ]
Render template This method will render the specified template file using the current application view. Although this method will work perfectly fine, it is recommended that you create your own custom view class that implements \Slim\ViewInterface instead of using this default view class. This default implementation is largely intended as an example. @var string $template Pathname of template file relative to templates directory @param array $data @throws \RuntimeException If resolved template pathname is not a valid file @return string The rendered template
[ "Render", "template" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/View.php#L138-L154
alanpich/slender
src/Core/View.php
View.resolveTemplate
protected function resolveTemplate($template) { if (!$this->pathCache[$template]) { foreach (array_reverse($this->templateDirs) as $dir) { $path = $dir . DIRECTORY_SEPARATOR . $template .'.'. $this->getFileExtension(); if (is_readable($path)) { $this->pathCache[$template] = $path; break; } } } return $this->pathCache[$template]; }
php
protected function resolveTemplate($template) { if (!$this->pathCache[$template]) { foreach (array_reverse($this->templateDirs) as $dir) { $path = $dir . DIRECTORY_SEPARATOR . $template .'.'. $this->getFileExtension(); if (is_readable($path)) { $this->pathCache[$template] = $path; break; } } } return $this->pathCache[$template]; }
[ "protected", "function", "resolveTemplate", "(", "$", "template", ")", "{", "if", "(", "!", "$", "this", "->", "pathCache", "[", "$", "template", "]", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "templateDirs", ")", "as", "$", "dir", ")", "{", "$", "path", "=", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "template", ".", "'.'", ".", "$", "this", "->", "getFileExtension", "(", ")", ";", "if", "(", "is_readable", "(", "$", "path", ")", ")", "{", "$", "this", "->", "pathCache", "[", "$", "template", "]", "=", "$", "path", ";", "break", ";", "}", "}", "}", "return", "$", "this", "->", "pathCache", "[", "$", "template", "]", ";", "}" ]
Resolves a template name to a file in $templateDirs @param $template
[ "Resolves", "a", "template", "name", "to", "a", "file", "in", "$templateDirs" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/View.php#L161-L176
aedart/laravel-helpers
src/Traits/Auth/Access/GateTrait.php
GateTrait.getGate
public function getGate(): ?Gate { if (!$this->hasGate()) { $this->setGate($this->getDefaultGate()); } return $this->gate; }
php
public function getGate(): ?Gate { if (!$this->hasGate()) { $this->setGate($this->getDefaultGate()); } return $this->gate; }
[ "public", "function", "getGate", "(", ")", ":", "?", "Gate", "{", "if", "(", "!", "$", "this", "->", "hasGate", "(", ")", ")", "{", "$", "this", "->", "setGate", "(", "$", "this", "->", "getDefaultGate", "(", ")", ")", ";", "}", "return", "$", "this", "->", "gate", ";", "}" ]
Get gate If no gate has been set, this method will set and return a default gate, if any such value is available @see getDefaultGate() @return Gate|null gate or null if none gate has been set
[ "Get", "gate" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Auth/Access/GateTrait.php#L53-L59
OpenClassrooms/ServiceProxy
src/Annotations/Cache.php
Cache.getId
public function getId() { if (null !== $this->id && self::MEMCACHE_KEY_MAX_LENGTH + self::QUOTES_LENGTH < mb_strlen($this->id)) { throw new InvalidCacheIdException('id is too long, MUST be inferior to 240'); } return $this->id; }
php
public function getId() { if (null !== $this->id && self::MEMCACHE_KEY_MAX_LENGTH + self::QUOTES_LENGTH < mb_strlen($this->id)) { throw new InvalidCacheIdException('id is too long, MUST be inferior to 240'); } return $this->id; }
[ "public", "function", "getId", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "id", "&&", "self", "::", "MEMCACHE_KEY_MAX_LENGTH", "+", "self", "::", "QUOTES_LENGTH", "<", "mb_strlen", "(", "$", "this", "->", "id", ")", ")", "{", "throw", "new", "InvalidCacheIdException", "(", "'id is too long, MUST be inferior to 240'", ")", ";", "}", "return", "$", "this", "->", "id", ";", "}" ]
@return string @throws InvalidCacheIdException
[ "@return", "string" ]
train
https://github.com/OpenClassrooms/ServiceProxy/blob/31f9f8be8f064b4ca36873df83fc3833f53da438/src/Annotations/Cache.php#L35-L42
phpmob/changmin
src/PhpMob/MediaBundle/DependencyInjection/Compiler/RegisterImageTypesPass.php
RegisterImageTypesPass.process
public function process(ContainerBuilder $container) { $registry = $container->getDefinition('phpmob.registry.image_types'); foreach ($container->findTaggedServiceIds('form.type') as $id => $attributes) { if (is_subclass_of($this->getClass($id, $container), ImageType::class)) { $container->getDefinition($id)->addMethodCall('setImageTypeRegistry', [$registry]); } } }
php
public function process(ContainerBuilder $container) { $registry = $container->getDefinition('phpmob.registry.image_types'); foreach ($container->findTaggedServiceIds('form.type') as $id => $attributes) { if (is_subclass_of($this->getClass($id, $container), ImageType::class)) { $container->getDefinition($id)->addMethodCall('setImageTypeRegistry', [$registry]); } } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "registry", "=", "$", "container", "->", "getDefinition", "(", "'phpmob.registry.image_types'", ")", ";", "foreach", "(", "$", "container", "->", "findTaggedServiceIds", "(", "'form.type'", ")", "as", "$", "id", "=>", "$", "attributes", ")", "{", "if", "(", "is_subclass_of", "(", "$", "this", "->", "getClass", "(", "$", "id", ",", "$", "container", ")", ",", "ImageType", "::", "class", ")", ")", "{", "$", "container", "->", "getDefinition", "(", "$", "id", ")", "->", "addMethodCall", "(", "'setImageTypeRegistry'", ",", "[", "$", "registry", "]", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/MediaBundle/DependencyInjection/Compiler/RegisterImageTypesPass.php#L28-L37
phpmob/changmin
src/PhpMob/MediaBundle/DependencyInjection/Compiler/RegisterImageTypesPass.php
RegisterImageTypesPass.getClass
private function getClass($id, ContainerBuilder $container) { $className = $container->findDefinition($id)->getClass(); if (false !== strpos($className, '%')) { $className = $container->getParameter(str_replace('%', '', $className)); } return $className; }
php
private function getClass($id, ContainerBuilder $container) { $className = $container->findDefinition($id)->getClass(); if (false !== strpos($className, '%')) { $className = $container->getParameter(str_replace('%', '', $className)); } return $className; }
[ "private", "function", "getClass", "(", "$", "id", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "className", "=", "$", "container", "->", "findDefinition", "(", "$", "id", ")", "->", "getClass", "(", ")", ";", "if", "(", "false", "!==", "strpos", "(", "$", "className", ",", "'%'", ")", ")", "{", "$", "className", "=", "$", "container", "->", "getParameter", "(", "str_replace", "(", "'%'", ",", "''", ",", "$", "className", ")", ")", ";", "}", "return", "$", "className", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/MediaBundle/DependencyInjection/Compiler/RegisterImageTypesPass.php#L42-L51
2amigos/yiifoundation
helpers/Html.php
Html.thumb
public static function thumb($src, $url = '#', $htmlOptions = array()) { static::addCssClass($htmlOptions, 'th'); return \CHtml::link(\CHtml::image($src), $url, $htmlOptions); }
php
public static function thumb($src, $url = '#', $htmlOptions = array()) { static::addCssClass($htmlOptions, 'th'); return \CHtml::link(\CHtml::image($src), $url, $htmlOptions); }
[ "public", "static", "function", "thumb", "(", "$", "src", ",", "$", "url", "=", "'#'", ",", "$", "htmlOptions", "=", "array", "(", ")", ")", "{", "static", "::", "addCssClass", "(", "$", "htmlOptions", ",", "'th'", ")", ";", "return", "\\", "CHtml", "::", "link", "(", "\\", "CHtml", "::", "image", "(", "$", "src", ")", ",", "$", "url", ",", "$", "htmlOptions", ")", ";", "}" ]
Renders a Foundation thumbnail @param $src @param string $url @param array $htmlOptions @return string
[ "Renders", "a", "Foundation", "thumbnail" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/helpers/Html.php#L161-L165
2amigos/yiifoundation
helpers/Html.php
Html.addCssClass
public static function addCssClass(&$options, $class) { if (isset($options['class'])) { $classes = ' ' . $options['class'] . ' '; if (($pos = strpos($classes, ' ' . $class . ' ')) === false) { $options['class'] .= ' ' . $class; } } else { $options['class'] = $class; } }
php
public static function addCssClass(&$options, $class) { if (isset($options['class'])) { $classes = ' ' . $options['class'] . ' '; if (($pos = strpos($classes, ' ' . $class . ' ')) === false) { $options['class'] .= ' ' . $class; } } else { $options['class'] = $class; } }
[ "public", "static", "function", "addCssClass", "(", "&", "$", "options", ",", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'class'", "]", ")", ")", "{", "$", "classes", "=", "' '", ".", "$", "options", "[", "'class'", "]", ".", "' '", ";", "if", "(", "(", "$", "pos", "=", "strpos", "(", "$", "classes", ",", "' '", ".", "$", "class", ".", "' '", ")", ")", "===", "false", ")", "{", "$", "options", "[", "'class'", "]", ".=", "' '", ".", "$", "class", ";", "}", "}", "else", "{", "$", "options", "[", "'class'", "]", "=", "$", "class", ";", "}", "}" ]
Adds a CSS class to the specified options. If the CSS class is already in the options, it will not be added again. @param array $options the options to be modified. @param string $class the CSS class to be added
[ "Adds", "a", "CSS", "class", "to", "the", "specified", "options", ".", "If", "the", "CSS", "class", "is", "already", "in", "the", "options", "it", "will", "not", "be", "added", "again", "." ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/helpers/Html.php#L173-L183
nyeholt/silverstripe-external-content
remoteclients/WebApiClient.php
WebApiClient.callMethod
public function callMethod($method, $args) { $methodDetails = isset($this->methods[$method]) ? $this->methods[$method] : null; if (!$methodDetails) { throw new Exception("$method does not have an appropriate mapping"); } $body = null; // use the method params to try caching the results // need to add in the baseUrl we're connecting to, and any global params // because the cache might be connecting via different users, and the // different users will have different sessions. This might need to be // tweaked to handle separate user logins at a later point in time $uri = $this->baseUrl . (isset($methodDetails['url']) ? $methodDetails['url'] : ''); // check for any replacements that are required if (preg_match_all('/{(\w+)}/', $uri, $matches)) { foreach ($matches[1] as $match) { if (isset($args[$match])) { $uri = str_replace('{'.$match.'}', $args[$match], $uri); } } } $cacheKey = md5($uri . $method . var_export($args, true) . var_export($this->globalParams, true)); $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; $cache = isset($methodDetails['cache']) ? $methodDetails['cache'] : self::$cache_length; if (mb_strtolower($requestType) == 'get' && $cache) { $body = CacheService::inst()->get($cacheKey); } if (!$body) { // Note that case is important! Some servers won't respond correctly // to get or Get requests $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; $client = $this->getClient($uri); $client->setMethod($requestType); // set the encoding type $client->setEncType(isset($methodDetails['enctype']) ? $methodDetails['enctype'] : Zend_Http_Client::ENC_URLENCODED); $paramMethod = $requestType == 'GET' ? 'setParameterGet' : 'setParameterPost'; if ($this->globalParams) { foreach ($this->globalParams as $key => $value) { $client->$paramMethod($key, $value); } } if (isset($methodDetails['params'])) { $paramNames = $methodDetails['params']; foreach ($paramNames as $index => $pname) { if (isset($args[$pname])) { $client->$paramMethod($pname, $args[$pname]); } else if (isset($args[$index])) { $client->$paramMethod($pname, $args[$index]); } } } if (isset($methodDetails['get'])) { foreach ($methodDetails['get'] as $k => $v) { $client->setParameterGet($k, $v); } } if (isset($methodDetails['post'])) { foreach ($methodDetails['post'] as $k => $v) { $client->setParameterPost($k, $v); } } if (isset($methodDetails['raw']) && $methodDetails['raw']) { $client->setRawData($args['raw_body']); } // request away $response = $client->request(); if ($response->isSuccessful()) { $body = $response->getBody(); if ($cache) { CacheService::inst()->store($cacheKey, $body, $cache); } } else { if ($response->getStatus() == 500) { error_log("Failure: ".$response->getBody()); error_log(var_export($client, true)); } throw new FailedRequestException("Failed executing $method: ".$response->getMessage()." for request to $uri (".$client->getUri(true).')', $response->getBody()); } } $returnType = isset($methodDetails['return']) ? $methodDetails['return'] : 'raw'; // see what we need to do with it if (isset($this->returnHandlers[$returnType])) { $handler = $this->returnHandlers[$returnType]; return $handler->handleReturn($body); } else { return $body; } }
php
public function callMethod($method, $args) { $methodDetails = isset($this->methods[$method]) ? $this->methods[$method] : null; if (!$methodDetails) { throw new Exception("$method does not have an appropriate mapping"); } $body = null; // use the method params to try caching the results // need to add in the baseUrl we're connecting to, and any global params // because the cache might be connecting via different users, and the // different users will have different sessions. This might need to be // tweaked to handle separate user logins at a later point in time $uri = $this->baseUrl . (isset($methodDetails['url']) ? $methodDetails['url'] : ''); // check for any replacements that are required if (preg_match_all('/{(\w+)}/', $uri, $matches)) { foreach ($matches[1] as $match) { if (isset($args[$match])) { $uri = str_replace('{'.$match.'}', $args[$match], $uri); } } } $cacheKey = md5($uri . $method . var_export($args, true) . var_export($this->globalParams, true)); $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; $cache = isset($methodDetails['cache']) ? $methodDetails['cache'] : self::$cache_length; if (mb_strtolower($requestType) == 'get' && $cache) { $body = CacheService::inst()->get($cacheKey); } if (!$body) { // Note that case is important! Some servers won't respond correctly // to get or Get requests $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; $client = $this->getClient($uri); $client->setMethod($requestType); // set the encoding type $client->setEncType(isset($methodDetails['enctype']) ? $methodDetails['enctype'] : Zend_Http_Client::ENC_URLENCODED); $paramMethod = $requestType == 'GET' ? 'setParameterGet' : 'setParameterPost'; if ($this->globalParams) { foreach ($this->globalParams as $key => $value) { $client->$paramMethod($key, $value); } } if (isset($methodDetails['params'])) { $paramNames = $methodDetails['params']; foreach ($paramNames as $index => $pname) { if (isset($args[$pname])) { $client->$paramMethod($pname, $args[$pname]); } else if (isset($args[$index])) { $client->$paramMethod($pname, $args[$index]); } } } if (isset($methodDetails['get'])) { foreach ($methodDetails['get'] as $k => $v) { $client->setParameterGet($k, $v); } } if (isset($methodDetails['post'])) { foreach ($methodDetails['post'] as $k => $v) { $client->setParameterPost($k, $v); } } if (isset($methodDetails['raw']) && $methodDetails['raw']) { $client->setRawData($args['raw_body']); } // request away $response = $client->request(); if ($response->isSuccessful()) { $body = $response->getBody(); if ($cache) { CacheService::inst()->store($cacheKey, $body, $cache); } } else { if ($response->getStatus() == 500) { error_log("Failure: ".$response->getBody()); error_log(var_export($client, true)); } throw new FailedRequestException("Failed executing $method: ".$response->getMessage()." for request to $uri (".$client->getUri(true).')', $response->getBody()); } } $returnType = isset($methodDetails['return']) ? $methodDetails['return'] : 'raw'; // see what we need to do with it if (isset($this->returnHandlers[$returnType])) { $handler = $this->returnHandlers[$returnType]; return $handler->handleReturn($body); } else { return $body; } }
[ "public", "function", "callMethod", "(", "$", "method", ",", "$", "args", ")", "{", "$", "methodDetails", "=", "isset", "(", "$", "this", "->", "methods", "[", "$", "method", "]", ")", "?", "$", "this", "->", "methods", "[", "$", "method", "]", ":", "null", ";", "if", "(", "!", "$", "methodDetails", ")", "{", "throw", "new", "Exception", "(", "\"$method does not have an appropriate mapping\"", ")", ";", "}", "$", "body", "=", "null", ";", "// use the method params to try caching the results", "// need to add in the baseUrl we're connecting to, and any global params", "// because the cache might be connecting via different users, and the", "// different users will have different sessions. This might need to be", "// tweaked to handle separate user logins at a later point in time", "$", "uri", "=", "$", "this", "->", "baseUrl", ".", "(", "isset", "(", "$", "methodDetails", "[", "'url'", "]", ")", "?", "$", "methodDetails", "[", "'url'", "]", ":", "''", ")", ";", "// \tcheck for any replacements that are required", "if", "(", "preg_match_all", "(", "'/{(\\w+)}/'", ",", "$", "uri", ",", "$", "matches", ")", ")", "{", "foreach", "(", "$", "matches", "[", "1", "]", "as", "$", "match", ")", "{", "if", "(", "isset", "(", "$", "args", "[", "$", "match", "]", ")", ")", "{", "$", "uri", "=", "str_replace", "(", "'{'", ".", "$", "match", ".", "'}'", ",", "$", "args", "[", "$", "match", "]", ",", "$", "uri", ")", ";", "}", "}", "}", "$", "cacheKey", "=", "md5", "(", "$", "uri", ".", "$", "method", ".", "var_export", "(", "$", "args", ",", "true", ")", ".", "var_export", "(", "$", "this", "->", "globalParams", ",", "true", ")", ")", ";", "$", "requestType", "=", "isset", "(", "$", "methodDetails", "[", "'method'", "]", ")", "?", "$", "methodDetails", "[", "'method'", "]", ":", "'GET'", ";", "$", "cache", "=", "isset", "(", "$", "methodDetails", "[", "'cache'", "]", ")", "?", "$", "methodDetails", "[", "'cache'", "]", ":", "self", "::", "$", "cache_length", ";", "if", "(", "mb_strtolower", "(", "$", "requestType", ")", "==", "'get'", "&&", "$", "cache", ")", "{", "$", "body", "=", "CacheService", "::", "inst", "(", ")", "->", "get", "(", "$", "cacheKey", ")", ";", "}", "if", "(", "!", "$", "body", ")", "{", "// Note that case is important! Some servers won't respond correctly", "// to get or Get requests", "$", "requestType", "=", "isset", "(", "$", "methodDetails", "[", "'method'", "]", ")", "?", "$", "methodDetails", "[", "'method'", "]", ":", "'GET'", ";", "$", "client", "=", "$", "this", "->", "getClient", "(", "$", "uri", ")", ";", "$", "client", "->", "setMethod", "(", "$", "requestType", ")", ";", "// set the encoding type", "$", "client", "->", "setEncType", "(", "isset", "(", "$", "methodDetails", "[", "'enctype'", "]", ")", "?", "$", "methodDetails", "[", "'enctype'", "]", ":", "Zend_Http_Client", "::", "ENC_URLENCODED", ")", ";", "$", "paramMethod", "=", "$", "requestType", "==", "'GET'", "?", "'setParameterGet'", ":", "'setParameterPost'", ";", "if", "(", "$", "this", "->", "globalParams", ")", "{", "foreach", "(", "$", "this", "->", "globalParams", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "client", "->", "$", "paramMethod", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "methodDetails", "[", "'params'", "]", ")", ")", "{", "$", "paramNames", "=", "$", "methodDetails", "[", "'params'", "]", ";", "foreach", "(", "$", "paramNames", "as", "$", "index", "=>", "$", "pname", ")", "{", "if", "(", "isset", "(", "$", "args", "[", "$", "pname", "]", ")", ")", "{", "$", "client", "->", "$", "paramMethod", "(", "$", "pname", ",", "$", "args", "[", "$", "pname", "]", ")", ";", "}", "else", "if", "(", "isset", "(", "$", "args", "[", "$", "index", "]", ")", ")", "{", "$", "client", "->", "$", "paramMethod", "(", "$", "pname", ",", "$", "args", "[", "$", "index", "]", ")", ";", "}", "}", "}", "if", "(", "isset", "(", "$", "methodDetails", "[", "'get'", "]", ")", ")", "{", "foreach", "(", "$", "methodDetails", "[", "'get'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "client", "->", "setParameterGet", "(", "$", "k", ",", "$", "v", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "methodDetails", "[", "'post'", "]", ")", ")", "{", "foreach", "(", "$", "methodDetails", "[", "'post'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "client", "->", "setParameterPost", "(", "$", "k", ",", "$", "v", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "methodDetails", "[", "'raw'", "]", ")", "&&", "$", "methodDetails", "[", "'raw'", "]", ")", "{", "$", "client", "->", "setRawData", "(", "$", "args", "[", "'raw_body'", "]", ")", ";", "}", "// request away", "$", "response", "=", "$", "client", "->", "request", "(", ")", ";", "if", "(", "$", "response", "->", "isSuccessful", "(", ")", ")", "{", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "if", "(", "$", "cache", ")", "{", "CacheService", "::", "inst", "(", ")", "->", "store", "(", "$", "cacheKey", ",", "$", "body", ",", "$", "cache", ")", ";", "}", "}", "else", "{", "if", "(", "$", "response", "->", "getStatus", "(", ")", "==", "500", ")", "{", "error_log", "(", "\"Failure: \"", ".", "$", "response", "->", "getBody", "(", ")", ")", ";", "error_log", "(", "var_export", "(", "$", "client", ",", "true", ")", ")", ";", "}", "throw", "new", "FailedRequestException", "(", "\"Failed executing $method: \"", ".", "$", "response", "->", "getMessage", "(", ")", ".", "\" for request to $uri (\"", ".", "$", "client", "->", "getUri", "(", "true", ")", ".", "')'", ",", "$", "response", "->", "getBody", "(", ")", ")", ";", "}", "}", "$", "returnType", "=", "isset", "(", "$", "methodDetails", "[", "'return'", "]", ")", "?", "$", "methodDetails", "[", "'return'", "]", ":", "'raw'", ";", "// see what we need to do with it", "if", "(", "isset", "(", "$", "this", "->", "returnHandlers", "[", "$", "returnType", "]", ")", ")", "{", "$", "handler", "=", "$", "this", "->", "returnHandlers", "[", "$", "returnType", "]", ";", "return", "$", "handler", "->", "handleReturn", "(", "$", "body", ")", ";", "}", "else", "{", "return", "$", "body", ";", "}", "}" ]
Call a method with the passed in arguments @param String $method @param array $args - a mapping of argumentName => argumentValue @param array $getParams Specific get params to add in @param array $postParams Specific post params to append @return mixed
[ "Call", "a", "method", "with", "the", "passed", "in", "arguments" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/remoteclients/WebApiClient.php#L193-L299
nyeholt/silverstripe-external-content
remoteclients/WebApiClient.php
WebApiClient.callUrl
public function callUrl($url, $args = array(), $returnType = 'raw', $requestType = 'GET', $cache = 300, $enctype = Zend_Http_Client::ENC_URLENCODED) { $body = null; // use the method params to try caching the results // need to add in the baseUrl we're connecting to, and any global params // because the cache might be connecting via different users, and the // different users will have different sessions. This might need to be // tweaked to handle separate user logins at a later point in time $cacheKey = md5($url . $requestType . var_export($args, true) . var_export($this->globalParams, true)); $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; if (mb_strtolower($requestType) == 'get' && $cache) { $body = CacheService::inst()->get($cacheKey); } if (!$body) { $uri = $url; $client = $this->getClient($uri); $client->setMethod($requestType); // set the encoding type $client->setEncType($enctype); $paramMethod = 'setParameter'.$requestType; // make sure to add the alfTicket parameter if ($this->globalParams) { foreach ($this->globalParams as $key => $value) { $client->$paramMethod($key, $value); } } foreach ($args as $index => $pname) { $client->$paramMethod($index, $pname); } // request away $response = $client->request(); if ($response->isSuccessful()) { $body = $response->getBody(); if ($cache) { CacheService::inst()->store($cacheKey, $body, $cache); } } else { if ($response->getStatus() == 500) { error_log("Failure: ".$response->getBody()); error_log(var_export($client, true)); } throw new FailedRequestException("Failed executing $url: ".$response->getMessage()." for request to $uri (".$client->getUri(true).')', $response->getBody()); } } // see what we need to do with it if (isset($this->returnHandlers[$returnType])) { $handler = $this->returnHandlers[$returnType]; return $handler->handleReturn($body); } else { return $body; } }
php
public function callUrl($url, $args = array(), $returnType = 'raw', $requestType = 'GET', $cache = 300, $enctype = Zend_Http_Client::ENC_URLENCODED) { $body = null; // use the method params to try caching the results // need to add in the baseUrl we're connecting to, and any global params // because the cache might be connecting via different users, and the // different users will have different sessions. This might need to be // tweaked to handle separate user logins at a later point in time $cacheKey = md5($url . $requestType . var_export($args, true) . var_export($this->globalParams, true)); $requestType = isset($methodDetails['method']) ? $methodDetails['method'] : 'GET'; if (mb_strtolower($requestType) == 'get' && $cache) { $body = CacheService::inst()->get($cacheKey); } if (!$body) { $uri = $url; $client = $this->getClient($uri); $client->setMethod($requestType); // set the encoding type $client->setEncType($enctype); $paramMethod = 'setParameter'.$requestType; // make sure to add the alfTicket parameter if ($this->globalParams) { foreach ($this->globalParams as $key => $value) { $client->$paramMethod($key, $value); } } foreach ($args as $index => $pname) { $client->$paramMethod($index, $pname); } // request away $response = $client->request(); if ($response->isSuccessful()) { $body = $response->getBody(); if ($cache) { CacheService::inst()->store($cacheKey, $body, $cache); } } else { if ($response->getStatus() == 500) { error_log("Failure: ".$response->getBody()); error_log(var_export($client, true)); } throw new FailedRequestException("Failed executing $url: ".$response->getMessage()." for request to $uri (".$client->getUri(true).')', $response->getBody()); } } // see what we need to do with it if (isset($this->returnHandlers[$returnType])) { $handler = $this->returnHandlers[$returnType]; return $handler->handleReturn($body); } else { return $body; } }
[ "public", "function", "callUrl", "(", "$", "url", ",", "$", "args", "=", "array", "(", ")", ",", "$", "returnType", "=", "'raw'", ",", "$", "requestType", "=", "'GET'", ",", "$", "cache", "=", "300", ",", "$", "enctype", "=", "Zend_Http_Client", "::", "ENC_URLENCODED", ")", "{", "$", "body", "=", "null", ";", "// use the method params to try caching the results", "// need to add in the baseUrl we're connecting to, and any global params", "// because the cache might be connecting via different users, and the", "// different users will have different sessions. This might need to be", "// tweaked to handle separate user logins at a later point in time", "$", "cacheKey", "=", "md5", "(", "$", "url", ".", "$", "requestType", ".", "var_export", "(", "$", "args", ",", "true", ")", ".", "var_export", "(", "$", "this", "->", "globalParams", ",", "true", ")", ")", ";", "$", "requestType", "=", "isset", "(", "$", "methodDetails", "[", "'method'", "]", ")", "?", "$", "methodDetails", "[", "'method'", "]", ":", "'GET'", ";", "if", "(", "mb_strtolower", "(", "$", "requestType", ")", "==", "'get'", "&&", "$", "cache", ")", "{", "$", "body", "=", "CacheService", "::", "inst", "(", ")", "->", "get", "(", "$", "cacheKey", ")", ";", "}", "if", "(", "!", "$", "body", ")", "{", "$", "uri", "=", "$", "url", ";", "$", "client", "=", "$", "this", "->", "getClient", "(", "$", "uri", ")", ";", "$", "client", "->", "setMethod", "(", "$", "requestType", ")", ";", "// set the encoding type", "$", "client", "->", "setEncType", "(", "$", "enctype", ")", ";", "$", "paramMethod", "=", "'setParameter'", ".", "$", "requestType", ";", "// make sure to add the alfTicket parameter", "if", "(", "$", "this", "->", "globalParams", ")", "{", "foreach", "(", "$", "this", "->", "globalParams", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "client", "->", "$", "paramMethod", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "foreach", "(", "$", "args", "as", "$", "index", "=>", "$", "pname", ")", "{", "$", "client", "->", "$", "paramMethod", "(", "$", "index", ",", "$", "pname", ")", ";", "}", "// request away", "$", "response", "=", "$", "client", "->", "request", "(", ")", ";", "if", "(", "$", "response", "->", "isSuccessful", "(", ")", ")", "{", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "if", "(", "$", "cache", ")", "{", "CacheService", "::", "inst", "(", ")", "->", "store", "(", "$", "cacheKey", ",", "$", "body", ",", "$", "cache", ")", ";", "}", "}", "else", "{", "if", "(", "$", "response", "->", "getStatus", "(", ")", "==", "500", ")", "{", "error_log", "(", "\"Failure: \"", ".", "$", "response", "->", "getBody", "(", ")", ")", ";", "error_log", "(", "var_export", "(", "$", "client", ",", "true", ")", ")", ";", "}", "throw", "new", "FailedRequestException", "(", "\"Failed executing $url: \"", ".", "$", "response", "->", "getMessage", "(", ")", ".", "\" for request to $uri (\"", ".", "$", "client", "->", "getUri", "(", "true", ")", ".", "')'", ",", "$", "response", "->", "getBody", "(", ")", ")", ";", "}", "}", "// see what we need to do with it", "if", "(", "isset", "(", "$", "this", "->", "returnHandlers", "[", "$", "returnType", "]", ")", ")", "{", "$", "handler", "=", "$", "this", "->", "returnHandlers", "[", "$", "returnType", "]", ";", "return", "$", "handler", "->", "handleReturn", "(", "$", "body", ")", ";", "}", "else", "{", "return", "$", "body", ";", "}", "}" ]
Call a URL directly, without it being mapped to a configured web method. This differs from the above in that the caller already knows what URL is trying to be called, so we can bypass the business of mapping arguments all over the place. We still maintain the globalParams for this client though @param $url The URL to call @param $args Parameters to be passed on the call @return mixed
[ "Call", "a", "URL", "directly", "without", "it", "being", "mapped", "to", "a", "configured", "web", "method", "." ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/remoteclients/WebApiClient.php#L316-L374
nyeholt/silverstripe-external-content
remoteclients/WebApiClient.php
WebApiClient.getClient
protected function getClient($uri) { // TODO For some reason the Alfresco client goes into an infinite loop when returning // the children of an item (when you call getChildren on the company home) // it returns itself as its own child, unless you recreate the client. It seems // to maintain all the request body... or something weird. if (!$this->httpClient || !$this->maintainSession) { $this->httpClient = new Zend_Http_Client($uri, array( 'maxredirects' => 0, 'timeout' => 10 ) ); if ($this->useCookies) { $this->httpClient->setCookieJar(); } } else { $this->httpClient->setUri($uri); } // clear it out if ($this->maintainSession) { $this->httpClient->resetParameters(); } if ($this->authInfo) { $this->httpClient->setAuth($this->authInfo['user'], $this->authInfo['pass']); } return $this->httpClient; }
php
protected function getClient($uri) { // TODO For some reason the Alfresco client goes into an infinite loop when returning // the children of an item (when you call getChildren on the company home) // it returns itself as its own child, unless you recreate the client. It seems // to maintain all the request body... or something weird. if (!$this->httpClient || !$this->maintainSession) { $this->httpClient = new Zend_Http_Client($uri, array( 'maxredirects' => 0, 'timeout' => 10 ) ); if ($this->useCookies) { $this->httpClient->setCookieJar(); } } else { $this->httpClient->setUri($uri); } // clear it out if ($this->maintainSession) { $this->httpClient->resetParameters(); } if ($this->authInfo) { $this->httpClient->setAuth($this->authInfo['user'], $this->authInfo['pass']); } return $this->httpClient; }
[ "protected", "function", "getClient", "(", "$", "uri", ")", "{", "// TODO For some reason the Alfresco client goes into an infinite loop when returning", "// the children of an item (when you call getChildren on the company home)", "// it returns itself as its own child, unless you recreate the client. It seems", "// to maintain all the request body... or something weird.", "if", "(", "!", "$", "this", "->", "httpClient", "||", "!", "$", "this", "->", "maintainSession", ")", "{", "$", "this", "->", "httpClient", "=", "new", "Zend_Http_Client", "(", "$", "uri", ",", "array", "(", "'maxredirects'", "=>", "0", ",", "'timeout'", "=>", "10", ")", ")", ";", "if", "(", "$", "this", "->", "useCookies", ")", "{", "$", "this", "->", "httpClient", "->", "setCookieJar", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "httpClient", "->", "setUri", "(", "$", "uri", ")", ";", "}", "// clear it out", "if", "(", "$", "this", "->", "maintainSession", ")", "{", "$", "this", "->", "httpClient", "->", "resetParameters", "(", ")", ";", "}", "if", "(", "$", "this", "->", "authInfo", ")", "{", "$", "this", "->", "httpClient", "->", "setAuth", "(", "$", "this", "->", "authInfo", "[", "'user'", "]", ",", "$", "this", "->", "authInfo", "[", "'pass'", "]", ")", ";", "}", "return", "$", "this", "->", "httpClient", ";", "}" ]
Create and return the http client, defined in a separate method for testing purposes @return Zend_Http_Client
[ "Create", "and", "return", "the", "http", "client", "defined", "in", "a", "separate", "method", "for", "testing", "purposes" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/remoteclients/WebApiClient.php#L389-L419
yuncms/framework
src/helpers/CronParseHelper.php
CronParseHelper.check
public static function check($cronstr, $checkCount = true) { $cronstr = trim($cronstr); $splitTags = preg_split('#\s+#', $cronstr); if ($checkCount && count($splitTags) !== 5) { return false; } foreach ($splitTags as $tag) { $r = '#^\*(\/\d+)?|\d+([\-\/]\d+(\/\d+)?)?(,\d+([\-\/]\d+(\/\d+)?)?)*$#'; if (preg_match($r, $tag) == false) { return false; } } return true; }
php
public static function check($cronstr, $checkCount = true) { $cronstr = trim($cronstr); $splitTags = preg_split('#\s+#', $cronstr); if ($checkCount && count($splitTags) !== 5) { return false; } foreach ($splitTags as $tag) { $r = '#^\*(\/\d+)?|\d+([\-\/]\d+(\/\d+)?)?(,\d+([\-\/]\d+(\/\d+)?)?)*$#'; if (preg_match($r, $tag) == false) { return false; } } return true; }
[ "public", "static", "function", "check", "(", "$", "cronstr", ",", "$", "checkCount", "=", "true", ")", "{", "$", "cronstr", "=", "trim", "(", "$", "cronstr", ")", ";", "$", "splitTags", "=", "preg_split", "(", "'#\\s+#'", ",", "$", "cronstr", ")", ";", "if", "(", "$", "checkCount", "&&", "count", "(", "$", "splitTags", ")", "!==", "5", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "splitTags", "as", "$", "tag", ")", "{", "$", "r", "=", "'#^\\*(\\/\\d+)?|\\d+([\\-\\/]\\d+(\\/\\d+)?)?(,\\d+([\\-\\/]\\d+(\\/\\d+)?)?)*$#'", ";", "if", "(", "preg_match", "(", "$", "r", ",", "$", "tag", ")", "==", "false", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
检查crontab格式是否支持 @param string $cronstr @return boolean true|false
[ "检查crontab格式是否支持" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/CronParseHelper.php#L34-L52
yuncms/framework
src/helpers/CronParseHelper.php
CronParseHelper.formatToDate
public static function formatToDate($cronStr, $maxSize = 1) { if (!static::check($cronStr)) { throw new \Exception("wrong format: $cronStr", 1); } self::$tags = preg_split('#\s+#', $cronStr); $crons = [ 'minutes' => static::parseTag(self::$tags[0], 0, 59), //分钟 'hours' => static::parseTag(self::$tags[1], 0, 23), //小时 'day' => static::parseTag(self::$tags[2], 1, 31), //一个月中的第几天 'month' => static::parseTag(self::$tags[3], 1, 12), //月份 'week' => static::parseTag(self::$tags[4], 0, 6), // 星期 ]; $crons['week'] = array_map(function ($item) { return static::$weekMap[$item]; }, $crons['week']); return self::getDateList($crons, $maxSize); }
php
public static function formatToDate($cronStr, $maxSize = 1) { if (!static::check($cronStr)) { throw new \Exception("wrong format: $cronStr", 1); } self::$tags = preg_split('#\s+#', $cronStr); $crons = [ 'minutes' => static::parseTag(self::$tags[0], 0, 59), //分钟 'hours' => static::parseTag(self::$tags[1], 0, 23), //小时 'day' => static::parseTag(self::$tags[2], 1, 31), //一个月中的第几天 'month' => static::parseTag(self::$tags[3], 1, 12), //月份 'week' => static::parseTag(self::$tags[4], 0, 6), // 星期 ]; $crons['week'] = array_map(function ($item) { return static::$weekMap[$item]; }, $crons['week']); return self::getDateList($crons, $maxSize); }
[ "public", "static", "function", "formatToDate", "(", "$", "cronStr", ",", "$", "maxSize", "=", "1", ")", "{", "if", "(", "!", "static", "::", "check", "(", "$", "cronStr", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"wrong format: $cronStr\"", ",", "1", ")", ";", "}", "self", "::", "$", "tags", "=", "preg_split", "(", "'#\\s+#'", ",", "$", "cronStr", ")", ";", "$", "crons", "=", "[", "'minutes'", "=>", "static", "::", "parseTag", "(", "self", "::", "$", "tags", "[", "0", "]", ",", "0", ",", "59", ")", ",", "//分钟", "'hours'", "=>", "static", "::", "parseTag", "(", "self", "::", "$", "tags", "[", "1", "]", ",", "0", ",", "23", ")", ",", "//小时", "'day'", "=>", "static", "::", "parseTag", "(", "self", "::", "$", "tags", "[", "2", "]", ",", "1", ",", "31", ")", ",", "//一个月中的第几天", "'month'", "=>", "static", "::", "parseTag", "(", "self", "::", "$", "tags", "[", "3", "]", ",", "1", ",", "12", ")", ",", "//月份", "'week'", "=>", "static", "::", "parseTag", "(", "self", "::", "$", "tags", "[", "4", "]", ",", "0", ",", "6", ")", ",", "// 星期", "]", ";", "$", "crons", "[", "'week'", "]", "=", "array_map", "(", "function", "(", "$", "item", ")", "{", "return", "static", "::", "$", "weekMap", "[", "$", "item", "]", ";", "}", ",", "$", "crons", "[", "'week'", "]", ")", ";", "return", "self", "::", "getDateList", "(", "$", "crons", ",", "$", "maxSize", ")", ";", "}" ]
格式化crontab格式字符串 @param string $cronstr @param int $maxSize 设置返回符合条件的时间数量, 默认为1 @return array 返回符合格式的时间 @throws \Exception
[ "格式化crontab格式字符串" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/CronParseHelper.php#L61-L78
yuncms/framework
src/helpers/CronParseHelper.php
CronParseHelper.getDateList
private static function getDateList(array $crons, $maxSize, $year = null) { $dates = []; // 年份基点 $nowyear = ($year) ? $year : date('Y'); // 时间基点已当前为准,用于过滤小于当前时间的日期 $nowtime = strtotime(date("Y-m-d H:i")); foreach ($crons['month'] as $month) { // 获取此月最大天数 $maxDay = cal_days_in_month(CAL_GREGORIAN, $month, $nowyear); foreach (range(1, $maxDay) as $day) { foreach ($crons['hours'] as $hours) { foreach ($crons['minutes'] as $minutes) { $i = mktime($hours, $minutes, 0, $month, $day, $nowyear); if ($nowtime >= $i) { continue; } $date = getdate($i); // 解析是第几天 if (self::$tags[2] != '*' && in_array($date['mday'], $crons['day'])) { $dates[] = date('Y-m-d H:i', $i); } // 解析星期几 if (self::$tags[4] != '*' && in_array($date['weekday'], $crons['week'])) { $dates[] = date('Y-m-d H:i', $i); } // 天与星期几 if (self::$tags[2] == '*' && self::$tags[4] == '*') { $dates[] = date('Y-m-d H:i', $i); } $dates = array_unique($dates); if (isset($dates) && count($dates) == $maxSize) { break 4; } } } } } // 已经递归获取了.但是还是没拿到符合的日期时间,说明指定的时期时间有问题 if ($year && !count($dates)) { return []; } if (count($dates) != $maxSize) { // 向下一年递归 $dates = array_merge(self::getDateList($crons, $maxSize, ($nowyear + 1)), $dates); } return $dates; }
php
private static function getDateList(array $crons, $maxSize, $year = null) { $dates = []; // 年份基点 $nowyear = ($year) ? $year : date('Y'); // 时间基点已当前为准,用于过滤小于当前时间的日期 $nowtime = strtotime(date("Y-m-d H:i")); foreach ($crons['month'] as $month) { // 获取此月最大天数 $maxDay = cal_days_in_month(CAL_GREGORIAN, $month, $nowyear); foreach (range(1, $maxDay) as $day) { foreach ($crons['hours'] as $hours) { foreach ($crons['minutes'] as $minutes) { $i = mktime($hours, $minutes, 0, $month, $day, $nowyear); if ($nowtime >= $i) { continue; } $date = getdate($i); // 解析是第几天 if (self::$tags[2] != '*' && in_array($date['mday'], $crons['day'])) { $dates[] = date('Y-m-d H:i', $i); } // 解析星期几 if (self::$tags[4] != '*' && in_array($date['weekday'], $crons['week'])) { $dates[] = date('Y-m-d H:i', $i); } // 天与星期几 if (self::$tags[2] == '*' && self::$tags[4] == '*') { $dates[] = date('Y-m-d H:i', $i); } $dates = array_unique($dates); if (isset($dates) && count($dates) == $maxSize) { break 4; } } } } } // 已经递归获取了.但是还是没拿到符合的日期时间,说明指定的时期时间有问题 if ($year && !count($dates)) { return []; } if (count($dates) != $maxSize) { // 向下一年递归 $dates = array_merge(self::getDateList($crons, $maxSize, ($nowyear + 1)), $dates); } return $dates; }
[ "private", "static", "function", "getDateList", "(", "array", "$", "crons", ",", "$", "maxSize", ",", "$", "year", "=", "null", ")", "{", "$", "dates", "=", "[", "]", ";", "// 年份基点", "$", "nowyear", "=", "(", "$", "year", ")", "?", "$", "year", ":", "date", "(", "'Y'", ")", ";", "// 时间基点已当前为准,用于过滤小于当前时间的日期", "$", "nowtime", "=", "strtotime", "(", "date", "(", "\"Y-m-d H:i\"", ")", ")", ";", "foreach", "(", "$", "crons", "[", "'month'", "]", "as", "$", "month", ")", "{", "// 获取此月最大天数", "$", "maxDay", "=", "cal_days_in_month", "(", "CAL_GREGORIAN", ",", "$", "month", ",", "$", "nowyear", ")", ";", "foreach", "(", "range", "(", "1", ",", "$", "maxDay", ")", "as", "$", "day", ")", "{", "foreach", "(", "$", "crons", "[", "'hours'", "]", "as", "$", "hours", ")", "{", "foreach", "(", "$", "crons", "[", "'minutes'", "]", "as", "$", "minutes", ")", "{", "$", "i", "=", "mktime", "(", "$", "hours", ",", "$", "minutes", ",", "0", ",", "$", "month", ",", "$", "day", ",", "$", "nowyear", ")", ";", "if", "(", "$", "nowtime", ">=", "$", "i", ")", "{", "continue", ";", "}", "$", "date", "=", "getdate", "(", "$", "i", ")", ";", "// 解析是第几天", "if", "(", "self", "::", "$", "tags", "[", "2", "]", "!=", "'*'", "&&", "in_array", "(", "$", "date", "[", "'mday'", "]", ",", "$", "crons", "[", "'day'", "]", ")", ")", "{", "$", "dates", "[", "]", "=", "date", "(", "'Y-m-d H:i'", ",", "$", "i", ")", ";", "}", "// 解析星期几", "if", "(", "self", "::", "$", "tags", "[", "4", "]", "!=", "'*'", "&&", "in_array", "(", "$", "date", "[", "'weekday'", "]", ",", "$", "crons", "[", "'week'", "]", ")", ")", "{", "$", "dates", "[", "]", "=", "date", "(", "'Y-m-d H:i'", ",", "$", "i", ")", ";", "}", "// 天与星期几", "if", "(", "self", "::", "$", "tags", "[", "2", "]", "==", "'*'", "&&", "self", "::", "$", "tags", "[", "4", "]", "==", "'*'", ")", "{", "$", "dates", "[", "]", "=", "date", "(", "'Y-m-d H:i'", ",", "$", "i", ")", ";", "}", "$", "dates", "=", "array_unique", "(", "$", "dates", ")", ";", "if", "(", "isset", "(", "$", "dates", ")", "&&", "count", "(", "$", "dates", ")", "==", "$", "maxSize", ")", "{", "break", "4", ";", "}", "}", "}", "}", "}", "// 已经递归获取了.但是还是没拿到符合的日期时间,说明指定的时期时间有问题", "if", "(", "$", "year", "&&", "!", "count", "(", "$", "dates", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "count", "(", "$", "dates", ")", "!=", "$", "maxSize", ")", "{", "// 向下一年递归", "$", "dates", "=", "array_merge", "(", "self", "::", "getDateList", "(", "$", "crons", ",", "$", "maxSize", ",", "(", "$", "nowyear", "+", "1", ")", ")", ",", "$", "dates", ")", ";", "}", "return", "$", "dates", ";", "}" ]
递归获取符合格式的日期,直到取到满足$maxSize的数为止 @param array $crons 解析crontab字符串后的数组 @param int $maxSize 最多返回多少数据的时间 @param int $year 指定年 @return array|null 符合条件的日期
[ "递归获取符合格式的日期", "直到取到满足$maxSize的数为止" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/CronParseHelper.php#L87-L147
yuncms/framework
src/helpers/CronParseHelper.php
CronParseHelper.parseTag
private static function parseTag($tag, $tmin, $tmax) { if ($tag == '*') { return range($tmin, $tmax); } $step = 1; $dateList = []; // x-x/2 情况 if (false !== strpos($tag, ',')) { $tmp = explode(',', $tag); // 处理 xxx-xxx/x,x,x-x foreach ($tmp as $t) { if (self::checkExp($t)) {// 递归处理 $dateList = array_merge(self::parseTag($t, $tmin, $tmax), $dateList); } else { $dateList[] = $t; } } } else if (false !== strpos($tag, '/') && false !== strpos($tag, '-')) { list($number, $mod) = explode('/', $tag); list($left, $right) = explode('-', $number); if ($left > $right) { throw new \Exception("$tag not support."); } foreach (range($left, $right) as $n) { if ($n % $mod === 0) { $dateList[] = $n; } } } else if (false !== strpos($tag, '/')) { $tmp = explode('/', $tag); $step = isset($tmp[1]) ? $tmp[1] : 1; $dateList = range($tmin, $tmax, $step); } else if (false !== strpos($tag, '-')) { list($left, $right) = explode('-', $tag); if ($left > $right) { throw new \Exception("$tag not support."); } $dateList = range($left, $right, $step); } else { $dateList = array($tag); } // 越界判断 foreach ($dateList as $num) { if ($num < $tmin || $num > $tmax) { throw new \Exception('Out of bounds.'); } } sort($dateList); return array_unique($dateList); }
php
private static function parseTag($tag, $tmin, $tmax) { if ($tag == '*') { return range($tmin, $tmax); } $step = 1; $dateList = []; // x-x/2 情况 if (false !== strpos($tag, ',')) { $tmp = explode(',', $tag); // 处理 xxx-xxx/x,x,x-x foreach ($tmp as $t) { if (self::checkExp($t)) {// 递归处理 $dateList = array_merge(self::parseTag($t, $tmin, $tmax), $dateList); } else { $dateList[] = $t; } } } else if (false !== strpos($tag, '/') && false !== strpos($tag, '-')) { list($number, $mod) = explode('/', $tag); list($left, $right) = explode('-', $number); if ($left > $right) { throw new \Exception("$tag not support."); } foreach (range($left, $right) as $n) { if ($n % $mod === 0) { $dateList[] = $n; } } } else if (false !== strpos($tag, '/')) { $tmp = explode('/', $tag); $step = isset($tmp[1]) ? $tmp[1] : 1; $dateList = range($tmin, $tmax, $step); } else if (false !== strpos($tag, '-')) { list($left, $right) = explode('-', $tag); if ($left > $right) { throw new \Exception("$tag not support."); } $dateList = range($left, $right, $step); } else { $dateList = array($tag); } // 越界判断 foreach ($dateList as $num) { if ($num < $tmin || $num > $tmax) { throw new \Exception('Out of bounds.'); } } sort($dateList); return array_unique($dateList); }
[ "private", "static", "function", "parseTag", "(", "$", "tag", ",", "$", "tmin", ",", "$", "tmax", ")", "{", "if", "(", "$", "tag", "==", "'*'", ")", "{", "return", "range", "(", "$", "tmin", ",", "$", "tmax", ")", ";", "}", "$", "step", "=", "1", ";", "$", "dateList", "=", "[", "]", ";", "// x-x/2 情况", "if", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "','", ")", ")", "{", "$", "tmp", "=", "explode", "(", "','", ",", "$", "tag", ")", ";", "// 处理 xxx-xxx/x,x,x-x", "foreach", "(", "$", "tmp", "as", "$", "t", ")", "{", "if", "(", "self", "::", "checkExp", "(", "$", "t", ")", ")", "{", "// 递归处理", "$", "dateList", "=", "array_merge", "(", "self", "::", "parseTag", "(", "$", "t", ",", "$", "tmin", ",", "$", "tmax", ")", ",", "$", "dateList", ")", ";", "}", "else", "{", "$", "dateList", "[", "]", "=", "$", "t", ";", "}", "}", "}", "else", "if", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "'/'", ")", "&&", "false", "!==", "strpos", "(", "$", "tag", ",", "'-'", ")", ")", "{", "list", "(", "$", "number", ",", "$", "mod", ")", "=", "explode", "(", "'/'", ",", "$", "tag", ")", ";", "list", "(", "$", "left", ",", "$", "right", ")", "=", "explode", "(", "'-'", ",", "$", "number", ")", ";", "if", "(", "$", "left", ">", "$", "right", ")", "{", "throw", "new", "\\", "Exception", "(", "\"$tag not support.\"", ")", ";", "}", "foreach", "(", "range", "(", "$", "left", ",", "$", "right", ")", "as", "$", "n", ")", "{", "if", "(", "$", "n", "%", "$", "mod", "===", "0", ")", "{", "$", "dateList", "[", "]", "=", "$", "n", ";", "}", "}", "}", "else", "if", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "'/'", ")", ")", "{", "$", "tmp", "=", "explode", "(", "'/'", ",", "$", "tag", ")", ";", "$", "step", "=", "isset", "(", "$", "tmp", "[", "1", "]", ")", "?", "$", "tmp", "[", "1", "]", ":", "1", ";", "$", "dateList", "=", "range", "(", "$", "tmin", ",", "$", "tmax", ",", "$", "step", ")", ";", "}", "else", "if", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "'-'", ")", ")", "{", "list", "(", "$", "left", ",", "$", "right", ")", "=", "explode", "(", "'-'", ",", "$", "tag", ")", ";", "if", "(", "$", "left", ">", "$", "right", ")", "{", "throw", "new", "\\", "Exception", "(", "\"$tag not support.\"", ")", ";", "}", "$", "dateList", "=", "range", "(", "$", "left", ",", "$", "right", ",", "$", "step", ")", ";", "}", "else", "{", "$", "dateList", "=", "array", "(", "$", "tag", ")", ";", "}", "// 越界判断", "foreach", "(", "$", "dateList", "as", "$", "num", ")", "{", "if", "(", "$", "num", "<", "$", "tmin", "||", "$", "num", ">", "$", "tmax", ")", "{", "throw", "new", "\\", "Exception", "(", "'Out of bounds.'", ")", ";", "}", "}", "sort", "(", "$", "dateList", ")", ";", "return", "array_unique", "(", "$", "dateList", ")", ";", "}" ]
解析元素 @param string $tag 元素标签 @param integer $tmin 最小值 @param integer $tmax 最大值 @return array @throws \Exception
[ "解析元素" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/CronParseHelper.php#L157-L213
yuncms/framework
src/helpers/CronParseHelper.php
CronParseHelper.checkExp
private static function checkExp($tag) { return (false !== strpos($tag, ',')) || (false !== strpos($tag, '-')) || (false !== strpos($tag, '/')); }
php
private static function checkExp($tag) { return (false !== strpos($tag, ',')) || (false !== strpos($tag, '-')) || (false !== strpos($tag, '/')); }
[ "private", "static", "function", "checkExp", "(", "$", "tag", ")", "{", "return", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "','", ")", ")", "||", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "'-'", ")", ")", "||", "(", "false", "!==", "strpos", "(", "$", "tag", ",", "'/'", ")", ")", ";", "}" ]
判断tag是否可再次切割 @return string 需要切割的标识符|null
[ "判断tag是否可再次切割" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/CronParseHelper.php#L219-L222
tomphp/patch-builder
spec/TomPHP/PatchBuilder/LineTracker/LineTrackerSpec.php
LineTrackerSpec.it_tracks_a_line_after_2_deletions
public function it_tracks_a_line_after_2_deletions() { $this->deleteLine(new LineNumber(5)); $this->deleteLine(new LineNumber(5)); $this->trackLine(new LineNumber(7))->getNumber()->shouldReturn(5); }
php
public function it_tracks_a_line_after_2_deletions() { $this->deleteLine(new LineNumber(5)); $this->deleteLine(new LineNumber(5)); $this->trackLine(new LineNumber(7))->getNumber()->shouldReturn(5); }
[ "public", "function", "it_tracks_a_line_after_2_deletions", "(", ")", "{", "$", "this", "->", "deleteLine", "(", "new", "LineNumber", "(", "5", ")", ")", ";", "$", "this", "->", "deleteLine", "(", "new", "LineNumber", "(", "5", ")", ")", ";", "$", "this", "->", "trackLine", "(", "new", "LineNumber", "(", "7", ")", ")", "->", "getNumber", "(", ")", "->", "shouldReturn", "(", "5", ")", ";", "}" ]
/* public function it_throws_exception_if_the_line_requested_has_been_deleted() { $this->deleteLine(new LineNumber(5)); $this->shouldThrow(new DeletedLineException(5)) ->duringTrackLine(5); }
[ "/", "*", "public", "function", "it_throws_exception_if_the_line_requested_has_been_deleted", "()", "{", "$this", "-", ">", "deleteLine", "(", "new", "LineNumber", "(", "5", "))", ";" ]
train
https://github.com/tomphp/patch-builder/blob/4419eaad23016c7db1deffc6cce3f539096c11ce/spec/TomPHP/PatchBuilder/LineTracker/LineTrackerSpec.php#L49-L55
zircote/AMQP
library/AMQP/Connection.php
Connection.setUri
public function setUri($uri) { if (null === $uri) { $uri = 'amqp://guest:guest@localhost:5672/'; } $this->uri = parse_url($uri); if (($this->uri['scheme'] != 'amqp' && $this->uri['scheme'] != 'amqps')) { throw new \UnexpectedValueException( sprintf( 'a valid URI scheme is request expected format [%s] ' . 'received: [%s]', 'tcp://user:pass@host:port/vhost', $uri ) ); } if (empty($this->uri['user']) || empty($this->uri['pass'])) { throw new \RuntimeException( 'AMQPLAIN Auth requires both a user and pass be specified' ); } if ($this->uri['scheme'] === 'amqps') { if (!extension_loaded('openssl')) { throw new \RuntimeException( 'SSL connection attempted however openssl extension is not loaded' ); } $ssl_context = stream_context_create(); foreach ($this->options['ssl_options'] as $k => $v) { stream_context_set_option($ssl_context, 'ssl', $k, $v); } } return $this; }
php
public function setUri($uri) { if (null === $uri) { $uri = 'amqp://guest:guest@localhost:5672/'; } $this->uri = parse_url($uri); if (($this->uri['scheme'] != 'amqp' && $this->uri['scheme'] != 'amqps')) { throw new \UnexpectedValueException( sprintf( 'a valid URI scheme is request expected format [%s] ' . 'received: [%s]', 'tcp://user:pass@host:port/vhost', $uri ) ); } if (empty($this->uri['user']) || empty($this->uri['pass'])) { throw new \RuntimeException( 'AMQPLAIN Auth requires both a user and pass be specified' ); } if ($this->uri['scheme'] === 'amqps') { if (!extension_loaded('openssl')) { throw new \RuntimeException( 'SSL connection attempted however openssl extension is not loaded' ); } $ssl_context = stream_context_create(); foreach ($this->options['ssl_options'] as $k => $v) { stream_context_set_option($ssl_context, 'ssl', $k, $v); } } return $this; }
[ "public", "function", "setUri", "(", "$", "uri", ")", "{", "if", "(", "null", "===", "$", "uri", ")", "{", "$", "uri", "=", "'amqp://guest:guest@localhost:5672/'", ";", "}", "$", "this", "->", "uri", "=", "parse_url", "(", "$", "uri", ")", ";", "if", "(", "(", "$", "this", "->", "uri", "[", "'scheme'", "]", "!=", "'amqp'", "&&", "$", "this", "->", "uri", "[", "'scheme'", "]", "!=", "'amqps'", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'a valid URI scheme is request expected format [%s] '", ".", "'received: [%s]'", ",", "'tcp://user:pass@host:port/vhost'", ",", "$", "uri", ")", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "uri", "[", "'user'", "]", ")", "||", "empty", "(", "$", "this", "->", "uri", "[", "'pass'", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'AMQPLAIN Auth requires both a user and pass be specified'", ")", ";", "}", "if", "(", "$", "this", "->", "uri", "[", "'scheme'", "]", "===", "'amqps'", ")", "{", "if", "(", "!", "extension_loaded", "(", "'openssl'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'SSL connection attempted however openssl extension is not loaded'", ")", ";", "}", "$", "ssl_context", "=", "stream_context_create", "(", ")", ";", "foreach", "(", "$", "this", "->", "options", "[", "'ssl_options'", "]", "as", "$", "k", "=>", "$", "v", ")", "{", "stream_context_set_option", "(", "$", "ssl_context", ",", "'ssl'", ",", "$", "k", ",", "$", "v", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
@param $uri @return Connection @throws \RuntimeException @throws \UnexpectedValueException
[ "@param", "$uri" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L162-L194
zircote/AMQP
library/AMQP/Connection.php
Connection.setOption
public function setOption($option, $value) { if (array_key_exists($option, $this->options)) { $this->options[$option] = $value; } return $this; }
php
public function setOption($option, $value) { if (array_key_exists($option, $this->options)) { $this->options[$option] = $value; } return $this; }
[ "public", "function", "setOption", "(", "$", "option", ",", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "option", ",", "$", "this", "->", "options", ")", ")", "{", "$", "this", "->", "options", "[", "$", "option", "]", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
@param $option @param $value @return Connection
[ "@param", "$option", "@param", "$value" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L224-L230
zircote/AMQP
library/AMQP/Connection.php
Connection.write
protected function write($data) { if ($this->debug) { Helper::debugMsg( '< [hex]:' . PHP_EOL . Helper::hexdump( $data, false, true, true ) ); } $len = strlen($data); while (true) { if (false === ($written = fwrite($this->sock, $data))) { throw new \Exception ('Error sending data'); } if ($written === 0) { throw new \Exception ('Broken pipe or closed connection'); } $info = stream_get_meta_data($this->sock); if ($info['timed_out']) { throw new \Exception("Error sending data. Socket connection timed out"); } $len = $len - $written; if ($len > 0) { $data = substr($data, 0 - $len); } else { break; } } }
php
protected function write($data) { if ($this->debug) { Helper::debugMsg( '< [hex]:' . PHP_EOL . Helper::hexdump( $data, false, true, true ) ); } $len = strlen($data); while (true) { if (false === ($written = fwrite($this->sock, $data))) { throw new \Exception ('Error sending data'); } if ($written === 0) { throw new \Exception ('Broken pipe or closed connection'); } $info = stream_get_meta_data($this->sock); if ($info['timed_out']) { throw new \Exception("Error sending data. Socket connection timed out"); } $len = $len - $written; if ($len > 0) { $data = substr($data, 0 - $len); } else { break; } } }
[ "protected", "function", "write", "(", "$", "data", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "'< [hex]:'", ".", "PHP_EOL", ".", "Helper", "::", "hexdump", "(", "$", "data", ",", "false", ",", "true", ",", "true", ")", ")", ";", "}", "$", "len", "=", "strlen", "(", "$", "data", ")", ";", "while", "(", "true", ")", "{", "if", "(", "false", "===", "(", "$", "written", "=", "fwrite", "(", "$", "this", "->", "sock", ",", "$", "data", ")", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Error sending data'", ")", ";", "}", "if", "(", "$", "written", "===", "0", ")", "{", "throw", "new", "\\", "Exception", "(", "'Broken pipe or closed connection'", ")", ";", "}", "$", "info", "=", "stream_get_meta_data", "(", "$", "this", "->", "sock", ")", ";", "if", "(", "$", "info", "[", "'timed_out'", "]", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error sending data. Socket connection timed out\"", ")", ";", "}", "$", "len", "=", "$", "len", "-", "$", "written", ";", "if", "(", "$", "len", ">", "0", ")", "{", "$", "data", "=", "substr", "(", "$", "data", ",", "0", "-", "$", "len", ")", ";", "}", "else", "{", "break", ";", "}", "}", "}" ]
@param string $data @throws \Exception
[ "@param", "string", "$data" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L360-L389
zircote/AMQP
library/AMQP/Connection.php
Connection.sendContent
public function sendContent( $channel, $classId, $weight, $bodySize, $packedProperties, $body ) { $outboundPacket = new Writer(); $outboundPacket->writeOctet(2); $outboundPacket->writeShort($channel); $outboundPacket->writeLong(strlen($packedProperties) + 12); $outboundPacket->writeShort($classId); $outboundPacket->writeShort($weight); $outboundPacket->writeLongLong($bodySize); $outboundPacket->write($packedProperties); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); while ($body) { $payload = substr($body, 0, $this->frameMax - 8); $body = substr($body, $this->frameMax - 8); $outboundPacket = new Writer(); $outboundPacket->writeOctet(3); $outboundPacket->writeShort($channel); $outboundPacket->writeLong(strlen($payload)); $outboundPacket->write($payload); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); } return $this; }
php
public function sendContent( $channel, $classId, $weight, $bodySize, $packedProperties, $body ) { $outboundPacket = new Writer(); $outboundPacket->writeOctet(2); $outboundPacket->writeShort($channel); $outboundPacket->writeLong(strlen($packedProperties) + 12); $outboundPacket->writeShort($classId); $outboundPacket->writeShort($weight); $outboundPacket->writeLongLong($bodySize); $outboundPacket->write($packedProperties); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); while ($body) { $payload = substr($body, 0, $this->frameMax - 8); $body = substr($body, $this->frameMax - 8); $outboundPacket = new Writer(); $outboundPacket->writeOctet(3); $outboundPacket->writeShort($channel); $outboundPacket->writeLong(strlen($payload)); $outboundPacket->write($payload); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); } return $this; }
[ "public", "function", "sendContent", "(", "$", "channel", ",", "$", "classId", ",", "$", "weight", ",", "$", "bodySize", ",", "$", "packedProperties", ",", "$", "body", ")", "{", "$", "outboundPacket", "=", "new", "Writer", "(", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "2", ")", ";", "$", "outboundPacket", "->", "writeShort", "(", "$", "channel", ")", ";", "$", "outboundPacket", "->", "writeLong", "(", "strlen", "(", "$", "packedProperties", ")", "+", "12", ")", ";", "$", "outboundPacket", "->", "writeShort", "(", "$", "classId", ")", ";", "$", "outboundPacket", "->", "writeShort", "(", "$", "weight", ")", ";", "$", "outboundPacket", "->", "writeLongLong", "(", "$", "bodySize", ")", ";", "$", "outboundPacket", "->", "write", "(", "$", "packedProperties", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "0xCE", ")", ";", "$", "outboundPacket", "=", "$", "outboundPacket", "->", "getvalue", "(", ")", ";", "$", "this", "->", "write", "(", "$", "outboundPacket", ")", ";", "while", "(", "$", "body", ")", "{", "$", "payload", "=", "substr", "(", "$", "body", ",", "0", ",", "$", "this", "->", "frameMax", "-", "8", ")", ";", "$", "body", "=", "substr", "(", "$", "body", ",", "$", "this", "->", "frameMax", "-", "8", ")", ";", "$", "outboundPacket", "=", "new", "Writer", "(", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "3", ")", ";", "$", "outboundPacket", "->", "writeShort", "(", "$", "channel", ")", ";", "$", "outboundPacket", "->", "writeLong", "(", "strlen", "(", "$", "payload", ")", ")", ";", "$", "outboundPacket", "->", "write", "(", "$", "payload", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "0xCE", ")", ";", "$", "outboundPacket", "=", "$", "outboundPacket", "->", "getvalue", "(", ")", ";", "$", "this", "->", "write", "(", "$", "outboundPacket", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $channel @param string $classId @param string $weight @param string $bodySize @param string $packedProperties @param string $body @return Connection
[ "@param", "string", "$channel", "@param", "string", "$classId", "@param", "string", "$weight", "@param", "string", "$bodySize", "@param", "string", "$packedProperties", "@param", "string", "$body" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L428-L464
zircote/AMQP
library/AMQP/Connection.php
Connection.sendChannelMethodFrame
public function sendChannelMethodFrame($channel, $methodSig, $args = '') { if ($args instanceof Writer) { $args = $args->getvalue(); } $outboundPacket = new Writer(); $outboundPacket->writeOctet(1); $outboundPacket->writeShort($channel); $outboundPacket->writeLong( strlen($args) + 4 ); // 4 = length of class_id and method_id // in payload $outboundPacket->writeShort($methodSig[0]); // class_id $outboundPacket->writeShort($methodSig[1]); // method_id $outboundPacket->write($args); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); if ($this->debug) { Helper::debugMsg( '< ' . Helper::methodSig($methodSig) . ': ' . AbstractChannel::$globalMethodNames[Helper::methodSig( $methodSig )] ); } return $this; }
php
public function sendChannelMethodFrame($channel, $methodSig, $args = '') { if ($args instanceof Writer) { $args = $args->getvalue(); } $outboundPacket = new Writer(); $outboundPacket->writeOctet(1); $outboundPacket->writeShort($channel); $outboundPacket->writeLong( strlen($args) + 4 ); // 4 = length of class_id and method_id // in payload $outboundPacket->writeShort($methodSig[0]); // class_id $outboundPacket->writeShort($methodSig[1]); // method_id $outboundPacket->write($args); $outboundPacket->writeOctet(0xCE); $outboundPacket = $outboundPacket->getvalue(); $this->write($outboundPacket); if ($this->debug) { Helper::debugMsg( '< ' . Helper::methodSig($methodSig) . ': ' . AbstractChannel::$globalMethodNames[Helper::methodSig( $methodSig )] ); } return $this; }
[ "public", "function", "sendChannelMethodFrame", "(", "$", "channel", ",", "$", "methodSig", ",", "$", "args", "=", "''", ")", "{", "if", "(", "$", "args", "instanceof", "Writer", ")", "{", "$", "args", "=", "$", "args", "->", "getvalue", "(", ")", ";", "}", "$", "outboundPacket", "=", "new", "Writer", "(", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "1", ")", ";", "$", "outboundPacket", "->", "writeShort", "(", "$", "channel", ")", ";", "$", "outboundPacket", "->", "writeLong", "(", "strlen", "(", "$", "args", ")", "+", "4", ")", ";", "// 4 = length of class_id and method_id", "// in payload", "$", "outboundPacket", "->", "writeShort", "(", "$", "methodSig", "[", "0", "]", ")", ";", "// class_id", "$", "outboundPacket", "->", "writeShort", "(", "$", "methodSig", "[", "1", "]", ")", ";", "// method_id", "$", "outboundPacket", "->", "write", "(", "$", "args", ")", ";", "$", "outboundPacket", "->", "writeOctet", "(", "0xCE", ")", ";", "$", "outboundPacket", "=", "$", "outboundPacket", "->", "getvalue", "(", ")", ";", "$", "this", "->", "write", "(", "$", "outboundPacket", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "'< '", ".", "Helper", "::", "methodSig", "(", "$", "methodSig", ")", ".", "': '", ".", "AbstractChannel", "::", "$", "globalMethodNames", "[", "Helper", "::", "methodSig", "(", "$", "methodSig", ")", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $channel @param string $methodSig @param Writer|string $args @return Connection
[ "@param", "string", "$channel", "@param", "string", "$methodSig", "@param", "Writer|string", "$args" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L473-L505
zircote/AMQP
library/AMQP/Connection.php
Connection.waitFrame
protected function waitFrame() { $frameType = $this->input->readOctet(); $channel = $this->input->readShort(); $size = $this->input->readLong(); $payload = $this->input->read($size); $ch = $this->input->readOctet(); if ($ch != 0xCE) { throw new \Exception( sprintf( 'Framing error, unexpected byte: %x', $ch ) ); } return array($frameType, $channel, $payload); }
php
protected function waitFrame() { $frameType = $this->input->readOctet(); $channel = $this->input->readShort(); $size = $this->input->readLong(); $payload = $this->input->read($size); $ch = $this->input->readOctet(); if ($ch != 0xCE) { throw new \Exception( sprintf( 'Framing error, unexpected byte: %x', $ch ) ); } return array($frameType, $channel, $payload); }
[ "protected", "function", "waitFrame", "(", ")", "{", "$", "frameType", "=", "$", "this", "->", "input", "->", "readOctet", "(", ")", ";", "$", "channel", "=", "$", "this", "->", "input", "->", "readShort", "(", ")", ";", "$", "size", "=", "$", "this", "->", "input", "->", "readLong", "(", ")", ";", "$", "payload", "=", "$", "this", "->", "input", "->", "read", "(", "$", "size", ")", ";", "$", "ch", "=", "$", "this", "->", "input", "->", "readOctet", "(", ")", ";", "if", "(", "$", "ch", "!=", "0xCE", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Framing error, unexpected byte: %x'", ",", "$", "ch", ")", ")", ";", "}", "return", "array", "(", "$", "frameType", ",", "$", "channel", ",", "$", "payload", ")", ";", "}" ]
Wait for a frame from the server @return array @throws \Exception
[ "Wait", "for", "a", "frame", "from", "the", "server" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L513-L530
zircote/AMQP
library/AMQP/Connection.php
Connection.waitChannel
public function waitChannel($channelId) { while (true) { list($frameType, $frameChannel, $payload) = $this->waitFrame(); if ($frameChannel == $channelId) { return array($frameType, $payload); } /** * Not the channel we were looking for. Queue this frame * for later, when the other channel is looking for frames. */ array_push( $this->channels[$frameChannel]->frame_queue, array($frameType, $payload) ); /** * If we just queued up a method for channel 0 (the Connection * itself) it's probably a close method in reaction to some * error, so deal with it right away. */ if (($frameType == 1) && ($frameChannel == 0)) { $this->wait(); } } return array(); }
php
public function waitChannel($channelId) { while (true) { list($frameType, $frameChannel, $payload) = $this->waitFrame(); if ($frameChannel == $channelId) { return array($frameType, $payload); } /** * Not the channel we were looking for. Queue this frame * for later, when the other channel is looking for frames. */ array_push( $this->channels[$frameChannel]->frame_queue, array($frameType, $payload) ); /** * If we just queued up a method for channel 0 (the Connection * itself) it's probably a close method in reaction to some * error, so deal with it right away. */ if (($frameType == 1) && ($frameChannel == 0)) { $this->wait(); } } return array(); }
[ "public", "function", "waitChannel", "(", "$", "channelId", ")", "{", "while", "(", "true", ")", "{", "list", "(", "$", "frameType", ",", "$", "frameChannel", ",", "$", "payload", ")", "=", "$", "this", "->", "waitFrame", "(", ")", ";", "if", "(", "$", "frameChannel", "==", "$", "channelId", ")", "{", "return", "array", "(", "$", "frameType", ",", "$", "payload", ")", ";", "}", "/**\n * Not the channel we were looking for. Queue this frame\n * for later, when the other channel is looking for frames.\n */", "array_push", "(", "$", "this", "->", "channels", "[", "$", "frameChannel", "]", "->", "frame_queue", ",", "array", "(", "$", "frameType", ",", "$", "payload", ")", ")", ";", "/**\n * If we just queued up a method for channel 0 (the Connection\n * itself) it's probably a close method in reaction to some\n * error, so deal with it right away.\n */", "if", "(", "(", "$", "frameType", "==", "1", ")", "&&", "(", "$", "frameChannel", "==", "0", ")", ")", "{", "$", "this", "->", "wait", "(", ")", ";", "}", "}", "return", "array", "(", ")", ";", "}" ]
Wait for a frame from the server destined for a particular channel. @param $channelId @return array
[ "Wait", "for", "a", "frame", "from", "the", "server", "destined", "for", "a", "particular", "channel", "." ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L539-L565
zircote/AMQP
library/AMQP/Connection.php
Connection.channel
public function channel($channelId = null) { if (isset($this->channels[$channelId])) { return $this->channels[$channelId]; } else { $channelId = $channelId ? : $this->getFreeChannelId(); $ch = new Channel($this->connection, $channelId); return $this->channels[$channelId] = $ch; } }
php
public function channel($channelId = null) { if (isset($this->channels[$channelId])) { return $this->channels[$channelId]; } else { $channelId = $channelId ? : $this->getFreeChannelId(); $ch = new Channel($this->connection, $channelId); return $this->channels[$channelId] = $ch; } }
[ "public", "function", "channel", "(", "$", "channelId", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "channels", "[", "$", "channelId", "]", ")", ")", "{", "return", "$", "this", "->", "channels", "[", "$", "channelId", "]", ";", "}", "else", "{", "$", "channelId", "=", "$", "channelId", "?", ":", "$", "this", "->", "getFreeChannelId", "(", ")", ";", "$", "ch", "=", "new", "Channel", "(", "$", "this", "->", "connection", ",", "$", "channelId", ")", ";", "return", "$", "this", "->", "channels", "[", "$", "channelId", "]", "=", "$", "ch", ";", "}", "}" ]
Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. @param string|null $channelId @return \AMQP\Channel
[ "Fetch", "a", "Channel", "object", "identified", "by", "the", "numeric", "channel_id", "or", "create", "that", "object", "if", "it", "doesn", "t", "already", "exist", "." ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L575-L584
zircote/AMQP
library/AMQP/Connection.php
Connection.close
public function close($replyCode = 0, $replyText = '', $methodSig = array(0, 0)) { $args = new Writer(); $args->writeShort($replyCode); $args->writeShortStr($replyText); $args->writeShort($methodSig[0]); // class_id $args->writeShort($methodSig[1]); // method_id $this->sendMethodFrame(array(10, 60), $args); return $this->wait( array( "10,61", // Connection.close_ok ) ); }
php
public function close($replyCode = 0, $replyText = '', $methodSig = array(0, 0)) { $args = new Writer(); $args->writeShort($replyCode); $args->writeShortStr($replyText); $args->writeShort($methodSig[0]); // class_id $args->writeShort($methodSig[1]); // method_id $this->sendMethodFrame(array(10, 60), $args); return $this->wait( array( "10,61", // Connection.close_ok ) ); }
[ "public", "function", "close", "(", "$", "replyCode", "=", "0", ",", "$", "replyText", "=", "''", ",", "$", "methodSig", "=", "array", "(", "0", ",", "0", ")", ")", "{", "$", "args", "=", "new", "Writer", "(", ")", ";", "$", "args", "->", "writeShort", "(", "$", "replyCode", ")", ";", "$", "args", "->", "writeShortStr", "(", "$", "replyText", ")", ";", "$", "args", "->", "writeShort", "(", "$", "methodSig", "[", "0", "]", ")", ";", "// class_id", "$", "args", "->", "writeShort", "(", "$", "methodSig", "[", "1", "]", ")", ";", "// method_id", "$", "this", "->", "sendMethodFrame", "(", "array", "(", "10", ",", "60", ")", ",", "$", "args", ")", ";", "return", "$", "this", "->", "wait", "(", "array", "(", "\"10,61\"", ",", "// Connection.close_ok", ")", ")", ";", "}" ]
request a connection close @param int $replyCode @param string $replyText @param array $methodSig @return mixed|null
[ "request", "a", "connection", "close" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/Connection.php#L595-L608