repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
minkphp/SahiClient
src/Client.php
Client.findTable
public function findTable($id = null, array $relations = array()) { return new Accessor\Table\TableAccessor($id, $relations, $this->con); }
php
public function findTable($id = null, array $relations = array()) { return new Accessor\Table\TableAccessor($id, $relations, $this->con); }
[ "public", "function", "findTable", "(", "$", "id", "=", "null", ",", "array", "$", "relations", "=", "array", "(", ")", ")", "{", "return", "new", "Accessor", "\\", "Table", "\\", "TableAccessor", "(", "$", "id", ",", "$", "relations", ",", "$", "thi...
Find table element. @param string $id element identifier @param array $relations tag relations (near, in, under) @return Accessor\Table\TableAccessor
[ "Find", "table", "element", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Client.php#L555-L558
train
orchestral/installer
src/Http/Controllers/InstallerController.php
InstallerController.store
public function store(Request $request, Installer $processor) { return $processor->store($this, $request->all()); }
php
public function store(Request $request, Installer $processor) { return $processor->store($this, $request->all()); }
[ "public", "function", "store", "(", "Request", "$", "request", ",", "Installer", "$", "processor", ")", "{", "return", "$", "processor", "->", "store", "(", "$", "this", ",", "$", "request", "->", "all", "(", ")", ")", ";", "}" ]
Create an adminstrator. POST (:orchestra)/install/create @param \Illuminate\Http\Request $request @param \Orchestra\Installation\Processor\Installer $processor @return mixed
[ "Create", "an", "adminstrator", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Http/Controllers/InstallerController.php#L48-L51
train
m1so/LeagueWrap
src/LeagueWrap/Cache/KeyGenerator.php
KeyGenerator.fromEndpoint
public static function fromEndpoint(Endpoint $endpoint) { return static::generateKey(strtolower($endpoint->getRegion()->getDomain()).$endpoint->getUrl()); }
php
public static function fromEndpoint(Endpoint $endpoint) { return static::generateKey(strtolower($endpoint->getRegion()->getDomain()).$endpoint->getUrl()); }
[ "public", "static", "function", "fromEndpoint", "(", "Endpoint", "$", "endpoint", ")", "{", "return", "static", "::", "generateKey", "(", "strtolower", "(", "$", "endpoint", "->", "getRegion", "(", ")", "->", "getDomain", "(", ")", ")", ".", "$", "endpoint...
Generate cache key from an Endpoint. @param Endpoint $endpoint @return string
[ "Generate", "cache", "key", "from", "an", "Endpoint", "." ]
c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2
https://github.com/m1so/LeagueWrap/blob/c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2/src/LeagueWrap/Cache/KeyGenerator.php#L44-L47
train
melisplatform/melis-front
src/Controller/MelisFrontSearchController.php
MelisFrontSearchController.addLuceneIndexAction
public function addLuceneIndexAction() { $moduleName = $this->params()->fromRoute('moduleName', null); $pageId = $this->params()->fromRoute('pageid', null); $excludes = $this->params()->fromRoute('expageid', null); $status = ''; /** @var \MelisEngine\Service\MelisSearchService $searchIndex */ $searchIndex = $this->getServiceLocator()->get('MelisSearch'); if ($moduleName && $pageId) { $tmpexPageIds = explode(';', $excludes); $exPageIds = []; foreach ($tmpexPageIds as $id) { if ($id) { $exPageIds[] = $id; } } /** Checks if the site's folder is that of MelisSite or Vendor */ $moduleDirectory = null; if (is_dir($_SERVER['DOCUMENT_ROOT'] . self::MELIS_SITES . $moduleName)) { /** Module is located inside MelisSites folder */ $moduleDirectory = $_SERVER['DOCUMENT_ROOT'] . self::MELIS_SITES; } elseif (is_dir($_SERVER['DOCUMENT_ROOT'] . self::VENDOR . $moduleName)) { /** Module is located inside Vendor folder */ $moduleDirectory = $_SERVER['DOCUMENT_ROOT'] . self::VENDOR; } $status = $searchIndex->createIndex($moduleName, $pageId, $exPageIds, $moduleDirectory); } $view = new ViewModel(); $view->setTerminal(true); $view->status = $status; return $view; }
php
public function addLuceneIndexAction() { $moduleName = $this->params()->fromRoute('moduleName', null); $pageId = $this->params()->fromRoute('pageid', null); $excludes = $this->params()->fromRoute('expageid', null); $status = ''; /** @var \MelisEngine\Service\MelisSearchService $searchIndex */ $searchIndex = $this->getServiceLocator()->get('MelisSearch'); if ($moduleName && $pageId) { $tmpexPageIds = explode(';', $excludes); $exPageIds = []; foreach ($tmpexPageIds as $id) { if ($id) { $exPageIds[] = $id; } } /** Checks if the site's folder is that of MelisSite or Vendor */ $moduleDirectory = null; if (is_dir($_SERVER['DOCUMENT_ROOT'] . self::MELIS_SITES . $moduleName)) { /** Module is located inside MelisSites folder */ $moduleDirectory = $_SERVER['DOCUMENT_ROOT'] . self::MELIS_SITES; } elseif (is_dir($_SERVER['DOCUMENT_ROOT'] . self::VENDOR . $moduleName)) { /** Module is located inside Vendor folder */ $moduleDirectory = $_SERVER['DOCUMENT_ROOT'] . self::VENDOR; } $status = $searchIndex->createIndex($moduleName, $pageId, $exPageIds, $moduleDirectory); } $view = new ViewModel(); $view->setTerminal(true); $view->status = $status; return $view; }
[ "public", "function", "addLuceneIndexAction", "(", ")", "{", "$", "moduleName", "=", "$", "this", "->", "params", "(", ")", "->", "fromRoute", "(", "'moduleName'", ",", "null", ")", ";", "$", "pageId", "=", "$", "this", "->", "params", "(", ")", "->", ...
This creates lists of index with the content of every page ID that has been crawled by this function. @param string moduleName - name of the site module where you can store all the indexes @param int pageid - root page ID of the site, child pages of this ID will also be crawled. @param int expageid - an array of page ID that you would like to exclude during the process of indexing Usage: Normal usage - domain.com/melissearchindex/module/Lbpam/pageid/3/exclude-pageid/0 | this will add the page and the child pages of the provided page ID With page exclusions: domain.com/melissearchindex/module/Lbpam/pageid/3/exclude-pageid/12;5;20;107 | this will add the page and the child pages of the provided ID page but it will exclude page ID 12, 5, 20, and 107. @return ViewModel
[ "This", "creates", "lists", "of", "index", "with", "the", "content", "of", "every", "page", "ID", "that", "has", "been", "crawled", "by", "this", "function", "." ]
5e03e32687970bb2201e4205612d5539500dc514
https://github.com/melisplatform/melis-front/blob/5e03e32687970bb2201e4205612d5539500dc514/src/Controller/MelisFrontSearchController.php#L32-L69
train
globalis-ms/puppet-skilled-framework
src/Library/QueryFilter.php
QueryFilter.getValue
public function getValue($name) { return (isset($this->options['params'][$name])) ? $this->options['params'][$name] : null; }
php
public function getValue($name) { return (isset($this->options['params'][$name])) ? $this->options['params'][$name] : null; }
[ "public", "function", "getValue", "(", "$", "name", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "options", "[", "'params'", "]", "[", "$", "name", "]", ")", ")", "?", "$", "this", "->", "options", "[", "'params'", "]", "[", "$", "na...
Get filter field value @param string $name @return mixed
[ "Get", "filter", "field", "value" ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Library/QueryFilter.php#L185-L188
train
globalis-ms/puppet-skilled-framework
src/Library/QueryFilter.php
QueryFilter.run
public function run($query) { $options = $this->options; if ($this->hasActiveFilters()) { foreach ($options['params'] as $param => $value) { $query->where( function ($query) use ($options, $param, $value) { $options['filters'][$param]($query, $value); } ); } } //Setting data for filter form $this->options['params'] = $options['params']; if ($options['save']) { $_SESSION[$options['save']] = $options['params']; } return $query; }
php
public function run($query) { $options = $this->options; if ($this->hasActiveFilters()) { foreach ($options['params'] as $param => $value) { $query->where( function ($query) use ($options, $param, $value) { $options['filters'][$param]($query, $value); } ); } } //Setting data for filter form $this->options['params'] = $options['params']; if ($options['save']) { $_SESSION[$options['save']] = $options['params']; } return $query; }
[ "public", "function", "run", "(", "$", "query", ")", "{", "$", "options", "=", "$", "this", "->", "options", ";", "if", "(", "$", "this", "->", "hasActiveFilters", "(", ")", ")", "{", "foreach", "(", "$", "options", "[", "'params'", "]", "as", "$",...
Apply filter on query @param \Globalis\PuppetSkilled\Database\Query\Builder|\Globalis\PuppetSkilled\Database\Magic\Builder $query @return \Globalis\PuppetSkilled\Database\Query\Builder
[ "Apply", "filter", "on", "query" ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Library/QueryFilter.php#L196-L215
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.start
public function start() : int { $pathToServerScript = $this->config['server_path']; if (!file_exists($pathToServerScript)) { throw new ControlException('Server script not found. Check server_path in your config file.'); } // check if process is already running: $serverPid = $this->getServerPid(); if ($serverPid !== 0) { return $serverPid; } // startup server: $phpPath = $this->config['php_path']; $startupCommand = escapeshellcmd($phpPath . ' ' . $pathToServerScript) . ' > /dev/null 2>&1 &'; exec($startupCommand); // return process id: $pid = $this->getServerPid(); if (empty($pid)) { throw new ControlException('Could not start server. (Empty Pid)'); } return $pid; }
php
public function start() : int { $pathToServerScript = $this->config['server_path']; if (!file_exists($pathToServerScript)) { throw new ControlException('Server script not found. Check server_path in your config file.'); } // check if process is already running: $serverPid = $this->getServerPid(); if ($serverPid !== 0) { return $serverPid; } // startup server: $phpPath = $this->config['php_path']; $startupCommand = escapeshellcmd($phpPath . ' ' . $pathToServerScript) . ' > /dev/null 2>&1 &'; exec($startupCommand); // return process id: $pid = $this->getServerPid(); if (empty($pid)) { throw new ControlException('Could not start server. (Empty Pid)'); } return $pid; }
[ "public", "function", "start", "(", ")", ":", "int", "{", "$", "pathToServerScript", "=", "$", "this", "->", "config", "[", "'server_path'", "]", ";", "if", "(", "!", "file_exists", "(", "$", "pathToServerScript", ")", ")", "{", "throw", "new", "ControlE...
Starts Server instance as a background process. @throws ControlException @return int Process id (0 if script could not be started).
[ "Starts", "Server", "instance", "as", "a", "background", "process", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L24-L48
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.stop
public function stop() : bool { $serverPid = $this->getServerPid(); if ($serverPid === 0) { return true; } $response = $this->sendCommand('stop'); if ($response !== 'ok') { throw new ControlException('Shutdown failed.'); } return true; }
php
public function stop() : bool { $serverPid = $this->getServerPid(); if ($serverPid === 0) { return true; } $response = $this->sendCommand('stop'); if ($response !== 'ok') { throw new ControlException('Shutdown failed.'); } return true; }
[ "public", "function", "stop", "(", ")", ":", "bool", "{", "$", "serverPid", "=", "$", "this", "->", "getServerPid", "(", ")", ";", "if", "(", "$", "serverPid", "===", "0", ")", "{", "return", "true", ";", "}", "$", "response", "=", "$", "this", "...
Sends "shutdown" command to Angela instance. @throws ControlException @return bool
[ "Sends", "shutdown", "command", "to", "Angela", "instance", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L56-L67
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.restart
public function restart() : int { $pid = $this->getServerPid(); if (empty($pid)) { return $this->start(); } $stopped = $this->stop(); if ($stopped !== true) { throw new ControlException('Error while stopping current Angela process.'); } return $this->start(); }
php
public function restart() : int { $pid = $this->getServerPid(); if (empty($pid)) { return $this->start(); } $stopped = $this->stop(); if ($stopped !== true) { throw new ControlException('Error while stopping current Angela process.'); } return $this->start(); }
[ "public", "function", "restart", "(", ")", ":", "int", "{", "$", "pid", "=", "$", "this", "->", "getServerPid", "(", ")", ";", "if", "(", "empty", "(", "$", "pid", ")", ")", "{", "return", "$", "this", "->", "start", "(", ")", ";", "}", "$", ...
Restarts Angela processes. @throws ControlException @return int Pid of new server process.
[ "Restarts", "Angela", "processes", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L75-L86
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.status
public function status() : array { $serverPid = $this->getServerPid(); if (empty($serverPid)) { throw new ControlException('Angela not currently running.'); } $response = $this->sendCommand('status'); if (empty($response)) { throw new ControlException('Error fetching status. (Incorrect response)'); } return json_decode($response, true); }
php
public function status() : array { $serverPid = $this->getServerPid(); if (empty($serverPid)) { throw new ControlException('Angela not currently running.'); } $response = $this->sendCommand('status'); if (empty($response)) { throw new ControlException('Error fetching status. (Incorrect response)'); } return json_decode($response, true); }
[ "public", "function", "status", "(", ")", ":", "array", "{", "$", "serverPid", "=", "$", "this", "->", "getServerPid", "(", ")", ";", "if", "(", "empty", "(", "$", "serverPid", ")", ")", "{", "throw", "new", "ControlException", "(", "'Angela not currentl...
Checks worker status of Angela instance. @throws ControlException @return array
[ "Checks", "worker", "status", "of", "Angela", "instance", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L94-L105
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.flushQueue
public function flushQueue() : bool { $serverPid = $this->getServerPid(); if (empty($serverPid)) { throw new ControlException('Angela not currently running.'); } $response = $this->sendCommand('flush_queue'); if ($response !== 'ok') { throw new ControlException('Error flushing queue. (Incorrect response)'); } return true; }
php
public function flushQueue() : bool { $serverPid = $this->getServerPid(); if (empty($serverPid)) { throw new ControlException('Angela not currently running.'); } $response = $this->sendCommand('flush_queue'); if ($response !== 'ok') { throw new ControlException('Error flushing queue. (Incorrect response)'); } return true; }
[ "public", "function", "flushQueue", "(", ")", ":", "bool", "{", "$", "serverPid", "=", "$", "this", "->", "getServerPid", "(", ")", ";", "if", "(", "empty", "(", "$", "serverPid", ")", ")", "{", "throw", "new", "ControlException", "(", "'Angela not curre...
Flushes all job queue in server instance. @throws ControlException @return bool
[ "Flushes", "all", "job", "queue", "in", "server", "instance", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L113-L124
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.kill
public function kill() : bool { // kill server process: $serverPid = $this->getServerPid(); if (!empty($serverPid)) { $this->killProcessById($serverPid); } // kill worker processes: $workerPids = []; foreach ($this->config['pool'] as $poolName => $poolConfig) { $pids = $this->getPidsByPath($poolConfig['worker_file']); if (empty($pids)) { continue; } $workerPids = array_merge($workerPids, $pids); } if (empty($workerPids)) { return true; } foreach ($workerPids as $pid) { $this->killProcessById($pid); } return true; }
php
public function kill() : bool { // kill server process: $serverPid = $this->getServerPid(); if (!empty($serverPid)) { $this->killProcessById($serverPid); } // kill worker processes: $workerPids = []; foreach ($this->config['pool'] as $poolName => $poolConfig) { $pids = $this->getPidsByPath($poolConfig['worker_file']); if (empty($pids)) { continue; } $workerPids = array_merge($workerPids, $pids); } if (empty($workerPids)) { return true; } foreach ($workerPids as $pid) { $this->killProcessById($pid); } return true; }
[ "public", "function", "kill", "(", ")", ":", "bool", "{", "// kill server process:", "$", "serverPid", "=", "$", "this", "->", "getServerPid", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "serverPid", ")", ")", "{", "$", "this", "->", "killProcess...
Tries to kill all Angela related processes. @return bool
[ "Tries", "to", "kill", "all", "Angela", "related", "processes", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L131-L155
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.getPidByPath
protected function getPidByPath(string $path) : int { $procInfo = []; $cliOutput = []; exec('ps x | grep ' . $path, $cliOutput); foreach ($cliOutput as $line) { $line = trim($line); if (empty($line)) { continue; } if (strpos($line, 'grep') !== false) { continue; } $procInfo = preg_split('#\s+#', $line); break; } if (empty($procInfo)) { return 0; } return (int)$procInfo[0]; }
php
protected function getPidByPath(string $path) : int { $procInfo = []; $cliOutput = []; exec('ps x | grep ' . $path, $cliOutput); foreach ($cliOutput as $line) { $line = trim($line); if (empty($line)) { continue; } if (strpos($line, 'grep') !== false) { continue; } $procInfo = preg_split('#\s+#', $line); break; } if (empty($procInfo)) { return 0; } return (int)$procInfo[0]; }
[ "protected", "function", "getPidByPath", "(", "string", "$", "path", ")", ":", "int", "{", "$", "procInfo", "=", "[", "]", ";", "$", "cliOutput", "=", "[", "]", ";", "exec", "(", "'ps x | grep '", ".", "$", "path", ",", "$", "cliOutput", ")", ";", ...
Tries to estimate PID by given path. @param string $path @return int
[ "Tries", "to", "estimate", "PID", "by", "given", "path", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L173-L193
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.getPidsByPath
protected function getPidsByPath(string $path) : array { $pids = []; $cliOutput = []; exec('ps x | grep ' . $path, $cliOutput); foreach ($cliOutput as $line) { $line = trim($line); if (empty($line)) { continue; } if (strpos($line, 'grep') !== false) { continue; } $procInfo = preg_split('#\s+#', $line); array_push($pids, (int)$procInfo[0]); } return $pids; }
php
protected function getPidsByPath(string $path) : array { $pids = []; $cliOutput = []; exec('ps x | grep ' . $path, $cliOutput); foreach ($cliOutput as $line) { $line = trim($line); if (empty($line)) { continue; } if (strpos($line, 'grep') !== false) { continue; } $procInfo = preg_split('#\s+#', $line); array_push($pids, (int)$procInfo[0]); } return $pids; }
[ "protected", "function", "getPidsByPath", "(", "string", "$", "path", ")", ":", "array", "{", "$", "pids", "=", "[", "]", ";", "$", "cliOutput", "=", "[", "]", ";", "exec", "(", "'ps x | grep '", ".", "$", "path", ",", "$", "cliOutput", ")", ";", "...
Tries to estimate all PIDs by given path. @param string $path @return array
[ "Tries", "to", "estimate", "all", "PIDs", "by", "given", "path", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L201-L218
train
nekudo/Angela
src/AngelaControl.php
AngelaControl.sendCommand
protected function sendCommand(string $command) : string { try { $client = new Client; $client->addServer($this->config['sockets']['client']); $response = $client->sendCommand($command); $client->close(); return $response; } catch (ClientException $e) { return 'error'; } }
php
protected function sendCommand(string $command) : string { try { $client = new Client; $client->addServer($this->config['sockets']['client']); $response = $client->sendCommand($command); $client->close(); return $response; } catch (ClientException $e) { return 'error'; } }
[ "protected", "function", "sendCommand", "(", "string", "$", "command", ")", ":", "string", "{", "try", "{", "$", "client", "=", "new", "Client", ";", "$", "client", "->", "addServer", "(", "$", "this", "->", "config", "[", "'sockets'", "]", "[", "'clie...
Sends a control command to Angela main process using socket connection. @param string $command @return string
[ "Sends", "a", "control", "command", "to", "Angela", "main", "process", "using", "socket", "connection", "." ]
6b8c0bef6f56be38155c9b78b0c888aa91271ebc
https://github.com/nekudo/Angela/blob/6b8c0bef6f56be38155c9b78b0c888aa91271ebc/src/AngelaControl.php#L238-L249
train
gamegos/nosql-php
src/Storage/OperationArguments.php
OperationArguments.checkType
protected function checkType($value, $type, $nullable = false) { if (gettype($value) === $type) { return true; } return $nullable && null === $value; }
php
protected function checkType($value, $type, $nullable = false) { if (gettype($value) === $type) { return true; } return $nullable && null === $value; }
[ "protected", "function", "checkType", "(", "$", "value", ",", "$", "type", ",", "$", "nullable", "=", "false", ")", "{", "if", "(", "gettype", "(", "$", "value", ")", "===", "$", "type", ")", "{", "return", "true", ";", "}", "return", "$", "nullabl...
Check if a value is in the specified type. @param mixed $value @param string $type @param bool $nullable @return bool @see OperationArguments::validateArgument() @see OperationArguments::validateArrayArgument()
[ "Check", "if", "a", "value", "is", "in", "the", "specified", "type", "." ]
3a4c205b50f10d9af464f02603439fe13af2e027
https://github.com/gamegos/nosql-php/blob/3a4c205b50f10d9af464f02603439fe13af2e027/src/Storage/OperationArguments.php#L51-L57
train
gamegos/nosql-php
src/Storage/OperationArguments.php
OperationArguments.validateArgument
public function validateArgument($argname, $value, $type, $nullable = false) { if (!$this->checkType($value, $type, $nullable)) { throw new OperationArgumentException(sprintf( 'Method %s() expects $%s to be %s, %s given.', $this->operation, $argname, $type, gettype($value) )); } }
php
public function validateArgument($argname, $value, $type, $nullable = false) { if (!$this->checkType($value, $type, $nullable)) { throw new OperationArgumentException(sprintf( 'Method %s() expects $%s to be %s, %s given.', $this->operation, $argname, $type, gettype($value) )); } }
[ "public", "function", "validateArgument", "(", "$", "argname", ",", "$", "value", ",", "$", "type", ",", "$", "nullable", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "checkType", "(", "$", "value", ",", "$", "type", ",", "$", "nullab...
Validate an argument. @param string $argname @param mixed $value @param string $type @param bool $nullable @throws \Gamegos\NoSql\Storage\Exception\OperationArgumentException
[ "Validate", "an", "argument", "." ]
3a4c205b50f10d9af464f02603439fe13af2e027
https://github.com/gamegos/nosql-php/blob/3a4c205b50f10d9af464f02603439fe13af2e027/src/Storage/OperationArguments.php#L67-L78
train
gamegos/nosql-php
src/Storage/OperationArguments.php
OperationArguments.validateArrayArgument
public function validateArrayArgument($argname, array $value, $type, $nullable = false) { foreach ($value as $element) { if (!$this->checkType($element, $type, $nullable)) { throw new OperationArgumentException(sprintf( 'Method %s() expects all of $%s elements to be %s, found %s.', $this->operation, $argname, $type, gettype($element) )); } } }
php
public function validateArrayArgument($argname, array $value, $type, $nullable = false) { foreach ($value as $element) { if (!$this->checkType($element, $type, $nullable)) { throw new OperationArgumentException(sprintf( 'Method %s() expects all of $%s elements to be %s, found %s.', $this->operation, $argname, $type, gettype($element) )); } } }
[ "public", "function", "validateArrayArgument", "(", "$", "argname", ",", "array", "$", "value", ",", "$", "type", ",", "$", "nullable", "=", "false", ")", "{", "foreach", "(", "$", "value", "as", "$", "element", ")", "{", "if", "(", "!", "$", "this",...
Validate elements in an argument in the type of array. @param string $argname @param array $value @param string $type @param bool $nullable @throws \Gamegos\NoSql\Storage\Exception\OperationArgumentException
[ "Validate", "elements", "in", "an", "argument", "in", "the", "type", "of", "array", "." ]
3a4c205b50f10d9af464f02603439fe13af2e027
https://github.com/gamegos/nosql-php/blob/3a4c205b50f10d9af464f02603439fe13af2e027/src/Storage/OperationArguments.php#L88-L101
train
gamegos/nosql-php
src/Storage/OperationArguments.php
OperationArguments.&
public function & get($argname) { if ($this->has($argname)) { return $this->values[$argname]; } throw new OutOfRangeException(sprintf('Argument %s does not exist.', $argname)); }
php
public function & get($argname) { if ($this->has($argname)) { return $this->values[$argname]; } throw new OutOfRangeException(sprintf('Argument %s does not exist.', $argname)); }
[ "public", "function", "&", "get", "(", "$", "argname", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "argname", ")", ")", "{", "return", "$", "this", "->", "values", "[", "$", "argname", "]", ";", "}", "throw", "new", "OutOfRangeExceptio...
Get reference of an argument. @param string $argname @return mixed @throws \OutOfRangeException If the argument is not set
[ "Get", "reference", "of", "an", "argument", "." ]
3a4c205b50f10d9af464f02603439fe13af2e027
https://github.com/gamegos/nosql-php/blob/3a4c205b50f10d9af464f02603439fe13af2e027/src/Storage/OperationArguments.php#L135-L141
train
gamegos/nosql-php
src/Storage/OperationArguments.php
OperationArguments.setValue
public function setValue(& $value) { if ('append' == $this->operation) { $this->validateArgument('value', $value, 'string'); } return $this->set('value', $value); }
php
public function setValue(& $value) { if ('append' == $this->operation) { $this->validateArgument('value', $value, 'string'); } return $this->set('value', $value); }
[ "public", "function", "setValue", "(", "&", "$", "value", ")", "{", "if", "(", "'append'", "==", "$", "this", "->", "operation", ")", "{", "$", "this", "->", "validateArgument", "(", "'value'", ",", "$", "value", ",", "'string'", ")", ";", "}", "retu...
Set the reference of the argument 'value'. Methods using this argument: {@link AbstractStorage::add()} {@link AbstractStorage::set()} {@link AbstractStorage::cas()} {@link AbstractStorage::append()} @param mixed $value @return \Gamegos\NoSql\Storage\OperationArguments
[ "Set", "the", "reference", "of", "the", "argument", "value", "." ]
3a4c205b50f10d9af464f02603439fe13af2e027
https://github.com/gamegos/nosql-php/blob/3a4c205b50f10d9af464f02603439fe13af2e027/src/Storage/OperationArguments.php#L322-L328
train
patrickbrouwers/Laravel-Doctrine
src/Auth/Passwords/DoctrineTokenRepository.php
DoctrineTokenRepository.createNewToken
protected function createNewToken(CanResetPassword $user) { $email = $user->getEmailForPasswordReset(); $value = str_shuffle(sha1($email . spl_object_hash($this) . microtime(true))); return hash_hmac('sha1', $value, $this->hashKey); }
php
protected function createNewToken(CanResetPassword $user) { $email = $user->getEmailForPasswordReset(); $value = str_shuffle(sha1($email . spl_object_hash($this) . microtime(true))); return hash_hmac('sha1', $value, $this->hashKey); }
[ "protected", "function", "createNewToken", "(", "CanResetPassword", "$", "user", ")", "{", "$", "email", "=", "$", "user", "->", "getEmailForPasswordReset", "(", ")", ";", "$", "value", "=", "str_shuffle", "(", "sha1", "(", "$", "email", ".", "spl_object_has...
Create a new token for the user. @param \Illuminate\Contracts\Auth\CanResetPassword $user @return string
[ "Create", "a", "new", "token", "for", "the", "user", "." ]
94471346af6b121000256b303e585e977cc416cd
https://github.com/patrickbrouwers/Laravel-Doctrine/blob/94471346af6b121000256b303e585e977cc416cd/src/Auth/Passwords/DoctrineTokenRepository.php#L62-L69
train
patrickbrouwers/Laravel-Doctrine
src/Auth/Passwords/DoctrineTokenRepository.php
DoctrineTokenRepository.deleteExpired
public function deleteExpired() { $expired = Carbon::now()->subSeconds($this->expires); $this->makeDelete() ->where('o.createdAt < :expired') ->setParameter('expired', $expired) ->getQuery() ->execute(); }
php
public function deleteExpired() { $expired = Carbon::now()->subSeconds($this->expires); $this->makeDelete() ->where('o.createdAt < :expired') ->setParameter('expired', $expired) ->getQuery() ->execute(); }
[ "public", "function", "deleteExpired", "(", ")", "{", "$", "expired", "=", "Carbon", "::", "now", "(", ")", "->", "subSeconds", "(", "$", "this", "->", "expires", ")", ";", "$", "this", "->", "makeDelete", "(", ")", "->", "where", "(", "'o.createdAt < ...
Delete expired reminders. @return void
[ "Delete", "expired", "reminders", "." ]
94471346af6b121000256b303e585e977cc416cd
https://github.com/patrickbrouwers/Laravel-Doctrine/blob/94471346af6b121000256b303e585e977cc416cd/src/Auth/Passwords/DoctrineTokenRepository.php#L144-L153
train
globalis-ms/puppet-skilled-framework
src/View/View.php
View.cell
public function cell($cell, array $data = [], array $options = []) { $parts = explode('::', $cell); if (count($parts) === 2) { list($cell, $action) = [$parts[0], $parts[1]]; } else { list($cell, $action) = [$parts[0], 'display']; } $className = Application::className($cell, 'View/' . self::VIEW_TYPE_CELL); $class = new $className($data); return $class->{$action}($options); }
php
public function cell($cell, array $data = [], array $options = []) { $parts = explode('::', $cell); if (count($parts) === 2) { list($cell, $action) = [$parts[0], $parts[1]]; } else { list($cell, $action) = [$parts[0], 'display']; } $className = Application::className($cell, 'View/' . self::VIEW_TYPE_CELL); $class = new $className($data); return $class->{$action}($options); }
[ "public", "function", "cell", "(", "$", "cell", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "parts", "=", "explode", "(", "'::'", ",", "$", "cell", ")", ";", "if", "(", "count", "(", "...
Load a cell @param string $cell @param array $data Data for cell constructor @param array $options Options for cell method @return mixed
[ "Load", "a", "cell" ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/View/View.php#L111-L122
train
globalis-ms/puppet-skilled-framework
src/View/View.php
View.element
public function element($name, array $data = []) { $view = new View(); $view->type(self::VIEW_TYPE_ELEMENT); $view->set(array_merge($this->viewVars, $data)); return $view->render($name); }
php
public function element($name, array $data = []) { $view = new View(); $view->type(self::VIEW_TYPE_ELEMENT); $view->set(array_merge($this->viewVars, $data)); return $view->render($name); }
[ "public", "function", "element", "(", "$", "name", ",", "array", "$", "data", "=", "[", "]", ")", "{", "$", "view", "=", "new", "View", "(", ")", ";", "$", "view", "->", "type", "(", "self", "::", "VIEW_TYPE_ELEMENT", ")", ";", "$", "view", "->",...
Load an element @param string $name @param array $data @return string
[ "Load", "an", "element" ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/View/View.php#L147-L153
train
globalis-ms/puppet-skilled-framework
src/View/View.php
View.viewContent
protected function viewContent($type, $view) { $ext = pathinfo($view, PATHINFO_EXTENSION); $view = ($ext === '') ? $view.'.php' : $view; foreach ($this->paths as $path) { $path .= $type . DIRECTORY_SEPARATOR; if ($this->context() && file_exists($path . trim($this->context(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $view) ) { $viewPath = $path . trim($this->context(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $view; break; } if (file_exists($path . $view)) { $viewPath = $path . $view; break; } } if (!isset($viewPath)) { throw new \RuntimeException('Unable to find the ' . $view); } ob_start(); include($viewPath); $content = ob_get_contents(); ob_end_clean(); return $content; }
php
protected function viewContent($type, $view) { $ext = pathinfo($view, PATHINFO_EXTENSION); $view = ($ext === '') ? $view.'.php' : $view; foreach ($this->paths as $path) { $path .= $type . DIRECTORY_SEPARATOR; if ($this->context() && file_exists($path . trim($this->context(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $view) ) { $viewPath = $path . trim($this->context(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $view; break; } if (file_exists($path . $view)) { $viewPath = $path . $view; break; } } if (!isset($viewPath)) { throw new \RuntimeException('Unable to find the ' . $view); } ob_start(); include($viewPath); $content = ob_get_contents(); ob_end_clean(); return $content; }
[ "protected", "function", "viewContent", "(", "$", "type", ",", "$", "view", ")", "{", "$", "ext", "=", "pathinfo", "(", "$", "view", ",", "PATHINFO_EXTENSION", ")", ";", "$", "view", "=", "(", "$", "ext", "===", "''", ")", "?", "$", "view", ".", ...
Render a view content @param string $type @param string $view @return string
[ "Render", "a", "view", "content" ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/View/View.php#L183-L209
train
techdivision/import-product-media
src/Observers/MediaGalleryUpdateObserver.php
MediaGalleryUpdateObserver.initializeProductMediaGallery
protected function initializeProductMediaGallery(array $attr) { // load the value and the attribute ID $value = $attr[MemberNames::VALUE]; $attributeId = $attr[MemberNames::ATTRIBUTE_ID]; // query whether the product media gallery entity already exists or not if ($entity = $this->loadProductMediaGallery($attributeId, $value)) { return $this->mergeEntity($entity, $attr); } // simply return the attributes return $attr; }
php
protected function initializeProductMediaGallery(array $attr) { // load the value and the attribute ID $value = $attr[MemberNames::VALUE]; $attributeId = $attr[MemberNames::ATTRIBUTE_ID]; // query whether the product media gallery entity already exists or not if ($entity = $this->loadProductMediaGallery($attributeId, $value)) { return $this->mergeEntity($entity, $attr); } // simply return the attributes return $attr; }
[ "protected", "function", "initializeProductMediaGallery", "(", "array", "$", "attr", ")", "{", "// load the value and the attribute ID", "$", "value", "=", "$", "attr", "[", "MemberNames", "::", "VALUE", "]", ";", "$", "attributeId", "=", "$", "attr", "[", "Memb...
Initialize the product media gallery with the passed attributes and returns an instance. @param array $attr The product media gallery attributes @return array The initialized product media gallery
[ "Initialize", "the", "product", "media", "gallery", "with", "the", "passed", "attributes", "and", "returns", "an", "instance", "." ]
124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06
https://github.com/techdivision/import-product-media/blob/124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06/src/Observers/MediaGalleryUpdateObserver.php#L44-L58
train
techdivision/import-product-media
src/Observers/MediaGalleryUpdateObserver.php
MediaGalleryUpdateObserver.initializeProductMediaGalleryValueToEntity
protected function initializeProductMediaGalleryValueToEntity(array $attr) { // load the value/entity ID $valueId = $attr[MemberNames::VALUE_ID]; $entityId = $attr[MemberNames::ENTITY_ID]; // query whether the product media gallery value to entity entity already exists or not if ($this->loadProductMediaGalleryValueToEntity($valueId, $entityId)) { return; } // simply return the attributes return $attr; }
php
protected function initializeProductMediaGalleryValueToEntity(array $attr) { // load the value/entity ID $valueId = $attr[MemberNames::VALUE_ID]; $entityId = $attr[MemberNames::ENTITY_ID]; // query whether the product media gallery value to entity entity already exists or not if ($this->loadProductMediaGalleryValueToEntity($valueId, $entityId)) { return; } // simply return the attributes return $attr; }
[ "protected", "function", "initializeProductMediaGalleryValueToEntity", "(", "array", "$", "attr", ")", "{", "// load the value/entity ID", "$", "valueId", "=", "$", "attr", "[", "MemberNames", "::", "VALUE_ID", "]", ";", "$", "entityId", "=", "$", "attr", "[", "...
Initialize the product media gallery value to entity with the passed attributes and returns an instance. @param array $attr The product media gallery value to entity attributes @return array|null The initialized product media gallery value to entity, or NULL if the product media gallery value to entity already exists
[ "Initialize", "the", "product", "media", "gallery", "value", "to", "entity", "with", "the", "passed", "attributes", "and", "returns", "an", "instance", "." ]
124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06
https://github.com/techdivision/import-product-media/blob/124f4ed08d96f61fdb1eeb5aafde1c5afbd93a06/src/Observers/MediaGalleryUpdateObserver.php#L67-L81
train
orchestral/installer
src/Specifications/Authentication.php
Authentication.parseAuthenticationConfiguration
protected function parseAuthenticationConfiguration(array $auth): array { $driver = $auth['defaults']['guard'] ?? null; $guard = $auth['guards'][$driver] ?? [ 'driver' => 'session', 'provider' => 'users', ]; $provider = $auth['providers'][$guard['provider']] ?? [ 'driver' => 'eloquent', 'model' => User::class, ]; return \compact('guard', 'provider'); }
php
protected function parseAuthenticationConfiguration(array $auth): array { $driver = $auth['defaults']['guard'] ?? null; $guard = $auth['guards'][$driver] ?? [ 'driver' => 'session', 'provider' => 'users', ]; $provider = $auth['providers'][$guard['provider']] ?? [ 'driver' => 'eloquent', 'model' => User::class, ]; return \compact('guard', 'provider'); }
[ "protected", "function", "parseAuthenticationConfiguration", "(", "array", "$", "auth", ")", ":", "array", "{", "$", "driver", "=", "$", "auth", "[", "'defaults'", "]", "[", "'guard'", "]", "??", "null", ";", "$", "guard", "=", "$", "auth", "[", "'guards...
Resolve auth configuration. @param array $auth @return array
[ "Resolve", "auth", "configuration", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Specifications/Authentication.php#L61-L76
train
protobuf-php/google-protobuf-proto
src/google/protobuf/FileOptions.php
FileOptions.setOptimizeFor
public function setOptimizeFor(\google\protobuf\FileOptions\OptimizeMode $value = null) { $this->optimize_for = $value; }
php
public function setOptimizeFor(\google\protobuf\FileOptions\OptimizeMode $value = null) { $this->optimize_for = $value; }
[ "public", "function", "setOptimizeFor", "(", "\\", "google", "\\", "protobuf", "\\", "FileOptions", "\\", "OptimizeMode", "$", "value", "=", "null", ")", "{", "$", "this", "->", "optimize_for", "=", "$", "value", ";", "}" ]
Set 'optimize_for' value @param \google\protobuf\FileOptions\OptimizeMode $value
[ "Set", "optimize_for", "value" ]
da1827b4a23fccd4eb998a8d4bcd972f2330bc29
https://github.com/protobuf-php/google-protobuf-proto/blob/da1827b4a23fccd4eb998a8d4bcd972f2330bc29/src/google/protobuf/FileOptions.php#L332-L335
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.doFilter
public function doFilter($text, $filters) { // Define all valid filters with their callback function. $callbacks = [ 'bbcode' => 'bbcode2html', 'clickable' => 'makeClickable', 'shortcode' => 'shortCode', 'markdown' => 'markdown', 'nl2br' => 'nl2br', 'purify' => 'purify', ]; // Make an array of the comma separated string $filters if (is_array($filters)) { $filter = $filters; } else { $filters = strtolower($filters); $filter = preg_replace('/\s/', '', explode(',', $filters)); } // For each filter, call its function with the $text as parameter. foreach ($filter as $key) { if (!isset($callbacks[$key])) { throw new Exception("The filter '$filters' is not a valid filter string due to '$key'."); } $text = call_user_func_array([$this, $callbacks[$key]], [$text]); } return $text; }
php
public function doFilter($text, $filters) { // Define all valid filters with their callback function. $callbacks = [ 'bbcode' => 'bbcode2html', 'clickable' => 'makeClickable', 'shortcode' => 'shortCode', 'markdown' => 'markdown', 'nl2br' => 'nl2br', 'purify' => 'purify', ]; // Make an array of the comma separated string $filters if (is_array($filters)) { $filter = $filters; } else { $filters = strtolower($filters); $filter = preg_replace('/\s/', '', explode(',', $filters)); } // For each filter, call its function with the $text as parameter. foreach ($filter as $key) { if (!isset($callbacks[$key])) { throw new Exception("The filter '$filters' is not a valid filter string due to '$key'."); } $text = call_user_func_array([$this, $callbacks[$key]], [$text]); } return $text; }
[ "public", "function", "doFilter", "(", "$", "text", ",", "$", "filters", ")", "{", "// Define all valid filters with their callback function.", "$", "callbacks", "=", "[", "'bbcode'", "=>", "'bbcode2html'", ",", "'clickable'", "=>", "'makeClickable'", ",", "'shortcode...
Call each filter. @deprecated deprecated since version 1.2 mosbth/textfilter in favour of parse(). @param string $text the text to filter. @param string|array $filters as comma separated list of filter, or filters sent in as array. @return string the formatted text.
[ "Call", "each", "filter", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L76-L105
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.setFilterConfig
public function setFilterConfig($filter, $config) { if (!$this->hasFilter($filter)) { throw new Exception("No such filter '$filter' exists."); } $this->config[$filter] = $config; }
php
public function setFilterConfig($filter, $config) { if (!$this->hasFilter($filter)) { throw new Exception("No such filter '$filter' exists."); } $this->config[$filter] = $config; }
[ "public", "function", "setFilterConfig", "(", "$", "filter", ",", "$", "config", ")", "{", "if", "(", "!", "$", "this", "->", "hasFilter", "(", "$", "filter", ")", ")", "{", "throw", "new", "Exception", "(", "\"No such filter '$filter' exists.\"", ")", ";"...
Set configuration for a certain filter. @param string $filter the label of the filter to set configuration for. @param array $config the configuration as an array. @return void
[ "Set", "configuration", "for", "a", "certain", "filter", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L117-L124
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.getFilterConfig
public function getFilterConfig($filter) { if (!$this->hasFilter($filter)) { throw new Exception("No such filter '$filter' exists."); } return isset($this->config[$filter]) ? $this->config[$filter] : []; }
php
public function getFilterConfig($filter) { if (!$this->hasFilter($filter)) { throw new Exception("No such filter '$filter' exists."); } return isset($this->config[$filter]) ? $this->config[$filter] : []; }
[ "public", "function", "getFilterConfig", "(", "$", "filter", ")", "{", "if", "(", "!", "$", "this", "->", "hasFilter", "(", "$", "filter", ")", ")", "{", "throw", "new", "Exception", "(", "\"No such filter '$filter' exists.\"", ")", ";", "}", "return", "is...
Get configuration for a certain filter. @param string $filter the label of the filter to get configuration for. @param array $config the configuration as an array. @return array the configuration as an array or empty array.
[ "Get", "configuration", "for", "a", "certain", "filter", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L136-L145
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.addToFrontmatter
private function addToFrontmatter($matter) { if (empty($matter) || !is_array($matter)) { return $this; } if (is_null($this->current->frontmatter)) { $this->current->frontmatter = []; } $this->current->frontmatter = array_merge($this->current->frontmatter, $matter); return $this; }
php
private function addToFrontmatter($matter) { if (empty($matter) || !is_array($matter)) { return $this; } if (is_null($this->current->frontmatter)) { $this->current->frontmatter = []; } $this->current->frontmatter = array_merge($this->current->frontmatter, $matter); return $this; }
[ "private", "function", "addToFrontmatter", "(", "$", "matter", ")", "{", "if", "(", "empty", "(", "$", "matter", ")", "||", "!", "is_array", "(", "$", "matter", ")", ")", "{", "return", "$", "this", ";", "}", "if", "(", "is_null", "(", "$", "this",...
Add array items to frontmatter. @deprecated since 1.2, replaced with filter\Frontmatter. @param array|null $matter key value array with items to add or null if empty. @return $this
[ "Add", "array", "items", "to", "frontmatter", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L201-L213
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.parse
public function parse($text, $filter) { $this->current = new \stdClass(); $this->current->frontmatter = []; $this->current->text = $text; foreach ($filter as $key) { $this->parseFactory($key); } $this->current->text = $this->getUntilStop($this->current->text); return $this->current; }
php
public function parse($text, $filter) { $this->current = new \stdClass(); $this->current->frontmatter = []; $this->current->text = $text; foreach ($filter as $key) { $this->parseFactory($key); } $this->current->text = $this->getUntilStop($this->current->text); return $this->current; }
[ "public", "function", "parse", "(", "$", "text", ",", "$", "filter", ")", "{", "$", "this", "->", "current", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "this", "->", "current", "->", "frontmatter", "=", "[", "]", ";", "$", "this", "->", "c...
Call each filter and return array with details of the formatted content. @param string $text the text to filter. @param array $filter array of filters to use. @throws Anax\TextFilter\Exception when filter does not exists. @return array with the formatted text and additional details.
[ "Call", "each", "filter", "and", "return", "array", "with", "details", "of", "the", "formatted", "content", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L314-L327
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.addExcerpt
public function addExcerpt($current) { list($excerpt, $hasMore) = $this->getUntilMore($current->text); $current->excerpt = $excerpt; $current->hasMore = $hasMore; }
php
public function addExcerpt($current) { list($excerpt, $hasMore) = $this->getUntilMore($current->text); $current->excerpt = $excerpt; $current->hasMore = $hasMore; }
[ "public", "function", "addExcerpt", "(", "$", "current", ")", "{", "list", "(", "$", "excerpt", ",", "$", "hasMore", ")", "=", "$", "this", "->", "getUntilMore", "(", "$", "current", "->", "text", ")", ";", "$", "current", "->", "excerpt", "=", "$", ...
Add excerpt as short version of text if available. @param object &$current same structure as returned by parse(). @return void.
[ "Add", "excerpt", "as", "short", "version", "of", "text", "if", "available", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L338-L343
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.extractFrontMatter
private function extractFrontMatter($text, $startToken, $stopToken) { $tokenLength = strlen($startToken); $start = strpos($text, $startToken); // Is a valid start? if ($start !== false && $start !== 0) { if ($text[$start - 1] !== "\n") { $start = false; } } $frontmatter = null; if ($start !== false) { $stop = strpos($text, $stopToken, $tokenLength - 1); if ($stop !== false && $text[$stop - 1] === "\n") { $length = $stop - ($start + $tokenLength); $frontmatter = substr($text, $start + $tokenLength, $length); $textStart = substr($text, 0, $start); $text = $textStart . substr($text, $stop + $tokenLength); } } return [$text, $frontmatter]; }
php
private function extractFrontMatter($text, $startToken, $stopToken) { $tokenLength = strlen($startToken); $start = strpos($text, $startToken); // Is a valid start? if ($start !== false && $start !== 0) { if ($text[$start - 1] !== "\n") { $start = false; } } $frontmatter = null; if ($start !== false) { $stop = strpos($text, $stopToken, $tokenLength - 1); if ($stop !== false && $text[$stop - 1] === "\n") { $length = $stop - ($start + $tokenLength); $frontmatter = substr($text, $start + $tokenLength, $length); $textStart = substr($text, 0, $start); $text = $textStart . substr($text, $stop + $tokenLength); } } return [$text, $frontmatter]; }
[ "private", "function", "extractFrontMatter", "(", "$", "text", ",", "$", "startToken", ",", "$", "stopToken", ")", "{", "$", "tokenLength", "=", "strlen", "(", "$", "startToken", ")", ";", "$", "start", "=", "strpos", "(", "$", "text", ",", "$", "start...
Extract front matter from text. @deprecated since 1.2, replaced with filter\Frontmatter. @param string $text the text to be parsed. @param string $startToken the start token. @param string $stopToken the stop token. @return array with the formatted text and the front matter.
[ "Extract", "front", "matter", "from", "text", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L358-L384
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.jsonFrontMatter
public function jsonFrontMatter($text) { list($text, $frontmatter) = $this->extractFrontMatter($text, "{{{\n", "}}}\n"); if (!empty($frontmatter)) { $frontmatter = json_decode($frontmatter, true); if (is_null($frontmatter)) { throw new Exception("Failed parsing JSON frontmatter."); } } return [ "text" => $text, "frontmatter" => $frontmatter ]; }
php
public function jsonFrontMatter($text) { list($text, $frontmatter) = $this->extractFrontMatter($text, "{{{\n", "}}}\n"); if (!empty($frontmatter)) { $frontmatter = json_decode($frontmatter, true); if (is_null($frontmatter)) { throw new Exception("Failed parsing JSON frontmatter."); } } return [ "text" => $text, "frontmatter" => $frontmatter ]; }
[ "public", "function", "jsonFrontMatter", "(", "$", "text", ")", "{", "list", "(", "$", "text", ",", "$", "frontmatter", ")", "=", "$", "this", "->", "extractFrontMatter", "(", "$", "text", ",", "\"{{{\\n\"", ",", "\"}}}\\n\"", ")", ";", "if", "(", "!",...
Extract JSON front matter from text. @deprecated since 1.2, replaced with filter\Frontmatter. @param string $text the text to be parsed. @return array with the formatted text and the front matter.
[ "Extract", "JSON", "front", "matter", "from", "text", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L397-L413
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.yamlFrontMatter
public function yamlFrontMatter($text) { list($text, $frontmatter) = $this->extractFrontMatter($text, "---\n", "...\n"); if (!empty($frontmatter)) { $frontmatter = $this->yamlParse("---\n$frontmatter...\n"); } return [ "text" => $text, "frontmatter" => $frontmatter ]; }
php
public function yamlFrontMatter($text) { list($text, $frontmatter) = $this->extractFrontMatter($text, "---\n", "...\n"); if (!empty($frontmatter)) { $frontmatter = $this->yamlParse("---\n$frontmatter...\n"); } return [ "text" => $text, "frontmatter" => $frontmatter ]; }
[ "public", "function", "yamlFrontMatter", "(", "$", "text", ")", "{", "list", "(", "$", "text", ",", "$", "frontmatter", ")", "=", "$", "this", "->", "extractFrontMatter", "(", "$", "text", ",", "\"---\\n\"", ",", "\"...\\n\"", ")", ";", "if", "(", "!",...
Extract YAML front matter from text. @deprecated since 1.2, replaced with filter\Frontmatter. @param string $text the text to be parsed. @return array with the formatted text and the front matter.
[ "Extract", "YAML", "front", "matter", "from", "text", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L426-L438
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.yamlParse
public function yamlParse($text) { if (function_exists("yaml_parse")) { // Prefer php5-yaml extension $parsed = yaml_parse($text); if ($parsed === false) { throw new Exception("Failed parsing YAML frontmatter."); } return $parsed; } if (method_exists("Symfony\Component\Yaml\Yaml", "parse")) { // symfony/yaml $parsed = \Symfony\Component\Yaml\Yaml::parse($text); return $parsed; } if (function_exists("spyc_load")) { // mustangostang/spyc $parsed = spyc_load($text); return $parsed; } throw new Exception("Could not find support for YAML."); }
php
public function yamlParse($text) { if (function_exists("yaml_parse")) { // Prefer php5-yaml extension $parsed = yaml_parse($text); if ($parsed === false) { throw new Exception("Failed parsing YAML frontmatter."); } return $parsed; } if (method_exists("Symfony\Component\Yaml\Yaml", "parse")) { // symfony/yaml $parsed = \Symfony\Component\Yaml\Yaml::parse($text); return $parsed; } if (function_exists("spyc_load")) { // mustangostang/spyc $parsed = spyc_load($text); return $parsed; } throw new Exception("Could not find support for YAML."); }
[ "public", "function", "yamlParse", "(", "$", "text", ")", "{", "if", "(", "function_exists", "(", "\"yaml_parse\"", ")", ")", "{", "// Prefer php5-yaml extension", "$", "parsed", "=", "yaml_parse", "(", "$", "text", ")", ";", "if", "(", "$", "parsed", "===...
Extract YAML front matter from text, use one of several available implementations of a YAML parser. @deprecated since 1.2, replaced with filter\Frontmatter. @param string $text the text to be parsed. @throws: Exception when parsing frontmatter fails. @return array with the formatted text and the front matter.
[ "Extract", "YAML", "front", "matter", "from", "text", "use", "one", "of", "several", "available", "implementations", "of", "a", "YAML", "parser", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L454-L480
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.getTitleFromFirstH1
public function getTitleFromFirstH1($text) { $matches = []; $title = null; if (preg_match("#<h1.*?>(.*)</h1>#", $text, $matches)) { $title = strip_tags($matches[1]); } return $title; }
php
public function getTitleFromFirstH1($text) { $matches = []; $title = null; if (preg_match("#<h1.*?>(.*)</h1>#", $text, $matches)) { $title = strip_tags($matches[1]); } return $title; }
[ "public", "function", "getTitleFromFirstH1", "(", "$", "text", ")", "{", "$", "matches", "=", "[", "]", ";", "$", "title", "=", "null", ";", "if", "(", "preg_match", "(", "\"#<h1.*?>(.*)</h1>#\"", ",", "$", "text", ",", "$", "matches", ")", ")", "{", ...
Get the title from the first H1. @param string $text the text to be parsed. @return string|null with the title, if its found.
[ "Get", "the", "title", "from", "the", "first", "H1", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L491-L501
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.getTitleFromFirstHeader
public function getTitleFromFirstHeader($text) { $matches = []; $title = null; if (preg_match("#<h[1-6].*?>(.*)</h[1-6]>#", $text, $matches)) { $title = strip_tags($matches[1]); } return $title; }
php
public function getTitleFromFirstHeader($text) { $matches = []; $title = null; if (preg_match("#<h[1-6].*?>(.*)</h[1-6]>#", $text, $matches)) { $title = strip_tags($matches[1]); } return $title; }
[ "public", "function", "getTitleFromFirstHeader", "(", "$", "text", ")", "{", "$", "matches", "=", "[", "]", ";", "$", "title", "=", "null", ";", "if", "(", "preg_match", "(", "\"#<h[1-6].*?>(.*)</h[1-6]>#\"", ",", "$", "text", ",", "$", "matches", ")", "...
Get the title from the first header. @param string $text the text to be parsed. @return string|null with the title, if its found.
[ "Get", "the", "title", "from", "the", "first", "header", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L512-L522
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.purify
public function purify($text) { $config = \HTMLPurifier_Config::createDefault(); $config->set("Cache.DefinitionImpl", null); //$config->set('Cache.SerializerPath', '/home/user/absolute/path'); $purifier = new \HTMLPurifier($config); return $purifier->purify($text); }
php
public function purify($text) { $config = \HTMLPurifier_Config::createDefault(); $config->set("Cache.DefinitionImpl", null); //$config->set('Cache.SerializerPath', '/home/user/absolute/path'); $purifier = new \HTMLPurifier($config); return $purifier->purify($text); }
[ "public", "function", "purify", "(", "$", "text", ")", "{", "$", "config", "=", "\\", "HTMLPurifier_Config", "::", "createDefault", "(", ")", ";", "$", "config", "->", "set", "(", "\"Cache.DefinitionImpl\"", ",", "null", ")", ";", "//$config->set('Cache.Serial...
Format text according to HTML Purifier. @param string $text that should be formatted. @return string as the formatted html-text.
[ "Format", "text", "according", "to", "HTML", "Purifier", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L648-L657
train
canax/textfilter
src/TextFilter/TextFilter.php
TextFilter.markdown
public function markdown($text) { $text = \Michelf\MarkdownExtra::defaultTransform($text); $text = \Michelf\SmartyPantsTypographer::defaultTransform( $text, "2" ); return $text; }
php
public function markdown($text) { $text = \Michelf\MarkdownExtra::defaultTransform($text); $text = \Michelf\SmartyPantsTypographer::defaultTransform( $text, "2" ); return $text; }
[ "public", "function", "markdown", "(", "$", "text", ")", "{", "$", "text", "=", "\\", "Michelf", "\\", "MarkdownExtra", "::", "defaultTransform", "(", "$", "text", ")", ";", "$", "text", "=", "\\", "Michelf", "\\", "SmartyPantsTypographer", "::", "defaultT...
Format text according to Markdown syntax. @param string $text the text that should be formatted. @return string as the formatted html-text.
[ "Format", "text", "according", "to", "Markdown", "syntax", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TextFilter.php#L668-L676
train
globalis-ms/puppet-skilled-framework
src/Database/Magic/Relations/MorphOneOrMany.php
MorphOneOrMany.getRelationQuery
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) { $query = parent::getRelationQuery($query, $parent, $columns); return $query->where($this->morphType, $this->morphClass); }
php
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) { $query = parent::getRelationQuery($query, $parent, $columns); return $query->where($this->morphType, $this->morphClass); }
[ "public", "function", "getRelationQuery", "(", "Builder", "$", "query", ",", "Builder", "$", "parent", ",", "$", "columns", "=", "[", "'*'", "]", ")", "{", "$", "query", "=", "parent", "::", "getRelationQuery", "(", "$", "query", ",", "$", "parent", ",...
Get the relationship query. @param \Globalis\PuppetSkilled\Database\Magic\Builder $query @param \Globalis\PuppetSkilled\Database\Magic\Builder $parent @param array|mixed $columns @return \Globalis\PuppetSkilled\Database\Magic\Builder
[ "Get", "the", "relationship", "query", "." ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Database/Magic/Relations/MorphOneOrMany.php#L216-L221
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.choose
public function choose($val, $isMultiple = null) { $arguments = array(json_encode($val)); if (null !== $isMultiple) { $arguments[] = (bool) $isMultiple ? 'true' : 'false'; } $this->con->executeStep( sprintf('_sahi._setSelected(%s, %s)', $this->getAccessor(), implode(', ', $arguments)) ); }
php
public function choose($val, $isMultiple = null) { $arguments = array(json_encode($val)); if (null !== $isMultiple) { $arguments[] = (bool) $isMultiple ? 'true' : 'false'; } $this->con->executeStep( sprintf('_sahi._setSelected(%s, %s)', $this->getAccessor(), implode(', ', $arguments)) ); }
[ "public", "function", "choose", "(", "$", "val", ",", "$", "isMultiple", "=", "null", ")", "{", "$", "arguments", "=", "array", "(", "json_encode", "(", "$", "val", ")", ")", ";", "if", "(", "null", "!==", "$", "isMultiple", ")", "{", "$", "argumen...
Choose option in select box. @param string $val option value @param boolean|null $isMultiple is multiple
[ "Choose", "option", "in", "select", "box", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L111-L121
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.setFile
public function setFile($path) { $this->con->executeStep( sprintf('_sahi._setFile(%s, %s)', $this->getAccessor(), json_encode($path)) ); }
php
public function setFile($path) { $this->con->executeStep( sprintf('_sahi._setFile(%s, %s)', $this->getAccessor(), json_encode($path)) ); }
[ "public", "function", "setFile", "(", "$", "path", ")", "{", "$", "this", "->", "con", "->", "executeStep", "(", "sprintf", "(", "'_sahi._setFile(%s, %s)'", ",", "$", "this", "->", "getAccessor", "(", ")", ",", "json_encode", "(", "$", "path", ")", ")", ...
Emulate setting filepath in a file input. @param string $path file path
[ "Emulate", "setting", "filepath", "in", "a", "file", "input", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L128-L133
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.dragDrop
public function dragDrop(AbstractAccessor $to) { $this->con->executeStep(sprintf('_sahi._dragDrop(%s, %s)', $this->getAccessor(), $to->getAccessor())); }
php
public function dragDrop(AbstractAccessor $to) { $this->con->executeStep(sprintf('_sahi._dragDrop(%s, %s)', $this->getAccessor(), $to->getAccessor())); }
[ "public", "function", "dragDrop", "(", "AbstractAccessor", "$", "to", ")", "{", "$", "this", "->", "con", "->", "executeStep", "(", "sprintf", "(", "'_sahi._dragDrop(%s, %s)'", ",", "$", "this", "->", "getAccessor", "(", ")", ",", "$", "to", "->", "getAcce...
Drag'n'Drop current element onto another. @param AbstractAccessor $to destination element
[ "Drag", "n", "Drop", "current", "element", "onto", "another", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L196-L199
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.dragDropXY
public function dragDropXY($x, $y, $relative = null) { $arguments = array($x, $y); if (null !== $relative) { $arguments[] = (bool) $relative ? 'true' : 'false'; } $this->con->executeStep( sprintf('_sahi._dragDropXY(%s, %s)', $this->getAccessor(), implode(', ', $arguments)) ); }
php
public function dragDropXY($x, $y, $relative = null) { $arguments = array($x, $y); if (null !== $relative) { $arguments[] = (bool) $relative ? 'true' : 'false'; } $this->con->executeStep( sprintf('_sahi._dragDropXY(%s, %s)', $this->getAccessor(), implode(', ', $arguments)) ); }
[ "public", "function", "dragDropXY", "(", "$", "x", ",", "$", "y", ",", "$", "relative", "=", "null", ")", "{", "$", "arguments", "=", "array", "(", "$", "x", ",", "$", "y", ")", ";", "if", "(", "null", "!==", "$", "relative", ")", "{", "$", "...
Drag'n'Drop current element into X,Y. @param integer $x X @param integer $y Y @param boolean|null $relative relativity of position
[ "Drag", "n", "Drop", "current", "element", "into", "X", "Y", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L208-L219
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.keyPress
public function keyPress($charInfo, $combo = null) { $this->con->executeStep( sprintf('_sahi._keyPress(%s, %s)', $this->getAccessor(), $this->getKeyArgumentsString($charInfo, $combo)) ); }
php
public function keyPress($charInfo, $combo = null) { $this->con->executeStep( sprintf('_sahi._keyPress(%s, %s)', $this->getAccessor(), $this->getKeyArgumentsString($charInfo, $combo)) ); }
[ "public", "function", "keyPress", "(", "$", "charInfo", ",", "$", "combo", "=", "null", ")", "{", "$", "this", "->", "con", "->", "executeStep", "(", "sprintf", "(", "'_sahi._keyPress(%s, %s)'", ",", "$", "this", "->", "getAccessor", "(", ")", ",", "$", ...
Simulate keypress event. @param string $charInfo a char (eg. ‘b’) OR charCode (eg. 98) OR array(13,13) for pressing ENTER @param string $combo CTRL|ALT|SHIFT|META
[ "Simulate", "keypress", "event", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L237-L242
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.setValue
public function setValue($val) { $this->con->executeStep( sprintf('_sahi._setValue(%s, %s)', $this->getAccessor(), json_encode($val)) ); }
php
public function setValue($val) { $this->con->executeStep( sprintf('_sahi._setValue(%s, %s)', $this->getAccessor(), json_encode($val)) ); }
[ "public", "function", "setValue", "(", "$", "val", ")", "{", "$", "this", "->", "con", "->", "executeStep", "(", "sprintf", "(", "'_sahi._setValue(%s, %s)'", ",", "$", "this", "->", "getAccessor", "(", ")", ",", "json_encode", "(", "$", "val", ")", ")", ...
Set text value. @param string $val value
[ "Set", "text", "value", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L275-L280
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.getAttr
public function getAttr($attr) { $attributeValue = $this->con->evaluateJavascript(sprintf('%s.getAttribute(%s)', $this->getAccessor(), json_encode($attr))); if ($attributeValue === false) { // see https://github.com/kriswallsmith/Buzz/pull/138 bug return ''; } return $attributeValue; }
php
public function getAttr($attr) { $attributeValue = $this->con->evaluateJavascript(sprintf('%s.getAttribute(%s)', $this->getAccessor(), json_encode($attr))); if ($attributeValue === false) { // see https://github.com/kriswallsmith/Buzz/pull/138 bug return ''; } return $attributeValue; }
[ "public", "function", "getAttr", "(", "$", "attr", ")", "{", "$", "attributeValue", "=", "$", "this", "->", "con", "->", "evaluateJavascript", "(", "sprintf", "(", "'%s.getAttribute(%s)'", ",", "$", "this", "->", "getAccessor", "(", ")", ",", "json_encode", ...
Return attribute value. @param string $attr attribute name @return string
[ "Return", "attribute", "value", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L309-L319
train
minkphp/SahiClient
src/Accessor/AbstractAccessor.php
AbstractAccessor.getKeyArgumentsString
private function getKeyArgumentsString($charInfo, $combo) { $arguments = json_encode($charInfo); if (null !== $combo) { $arguments .= ', ' . json_encode($combo); } return $arguments; }
php
private function getKeyArgumentsString($charInfo, $combo) { $arguments = json_encode($charInfo); if (null !== $combo) { $arguments .= ', ' . json_encode($combo); } return $arguments; }
[ "private", "function", "getKeyArgumentsString", "(", "$", "charInfo", ",", "$", "combo", ")", "{", "$", "arguments", "=", "json_encode", "(", "$", "charInfo", ")", ";", "if", "(", "null", "!==", "$", "combo", ")", "{", "$", "arguments", ".=", "', '", "...
Return Key arguments string. @param string $charInfo a char (eg. ‘b’) OR charCode (eg. 98) OR array(13,13) for pressing ENTER @param string $combo CTRL|ALT|SHIFT|META @return string
[ "Return", "Key", "arguments", "string", "." ]
edd87e8445c4a1c28233eeae5f226fac7afc5ed8
https://github.com/minkphp/SahiClient/blob/edd87e8445c4a1c28233eeae5f226fac7afc5ed8/src/Accessor/AbstractAccessor.php#L414-L423
train
rchouinard/rych-otp
src/AbstractOTP.php
AbstractOTP.setSecret
public function setSecret($secret) { if (!$secret instanceof Seed) { $secret = new Seed($secret); } $this->secret = $secret; return $this; }
php
public function setSecret($secret) { if (!$secret instanceof Seed) { $secret = new Seed($secret); } $this->secret = $secret; return $this; }
[ "public", "function", "setSecret", "(", "$", "secret", ")", "{", "if", "(", "!", "$", "secret", "instanceof", "Seed", ")", "{", "$", "secret", "=", "new", "Seed", "(", "$", "secret", ")", ";", "}", "$", "this", "->", "secret", "=", "$", "secret", ...
Set the shared secret @param Seed|string $secret @return self Returns an instance of self for method chaining.
[ "Set", "the", "shared", "secret" ]
b3c7fc11284c546cd291f14fb383a7d49ab23832
https://github.com/rchouinard/rych-otp/blob/b3c7fc11284c546cd291f14fb383a7d49ab23832/src/AbstractOTP.php#L55-L63
train
rchouinard/rych-otp
src/AbstractOTP.php
AbstractOTP.truncateHash
protected static function truncateHash($hash) { $offset = ord($hash[19]) & 0xf; $value = (ord($hash[$offset + 0]) & 0x7f) << 24; $value |= (ord($hash[$offset + 1]) & 0xff) << 16; $value |= (ord($hash[$offset + 2]) & 0xff) << 8; $value |= (ord($hash[$offset + 3]) & 0xff); return $value; }
php
protected static function truncateHash($hash) { $offset = ord($hash[19]) & 0xf; $value = (ord($hash[$offset + 0]) & 0x7f) << 24; $value |= (ord($hash[$offset + 1]) & 0xff) << 16; $value |= (ord($hash[$offset + 2]) & 0xff) << 8; $value |= (ord($hash[$offset + 3]) & 0xff); return $value; }
[ "protected", "static", "function", "truncateHash", "(", "$", "hash", ")", "{", "$", "offset", "=", "ord", "(", "$", "hash", "[", "19", "]", ")", "&", "0xf", ";", "$", "value", "=", "(", "ord", "(", "$", "hash", "[", "$", "offset", "+", "0", "]"...
Extract 4 bytes from a hash value Uses the method defined in RFC 4226, § 5.4. @static @param string $hash Hash value. @return integer Returns the truncated hash value.
[ "Extract", "4", "bytes", "from", "a", "hash", "value" ]
b3c7fc11284c546cd291f14fb383a7d49ab23832
https://github.com/rchouinard/rych-otp/blob/b3c7fc11284c546cd291f14fb383a7d49ab23832/src/AbstractOTP.php#L74-L83
train
rchouinard/rych-otp
src/AbstractOTP.php
AbstractOTP.counterToString
protected static function counterToString($counter) { $temp = ''; while ($counter != 0) { $temp .= chr($counter & 0xff); $counter >>= 8; } return substr(str_pad(strrev($temp), 8, "\0", STR_PAD_LEFT), 0, 8); }
php
protected static function counterToString($counter) { $temp = ''; while ($counter != 0) { $temp .= chr($counter & 0xff); $counter >>= 8; } return substr(str_pad(strrev($temp), 8, "\0", STR_PAD_LEFT), 0, 8); }
[ "protected", "static", "function", "counterToString", "(", "$", "counter", ")", "{", "$", "temp", "=", "''", ";", "while", "(", "$", "counter", "!=", "0", ")", "{", "$", "temp", ".=", "chr", "(", "$", "counter", "&", "0xff", ")", ";", "$", "counter...
Convert an integer counter into a string of 8 bytes @static @param integer $counter The counter value. @return string Returns an 8-byte binary string.
[ "Convert", "an", "integer", "counter", "into", "a", "string", "of", "8", "bytes" ]
b3c7fc11284c546cd291f14fb383a7d49ab23832
https://github.com/rchouinard/rych-otp/blob/b3c7fc11284c546cd291f14fb383a7d49ab23832/src/AbstractOTP.php#L92-L101
train
nanbando/core
src/Bundle/Command/CheckCommand.php
CheckCommand.checkBackups
private function checkBackups(SymfonyStyle $io, array $backups) { /** @var PluginRegistry $plugins */ $plugins = $this->getContainer()->get('plugins'); foreach ($backups as $name => $backup) { $this->checkBackup($plugins, $io, $name, $backup); } }
php
private function checkBackups(SymfonyStyle $io, array $backups) { /** @var PluginRegistry $plugins */ $plugins = $this->getContainer()->get('plugins'); foreach ($backups as $name => $backup) { $this->checkBackup($plugins, $io, $name, $backup); } }
[ "private", "function", "checkBackups", "(", "SymfonyStyle", "$", "io", ",", "array", "$", "backups", ")", "{", "/** @var PluginRegistry $plugins */", "$", "plugins", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'plugins'", ")", ";", "...
Check backup-configuration. @param SymfonyStyle $io @param array $backups
[ "Check", "backup", "-", "configuration", "." ]
790f5c6339753bffafb50a846ccb6bab81f26877
https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Bundle/Command/CheckCommand.php#L79-L86
train
nanbando/core
src/Bundle/Command/CheckCommand.php
CheckCommand.checkBackup
private function checkBackup(PluginRegistry $plugins, SymfonyStyle $io, $name, array $backup) { $io->section('Backup: ' . $name); if (!$plugins->has($backup['plugin'])) { $io->warning(sprintf('Plugin "%s" not found', $backup['plugin'])); return false; } $optionsResolver = new OptionsResolver(); $plugins->getPlugin($backup['plugin'])->configureOptionsResolver($optionsResolver); try { $parameter = $optionsResolver->resolve($backup['parameter']); } catch (InvalidArgumentException $e) { $io->warning(sprintf('Parameter not valid' . PHP_EOL . PHP_EOL . 'Message: "%s"', $e->getMessage())); return false; } $io->write('Process: '); $process = 'All'; if (0 < count($backup['process'])) { $process = '["' . implode('", "', $backup['process']) . '""]'; } $io->writeln($process); $io->write('Parameter:'); $messages = array_filter(explode("\r\n", Yaml::dump($parameter))); $io->block($messages, null, null, ' '); $io->writeln('OK'); return true; }
php
private function checkBackup(PluginRegistry $plugins, SymfonyStyle $io, $name, array $backup) { $io->section('Backup: ' . $name); if (!$plugins->has($backup['plugin'])) { $io->warning(sprintf('Plugin "%s" not found', $backup['plugin'])); return false; } $optionsResolver = new OptionsResolver(); $plugins->getPlugin($backup['plugin'])->configureOptionsResolver($optionsResolver); try { $parameter = $optionsResolver->resolve($backup['parameter']); } catch (InvalidArgumentException $e) { $io->warning(sprintf('Parameter not valid' . PHP_EOL . PHP_EOL . 'Message: "%s"', $e->getMessage())); return false; } $io->write('Process: '); $process = 'All'; if (0 < count($backup['process'])) { $process = '["' . implode('", "', $backup['process']) . '""]'; } $io->writeln($process); $io->write('Parameter:'); $messages = array_filter(explode("\r\n", Yaml::dump($parameter))); $io->block($messages, null, null, ' '); $io->writeln('OK'); return true; }
[ "private", "function", "checkBackup", "(", "PluginRegistry", "$", "plugins", ",", "SymfonyStyle", "$", "io", ",", "$", "name", ",", "array", "$", "backup", ")", "{", "$", "io", "->", "section", "(", "'Backup: '", ".", "$", "name", ")", ";", "if", "(", ...
Check single backup-configuration. @param PluginRegistry $plugins @param SymfonyStyle $io @param string $name @param array $backup @return bool
[ "Check", "single", "backup", "-", "configuration", "." ]
790f5c6339753bffafb50a846ccb6bab81f26877
https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Bundle/Command/CheckCommand.php#L98-L132
train
nanbando/core
src/Bundle/Command/CheckCommand.php
CheckCommand.getBackups
private function getBackups() { $backups = $this->getContainer()->getParameter('nanbando.backup'); $preset = []; if ($name = $this->getParameter('nanbando.application.name')) { /** @var PresetStore $presetStore */ $presetStore = $this->getContainer()->get('presets'); $preset = $presetStore->getPreset( $name, $this->getParameter('nanbando.application.version'), $this->getParameter('nanbando.application.options') ); } return array_merge($preset, $backups); }
php
private function getBackups() { $backups = $this->getContainer()->getParameter('nanbando.backup'); $preset = []; if ($name = $this->getParameter('nanbando.application.name')) { /** @var PresetStore $presetStore */ $presetStore = $this->getContainer()->get('presets'); $preset = $presetStore->getPreset( $name, $this->getParameter('nanbando.application.version'), $this->getParameter('nanbando.application.options') ); } return array_merge($preset, $backups); }
[ "private", "function", "getBackups", "(", ")", "{", "$", "backups", "=", "$", "this", "->", "getContainer", "(", ")", "->", "getParameter", "(", "'nanbando.backup'", ")", ";", "$", "preset", "=", "[", "]", ";", "if", "(", "$", "name", "=", "$", "this...
Returns backup configuration and merge it with preset if exists. @return array
[ "Returns", "backup", "configuration", "and", "merge", "it", "with", "preset", "if", "exists", "." ]
790f5c6339753bffafb50a846ccb6bab81f26877
https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Bundle/Command/CheckCommand.php#L139-L155
train
nanbando/core
src/Bundle/Command/CheckCommand.php
CheckCommand.getParameter
public function getParameter($name, $default = null) { if (!$this->getContainer()->hasParameter($name)) { return $default; } return $this->getContainer()->getParameter($name); }
php
public function getParameter($name, $default = null) { if (!$this->getContainer()->hasParameter($name)) { return $default; } return $this->getContainer()->getParameter($name); }
[ "public", "function", "getParameter", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "getContainer", "(", ")", "->", "hasParameter", "(", "$", "name", ")", ")", "{", "return", "$", "default", ";", "...
Returns container parameter or default value. @param string $name @param mixed $default @return mixed
[ "Returns", "container", "parameter", "or", "default", "value", "." ]
790f5c6339753bffafb50a846ccb6bab81f26877
https://github.com/nanbando/core/blob/790f5c6339753bffafb50a846ccb6bab81f26877/src/Bundle/Command/CheckCommand.php#L165-L172
train
t9221823420/yii2-base
src/traits/ActiveRecordTrait.php
ActiveRecordTrait.attributes
public function attributes( ?array $only = null, ?array $except = null, ?bool $schemaOnly = false ) { $names = array_keys( static::getTableSchema()->columns ); if( !$schemaOnly ) { $class = new \ReflectionClass( $this ); foreach( $class->getProperties( \ReflectionProperty::IS_PUBLIC ) as $property ) { if( !$property->isStatic() ) { $names[] = $property->getName(); } } } $names = array_unique( $names ); if( $only ) { $names = array_intersect( $only, $names ); } if( $except ) { $names = array_diff( $names, $except ); } return $names; }
php
public function attributes( ?array $only = null, ?array $except = null, ?bool $schemaOnly = false ) { $names = array_keys( static::getTableSchema()->columns ); if( !$schemaOnly ) { $class = new \ReflectionClass( $this ); foreach( $class->getProperties( \ReflectionProperty::IS_PUBLIC ) as $property ) { if( !$property->isStatic() ) { $names[] = $property->getName(); } } } $names = array_unique( $names ); if( $only ) { $names = array_intersect( $only, $names ); } if( $except ) { $names = array_diff( $names, $except ); } return $names; }
[ "public", "function", "attributes", "(", "?", "array", "$", "only", "=", "null", ",", "?", "array", "$", "except", "=", "null", ",", "?", "bool", "$", "schemaOnly", "=", "false", ")", "{", "$", "names", "=", "array_keys", "(", "static", "::", "getTab...
Returns the list of all attribute names of the model. The default implementation will return all column names of the table associated with this AR class. @return array list of attribute names.
[ "Returns", "the", "list", "of", "all", "attribute", "names", "of", "the", "model", ".", "The", "default", "implementation", "will", "return", "all", "column", "names", "of", "the", "table", "associated", "with", "this", "AR", "class", "." ]
61be4e46c41dd466722a38b952defd3e872ed3dd
https://github.com/t9221823420/yii2-base/blob/61be4e46c41dd466722a38b952defd3e872ed3dd/src/traits/ActiveRecordTrait.php#L388-L415
train
dframe/database
src/PdoWrapper.php
PdoWrapper.getPDO
public static function getPDO($dsn, $username, $password, $settings = ['attributes' => []]) { // if not set self pdo object property or pdo set as null if (!isset(self::$PDO) || (self::$PDO !== null)) { self::$PDO = new self($dsn, $username, $password, $settings); // set class pdo property with new connection } // return class property object return self::$PDO; }
php
public static function getPDO($dsn, $username, $password, $settings = ['attributes' => []]) { // if not set self pdo object property or pdo set as null if (!isset(self::$PDO) || (self::$PDO !== null)) { self::$PDO = new self($dsn, $username, $password, $settings); // set class pdo property with new connection } // return class property object return self::$PDO; }
[ "public", "static", "function", "getPDO", "(", "$", "dsn", ",", "$", "username", ",", "$", "password", ",", "$", "settings", "=", "[", "'attributes'", "=>", "[", "]", "]", ")", "{", "// if not set self pdo object property or pdo set as null", "if", "(", "!", ...
Get Instance of PDO Class as Singleton Pattern. @param array|string $dsn @param $username @param $password @param array $settings @return PdoWrapper|object
[ "Get", "Instance", "of", "PDO", "Class", "as", "Singleton", "Pattern", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L203-L212
train
dframe/database
src/PdoWrapper.php
PdoWrapper.result
public function result($row = 0) { return isset($this->results[$row]) ? $this->results[$row] : false; }
php
public function result($row = 0) { return isset($this->results[$row]) ? $this->results[$row] : false; }
[ "public", "function", "result", "(", "$", "row", "=", "0", ")", "{", "return", "isset", "(", "$", "this", "->", "results", "[", "$", "row", "]", ")", "?", "$", "this", "->", "results", "[", "$", "row", "]", ":", "false", ";", "}" ]
Return PDO Query result by index value. @param int $row @return array|bool
[ "Return", "PDO", "Query", "result", "by", "index", "value", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L221-L224
train
dframe/database
src/PdoWrapper.php
PdoWrapper.error
public function error($msg) { file_put_contents($this->config['logDir'] . self::LOG_FILE, date('Y-m-d h:m:s') . ' :: ' . $msg . "\n", FILE_APPEND); // log set as true if ($this->log) { // show executed query with error $this->showQuery(); // die code $this->helper()->errorBox($msg); } throw new \PDOException($msg); }
php
public function error($msg) { file_put_contents($this->config['logDir'] . self::LOG_FILE, date('Y-m-d h:m:s') . ' :: ' . $msg . "\n", FILE_APPEND); // log set as true if ($this->log) { // show executed query with error $this->showQuery(); // die code $this->helper()->errorBox($msg); } throw new \PDOException($msg); }
[ "public", "function", "error", "(", "$", "msg", ")", "{", "file_put_contents", "(", "$", "this", "->", "config", "[", "'logDir'", "]", ".", "self", "::", "LOG_FILE", ",", "date", "(", "'Y-m-d h:m:s'", ")", ".", "' :: '", ".", "$", "msg", ".", "\"\\n\""...
Catch Error in txt file. @param mixed $msg
[ "Catch", "Error", "in", "txt", "file", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L368-L382
train
dframe/database
src/PdoWrapper.php
PdoWrapper.showQuery
public function showQuery($logfile = false) { if (!$logfile) { echo "<div style='color:#990099; border:1px solid #777; padding:2px; background-color: #E5E5E5;'>"; echo " Executed Query -> <span style='color:#008000;'> "; echo $this->helper()->formatSQL($this->interpolateQuery()); echo '</span></div>'; } file_put_contents($this->config['logDir'] . self::LOG_FILE, date('Y-m-d h:m:s') . ' :: ' . $this->interpolateQuery() . "\n", FILE_APPEND); return $this; }
php
public function showQuery($logfile = false) { if (!$logfile) { echo "<div style='color:#990099; border:1px solid #777; padding:2px; background-color: #E5E5E5;'>"; echo " Executed Query -> <span style='color:#008000;'> "; echo $this->helper()->formatSQL($this->interpolateQuery()); echo '</span></div>'; } file_put_contents($this->config['logDir'] . self::LOG_FILE, date('Y-m-d h:m:s') . ' :: ' . $this->interpolateQuery() . "\n", FILE_APPEND); return $this; }
[ "public", "function", "showQuery", "(", "$", "logfile", "=", "false", ")", "{", "if", "(", "!", "$", "logfile", ")", "{", "echo", "\"<div style='color:#990099; border:1px solid #777; padding:2px; background-color: #E5E5E5;'>\"", ";", "echo", "\" Executed Query -> <span styl...
Show executed query on call. @param bool $logfile set true if wanna log all query in file @return self
[ "Show", "executed", "query", "on", "call", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L391-L404
train
dframe/database
src/PdoWrapper.php
PdoWrapper.getFieldFromArrayKey
public function getFieldFromArrayKey($array_key) { // get table column from array key $key_array = explode(' ', $array_key); // check no of chunk return (count($key_array) == '2') ? $key_array[0] : ((count($key_array) > 2) ? $key_array[1] : $key_array[0]); }
php
public function getFieldFromArrayKey($array_key) { // get table column from array key $key_array = explode(' ', $array_key); // check no of chunk return (count($key_array) == '2') ? $key_array[0] : ((count($key_array) > 2) ? $key_array[1] : $key_array[0]); }
[ "public", "function", "getFieldFromArrayKey", "(", "$", "array_key", ")", "{", "// get table column from array key", "$", "key_array", "=", "explode", "(", "' '", ",", "$", "array_key", ")", ";", "// check no of chunk", "return", "(", "count", "(", "$", "key_array...
Return real table column from array key. @param string $array_key @return mixed
[ "Return", "real", "table", "column", "from", "array", "key", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L511-L517
train
dframe/database
src/PdoWrapper.php
PdoWrapper.insert
public function insert($table, $data = []) { // check if table name not empty if (!empty($table)) { // and array data not empty if (count($data) > 0 && is_array($data)) { // get array insert data in temp array $tmp = []; foreach ($data as $f => $v) { $tmp[] = ":s_$f"; } // make name space param for pdo insert statement $sNameSpaceParam = implode(',', $tmp); // unset temp var unset($tmp); // get insert fields name $sFields = implode(',', array_keys($data)); // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);"; // pdo prepare statement $this->STH = $this->prepare($this->sql); // set class where property with array data $this->data = $data; // bind pdo param $this->_bindPdoNameSpace($data); // use try catch block to get pdo error try { // execute pdo statement if ($this->STH->execute()) { // set class property with last insert id $this->lastId = $this->lastInsertId(); // close pdo $this->STH->closeCursor(); // return this object return $this; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Data not in valid format..'); } } else { self::error('Table name not found..'); } }
php
public function insert($table, $data = []) { // check if table name not empty if (!empty($table)) { // and array data not empty if (count($data) > 0 && is_array($data)) { // get array insert data in temp array $tmp = []; foreach ($data as $f => $v) { $tmp[] = ":s_$f"; } // make name space param for pdo insert statement $sNameSpaceParam = implode(',', $tmp); // unset temp var unset($tmp); // get insert fields name $sFields = implode(',', array_keys($data)); // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);"; // pdo prepare statement $this->STH = $this->prepare($this->sql); // set class where property with array data $this->data = $data; // bind pdo param $this->_bindPdoNameSpace($data); // use try catch block to get pdo error try { // execute pdo statement if ($this->STH->execute()) { // set class property with last insert id $this->lastId = $this->lastInsertId(); // close pdo $this->STH->closeCursor(); // return this object return $this; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Data not in valid format..'); } } else { self::error('Table name not found..'); } }
[ "public", "function", "insert", "(", "$", "table", ",", "$", "data", "=", "[", "]", ")", "{", "// check if table name not empty", "if", "(", "!", "empty", "(", "$", "table", ")", ")", "{", "// and array data not empty", "if", "(", "count", "(", "$", "dat...
Execute PDO Insert. @param string $table @param array $data @return self|void
[ "Execute", "PDO", "Insert", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L718-L766
train
dframe/database
src/PdoWrapper.php
PdoWrapper.insertBatch
public function insertBatch($table, $data = [], $safeModeInsert = true) { // PDO transactions start $this->start(); // check if table name not empty if (!empty($table)) { // and array data not empty if (count($data) > 0 && is_array($data)) { // get array insert data in temp array $tmp = []; foreach ($data[0] as $f => $v) { $tmp[] = ":s_$f"; } // make name space param for pdo insert statement $sNameSpaceParam = implode(', ', $tmp); // unset temp var unset($tmp); // get insert fields name $sFields = implode(', ', array_keys($data[0])); // handle safe mode. If it is set as false means user not using bind param in pdo if (!$safeModeInsert) { // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES "; foreach ($data as $key => $value) { $this->sql .= '(' . "'" . implode("', '", array_values($value)) . "'" . '), '; } $this->sql = rtrim($this->sql, ', '); // return this object // return $this; // pdo prepare statement $this->STH = $this->prepare($this->sql); // start try catch block try { // execute pdo statement if ($this->STH->execute()) { // store all last insert id in array $this->allLastId[] = $this->lastInsertId(); } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); // PDO Rollback $this->back(); }// end try catch block // PDO Commit $this->end(); // close pdo $this->STH->closeCursor(); // return this object return $this; } // end here safe mode // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);"; // pdo prepare statement $this->STH = $this->prepare($this->sql); // set class property with array $this->data = $data; // set batch insert flag true $this->batch = true; // parse batch array data foreach ($data as $key => $value) { // bind pdo param $this->_bindPdoNameSpace($value); try { // execute pdo statement if ($this->STH->execute()) { // set class property with last insert id as array $this->allLastId[] = $this->lastInsertId(); } else { self::error($this->STH->errorInfo()); // on error PDO Rollback $this->back(); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); // on error PDO Rollback $this->back(); } } // fine now PDO Commit $this->end(); // close pdo $this->STH->closeCursor(); // return this object return $this; } else { self::error('Data not in valid format..'); } } else { self::error('Table name not found..'); } }
php
public function insertBatch($table, $data = [], $safeModeInsert = true) { // PDO transactions start $this->start(); // check if table name not empty if (!empty($table)) { // and array data not empty if (count($data) > 0 && is_array($data)) { // get array insert data in temp array $tmp = []; foreach ($data[0] as $f => $v) { $tmp[] = ":s_$f"; } // make name space param for pdo insert statement $sNameSpaceParam = implode(', ', $tmp); // unset temp var unset($tmp); // get insert fields name $sFields = implode(', ', array_keys($data[0])); // handle safe mode. If it is set as false means user not using bind param in pdo if (!$safeModeInsert) { // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES "; foreach ($data as $key => $value) { $this->sql .= '(' . "'" . implode("', '", array_values($value)) . "'" . '), '; } $this->sql = rtrim($this->sql, ', '); // return this object // return $this; // pdo prepare statement $this->STH = $this->prepare($this->sql); // start try catch block try { // execute pdo statement if ($this->STH->execute()) { // store all last insert id in array $this->allLastId[] = $this->lastInsertId(); } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); // PDO Rollback $this->back(); }// end try catch block // PDO Commit $this->end(); // close pdo $this->STH->closeCursor(); // return this object return $this; } // end here safe mode // set pdo insert statement in class property $this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);"; // pdo prepare statement $this->STH = $this->prepare($this->sql); // set class property with array $this->data = $data; // set batch insert flag true $this->batch = true; // parse batch array data foreach ($data as $key => $value) { // bind pdo param $this->_bindPdoNameSpace($value); try { // execute pdo statement if ($this->STH->execute()) { // set class property with last insert id as array $this->allLastId[] = $this->lastInsertId(); } else { self::error($this->STH->errorInfo()); // on error PDO Rollback $this->back(); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); // on error PDO Rollback $this->back(); } } // fine now PDO Commit $this->end(); // close pdo $this->STH->closeCursor(); // return this object return $this; } else { self::error('Data not in valid format..'); } } else { self::error('Table name not found..'); } }
[ "public", "function", "insertBatch", "(", "$", "table", ",", "$", "data", "=", "[", "]", ",", "$", "safeModeInsert", "=", "true", ")", "{", "// PDO transactions start", "$", "this", "->", "start", "(", ")", ";", "// check if table name not empty", "if", "(",...
Execute PDO Insert as Batch Data. @param string $table mysql table name @param array $data mysql insert array data @param bool $safeModeInsert set true if want to use pdo bind param @return self last insert ID
[ "Execute", "PDO", "Insert", "as", "Batch", "Data", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L777-L876
train
dframe/database
src/PdoWrapper.php
PdoWrapper.update
public function update($table = '', $data = [], $arrayWhere = [], $other = '') { // if table name is empty if (!empty($table)) { // check if array data and where array is more then 0 if (count($data) > 0 && count($arrayWhere) > 0) { // parse array data and make a temp array $tmp = []; foreach ($data as $k => $v) { $tmp[] = "$k = :s_$k"; } // join temp array value with , $sFields = implode(', ', $tmp); // delete temp array from memory unset($tmp); $tmp = []; // parse where array and store in temp array foreach ($arrayWhere as $k => $v) { $tmp[] = "$k = :s_$k"; } $this->data = $data; $this->arrayWhere = $arrayWhere; // join where array value with AND operator and create where condition $where = implode(' AND ', $tmp); // unset temp array unset($tmp); // make sql query to update $this->sql = "UPDATE `$table` SET $sFields WHERE $where $other;"; // on PDO prepare statement $this->STH = $this->prepare($this->sql); // bind pdo param for update statement $this->_bindPdoNameSpace($data); // bind pdo param for where clause $this->_bindPdoNameSpace($arrayWhere); // try catch block start try { // if PDO run if ($this->STH->execute()) { // get affected rows $this->affectedRows = $this->STH->rowCount(); // close PDO $this->STH->closeCursor(); // return self object return $this; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } // try catch block end } else { self::error('update statement not in valid format..'); } } else { self::error('Table name not found..'); } }
php
public function update($table = '', $data = [], $arrayWhere = [], $other = '') { // if table name is empty if (!empty($table)) { // check if array data and where array is more then 0 if (count($data) > 0 && count($arrayWhere) > 0) { // parse array data and make a temp array $tmp = []; foreach ($data as $k => $v) { $tmp[] = "$k = :s_$k"; } // join temp array value with , $sFields = implode(', ', $tmp); // delete temp array from memory unset($tmp); $tmp = []; // parse where array and store in temp array foreach ($arrayWhere as $k => $v) { $tmp[] = "$k = :s_$k"; } $this->data = $data; $this->arrayWhere = $arrayWhere; // join where array value with AND operator and create where condition $where = implode(' AND ', $tmp); // unset temp array unset($tmp); // make sql query to update $this->sql = "UPDATE `$table` SET $sFields WHERE $where $other;"; // on PDO prepare statement $this->STH = $this->prepare($this->sql); // bind pdo param for update statement $this->_bindPdoNameSpace($data); // bind pdo param for where clause $this->_bindPdoNameSpace($arrayWhere); // try catch block start try { // if PDO run if ($this->STH->execute()) { // get affected rows $this->affectedRows = $this->STH->rowCount(); // close PDO $this->STH->closeCursor(); // return self object return $this; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } // try catch block end } else { self::error('update statement not in valid format..'); } } else { self::error('Table name not found..'); } }
[ "public", "function", "update", "(", "$", "table", "=", "''", ",", "$", "data", "=", "[", "]", ",", "$", "arrayWhere", "=", "[", "]", ",", "$", "other", "=", "''", ")", "{", "// if table name is empty", "if", "(", "!", "empty", "(", "$", "table", ...
Execute PDO Update Statement Get No OF Affected Rows updated. @param string $table @param array $data @param array $arrayWhere @param string $other @return self|void
[ "Execute", "PDO", "Update", "Statement", "Get", "No", "OF", "Affected", "Rows", "updated", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L916-L975
train
dframe/database
src/PdoWrapper.php
PdoWrapper.count
public function count($table = '', $where = '') { // if table name not pass if (!empty($table)) { if (empty($where)) { $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table`;"; // create count query } else { $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table` WHERE $where;"; // create count query } // pdo prepare statement $this->STH = $this->prepare($this->sql); try { if ($this->STH->execute()) { // fetch array result $this->results = $this->STH->fetch(); // close pdo $this->STH->closeCursor(); // return number of count return $this->results['NUMROWS']; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Table name not found..'); } }
php
public function count($table = '', $where = '') { // if table name not pass if (!empty($table)) { if (empty($where)) { $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table`;"; // create count query } else { $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table` WHERE $where;"; // create count query } // pdo prepare statement $this->STH = $this->prepare($this->sql); try { if ($this->STH->execute()) { // fetch array result $this->results = $this->STH->fetch(); // close pdo $this->STH->closeCursor(); // return number of count return $this->results['NUMROWS']; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Table name not found..'); } }
[ "public", "function", "count", "(", "$", "table", "=", "''", ",", "$", "where", "=", "''", ")", "{", "// if table name not pass", "if", "(", "!", "empty", "(", "$", "table", ")", ")", "{", "if", "(", "empty", "(", "$", "where", ")", ")", "{", "$"...
Get Total Number Of Records in Requested Table. @param string $table @param string $where @return number
[ "Get", "Total", "Number", "Of", "Records", "in", "Requested", "Table", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L1071-L1102
train
dframe/database
src/PdoWrapper.php
PdoWrapper.truncate
public function truncate($table = '') { // if table name not pass if (!empty($table)) { // create count query $this->sql = "TRUNCATE TABLE `$table`;"; // pdo prepare statement $this->STH = $this->prepare($this->sql); try { if ($this->STH->execute()) { // close pdo $this->STH->closeCursor(); // return number of count return true; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Table name not found..'); } }
php
public function truncate($table = '') { // if table name not pass if (!empty($table)) { // create count query $this->sql = "TRUNCATE TABLE `$table`;"; // pdo prepare statement $this->STH = $this->prepare($this->sql); try { if ($this->STH->execute()) { // close pdo $this->STH->closeCursor(); // return number of count return true; } else { self::error($this->STH->errorInfo()); } } catch (\PDOException $e) { // get pdo error and pass on error method self::error($e->getMessage() . ': ' . __LINE__); } } else { self::error('Table name not found..'); } }
[ "public", "function", "truncate", "(", "$", "table", "=", "''", ")", "{", "// if table name not pass", "if", "(", "!", "empty", "(", "$", "table", ")", ")", "{", "// create count query", "$", "this", "->", "sql", "=", "\"TRUNCATE TABLE `$table`;\"", ";", "//...
Truncate a MySQL table. @param string $table @return bool
[ "Truncate", "a", "MySQL", "table", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L1111-L1136
train
dframe/database
src/PdoWrapper.php
PdoWrapper.describe
public function describe($table = '') { $this->sql = $sql = "DESC $table;"; $this->STH = $this->prepare($sql); $this->STH->execute(); $colList = $this->STH->fetchAll(); $field = []; $type = []; foreach ($colList as $key) { $field[] = $key['Field']; $type[] = $key['Type']; } return array_combine($field, $type); }
php
public function describe($table = '') { $this->sql = $sql = "DESC $table;"; $this->STH = $this->prepare($sql); $this->STH->execute(); $colList = $this->STH->fetchAll(); $field = []; $type = []; foreach ($colList as $key) { $field[] = $key['Field']; $type[] = $key['Type']; } return array_combine($field, $type); }
[ "public", "function", "describe", "(", "$", "table", "=", "''", ")", "{", "$", "this", "->", "sql", "=", "$", "sql", "=", "\"DESC $table;\"", ";", "$", "this", "->", "STH", "=", "$", "this", "->", "prepare", "(", "$", "sql", ")", ";", "$", "this"...
Return Table Fields of Requested Table. @param string $table @return array Field Type and Field Name
[ "Return", "Table", "Fields", "of", "Requested", "Table", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L1179-L1194
train
dframe/database
src/PdoWrapper.php
PdoWrapper.pdoPrepare
public function pdoPrepare($statement, $options = []) { $this->STH = $this->prepare($statement, $options); return $this; }
php
public function pdoPrepare($statement, $options = []) { $this->STH = $this->prepare($statement, $options); return $this; }
[ "public", "function", "pdoPrepare", "(", "$", "statement", ",", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "STH", "=", "$", "this", "->", "prepare", "(", "$", "statement", ",", "$", "options", ")", ";", "return", "$", "this", ";", ...
prepare PDO Query. @param string $statement @param array $options Value @return self
[ "prepare", "PDO", "Query", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/PdoWrapper.php#L1214-L1219
train
globalis-ms/puppet-skilled-framework
src/Event/Dispatcher.php
Dispatcher.sortListeners
protected function sortListeners($eventName) { // If listeners exist for the given event, we will sort them by the priority // so that we can call them in the correct order. We will cache off these // sorted event listeners so we do not have to re-sort on every events. $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : []; if (class_exists($eventName)) { foreach (class_implements($eventName) as $interface) { if (isset($this->listeners[$interface])) { foreach ($this->listeners[$interface] as $priority => $names) { if (isset($listeners[$priority])) { $listeners[$priority] = array_merge($listeners[$priority], $names); } else { $listeners[$priority] = $names; } } } } } if ($listeners) { krsort($listeners); $this->sorted[$eventName] = call_user_func_array('array_merge', $listeners); } else { $this->sorted[$eventName] = []; } }
php
protected function sortListeners($eventName) { // If listeners exist for the given event, we will sort them by the priority // so that we can call them in the correct order. We will cache off these // sorted event listeners so we do not have to re-sort on every events. $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : []; if (class_exists($eventName)) { foreach (class_implements($eventName) as $interface) { if (isset($this->listeners[$interface])) { foreach ($this->listeners[$interface] as $priority => $names) { if (isset($listeners[$priority])) { $listeners[$priority] = array_merge($listeners[$priority], $names); } else { $listeners[$priority] = $names; } } } } } if ($listeners) { krsort($listeners); $this->sorted[$eventName] = call_user_func_array('array_merge', $listeners); } else { $this->sorted[$eventName] = []; } }
[ "protected", "function", "sortListeners", "(", "$", "eventName", ")", "{", "// If listeners exist for the given event, we will sort them by the priority", "// so that we can call them in the correct order. We will cache off these", "// sorted event listeners so we do not have to re-sort on every...
Sort the listeners for a given event by priority. @param string $eventName @return void
[ "Sort", "the", "listeners", "for", "a", "given", "event", "by", "priority", "." ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Event/Dispatcher.php#L257-L286
train
globalis-ms/puppet-skilled-framework
src/Queue/DatabaseQueue.php
DatabaseQueue.isReservedButExpired
protected function isReservedButExpired($query) { $expiration = Carbon::now()->subSeconds($this->expire)->getTimestamp(); $query->orWhere(function ($query) use ($expiration) { $query->where('reserved_at', '<=', $expiration); }); }
php
protected function isReservedButExpired($query) { $expiration = Carbon::now()->subSeconds($this->expire)->getTimestamp(); $query->orWhere(function ($query) use ($expiration) { $query->where('reserved_at', '<=', $expiration); }); }
[ "protected", "function", "isReservedButExpired", "(", "$", "query", ")", "{", "$", "expiration", "=", "Carbon", "::", "now", "(", ")", "->", "subSeconds", "(", "$", "this", "->", "expire", ")", "->", "getTimestamp", "(", ")", ";", "$", "query", "->", "...
Modify the query to check for jobs that are reserved but have expired. @param \Globalis\PuppetSkilled\Database\Query\Builder $query @return void
[ "Modify", "the", "query", "to", "check", "for", "jobs", "that", "are", "reserved", "but", "have", "expired", "." ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Queue/DatabaseQueue.php#L237-L244
train
dframe/database
src/HavingStringChunk.php
HavingStringChunk.flatter
public function flatter($array) { $result = []; foreach ($array as $item) { if (is_array($item)) { $result = array_merge($result, $this->flatter($item)); } else { $result[] = $item; } } return $result; }
php
public function flatter($array) { $result = []; foreach ($array as $item) { if (is_array($item)) { $result = array_merge($result, $this->flatter($item)); } else { $result[] = $item; } } return $result; }
[ "public", "function", "flatter", "(", "$", "array", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "item", ")", "{", "if", "(", "is_array", "(", "$", "item", ")", ")", "{", "$", "result", "=", "array_merge",...
Flatter function. @param array $array @return array
[ "Flatter", "function", "." ]
6d9ac90d695c33b5e417b58f2134f86f79918387
https://github.com/dframe/database/blob/6d9ac90d695c33b5e417b58f2134f86f79918387/src/HavingStringChunk.php#L70-L82
train
melisplatform/melis-front
src/Controller/Plugin/MelisFrontMenuPlugin.php
MelisFrontMenuPlugin.checkValidPagesRecursive
public function checkValidPagesRecursive($siteMenu = array()) { $checkedSiteMenu = array(); foreach($siteMenu as $key => $val){ if($val['menu'] != 'NONE'){ if($val['menu'] == 'NOLINK'){ $val['uri'] = '#'; } if(!empty($val['pages'])){ $pages = $this->checkValidPagesRecursive($val['pages']); if(!empty($pages)){ $val['pages'] = $pages; } } $checkedSiteMenu[] = $val; } } return $checkedSiteMenu; }
php
public function checkValidPagesRecursive($siteMenu = array()) { $checkedSiteMenu = array(); foreach($siteMenu as $key => $val){ if($val['menu'] != 'NONE'){ if($val['menu'] == 'NOLINK'){ $val['uri'] = '#'; } if(!empty($val['pages'])){ $pages = $this->checkValidPagesRecursive($val['pages']); if(!empty($pages)){ $val['pages'] = $pages; } } $checkedSiteMenu[] = $val; } } return $checkedSiteMenu; }
[ "public", "function", "checkValidPagesRecursive", "(", "$", "siteMenu", "=", "array", "(", ")", ")", "{", "$", "checkedSiteMenu", "=", "array", "(", ")", ";", "foreach", "(", "$", "siteMenu", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "...
This method checks the show menu option of the page,
[ "This", "method", "checks", "the", "show", "menu", "option", "of", "the", "page" ]
5e03e32687970bb2201e4205612d5539500dc514
https://github.com/melisplatform/melis-front/blob/5e03e32687970bb2201e4205612d5539500dc514/src/Controller/Plugin/MelisFrontMenuPlugin.php#L229-L256
train
MetaModels/attribute_tabletext
src/Attribute/TableText.php
TableText.getSetValues
protected function getSetValues($arrCell, $intId) { return array( 'tstamp' => time(), 'value' => (string) $arrCell['value'], 'att_id' => $this->get('id'), 'row' => (int) $arrCell['row'], 'col' => (int) $arrCell['col'], 'item_id' => $intId, ); }
php
protected function getSetValues($arrCell, $intId) { return array( 'tstamp' => time(), 'value' => (string) $arrCell['value'], 'att_id' => $this->get('id'), 'row' => (int) $arrCell['row'], 'col' => (int) $arrCell['col'], 'item_id' => $intId, ); }
[ "protected", "function", "getSetValues", "(", "$", "arrCell", ",", "$", "intId", ")", "{", "return", "array", "(", "'tstamp'", "=>", "time", "(", ")", ",", "'value'", "=>", "(", "string", ")", "$", "arrCell", "[", "'value'", "]", ",", "'att_id'", "=>",...
Calculate the array of query parameters for the given cell. @param array $arrCell The cell to calculate. @param int $intId The data set id. @return array
[ "Calculate", "the", "array", "of", "query", "parameters", "for", "the", "given", "cell", "." ]
b94d9da9bf38a94c320d7c36b6e8f8136bbbcc82
https://github.com/MetaModels/attribute_tabletext/blob/b94d9da9bf38a94c320d7c36b6e8f8136bbbcc82/src/Attribute/TableText.php#L358-L368
train
m1so/LeagueWrap
src/LeagueWrap/Api/BaseApi.php
BaseApi.getAsync
protected function getAsync(array $endpoints, $params = []) { /** @var Promise[] $promises */ $promises = array_map(function (Endpoint $endpoint) use ($params) { $isCached = $this->client->getCache() && $this->client->getCache()->getItem(KeyGenerator::fromEndpoint($endpoint))->isHit(); if ($endpoint->countsTowardsLimit() && !$isCached) { try { $this->client->getMethodRateLimiter()->hit($endpoint); $this->client->getAppRateLimiter()->hit($endpoint); } catch (RateLimitReachedException $e) { return new RejectedPromise($e); } } return $this->client->getHttpClient() ->sendAsyncRequest($this->buildRequest($endpoint, $params)) ->then(function (ResponseInterface $response) use ($endpoint) { return $response ->withHeader('X-Endpoint', $endpoint->getName()) ->withHeader('X-Request', $endpoint->getUrl()) ->withHeader('X-Region', $endpoint->getRegion()->getName()); }); }, is_array($endpoints) ? $endpoints : [$endpoints]); // Wait for multiple requests to complete, even if some fail if (count($promises) > 1) { $results = \GuzzleHttp\Promise\settle($promises)->wait(); return BatchResult::fromSettledPromises($results); } // Resolve a single request $result = $promises[0]->wait(); if (! $result instanceof ResponseInterface) { throw $result; } return Result::fromPsr7($result); }
php
protected function getAsync(array $endpoints, $params = []) { /** @var Promise[] $promises */ $promises = array_map(function (Endpoint $endpoint) use ($params) { $isCached = $this->client->getCache() && $this->client->getCache()->getItem(KeyGenerator::fromEndpoint($endpoint))->isHit(); if ($endpoint->countsTowardsLimit() && !$isCached) { try { $this->client->getMethodRateLimiter()->hit($endpoint); $this->client->getAppRateLimiter()->hit($endpoint); } catch (RateLimitReachedException $e) { return new RejectedPromise($e); } } return $this->client->getHttpClient() ->sendAsyncRequest($this->buildRequest($endpoint, $params)) ->then(function (ResponseInterface $response) use ($endpoint) { return $response ->withHeader('X-Endpoint', $endpoint->getName()) ->withHeader('X-Request', $endpoint->getUrl()) ->withHeader('X-Region', $endpoint->getRegion()->getName()); }); }, is_array($endpoints) ? $endpoints : [$endpoints]); // Wait for multiple requests to complete, even if some fail if (count($promises) > 1) { $results = \GuzzleHttp\Promise\settle($promises)->wait(); return BatchResult::fromSettledPromises($results); } // Resolve a single request $result = $promises[0]->wait(); if (! $result instanceof ResponseInterface) { throw $result; } return Result::fromPsr7($result); }
[ "protected", "function", "getAsync", "(", "array", "$", "endpoints", ",", "$", "params", "=", "[", "]", ")", "{", "/** @var Promise[] $promises */", "$", "promises", "=", "array_map", "(", "function", "(", "Endpoint", "$", "endpoint", ")", "use", "(", "$", ...
Perform one or more async requests. @param Endpoint[] $endpoints @param array $params @return Result|BatchResult
[ "Perform", "one", "or", "more", "async", "requests", "." ]
c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2
https://github.com/m1so/LeagueWrap/blob/c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2/src/LeagueWrap/Api/BaseApi.php#L87-L127
train
m1so/LeagueWrap
src/LeagueWrap/Api/BaseApi.php
BaseApi.loadAllEndpoints
private function loadAllEndpoints() { self::$endpointClasses = array_map(function ($classPath) { // For ./Api/Endpoints/MatchById -> ('MatchById.php') list($endpointClass) = array_slice(explode('/', $classPath), -1, 1); // Build the full class name with namespace $fullClassName = join('\\', [__NAMESPACE__, 'Endpoints', str_replace('.php', '', $endpointClass)]); /** @var Endpoint $endpoint */ $endpoint = new $fullClassName($this->region); self::$endpointDefinitions[$endpoint->getName()] = [ 'class' => $fullClassName, 'instance' => $endpoint, ]; return $fullClassName; }, glob(__DIR__.'/Endpoints/*.php')); }
php
private function loadAllEndpoints() { self::$endpointClasses = array_map(function ($classPath) { // For ./Api/Endpoints/MatchById -> ('MatchById.php') list($endpointClass) = array_slice(explode('/', $classPath), -1, 1); // Build the full class name with namespace $fullClassName = join('\\', [__NAMESPACE__, 'Endpoints', str_replace('.php', '', $endpointClass)]); /** @var Endpoint $endpoint */ $endpoint = new $fullClassName($this->region); self::$endpointDefinitions[$endpoint->getName()] = [ 'class' => $fullClassName, 'instance' => $endpoint, ]; return $fullClassName; }, glob(__DIR__.'/Endpoints/*.php')); }
[ "private", "function", "loadAllEndpoints", "(", ")", "{", "self", "::", "$", "endpointClasses", "=", "array_map", "(", "function", "(", "$", "classPath", ")", "{", "// For ./Api/Endpoints/MatchById -> ('MatchById.php')", "list", "(", "$", "endpointClass", ")", "=", ...
Load all available endpoints as an array of full class names with namespace strings. The endpoints are contained within a folder structure that is only 1 level deep.
[ "Load", "all", "available", "endpoints", "as", "an", "array", "of", "full", "class", "names", "with", "namespace", "strings", ".", "The", "endpoints", "are", "contained", "within", "a", "folder", "structure", "that", "is", "only", "1", "level", "deep", "." ]
c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2
https://github.com/m1so/LeagueWrap/blob/c1dacaad747a958900eeb55dd0d3f6ba0c29bbd2/src/LeagueWrap/Api/BaseApi.php#L143-L162
train
LearningLocker/Moodle-xAPI-Translator
src/Events/FacetofaceAttend.php
FacetofaceAttend.getSignupEvent
private function getSignupEvent($signup, $opts) { $currentStatus = null; $previousAttendance = false; $previousPartialAttendance = false; foreach ($signup->statuses as $status) { if ($status->timecreated == $opts['event']['timecreated']) { $currentStatus = $status; } else if ($status->timecreated < $opts['event']['timecreated'] && $status->statuscode == $this->statuscodes->partial) { $previousPartialAttendance = true; } else if ($status->timecreated < $opts['event']['timecreated'] && $status->statuscode == $this->statuscodes->attended) { $previousAttendance = true; } } if (is_null($currentStatus)){ // There is no status with a timestamp matching the event. return null; } $duration = null; $completion = null; if ($currentStatus->statuscode == $this->statuscodes->attended){ if ($previousAttendance == true){ // Attendance has already been recorded for this user and session.' return null; } $duration = $this->sessionDuration; $completion = true; } else if ($currentStatus->statuscode == $this->statuscodes->partial){ if ($previousPartialAttendance == true){ // Partial attendance has already been recorded for this user and session. return null; } $duration = $this->sessionDuration * $this->partialAttendanceDurationCredit; $completion = false; } else { // This user did not attend this session. return null; } return [ 'recipe' => 'training_session_attend', 'attendee_id' => $signup->attendee->id, 'attendee_url' => $signup->attendee->url, 'attendee_name' => $signup->attendee->fullname, 'attempt_duration' => "PT".(string) $duration."S", 'attempt_completion' => $completion ]; }
php
private function getSignupEvent($signup, $opts) { $currentStatus = null; $previousAttendance = false; $previousPartialAttendance = false; foreach ($signup->statuses as $status) { if ($status->timecreated == $opts['event']['timecreated']) { $currentStatus = $status; } else if ($status->timecreated < $opts['event']['timecreated'] && $status->statuscode == $this->statuscodes->partial) { $previousPartialAttendance = true; } else if ($status->timecreated < $opts['event']['timecreated'] && $status->statuscode == $this->statuscodes->attended) { $previousAttendance = true; } } if (is_null($currentStatus)){ // There is no status with a timestamp matching the event. return null; } $duration = null; $completion = null; if ($currentStatus->statuscode == $this->statuscodes->attended){ if ($previousAttendance == true){ // Attendance has already been recorded for this user and session.' return null; } $duration = $this->sessionDuration; $completion = true; } else if ($currentStatus->statuscode == $this->statuscodes->partial){ if ($previousPartialAttendance == true){ // Partial attendance has already been recorded for this user and session. return null; } $duration = $this->sessionDuration * $this->partialAttendanceDurationCredit; $completion = false; } else { // This user did not attend this session. return null; } return [ 'recipe' => 'training_session_attend', 'attendee_id' => $signup->attendee->id, 'attendee_url' => $signup->attendee->url, 'attendee_name' => $signup->attendee->fullname, 'attempt_duration' => "PT".(string) $duration."S", 'attempt_completion' => $completion ]; }
[ "private", "function", "getSignupEvent", "(", "$", "signup", ",", "$", "opts", ")", "{", "$", "currentStatus", "=", "null", ";", "$", "previousAttendance", "=", "false", ";", "$", "previousPartialAttendance", "=", "false", ";", "foreach", "(", "$", "signup",...
Create an event for a signup or null if no event is required. @param [String => Mixed] $signup @param [String => Mixed] $opts @return [String => Mixed]
[ "Create", "an", "event", "for", "a", "signup", "or", "null", "if", "no", "event", "is", "required", "." ]
5d196b5059f0f5dcdd98f784ad814a39cd5d736c
https://github.com/LearningLocker/Moodle-xAPI-Translator/blob/5d196b5059f0f5dcdd98f784ad814a39cd5d736c/src/Events/FacetofaceAttend.php#L45-L96
train
esmero/webform_strawberryfield
src/Plugin/WebformHandler/strawberryFieldharvester.php
strawberryFieldharvester.processFileField
public function processFileField(array $element, WebformSubmissionInterface $webform_submission, &$cleanvalues) { $key = $element['#webform_key']; $original_data = $webform_submission->getOriginalData(); $value = isset($cleanvalues[$key]) ? $cleanvalues[$key] : []; $fids = (is_array($value)) ? $value : [$value]; $original_value = isset($original_data[$key]) ? $original_data[$key] : []; $original_fids = (is_array($original_value)) ? $original_value : [$original_value]; // Delete the old file uploads? // @TODO build some cleanup logic here. Could be moved to attached field hook. $delete_fids = array_diff($original_fids, $fids); // @TODO what do we do with removed files? // Idea. Check the fileUsage. If there is still some other than this one // don't remove. // But also, if a revision is using it? what a mess! // @see \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::deleteFiles // Exit if there is no fids. if (empty($fids)) { return; } /** @var \Drupal\file\FileInterface[] $files */ try { $files = $this->entityTypeManager->getStorage('file')->loadMultiple( $fids ); } catch (InvalidPluginDefinitionException $e) { } catch (PluginNotFoundException $e) { } $fileinfo_many = []; //@TODO refactor this urgently to a NEW TECHMD class. foreach ($files as $file) { $fileinfo = []; if (isset($cleanvalues['as:image'])) { $fileinfo = $this->check_file_in_metadata( $cleanvalues['as:image'], (int) $file->id() ); if ($fileinfo) { $fileinfo_many[$fileinfo['dr:url']] = $fileinfo; } } if (!$fileinfo) { // Only do this is file was not previusly processed and stored. $uri = $file->getFileUri(); $md5 = md5_file($uri); $fileinfo = [ 'type' => 'Image', 'dr:url' => $uri, 'url' => $uri, 'checksum' => $md5, 'dr:for' => $key, 'dr:fid' => (int) $file->id(), 'name' => $file->getFilename(), ]; $relativefolder = substr($md5, 0, 3); $source_uri = $file->getFileUri(); $realpath_uri = $this->fileSystem->realpath($source_uri); if (empty(!$realpath_uri)) { $command = escapeshellcmd( '/usr/local/bin/fido ' . $realpath_uri . ' -pronom_only -matchprintf ' ); // @TODO handle the exit code from output $output = shell_exec($command . '"OK,%(info.puid)" -q'); } // We will use the original scheme here since our HD operations are over. $destination_uri = $this->getFileDestinationUri( $element, $file, $relativefolder, $webform_submission ); //Use the wished storagepoint as key. //Then the node save hook will deal with moving data. $fileinfo_many[$destination_uri] = $fileinfo; } } $cleanvalues['as:image'] = $fileinfo_many; }
php
public function processFileField(array $element, WebformSubmissionInterface $webform_submission, &$cleanvalues) { $key = $element['#webform_key']; $original_data = $webform_submission->getOriginalData(); $value = isset($cleanvalues[$key]) ? $cleanvalues[$key] : []; $fids = (is_array($value)) ? $value : [$value]; $original_value = isset($original_data[$key]) ? $original_data[$key] : []; $original_fids = (is_array($original_value)) ? $original_value : [$original_value]; // Delete the old file uploads? // @TODO build some cleanup logic here. Could be moved to attached field hook. $delete_fids = array_diff($original_fids, $fids); // @TODO what do we do with removed files? // Idea. Check the fileUsage. If there is still some other than this one // don't remove. // But also, if a revision is using it? what a mess! // @see \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::deleteFiles // Exit if there is no fids. if (empty($fids)) { return; } /** @var \Drupal\file\FileInterface[] $files */ try { $files = $this->entityTypeManager->getStorage('file')->loadMultiple( $fids ); } catch (InvalidPluginDefinitionException $e) { } catch (PluginNotFoundException $e) { } $fileinfo_many = []; //@TODO refactor this urgently to a NEW TECHMD class. foreach ($files as $file) { $fileinfo = []; if (isset($cleanvalues['as:image'])) { $fileinfo = $this->check_file_in_metadata( $cleanvalues['as:image'], (int) $file->id() ); if ($fileinfo) { $fileinfo_many[$fileinfo['dr:url']] = $fileinfo; } } if (!$fileinfo) { // Only do this is file was not previusly processed and stored. $uri = $file->getFileUri(); $md5 = md5_file($uri); $fileinfo = [ 'type' => 'Image', 'dr:url' => $uri, 'url' => $uri, 'checksum' => $md5, 'dr:for' => $key, 'dr:fid' => (int) $file->id(), 'name' => $file->getFilename(), ]; $relativefolder = substr($md5, 0, 3); $source_uri = $file->getFileUri(); $realpath_uri = $this->fileSystem->realpath($source_uri); if (empty(!$realpath_uri)) { $command = escapeshellcmd( '/usr/local/bin/fido ' . $realpath_uri . ' -pronom_only -matchprintf ' ); // @TODO handle the exit code from output $output = shell_exec($command . '"OK,%(info.puid)" -q'); } // We will use the original scheme here since our HD operations are over. $destination_uri = $this->getFileDestinationUri( $element, $file, $relativefolder, $webform_submission ); //Use the wished storagepoint as key. //Then the node save hook will deal with moving data. $fileinfo_many[$destination_uri] = $fileinfo; } } $cleanvalues['as:image'] = $fileinfo_many; }
[ "public", "function", "processFileField", "(", "array", "$", "element", ",", "WebformSubmissionInterface", "$", "webform_submission", ",", "&", "$", "cleanvalues", ")", "{", "$", "key", "=", "$", "element", "[", "'#webform_key'", "]", ";", "$", "original_data", ...
Process temp files and make them permanent @param array $element An associative array containing the file webform element. @param \Drupal\webform\webformSubmissionInterface $webform_submission @param $cleanvalues
[ "Process", "temp", "files", "and", "make", "them", "permanent" ]
7b2bd47dc01a948325a44499ff0ec3c8d9fb4efa
https://github.com/esmero/webform_strawberryfield/blob/7b2bd47dc01a948325a44499ff0ec3c8d9fb4efa/src/Plugin/WebformHandler/strawberryFieldharvester.php#L324-L412
train
esmero/webform_strawberryfield
src/Plugin/WebformHandler/strawberryFieldharvester.php
strawberryFieldharvester.getUriSchemeForManagedFile
protected function getUriSchemeForManagedFile(array $element) { if (isset($element['#uri_scheme'])) { return $element['#uri_scheme']; } $scheme_options = \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::getVisibleStreamWrappers(); if (isset($scheme_options['private'])) { return 'private'; } elseif (isset($scheme_options['public'])) { return 'public'; } else { return 'private'; } }
php
protected function getUriSchemeForManagedFile(array $element) { if (isset($element['#uri_scheme'])) { return $element['#uri_scheme']; } $scheme_options = \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::getVisibleStreamWrappers(); if (isset($scheme_options['private'])) { return 'private'; } elseif (isset($scheme_options['public'])) { return 'public'; } else { return 'private'; } }
[ "protected", "function", "getUriSchemeForManagedFile", "(", "array", "$", "element", ")", "{", "if", "(", "isset", "(", "$", "element", "[", "'#uri_scheme'", "]", ")", ")", "{", "return", "$", "element", "[", "'#uri_scheme'", "]", ";", "}", "$", "scheme_op...
Gets valid upload stream wrapper schemes. @param array $element @return mixed|string
[ "Gets", "valid", "upload", "stream", "wrapper", "schemes", "." ]
7b2bd47dc01a948325a44499ff0ec3c8d9fb4efa
https://github.com/esmero/webform_strawberryfield/blob/7b2bd47dc01a948325a44499ff0ec3c8d9fb4efa/src/Plugin/WebformHandler/strawberryFieldharvester.php#L516-L530
train
t9221823420/yii2-base
src/traits/ViewContextTrait.php
ViewContextTrait.getLayoutPath
public function getLayoutPath( $sufix = 'layouts' ) { if( $this->_layoutPath === null ) { $path = parent::getLayoutPath(); if( !is_dir( $path ) && $parentPath = $this->getParentPath( $sufix ) ) { $path = $parentPath; } $this->_layoutPath = $path; } return $this->_layoutPath; }
php
public function getLayoutPath( $sufix = 'layouts' ) { if( $this->_layoutPath === null ) { $path = parent::getLayoutPath(); if( !is_dir( $path ) && $parentPath = $this->getParentPath( $sufix ) ) { $path = $parentPath; } $this->_layoutPath = $path; } return $this->_layoutPath; }
[ "public", "function", "getLayoutPath", "(", "$", "sufix", "=", "'layouts'", ")", "{", "if", "(", "$", "this", "->", "_layoutPath", "===", "null", ")", "{", "$", "path", "=", "parent", "::", "getLayoutPath", "(", ")", ";", "if", "(", "!", "is_dir", "(...
Returns the directory that contains layout view files for this module. @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
[ "Returns", "the", "directory", "that", "contains", "layout", "view", "files", "for", "this", "module", "." ]
61be4e46c41dd466722a38b952defd3e872ed3dd
https://github.com/t9221823420/yii2-base/blob/61be4e46c41dd466722a38b952defd3e872ed3dd/src/traits/ViewContextTrait.php#L38-L54
train
orchestral/installer
src/Processors/Installer.php
Installer.prepare
public function prepare($listener) { if (! $this->requirements->check()) { return $listener->preparationNotCompleted(); } $this->installer->migrate(); return $listener->preparationCompleted(); }
php
public function prepare($listener) { if (! $this->requirements->check()) { return $listener->preparationNotCompleted(); } $this->installer->migrate(); return $listener->preparationCompleted(); }
[ "public", "function", "prepare", "(", "$", "listener", ")", "{", "if", "(", "!", "$", "this", "->", "requirements", "->", "check", "(", ")", ")", "{", "return", "$", "listener", "->", "preparationNotCompleted", "(", ")", ";", "}", "$", "this", "->", ...
Run migration and prepare the database. @param object $listener @return mixed
[ "Run", "migration", "and", "prepare", "the", "database", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Processors/Installer.php#L72-L81
train
orchestral/installer
src/Processors/Installer.php
Installer.create
public function create($listener) { $model = new Fluent([ 'site' => ['name' => \config('app.name', 'Orchestra Platform')], ]); $form = $this->presenter->form($model); return $listener->createSucceed(\compact('form', 'model')); }
php
public function create($listener) { $model = new Fluent([ 'site' => ['name' => \config('app.name', 'Orchestra Platform')], ]); $form = $this->presenter->form($model); return $listener->createSucceed(\compact('form', 'model')); }
[ "public", "function", "create", "(", "$", "listener", ")", "{", "$", "model", "=", "new", "Fluent", "(", "[", "'site'", "=>", "[", "'name'", "=>", "\\", "config", "(", "'app.name'", ",", "'Orchestra Platform'", ")", "]", ",", "]", ")", ";", "$", "for...
Display initial user and site configuration page. @param object $listener @return mixed
[ "Display", "initial", "user", "and", "site", "configuration", "page", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Processors/Installer.php#L90-L99
train
orchestral/installer
src/Concerns/FileLoader.php
FileLoader.requireInstallerFiles
protected function requireInstallerFiles(bool $once = true): void { $paths = \config('orchestra/installer::installers.paths', []); $method = ($once === true ? 'requireOnce' : 'getRequire'); foreach ($paths as $path) { $file = \rtrim($path, '/').'/installer.php'; if (File::exists($file)) { File::{$method}($file); } } }
php
protected function requireInstallerFiles(bool $once = true): void { $paths = \config('orchestra/installer::installers.paths', []); $method = ($once === true ? 'requireOnce' : 'getRequire'); foreach ($paths as $path) { $file = \rtrim($path, '/').'/installer.php'; if (File::exists($file)) { File::{$method}($file); } } }
[ "protected", "function", "requireInstallerFiles", "(", "bool", "$", "once", "=", "true", ")", ":", "void", "{", "$", "paths", "=", "\\", "config", "(", "'orchestra/installer::installers.paths'", ",", "[", "]", ")", ";", "$", "method", "=", "(", "$", "once"...
Requires the installer files. @param bool $once @return void
[ "Requires", "the", "installer", "files", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Concerns/FileLoader.php#L43-L56
train
globalis-ms/puppet-skilled-framework
src/Queue/Service.php
Service.dispatch
public function dispatch(Queueable $job) { if (isset($job->queue, $job->delay)) { return $this->connection->laterOn($job->queue, $job->delay, $job); } if (isset($job->queue)) { return $this->connection->pushOn($job->queue, $job); } if (isset($job->delay)) { return $this->connection->later($job->delay, $job); } return $this->connection->push($job); }
php
public function dispatch(Queueable $job) { if (isset($job->queue, $job->delay)) { return $this->connection->laterOn($job->queue, $job->delay, $job); } if (isset($job->queue)) { return $this->connection->pushOn($job->queue, $job); } if (isset($job->delay)) { return $this->connection->later($job->delay, $job); } return $this->connection->push($job); }
[ "public", "function", "dispatch", "(", "Queueable", "$", "job", ")", "{", "if", "(", "isset", "(", "$", "job", "->", "queue", ",", "$", "job", "->", "delay", ")", ")", "{", "return", "$", "this", "->", "connection", "->", "laterOn", "(", "$", "job"...
Dispatch a job behind a queue. @param \Globalis\PuppetSkilled\Queue\Queueable $job @return mixed
[ "Dispatch", "a", "job", "behind", "a", "queue", "." ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Queue/Service.php#L32-L45
train
globalis-ms/puppet-skilled-framework
src/Queue/Service.php
Service.failJob
protected function failJob($job, $e) { if ($job->isDeleted()) { return; } $job->delete(); $job->failed($e); }
php
protected function failJob($job, $e) { if ($job->isDeleted()) { return; } $job->delete(); $job->failed($e); }
[ "protected", "function", "failJob", "(", "$", "job", ",", "$", "e", ")", "{", "if", "(", "$", "job", "->", "isDeleted", "(", ")", ")", "{", "return", ";", "}", "$", "job", "->", "delete", "(", ")", ";", "$", "job", "->", "failed", "(", "$", "...
Mark the given job as failed and raise the relevant event. @param \Globlias\PuppetSkilled\Queue\Job\Base $job @param \Exception $e @return void
[ "Mark", "the", "given", "job", "as", "failed", "and", "raise", "the", "relevant", "event", "." ]
4bb9ff30a32210f54add1f0e53d4769d26eb3c29
https://github.com/globalis-ms/puppet-skilled-framework/blob/4bb9ff30a32210f54add1f0e53d4769d26eb3c29/src/Queue/Service.php#L134-L141
train
canax/textfilter
src/TextFilter/TShortcode.php
TShortcode.shortCode
public function shortCode($text) { /* Needs PHP 7 $patternsAndCallbacks = [ "/\[(FIGURE)[\s+](.+)\]/" => function ($match) { return self::ShortCodeFigure($matches[2]); }, "/(```([\w]*))\n([^`]*)```[\n]{1}/s" => function ($match) { return $this->syntaxHighlightGeSHi($matches[3], $matches[2]); }, ]; return preg_replace_callback_array($patternsAndCallbacks, $text); */ $patterns = [ "/\[(FIGURE)[\s+](.+)\]/", //'/\[(YOUTUBE) src=(.+) width=(.+) caption=(.+)\]/', "/\[(YOUTUBE)[\s+](.+)\]/", "/\[(CODEPEN)[\s+](.+)\]/", "/\[(ASCIINEMA)[\s+](.+)\]/", "/\[(BOOK)[\s+](.+)\]/", //"/(```)([\w]*)\n([.]*)```[\n]{1}/s", "/(```)([\w]*)\n(.*?)```\n/s", '/\[(INFO)\]/', '/\[(\/INFO)\]/', '/\[(WARNING)\]/', '/\[(\/WARNING)\]/', ]; return preg_replace_callback( $patterns, function ($matches) { switch ($matches[1]) { case "FIGURE": return self::shortCodeFigure($matches[2]); break; case "YOUTUBE": return self::shortCodeYoutube($matches[2]); break; case "CODEPEN": return self::shortCodeCodepen($matches[2]); break; case "ASCIINEMA": return self::shortCodeAsciinema($matches[2]); break; case "BOOK": return self::shortCodeBook($matches[2]); break; case "```": //return $this->syntaxHighlightGeSHi($matches[3], $matches[2]); return $this->syntaxHighlightJs($matches[3], $matches[2]); break; case 'INFO': return <<<EOD <div class="info"> <span class="icon fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-info fa-stack-1x fa-inverse" aria-hidden="true"></i> </span> <div markdown=1> EOD; break; case 'WARNING': return <<<EOD <div class="warning"> <span class="icon fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-exclamation-triangle fa-stack-1x fa-inverse" aria-hidden="true"></i> </span> <div markdown=1> EOD; break; case '/INFO': case '/WARNING': return "</div></div>"; break; default: return "{$matches[1]} is unknown shortcode."; } }, $text ); }
php
public function shortCode($text) { /* Needs PHP 7 $patternsAndCallbacks = [ "/\[(FIGURE)[\s+](.+)\]/" => function ($match) { return self::ShortCodeFigure($matches[2]); }, "/(```([\w]*))\n([^`]*)```[\n]{1}/s" => function ($match) { return $this->syntaxHighlightGeSHi($matches[3], $matches[2]); }, ]; return preg_replace_callback_array($patternsAndCallbacks, $text); */ $patterns = [ "/\[(FIGURE)[\s+](.+)\]/", //'/\[(YOUTUBE) src=(.+) width=(.+) caption=(.+)\]/', "/\[(YOUTUBE)[\s+](.+)\]/", "/\[(CODEPEN)[\s+](.+)\]/", "/\[(ASCIINEMA)[\s+](.+)\]/", "/\[(BOOK)[\s+](.+)\]/", //"/(```)([\w]*)\n([.]*)```[\n]{1}/s", "/(```)([\w]*)\n(.*?)```\n/s", '/\[(INFO)\]/', '/\[(\/INFO)\]/', '/\[(WARNING)\]/', '/\[(\/WARNING)\]/', ]; return preg_replace_callback( $patterns, function ($matches) { switch ($matches[1]) { case "FIGURE": return self::shortCodeFigure($matches[2]); break; case "YOUTUBE": return self::shortCodeYoutube($matches[2]); break; case "CODEPEN": return self::shortCodeCodepen($matches[2]); break; case "ASCIINEMA": return self::shortCodeAsciinema($matches[2]); break; case "BOOK": return self::shortCodeBook($matches[2]); break; case "```": //return $this->syntaxHighlightGeSHi($matches[3], $matches[2]); return $this->syntaxHighlightJs($matches[3], $matches[2]); break; case 'INFO': return <<<EOD <div class="info"> <span class="icon fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-info fa-stack-1x fa-inverse" aria-hidden="true"></i> </span> <div markdown=1> EOD; break; case 'WARNING': return <<<EOD <div class="warning"> <span class="icon fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-exclamation-triangle fa-stack-1x fa-inverse" aria-hidden="true"></i> </span> <div markdown=1> EOD; break; case '/INFO': case '/WARNING': return "</div></div>"; break; default: return "{$matches[1]} is unknown shortcode."; } }, $text ); }
[ "public", "function", "shortCode", "(", "$", "text", ")", "{", "/* Needs PHP 7\n $patternsAndCallbacks = [\n \"/\\[(FIGURE)[\\s+](.+)\\]/\" => function ($match) {\n return self::ShortCodeFigure($matches[2]);\n },\n \"/(```([\\w]*))\\n([^`]*)```[...
Shortcode to quicker format text as HTML. @param string $text text to be converted. @return string the formatted text.
[ "Shortcode", "to", "quicker", "format", "text", "as", "HTML", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TShortcode.php#L18-L110
train
canax/textfilter
src/TextFilter/TShortcode.php
TShortcode.shortCodeInit
public static function shortCodeInit($options) { preg_match_all('/[a-zA-Z0-9]+="[^"]+"|\S+/', $options, $matches); $res = array(); foreach ($matches[0] as $match) { $pos = strpos($match, '='); if ($pos === false) { $res[$match] = true; } else { $key = substr($match, 0, $pos); $val = trim(substr($match, $pos+1), '"'); $res[$key] = $val; } } return $res; }
php
public static function shortCodeInit($options) { preg_match_all('/[a-zA-Z0-9]+="[^"]+"|\S+/', $options, $matches); $res = array(); foreach ($matches[0] as $match) { $pos = strpos($match, '='); if ($pos === false) { $res[$match] = true; } else { $key = substr($match, 0, $pos); $val = trim(substr($match, $pos+1), '"'); $res[$key] = $val; } } return $res; }
[ "public", "static", "function", "shortCodeInit", "(", "$", "options", ")", "{", "preg_match_all", "(", "'/[a-zA-Z0-9]+=\"[^\"]+\"|\\S+/'", ",", "$", "options", ",", "$", "matches", ")", ";", "$", "res", "=", "array", "(", ")", ";", "foreach", "(", "$", "ma...
Init shortcode handling by preparing the option list to an array, for those using arguments. @param string $options for the shortcode. @return array with all the options.
[ "Init", "shortcode", "handling", "by", "preparing", "the", "option", "list", "to", "an", "array", "for", "those", "using", "arguments", "." ]
a90177cd404b093541222fd0d6cf71907ac2ce25
https://github.com/canax/textfilter/blob/a90177cd404b093541222fd0d6cf71907ac2ce25/src/TextFilter/TShortcode.php#L122-L139
train
Arachne/Forms
src/Application/FormComponent.php
FormComponent.processSubmit
protected function processSubmit(FormInterface $form, Request $request): void { // Restored request should only render the form, not immediately submit it. if ($request->hasFlag(Request::RESTORED)) { return; } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $data = $form->getData(); if ($form->isValid()) { $this->onSuccess($data, $this); } else { $this->onError($data, $this); } $this->onSubmit($data, $this); }
php
protected function processSubmit(FormInterface $form, Request $request): void { // Restored request should only render the form, not immediately submit it. if ($request->hasFlag(Request::RESTORED)) { return; } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $data = $form->getData(); if ($form->isValid()) { $this->onSuccess($data, $this); } else { $this->onError($data, $this); } $this->onSubmit($data, $this); }
[ "protected", "function", "processSubmit", "(", "FormInterface", "$", "form", ",", "Request", "$", "request", ")", ":", "void", "{", "// Restored request should only render the form, not immediately submit it.", "if", "(", "$", "request", "->", "hasFlag", "(", "Request",...
Submits the form.
[ "Submits", "the", "form", "." ]
8b43ec55eca9e5a5946cc40d6840f539b6936371
https://github.com/Arachne/Forms/blob/8b43ec55eca9e5a5946cc40d6840f539b6936371/src/Application/FormComponent.php#L171-L190
train
Arachne/Forms
src/Application/FormComponent.php
FormComponent.processValidate
protected function processValidate(FormInterface $form, Request $request): void { /** @var Presenter $presenter */ $presenter = $this->getPresenter(); if (!$presenter->isAjax()) { throw new BadRequestException('The validate signal is only allowed in ajax mode.'); } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $view = $this->getView(); $errors = []; $this->walkErrors( $form->getErrors(true, false), $view, function (FormView $view) use (&$errors) { $errors[$view->vars['id']] = $this->renderer->searchAndRenderBlock($view, 'errors_content'); } ); $presenter->sendJson((object) ['errors' => $errors]); }
php
protected function processValidate(FormInterface $form, Request $request): void { /** @var Presenter $presenter */ $presenter = $this->getPresenter(); if (!$presenter->isAjax()) { throw new BadRequestException('The validate signal is only allowed in ajax mode.'); } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $view = $this->getView(); $errors = []; $this->walkErrors( $form->getErrors(true, false), $view, function (FormView $view) use (&$errors) { $errors[$view->vars['id']] = $this->renderer->searchAndRenderBlock($view, 'errors_content'); } ); $presenter->sendJson((object) ['errors' => $errors]); }
[ "protected", "function", "processValidate", "(", "FormInterface", "$", "form", ",", "Request", "$", "request", ")", ":", "void", "{", "/** @var Presenter $presenter */", "$", "presenter", "=", "$", "this", "->", "getPresenter", "(", ")", ";", "if", "(", "!", ...
Provides ajax validation.
[ "Provides", "ajax", "validation", "." ]
8b43ec55eca9e5a5946cc40d6840f539b6936371
https://github.com/Arachne/Forms/blob/8b43ec55eca9e5a5946cc40d6840f539b6936371/src/Application/FormComponent.php#L195-L219
train
Arachne/Forms
src/Application/FormComponent.php
FormComponent.processRender
protected function processRender(FormInterface $form, Request $request): void { /** @var Presenter $presenter */ $presenter = $this->getPresenter(); if (!$presenter->isAjax()) { throw new BadRequestException('The render signal is only allowed in ajax mode.'); } $fields = $request->getPost($this->lookupPath(Presenter::class, true).self::NAME_SEPARATOR.'fields'); if (!$fields) { throw new BadRequestException('No fields specified for rendering.'); } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $view = $this->getView(); $widgets = []; foreach ($fields as $field) { // Validate the field identifier for security reasons. A dot in the identifier would be particularly dangerous. if (!Strings::match($field, '~^(?:\[\w++\])++$~')) { throw new BadRequestException( sprintf('Field identifier "%s" contains unallowed characters.', $field) ); } // Skip duplicates. The renderer would return an empty string on second try. if (isset($widgets[$field])) { continue; } // Wrap an exception from PropertyAccessor in a BadRequestException. try { $fieldView = $this->propertyAccessor->getValue($view, $field); } catch (ExceptionInterface $e) { throw new BadRequestException( sprintf('FormView not found for field identifier "%s".', $field), 0, $e ); } // Render the field widget. $widgets[$field] = $this->renderer->searchAndRenderBlock($fieldView, 'widget'); } $presenter->sendJson((object) ['widgets' => $widgets]); }
php
protected function processRender(FormInterface $form, Request $request): void { /** @var Presenter $presenter */ $presenter = $this->getPresenter(); if (!$presenter->isAjax()) { throw new BadRequestException('The render signal is only allowed in ajax mode.'); } $fields = $request->getPost($this->lookupPath(Presenter::class, true).self::NAME_SEPARATOR.'fields'); if (!$fields) { throw new BadRequestException('No fields specified for rendering.'); } $form->handleRequest($request); if (!$form->isSubmitted()) { throw new BadRequestException('The form was not submitted.'); } $view = $this->getView(); $widgets = []; foreach ($fields as $field) { // Validate the field identifier for security reasons. A dot in the identifier would be particularly dangerous. if (!Strings::match($field, '~^(?:\[\w++\])++$~')) { throw new BadRequestException( sprintf('Field identifier "%s" contains unallowed characters.', $field) ); } // Skip duplicates. The renderer would return an empty string on second try. if (isset($widgets[$field])) { continue; } // Wrap an exception from PropertyAccessor in a BadRequestException. try { $fieldView = $this->propertyAccessor->getValue($view, $field); } catch (ExceptionInterface $e) { throw new BadRequestException( sprintf('FormView not found for field identifier "%s".', $field), 0, $e ); } // Render the field widget. $widgets[$field] = $this->renderer->searchAndRenderBlock($fieldView, 'widget'); } $presenter->sendJson((object) ['widgets' => $widgets]); }
[ "protected", "function", "processRender", "(", "FormInterface", "$", "form", ",", "Request", "$", "request", ")", ":", "void", "{", "/** @var Presenter $presenter */", "$", "presenter", "=", "$", "this", "->", "getPresenter", "(", ")", ";", "if", "(", "!", "...
Renders only specified fields. Useful for dynamic ajax forms.
[ "Renders", "only", "specified", "fields", ".", "Useful", "for", "dynamic", "ajax", "forms", "." ]
8b43ec55eca9e5a5946cc40d6840f539b6936371
https://github.com/Arachne/Forms/blob/8b43ec55eca9e5a5946cc40d6840f539b6936371/src/Application/FormComponent.php#L237-L286
train
brightnucleus/shortcodes
src/ShortcodeUI.php
ShortcodeUI.register
public function register( $context = null ) { if ( ! $this->is_needed() ) { return; } \shortcode_ui_register_for_shortcode( $this->shortcode_tag, $this->config ); }
php
public function register( $context = null ) { if ( ! $this->is_needed() ) { return; } \shortcode_ui_register_for_shortcode( $this->shortcode_tag, $this->config ); }
[ "public", "function", "register", "(", "$", "context", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "is_needed", "(", ")", ")", "{", "return", ";", "}", "\\", "shortcode_ui_register_for_shortcode", "(", "$", "this", "->", "shortcode_tag", ",...
Register the shortcode UI handler function with WordPress. @since 0.1.0 @param mixed $context Data about the context in which the call is made. @return void
[ "Register", "the", "shortcode", "UI", "handler", "function", "with", "WordPress", "." ]
5db6fa3c18db856ab550e56960a844d6aa99dabb
https://github.com/brightnucleus/shortcodes/blob/5db6fa3c18db856ab550e56960a844d6aa99dabb/src/ShortcodeUI.php#L80-L89
train
clue/reactphp-quassel
src/Io/DatastreamProtocol.php
DatastreamProtocol.mapToList
public function mapToList($map) { $list = array(); foreach ($map as $key => $value) { // explicitly pass key as UTF-8 byte array // pass value with automatic type detection $list []= new QVariant($key, Types::TYPE_QBYTE_ARRAY); $list []= $value; } return $list; }
php
public function mapToList($map) { $list = array(); foreach ($map as $key => $value) { // explicitly pass key as UTF-8 byte array // pass value with automatic type detection $list []= new QVariant($key, Types::TYPE_QBYTE_ARRAY); $list []= $value; } return $list; }
[ "public", "function", "mapToList", "(", "$", "map", ")", "{", "$", "list", "=", "array", "(", ")", ";", "foreach", "(", "$", "map", "as", "$", "key", "=>", "$", "value", ")", "{", "// explicitly pass key as UTF-8 byte array", "// pass value with automatic type...
converts the given map to a list @param mixed[]|array<mixed> $map @return mixed[]|array<mixed> @internal
[ "converts", "the", "given", "map", "to", "a", "list" ]
379d63fdfc068d3571985a2afeea50c248ad3014
https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Io/DatastreamProtocol.php#L101-L111
train
clue/reactphp-quassel
src/Io/DatastreamProtocol.php
DatastreamProtocol.listToMap
public function listToMap(array $list) { $map = array(); for ($i = 0, $n = count($list); $i < $n; $i += 2) { $map[$list[$i]] = $list[$i + 1]; } return (object)$map; }
php
public function listToMap(array $list) { $map = array(); for ($i = 0, $n = count($list); $i < $n; $i += 2) { $map[$list[$i]] = $list[$i + 1]; } return (object)$map; }
[ "public", "function", "listToMap", "(", "array", "$", "list", ")", "{", "$", "map", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ",", "$", "n", "=", "count", "(", "$", "list", ")", ";", "$", "i", "<", "$", "n", ";", "$", "...
converts the given list to a map @param mixed[]|array<mixed> $list @return \stdClass `map<string,mixed>` @internal
[ "converts", "the", "given", "list", "to", "a", "map" ]
379d63fdfc068d3571985a2afeea50c248ad3014
https://github.com/clue/reactphp-quassel/blob/379d63fdfc068d3571985a2afeea50c248ad3014/src/Io/DatastreamProtocol.php#L120-L127
train
orchestral/installer
src/Installation.php
Installation.make
public function make(array $input, bool $multiple = true): bool { try { $this->validate($input); } catch (ValidationException $e) { Session::flash('errors', $e->validator->messages()); return false; } try { ! $multiple && $this->hasNoExistingUser(); $this->create( $this->createUser($input), $input ); // Installation is successful, we should be able to generate // success message to notify the user. Installer route will be // disabled after this point. Messages::add('success', \trans('orchestra/foundation::install.user.created')); return true; } catch (Exception $e) { Messages::add('error', $e->getMessage()); } return false; }
php
public function make(array $input, bool $multiple = true): bool { try { $this->validate($input); } catch (ValidationException $e) { Session::flash('errors', $e->validator->messages()); return false; } try { ! $multiple && $this->hasNoExistingUser(); $this->create( $this->createUser($input), $input ); // Installation is successful, we should be able to generate // success message to notify the user. Installer route will be // disabled after this point. Messages::add('success', \trans('orchestra/foundation::install.user.created')); return true; } catch (Exception $e) { Messages::add('error', $e->getMessage()); } return false; }
[ "public", "function", "make", "(", "array", "$", "input", ",", "bool", "$", "multiple", "=", "true", ")", ":", "bool", "{", "try", "{", "$", "this", "->", "validate", "(", "$", "input", ")", ";", "}", "catch", "(", "ValidationException", "$", "e", ...
Create adminstrator account. @param array $input @param bool $multiple @return bool
[ "Create", "adminstrator", "account", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Installation.php#L62-L90
train
orchestral/installer
src/Installation.php
Installation.create
public function create(User $user, array $input): void { $memory = \app('orchestra.memory')->make(); // Bootstrap auth services, so we can use orchestra/auth package // configuration. $actions = ['Manage Orchestra', 'Manage Users']; $admin = \config('orchestra/foundation::roles.admin', 1); $roles = Role::pluck('name', 'id')->all(); $theme = [ 'frontend' => 'default', 'backend' => 'default', ]; // Attach Administrator role to the newly created administrator. $user->roles()->sync([$admin]); // Add some basic configuration for Orchestra Platform, including // email configuration. $memory->put('site.name', $input['site_name']); $memory->put('site.theme', $theme); $memory->put('email', \config('mail')); $memory->put('email.from', [ 'name' => $input['site_name'], 'address' => $input['email'], ]); // We should also create a basic ACL for Orchestra Platform, since // the basic roles is create using Fluent Query Builder we need // to manually insert the roles. $acl = \app('orchestra.platform.acl'); $acl->attach($memory); $acl->actions()->attach($actions); $acl->roles()->attach(\array_values($roles)); $acl->allow($roles[$admin], $actions); \event('orchestra.install: acl', [$acl]); }
php
public function create(User $user, array $input): void { $memory = \app('orchestra.memory')->make(); // Bootstrap auth services, so we can use orchestra/auth package // configuration. $actions = ['Manage Orchestra', 'Manage Users']; $admin = \config('orchestra/foundation::roles.admin', 1); $roles = Role::pluck('name', 'id')->all(); $theme = [ 'frontend' => 'default', 'backend' => 'default', ]; // Attach Administrator role to the newly created administrator. $user->roles()->sync([$admin]); // Add some basic configuration for Orchestra Platform, including // email configuration. $memory->put('site.name', $input['site_name']); $memory->put('site.theme', $theme); $memory->put('email', \config('mail')); $memory->put('email.from', [ 'name' => $input['site_name'], 'address' => $input['email'], ]); // We should also create a basic ACL for Orchestra Platform, since // the basic roles is create using Fluent Query Builder we need // to manually insert the roles. $acl = \app('orchestra.platform.acl'); $acl->attach($memory); $acl->actions()->attach($actions); $acl->roles()->attach(\array_values($roles)); $acl->allow($roles[$admin], $actions); \event('orchestra.install: acl', [$acl]); }
[ "public", "function", "create", "(", "User", "$", "user", ",", "array", "$", "input", ")", ":", "void", "{", "$", "memory", "=", "\\", "app", "(", "'orchestra.memory'", ")", "->", "make", "(", ")", ";", "// Bootstrap auth services, so we can use orchestra/auth...
Run application setup. @param \Orchestra\Model\User $user @param array $input @return void
[ "Run", "application", "setup", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Installation.php#L100-L138
train
orchestral/installer
src/Installation.php
Installation.validate
public function validate(array $input): bool { // Grab input fields and define the rules for user validations. $rules = [ 'email' => ['required', 'email'], 'password' => ['required'], 'fullname' => ['required'], 'site_name' => ['required'], ]; $validation = \app('validator')->make($input, $rules); // Validate user registration, we should stop this process if // the user not properly formatted. if ($validation->fails()) { throw new ValidationException($validation); } return true; }
php
public function validate(array $input): bool { // Grab input fields and define the rules for user validations. $rules = [ 'email' => ['required', 'email'], 'password' => ['required'], 'fullname' => ['required'], 'site_name' => ['required'], ]; $validation = \app('validator')->make($input, $rules); // Validate user registration, we should stop this process if // the user not properly formatted. if ($validation->fails()) { throw new ValidationException($validation); } return true; }
[ "public", "function", "validate", "(", "array", "$", "input", ")", ":", "bool", "{", "// Grab input fields and define the rules for user validations.", "$", "rules", "=", "[", "'email'", "=>", "[", "'required'", ",", "'email'", "]", ",", "'password'", "=>", "[", ...
Validate request. @param array $input @throws \Illuminate\Validation\ValidationException @return bool
[ "Validate", "request", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Installation.php#L149-L168
train
orchestral/installer
src/Installation.php
Installation.createUser
public function createUser(array $input): User { User::unguard(); $user = new User([ 'email' => $input['email'], 'password' => $input['password'], 'fullname' => $input['fullname'], 'status' => User::VERIFIED, ]); \event('orchestra.install: user', [$user, $input]); $user->save(); return $user; }
php
public function createUser(array $input): User { User::unguard(); $user = new User([ 'email' => $input['email'], 'password' => $input['password'], 'fullname' => $input['fullname'], 'status' => User::VERIFIED, ]); \event('orchestra.install: user', [$user, $input]); $user->save(); return $user; }
[ "public", "function", "createUser", "(", "array", "$", "input", ")", ":", "User", "{", "User", "::", "unguard", "(", ")", ";", "$", "user", "=", "new", "User", "(", "[", "'email'", "=>", "$", "input", "[", "'email'", "]", ",", "'password'", "=>", "...
Create user account. @param array $input @return \Orchestra\Model\User
[ "Create", "user", "account", "." ]
f49e251916567ce461b2dc47017fc8d8959ae6cc
https://github.com/orchestral/installer/blob/f49e251916567ce461b2dc47017fc8d8959ae6cc/src/Installation.php#L177-L193
train