id
int32
0
241k
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
32,900
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.parseLog
protected function parseLog($content, $allowedEnvironment = null, $allowedLevel = []) { $log = []; $parsed = $this->parser->parseLogContent($content); extract($parsed, EXTR_PREFIX_ALL, 'parsed'); if (empty($parsed_headerSet)) { return $log; } $needReFormat = in_array('Next', $parsed_headerSet); $newContent = null; foreach ($parsed_headerSet as $key => $header) { if (empty($parsed_dateSet[$key])) { $parsed_dateSet[$key] = $parsed_dateSet[$key-1]; $parsed_envSet[$key] = $parsed_envSet[$key-1]; $parsed_levelSet[$key] = $parsed_levelSet[$key-1]; $header = str_replace("Next", $parsed_headerSet[$key-1], $header); } $newContent .= $header.' '.$parsed_bodySet[$key]; if ((empty($allowedEnvironment) || $allowedEnvironment == $parsed_envSet[$key]) && $this->levelable->filter($parsed_levelSet[$key], $allowedLevel)) { $log[] = [ 'environment' => $parsed_envSet[$key], 'level' => $parsed_levelSet[$key], 'date' => $parsed_dateSet[$key], 'file_path' => $this->getCurrentLogPath(), 'header' => $header, 'body' => $parsed_bodySet[$key] ]; } } if ($needReFormat) { file_put_contents($this->getCurrentLogPath(), $newContent); } return $log; }
php
protected function parseLog($content, $allowedEnvironment = null, $allowedLevel = []) { $log = []; $parsed = $this->parser->parseLogContent($content); extract($parsed, EXTR_PREFIX_ALL, 'parsed'); if (empty($parsed_headerSet)) { return $log; } $needReFormat = in_array('Next', $parsed_headerSet); $newContent = null; foreach ($parsed_headerSet as $key => $header) { if (empty($parsed_dateSet[$key])) { $parsed_dateSet[$key] = $parsed_dateSet[$key-1]; $parsed_envSet[$key] = $parsed_envSet[$key-1]; $parsed_levelSet[$key] = $parsed_levelSet[$key-1]; $header = str_replace("Next", $parsed_headerSet[$key-1], $header); } $newContent .= $header.' '.$parsed_bodySet[$key]; if ((empty($allowedEnvironment) || $allowedEnvironment == $parsed_envSet[$key]) && $this->levelable->filter($parsed_levelSet[$key], $allowedLevel)) { $log[] = [ 'environment' => $parsed_envSet[$key], 'level' => $parsed_levelSet[$key], 'date' => $parsed_dateSet[$key], 'file_path' => $this->getCurrentLogPath(), 'header' => $header, 'body' => $parsed_bodySet[$key] ]; } } if ($needReFormat) { file_put_contents($this->getCurrentLogPath(), $newContent); } return $log; }
[ "protected", "function", "parseLog", "(", "$", "content", ",", "$", "allowedEnvironment", "=", "null", ",", "$", "allowedLevel", "=", "[", "]", ")", "{", "$", "log", "=", "[", "]", ";", "$", "parsed", "=", "$", "this", "->", "parser", "->", "parseLogContent", "(", "$", "content", ")", ";", "extract", "(", "$", "parsed", ",", "EXTR_PREFIX_ALL", ",", "'parsed'", ")", ";", "if", "(", "empty", "(", "$", "parsed_headerSet", ")", ")", "{", "return", "$", "log", ";", "}", "$", "needReFormat", "=", "in_array", "(", "'Next'", ",", "$", "parsed_headerSet", ")", ";", "$", "newContent", "=", "null", ";", "foreach", "(", "$", "parsed_headerSet", "as", "$", "key", "=>", "$", "header", ")", "{", "if", "(", "empty", "(", "$", "parsed_dateSet", "[", "$", "key", "]", ")", ")", "{", "$", "parsed_dateSet", "[", "$", "key", "]", "=", "$", "parsed_dateSet", "[", "$", "key", "-", "1", "]", ";", "$", "parsed_envSet", "[", "$", "key", "]", "=", "$", "parsed_envSet", "[", "$", "key", "-", "1", "]", ";", "$", "parsed_levelSet", "[", "$", "key", "]", "=", "$", "parsed_levelSet", "[", "$", "key", "-", "1", "]", ";", "$", "header", "=", "str_replace", "(", "\"Next\"", ",", "$", "parsed_headerSet", "[", "$", "key", "-", "1", "]", ",", "$", "header", ")", ";", "}", "$", "newContent", ".=", "$", "header", ".", "' '", ".", "$", "parsed_bodySet", "[", "$", "key", "]", ";", "if", "(", "(", "empty", "(", "$", "allowedEnvironment", ")", "||", "$", "allowedEnvironment", "==", "$", "parsed_envSet", "[", "$", "key", "]", ")", "&&", "$", "this", "->", "levelable", "->", "filter", "(", "$", "parsed_levelSet", "[", "$", "key", "]", ",", "$", "allowedLevel", ")", ")", "{", "$", "log", "[", "]", "=", "[", "'environment'", "=>", "$", "parsed_envSet", "[", "$", "key", "]", ",", "'level'", "=>", "$", "parsed_levelSet", "[", "$", "key", "]", ",", "'date'", "=>", "$", "parsed_dateSet", "[", "$", "key", "]", ",", "'file_path'", "=>", "$", "this", "->", "getCurrentLogPath", "(", ")", ",", "'header'", "=>", "$", "header", ",", "'body'", "=>", "$", "parsed_bodySet", "[", "$", "key", "]", "]", ";", "}", "}", "if", "(", "$", "needReFormat", ")", "{", "file_put_contents", "(", "$", "this", "->", "getCurrentLogPath", "(", ")", ",", "$", "newContent", ")", ";", "}", "return", "$", "log", ";", "}" ]
Parses the content of the file separating the errors into a single array. @param string $content @param string $allowedEnvironment @param array $allowedLevel @return array
[ "Parses", "the", "content", "of", "the", "file", "separating", "the", "errors", "into", "a", "single", "array", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L697-L739
32,901
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogReader.php
LogReader.getLogFileList
protected function getLogFileList($forceName = null) { $path = $this->getLogPath(); if (is_dir($path)) { /* * Matches files in the log directory with the special name' */ $logPath = sprintf('%s%s%s', $path, DIRECTORY_SEPARATOR, $this->getLogFilename()); /* * Force matches all files in the log directory' */ if (!is_null($forceName)) { $logPath = sprintf('%s%s%s', $path, DIRECTORY_SEPARATOR, $forceName); } return glob($logPath, GLOB_BRACE); } return false; }
php
protected function getLogFileList($forceName = null) { $path = $this->getLogPath(); if (is_dir($path)) { /* * Matches files in the log directory with the special name' */ $logPath = sprintf('%s%s%s', $path, DIRECTORY_SEPARATOR, $this->getLogFilename()); /* * Force matches all files in the log directory' */ if (!is_null($forceName)) { $logPath = sprintf('%s%s%s', $path, DIRECTORY_SEPARATOR, $forceName); } return glob($logPath, GLOB_BRACE); } return false; }
[ "protected", "function", "getLogFileList", "(", "$", "forceName", "=", "null", ")", "{", "$", "path", "=", "$", "this", "->", "getLogPath", "(", ")", ";", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "/*\n * Matches files in the log directory with the special name'\n */", "$", "logPath", "=", "sprintf", "(", "'%s%s%s'", ",", "$", "path", ",", "DIRECTORY_SEPARATOR", ",", "$", "this", "->", "getLogFilename", "(", ")", ")", ";", "/*\n * Force matches all files in the log directory'\n */", "if", "(", "!", "is_null", "(", "$", "forceName", ")", ")", "{", "$", "logPath", "=", "sprintf", "(", "'%s%s%s'", ",", "$", "path", ",", "DIRECTORY_SEPARATOR", ",", "$", "forceName", ")", ";", "}", "return", "glob", "(", "$", "logPath", ",", "GLOB_BRACE", ")", ";", "}", "return", "false", ";", "}" ]
Returns an array of log file paths. @param null|string $forceName @return bool|array
[ "Returns", "an", "array", "of", "log", "file", "paths", "." ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogReader.php#L774-L796
32,902
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogParser.php
LogParser.parseLogContent
public function parseLogContent($content) { $headerSet = $dateSet = $envSet = $levelSet = $bodySet = []; $pattern = "/^" .self::LOG_DATE_PATTERN. "\s" .self::LOG_ENVIRONMENT_PATTERN. "\." .self::LOG_LEVEL_PATTERN. "\:|Next/m"; preg_match_all($pattern, $content, $matchs); if (is_array($matchs)) { $bodySet = array_map('ltrim', preg_split($pattern, $content)); if (empty($bodySet[0]) && count($bodySet) > count($matchs[0])) { array_shift($bodySet); } $headerSet = $matchs[0]; $dateSet = $matchs[1]; $envSet = $matchs[2]; $levelSet = $matchs[3]; $bodySet = $bodySet; } return compact('headerSet', 'dateSet', 'envSet', 'levelSet', 'bodySet'); }
php
public function parseLogContent($content) { $headerSet = $dateSet = $envSet = $levelSet = $bodySet = []; $pattern = "/^" .self::LOG_DATE_PATTERN. "\s" .self::LOG_ENVIRONMENT_PATTERN. "\." .self::LOG_LEVEL_PATTERN. "\:|Next/m"; preg_match_all($pattern, $content, $matchs); if (is_array($matchs)) { $bodySet = array_map('ltrim', preg_split($pattern, $content)); if (empty($bodySet[0]) && count($bodySet) > count($matchs[0])) { array_shift($bodySet); } $headerSet = $matchs[0]; $dateSet = $matchs[1]; $envSet = $matchs[2]; $levelSet = $matchs[3]; $bodySet = $bodySet; } return compact('headerSet', 'dateSet', 'envSet', 'levelSet', 'bodySet'); }
[ "public", "function", "parseLogContent", "(", "$", "content", ")", "{", "$", "headerSet", "=", "$", "dateSet", "=", "$", "envSet", "=", "$", "levelSet", "=", "$", "bodySet", "=", "[", "]", ";", "$", "pattern", "=", "\"/^\"", ".", "self", "::", "LOG_DATE_PATTERN", ".", "\"\\s\"", ".", "self", "::", "LOG_ENVIRONMENT_PATTERN", ".", "\"\\.\"", ".", "self", "::", "LOG_LEVEL_PATTERN", ".", "\"\\:|Next/m\"", ";", "preg_match_all", "(", "$", "pattern", ",", "$", "content", ",", "$", "matchs", ")", ";", "if", "(", "is_array", "(", "$", "matchs", ")", ")", "{", "$", "bodySet", "=", "array_map", "(", "'ltrim'", ",", "preg_split", "(", "$", "pattern", ",", "$", "content", ")", ")", ";", "if", "(", "empty", "(", "$", "bodySet", "[", "0", "]", ")", "&&", "count", "(", "$", "bodySet", ")", ">", "count", "(", "$", "matchs", "[", "0", "]", ")", ")", "{", "array_shift", "(", "$", "bodySet", ")", ";", "}", "$", "headerSet", "=", "$", "matchs", "[", "0", "]", ";", "$", "dateSet", "=", "$", "matchs", "[", "1", "]", ";", "$", "envSet", "=", "$", "matchs", "[", "2", "]", ";", "$", "levelSet", "=", "$", "matchs", "[", "3", "]", ";", "$", "bodySet", "=", "$", "bodySet", ";", "}", "return", "compact", "(", "'headerSet'", ",", "'dateSet'", ",", "'envSet'", ",", "'levelSet'", ",", "'bodySet'", ")", ";", "}" ]
Parses content of the log file into an array containing the necessary information @param string $content @return array Structure is ['headerSet' => [], 'dateSet' => [], 'envSet' => [], 'levelSet' => [], 'bodySet' => []]
[ "Parses", "content", "of", "the", "log", "file", "into", "an", "array", "containing", "the", "necessary", "information" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogParser.php#L33-L56
32,903
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogParser.php
LogParser.parseLogBody
public function parseLogBody($content) { $pattern = "/^".self::STACK_TRACE_DIVIDER_PATTERN."/m"; $parts = array_map('ltrim', preg_split($pattern, $content)); $context = $parts[0]; $stack_traces = (isset($parts[1])) ? $parts[1] : null; return compact('context', 'stack_traces'); }
php
public function parseLogBody($content) { $pattern = "/^".self::STACK_TRACE_DIVIDER_PATTERN."/m"; $parts = array_map('ltrim', preg_split($pattern, $content)); $context = $parts[0]; $stack_traces = (isset($parts[1])) ? $parts[1] : null; return compact('context', 'stack_traces'); }
[ "public", "function", "parseLogBody", "(", "$", "content", ")", "{", "$", "pattern", "=", "\"/^\"", ".", "self", "::", "STACK_TRACE_DIVIDER_PATTERN", ".", "\"/m\"", ";", "$", "parts", "=", "array_map", "(", "'ltrim'", ",", "preg_split", "(", "$", "pattern", ",", "$", "content", ")", ")", ";", "$", "context", "=", "$", "parts", "[", "0", "]", ";", "$", "stack_traces", "=", "(", "isset", "(", "$", "parts", "[", "1", "]", ")", ")", "?", "$", "parts", "[", "1", "]", ":", "null", ";", "return", "compact", "(", "'context'", ",", "'stack_traces'", ")", ";", "}" ]
Parses the body part of the log entry into an array containing the necessary information @param string $content @return array Structure is ['context' => '', 'stack_traces' => '']
[ "Parses", "the", "body", "part", "of", "the", "log", "entry", "into", "an", "array", "containing", "the", "necessary", "information" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogParser.php#L65-L73
32,904
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogParser.php
LogParser.parseLogContext
public function parseLogContext($content) { $content = trim($content); $pattern = "/^".self::CONTEXT_EXCEPTION_PATTERN.self::CONTEXT_MESSAGE_PATTERN.self::CONTEXT_IN_PATTERN."$/ms"; preg_match($pattern, $content, $matchs); $exception = isset($matchs[1]) ? $matchs[1] : null; $message = isset($matchs[2]) ? $matchs[3] : $content; $in = isset($matchs[4]) ? $matchs[4] : null; $line = isset($matchs[5]) ? $matchs[5] : null; return compact('message', 'exception', 'in', 'line'); }
php
public function parseLogContext($content) { $content = trim($content); $pattern = "/^".self::CONTEXT_EXCEPTION_PATTERN.self::CONTEXT_MESSAGE_PATTERN.self::CONTEXT_IN_PATTERN."$/ms"; preg_match($pattern, $content, $matchs); $exception = isset($matchs[1]) ? $matchs[1] : null; $message = isset($matchs[2]) ? $matchs[3] : $content; $in = isset($matchs[4]) ? $matchs[4] : null; $line = isset($matchs[5]) ? $matchs[5] : null; return compact('message', 'exception', 'in', 'line'); }
[ "public", "function", "parseLogContext", "(", "$", "content", ")", "{", "$", "content", "=", "trim", "(", "$", "content", ")", ";", "$", "pattern", "=", "\"/^\"", ".", "self", "::", "CONTEXT_EXCEPTION_PATTERN", ".", "self", "::", "CONTEXT_MESSAGE_PATTERN", ".", "self", "::", "CONTEXT_IN_PATTERN", ".", "\"$/ms\"", ";", "preg_match", "(", "$", "pattern", ",", "$", "content", ",", "$", "matchs", ")", ";", "$", "exception", "=", "isset", "(", "$", "matchs", "[", "1", "]", ")", "?", "$", "matchs", "[", "1", "]", ":", "null", ";", "$", "message", "=", "isset", "(", "$", "matchs", "[", "2", "]", ")", "?", "$", "matchs", "[", "3", "]", ":", "$", "content", ";", "$", "in", "=", "isset", "(", "$", "matchs", "[", "4", "]", ")", "?", "$", "matchs", "[", "4", "]", ":", "null", ";", "$", "line", "=", "isset", "(", "$", "matchs", "[", "5", "]", ")", "?", "$", "matchs", "[", "5", "]", ":", "null", ";", "return", "compact", "(", "'message'", ",", "'exception'", ",", "'in'", ",", "'line'", ")", ";", "}" ]
Parses the context part of the log entry into an array containing the necessary information @param string $content @return array Structure is ['message' => '', 'exception' => '', 'in' => '', 'line' => '']
[ "Parses", "the", "context", "part", "of", "the", "log", "entry", "into", "an", "array", "containing", "the", "necessary", "information" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogParser.php#L82-L95
32,905
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogParser.php
LogParser.parseStackTrace
public function parseStackTrace($content) { $content = trim($content); $pattern = "/^".self::STACK_TRACE_INDEX_PATTERN."/m"; if (empty($content)) { return []; } $traces = preg_split($pattern, $content); if (empty($trace[0])) { array_shift($traces); } return $traces; }
php
public function parseStackTrace($content) { $content = trim($content); $pattern = "/^".self::STACK_TRACE_INDEX_PATTERN."/m"; if (empty($content)) { return []; } $traces = preg_split($pattern, $content); if (empty($trace[0])) { array_shift($traces); } return $traces; }
[ "public", "function", "parseStackTrace", "(", "$", "content", ")", "{", "$", "content", "=", "trim", "(", "$", "content", ")", ";", "$", "pattern", "=", "\"/^\"", ".", "self", "::", "STACK_TRACE_INDEX_PATTERN", ".", "\"/m\"", ";", "if", "(", "empty", "(", "$", "content", ")", ")", "{", "return", "[", "]", ";", "}", "$", "traces", "=", "preg_split", "(", "$", "pattern", ",", "$", "content", ")", ";", "if", "(", "empty", "(", "$", "trace", "[", "0", "]", ")", ")", "{", "array_shift", "(", "$", "traces", ")", ";", "}", "return", "$", "traces", ";", "}" ]
Parses the stack trace part of the log entry into an array containing the necessary information @param string $content @return array
[ "Parses", "the", "stack", "trace", "part", "of", "the", "log", "entry", "into", "an", "array", "containing", "the", "necessary", "information" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogParser.php#L104-L120
32,906
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/LogParser.php
LogParser.parseTraceEntry
public function parseTraceEntry($content) { $content = trim($content); $caught_at = $content; $in = $line = null; if (!empty($content) && preg_match("/.*".self::TRACE_IN_DIVIDER_PATTERN.".*/", $content)) { $split = array_map('trim', preg_split("/".self::TRACE_IN_DIVIDER_PATTERN."/", $content)); $in = trim($split[0]); $caught_at = (isset($split[1])) ? $split[1] : null; if (preg_match("/^".self::TRACE_FILE_PATTERN."$/", $in, $matchs)) { $in = trim($matchs[1]); $line = $matchs[2]; } } return compact('caught_at', 'in', 'line'); }
php
public function parseTraceEntry($content) { $content = trim($content); $caught_at = $content; $in = $line = null; if (!empty($content) && preg_match("/.*".self::TRACE_IN_DIVIDER_PATTERN.".*/", $content)) { $split = array_map('trim', preg_split("/".self::TRACE_IN_DIVIDER_PATTERN."/", $content)); $in = trim($split[0]); $caught_at = (isset($split[1])) ? $split[1] : null; if (preg_match("/^".self::TRACE_FILE_PATTERN."$/", $in, $matchs)) { $in = trim($matchs[1]); $line = $matchs[2]; } } return compact('caught_at', 'in', 'line'); }
[ "public", "function", "parseTraceEntry", "(", "$", "content", ")", "{", "$", "content", "=", "trim", "(", "$", "content", ")", ";", "$", "caught_at", "=", "$", "content", ";", "$", "in", "=", "$", "line", "=", "null", ";", "if", "(", "!", "empty", "(", "$", "content", ")", "&&", "preg_match", "(", "\"/.*\"", ".", "self", "::", "TRACE_IN_DIVIDER_PATTERN", ".", "\".*/\"", ",", "$", "content", ")", ")", "{", "$", "split", "=", "array_map", "(", "'trim'", ",", "preg_split", "(", "\"/\"", ".", "self", "::", "TRACE_IN_DIVIDER_PATTERN", ".", "\"/\"", ",", "$", "content", ")", ")", ";", "$", "in", "=", "trim", "(", "$", "split", "[", "0", "]", ")", ";", "$", "caught_at", "=", "(", "isset", "(", "$", "split", "[", "1", "]", ")", ")", "?", "$", "split", "[", "1", "]", ":", "null", ";", "if", "(", "preg_match", "(", "\"/^\"", ".", "self", "::", "TRACE_FILE_PATTERN", ".", "\"$/\"", ",", "$", "in", ",", "$", "matchs", ")", ")", "{", "$", "in", "=", "trim", "(", "$", "matchs", "[", "1", "]", ")", ";", "$", "line", "=", "$", "matchs", "[", "2", "]", ";", "}", "}", "return", "compact", "(", "'caught_at'", ",", "'in'", ",", "'line'", ")", ";", "}" ]
Parses the content of the trace entry into an array containing the necessary information @param string $content @return array Structure is ['caught_at' => '', 'in' => '', 'line' => '']
[ "Parses", "the", "content", "of", "the", "trace", "entry", "into", "an", "array", "containing", "the", "necessary", "information" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/LogParser.php#L129-L149
32,907
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Console/Traits/SetLogReaderParamTrait.php
SetLogReaderParamTrait.setLogReaderParam
protected function setLogReaderParam() { if (array_key_exists('log-path', $this->option()) && ! empty($this->option('log-path'))) { $this->reader->setLogPath($this->option('log-path')); } if (array_key_exists('order-by', $this->option()) && ! empty($this->option('order-by'))) { if (array_key_exists('order-direction', $this->option()) && ! empty($this->option('order-direction'))) { $this->reader->orderBy($this->option('order-by'), $this->option('order-direction')); } else { $this->reader->orderBy($this->option('order-by')); } } if (array_key_exists('with-read', $this->option()) && $this->option('with-read')) { $this->reader->withRead(); } if (array_key_exists('file-name', $this->option())) { $this->reader->filename($this->option('file-name')); } if (array_key_exists('env', $this->option())) { $this->reader->environment($this->option('env')); } if (array_key_exists('level', $this->option())) { $this->reader->level($this->option('level')); } }
php
protected function setLogReaderParam() { if (array_key_exists('log-path', $this->option()) && ! empty($this->option('log-path'))) { $this->reader->setLogPath($this->option('log-path')); } if (array_key_exists('order-by', $this->option()) && ! empty($this->option('order-by'))) { if (array_key_exists('order-direction', $this->option()) && ! empty($this->option('order-direction'))) { $this->reader->orderBy($this->option('order-by'), $this->option('order-direction')); } else { $this->reader->orderBy($this->option('order-by')); } } if (array_key_exists('with-read', $this->option()) && $this->option('with-read')) { $this->reader->withRead(); } if (array_key_exists('file-name', $this->option())) { $this->reader->filename($this->option('file-name')); } if (array_key_exists('env', $this->option())) { $this->reader->environment($this->option('env')); } if (array_key_exists('level', $this->option())) { $this->reader->level($this->option('level')); } }
[ "protected", "function", "setLogReaderParam", "(", ")", "{", "if", "(", "array_key_exists", "(", "'log-path'", ",", "$", "this", "->", "option", "(", ")", ")", "&&", "!", "empty", "(", "$", "this", "->", "option", "(", "'log-path'", ")", ")", ")", "{", "$", "this", "->", "reader", "->", "setLogPath", "(", "$", "this", "->", "option", "(", "'log-path'", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "'order-by'", ",", "$", "this", "->", "option", "(", ")", ")", "&&", "!", "empty", "(", "$", "this", "->", "option", "(", "'order-by'", ")", ")", ")", "{", "if", "(", "array_key_exists", "(", "'order-direction'", ",", "$", "this", "->", "option", "(", ")", ")", "&&", "!", "empty", "(", "$", "this", "->", "option", "(", "'order-direction'", ")", ")", ")", "{", "$", "this", "->", "reader", "->", "orderBy", "(", "$", "this", "->", "option", "(", "'order-by'", ")", ",", "$", "this", "->", "option", "(", "'order-direction'", ")", ")", ";", "}", "else", "{", "$", "this", "->", "reader", "->", "orderBy", "(", "$", "this", "->", "option", "(", "'order-by'", ")", ")", ";", "}", "}", "if", "(", "array_key_exists", "(", "'with-read'", ",", "$", "this", "->", "option", "(", ")", ")", "&&", "$", "this", "->", "option", "(", "'with-read'", ")", ")", "{", "$", "this", "->", "reader", "->", "withRead", "(", ")", ";", "}", "if", "(", "array_key_exists", "(", "'file-name'", ",", "$", "this", "->", "option", "(", ")", ")", ")", "{", "$", "this", "->", "reader", "->", "filename", "(", "$", "this", "->", "option", "(", "'file-name'", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "'env'", ",", "$", "this", "->", "option", "(", ")", ")", ")", "{", "$", "this", "->", "reader", "->", "environment", "(", "$", "this", "->", "option", "(", "'env'", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "'level'", ",", "$", "this", "->", "option", "(", ")", ")", ")", "{", "$", "this", "->", "reader", "->", "level", "(", "$", "this", "->", "option", "(", "'level'", ")", ")", ";", "}", "}" ]
Set parameters for LogReader @return void
[ "Set", "parameters", "for", "LogReader" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Console/Traits/SetLogReaderParamTrait.php#L10-L39
32,908
JackieDo/Laravel-Log-Reader
src/Jackiedo/LogReader/Console/Commands/LogReaderGetCommand.php
LogReaderGetCommand.getLogEntries
protected function getLogEntries() { if ($this->option('paginate')) { $logs = $this->reader->paginate($this->option('per-page'), $this->option('page')); $total = $logs->total(); $this->line("You have total ".$total." log ".(($total > 1) ? 'entries' : 'entry')."."); $this->line("You are viewing page ".$logs->currentPage()."/".$logs->lastPage()." as follow:\r\n"); } else { $logs = $this->reader->get(); $total = $logs->count(); $this->line("You have total ".$total." log ".(($total > 1) ? 'entries' : 'entry')." as follow:\r\n"); } return $logs; }
php
protected function getLogEntries() { if ($this->option('paginate')) { $logs = $this->reader->paginate($this->option('per-page'), $this->option('page')); $total = $logs->total(); $this->line("You have total ".$total." log ".(($total > 1) ? 'entries' : 'entry')."."); $this->line("You are viewing page ".$logs->currentPage()."/".$logs->lastPage()." as follow:\r\n"); } else { $logs = $this->reader->get(); $total = $logs->count(); $this->line("You have total ".$total." log ".(($total > 1) ? 'entries' : 'entry')." as follow:\r\n"); } return $logs; }
[ "protected", "function", "getLogEntries", "(", ")", "{", "if", "(", "$", "this", "->", "option", "(", "'paginate'", ")", ")", "{", "$", "logs", "=", "$", "this", "->", "reader", "->", "paginate", "(", "$", "this", "->", "option", "(", "'per-page'", ")", ",", "$", "this", "->", "option", "(", "'page'", ")", ")", ";", "$", "total", "=", "$", "logs", "->", "total", "(", ")", ";", "$", "this", "->", "line", "(", "\"You have total \"", ".", "$", "total", ".", "\" log \"", ".", "(", "(", "$", "total", ">", "1", ")", "?", "'entries'", ":", "'entry'", ")", ".", "\".\"", ")", ";", "$", "this", "->", "line", "(", "\"You are viewing page \"", ".", "$", "logs", "->", "currentPage", "(", ")", ".", "\"/\"", ".", "$", "logs", "->", "lastPage", "(", ")", ".", "\" as follow:\\r\\n\"", ")", ";", "}", "else", "{", "$", "logs", "=", "$", "this", "->", "reader", "->", "get", "(", ")", ";", "$", "total", "=", "$", "logs", "->", "count", "(", ")", ";", "$", "this", "->", "line", "(", "\"You have total \"", ".", "$", "total", ".", "\" log \"", ".", "(", "(", "$", "total", ">", "1", ")", "?", "'entries'", ":", "'entry'", ")", ".", "\" as follow:\\r\\n\"", ")", ";", "}", "return", "$", "logs", ";", "}" ]
Reading log files and get log entries @return mixed
[ "Reading", "log", "files", "and", "get", "log", "entries" ]
10c6b52b52cde4250e40bae83d7a17f0532adfc2
https://github.com/JackieDo/Laravel-Log-Reader/blob/10c6b52b52cde4250e40bae83d7a17f0532adfc2/src/Jackiedo/LogReader/Console/Commands/LogReaderGetCommand.php#L60-L76
32,909
silinternational/email-service-php-client
src/EmailServiceClient.php
EmailServiceClient.email
public function email(array $config = []) { $result = $this->emailInternal($config); $statusCode = (int)$result['statusCode']; if ($statusCode >= 200 && $statusCode < 300) { return $this->getResultAsArrayWithoutStatusCode($result); } $this->reportUnexpectedResponse($result, 1503511660); }
php
public function email(array $config = []) { $result = $this->emailInternal($config); $statusCode = (int)$result['statusCode']; if ($statusCode >= 200 && $statusCode < 300) { return $this->getResultAsArrayWithoutStatusCode($result); } $this->reportUnexpectedResponse($result, 1503511660); }
[ "public", "function", "email", "(", "array", "$", "config", "=", "[", "]", ")", "{", "$", "result", "=", "$", "this", "->", "emailInternal", "(", "$", "config", ")", ";", "$", "statusCode", "=", "(", "int", ")", "$", "result", "[", "'statusCode'", "]", ";", "if", "(", "$", "statusCode", ">=", "200", "&&", "$", "statusCode", "<", "300", ")", "{", "return", "$", "this", "->", "getResultAsArrayWithoutStatusCode", "(", "$", "result", ")", ";", "}", "$", "this", "->", "reportUnexpectedResponse", "(", "$", "result", ",", "1503511660", ")", ";", "}" ]
Create an email with the given information. @param array $config An array key/value pairs of attributes for the new email. @return array An array of information about the email. @throws EmailServiceClientException
[ "Create", "an", "email", "with", "the", "given", "information", "." ]
02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e
https://github.com/silinternational/email-service-php-client/blob/02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e/src/EmailServiceClient.php#L148-L158
32,910
silinternational/email-service-php-client
src/EmailServiceClient.php
EmailServiceClient.assertTrustedIp
private function assertTrustedIp() { $baseHost = parse_url($this->serviceUri, PHP_URL_HOST); $serviceIp = gethostbyname( $baseHost ); if ( ! $this->isTrustedIpAddress($serviceIp)) { throw new EmailServiceClientException( 'The service has an IP that is not trusted ... ' . $serviceIp, 1503511662 ); } }
php
private function assertTrustedIp() { $baseHost = parse_url($this->serviceUri, PHP_URL_HOST); $serviceIp = gethostbyname( $baseHost ); if ( ! $this->isTrustedIpAddress($serviceIp)) { throw new EmailServiceClientException( 'The service has an IP that is not trusted ... ' . $serviceIp, 1503511662 ); } }
[ "private", "function", "assertTrustedIp", "(", ")", "{", "$", "baseHost", "=", "parse_url", "(", "$", "this", "->", "serviceUri", ",", "PHP_URL_HOST", ")", ";", "$", "serviceIp", "=", "gethostbyname", "(", "$", "baseHost", ")", ";", "if", "(", "!", "$", "this", "->", "isTrustedIpAddress", "(", "$", "serviceIp", ")", ")", "{", "throw", "new", "EmailServiceClientException", "(", "'The service has an IP that is not trusted ... '", ".", "$", "serviceIp", ",", "1503511662", ")", ";", "}", "}" ]
Determine whether any of the service's IPs are not in the trusted ranges @throws Exception
[ "Determine", "whether", "any", "of", "the", "service", "s", "IPs", "are", "not", "in", "the", "trusted", "ranges" ]
02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e
https://github.com/silinternational/email-service-php-client/blob/02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e/src/EmailServiceClient.php#L207-L220
32,911
silinternational/email-service-php-client
src/EmailServiceClient.php
EmailServiceClient.isTrustedIpAddress
private function isTrustedIpAddress($ipAddress) { foreach ($this->trustedIpRanges as $trustedIpBlock) { if ($trustedIpBlock->containsIP($ipAddress)) { return true; } } return false; }
php
private function isTrustedIpAddress($ipAddress) { foreach ($this->trustedIpRanges as $trustedIpBlock) { if ($trustedIpBlock->containsIP($ipAddress)) { return true; } } return false; }
[ "private", "function", "isTrustedIpAddress", "(", "$", "ipAddress", ")", "{", "foreach", "(", "$", "this", "->", "trustedIpRanges", "as", "$", "trustedIpBlock", ")", "{", "if", "(", "$", "trustedIpBlock", "->", "containsIP", "(", "$", "ipAddress", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether the service's IP address is in a trusted range. @param string $ipAddress The IP address in question. @return bool
[ "Determine", "whether", "the", "service", "s", "IP", "address", "is", "in", "a", "trusted", "range", "." ]
02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e
https://github.com/silinternational/email-service-php-client/blob/02f438d133a2ccbf057a6d4d24b8fcdab8c2d63e/src/EmailServiceClient.php#L228-L237
32,912
QoboLtd/qobo-robo
src/Command/Mysql/DbFindReplace.php
DbFindReplace.mysqlDbFindReplace
public function mysqlDbFindReplace( $search, $replace, $db, $user = 'root', $pass = '', $host = 'localhost', $port = null, $opts = ['format' => 'table', 'fields' => ''] ) { $result = $this->taskMysqlDbFindReplace() ->search($search) ->replace($replace) ->db($db) ->user($user) ->pass($pass) ->host($host) ->port($port) ->hide($pass) ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } return true; }
php
public function mysqlDbFindReplace( $search, $replace, $db, $user = 'root', $pass = '', $host = 'localhost', $port = null, $opts = ['format' => 'table', 'fields' => ''] ) { $result = $this->taskMysqlDbFindReplace() ->search($search) ->replace($replace) ->db($db) ->user($user) ->pass($pass) ->host($host) ->port($port) ->hide($pass) ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } return true; }
[ "public", "function", "mysqlDbFindReplace", "(", "$", "search", ",", "$", "replace", ",", "$", "db", ",", "$", "user", "=", "'root'", ",", "$", "pass", "=", "''", ",", "$", "host", "=", "'localhost'", ",", "$", "port", "=", "null", ",", "$", "opts", "=", "[", "'format'", "=>", "'table'", ",", "'fields'", "=>", "''", "]", ")", "{", "$", "result", "=", "$", "this", "->", "taskMysqlDbFindReplace", "(", ")", "->", "search", "(", "$", "search", ")", "->", "replace", "(", "$", "replace", ")", "->", "db", "(", "$", "db", ")", "->", "user", "(", "$", "user", ")", "->", "pass", "(", "$", "pass", ")", "->", "host", "(", "$", "host", ")", "->", "port", "(", "$", "port", ")", "->", "hide", "(", "$", "pass", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "exitError", "(", "\"Failed to run command\"", ")", ";", "}", "return", "true", ";", "}" ]
Run find-replace on MySQL database @param string $search Search string @param string $replace Replacement string @param string $db Database name @param string $user MySQL user to bind with @param string $pass (Optional) MySQL user password @param string $host (Optional) MySQL server host @param string $port (Optional) MySQL server port @option string $format Output format (table, list, csv, json, xml) @option string $fields Limit output to given fields, comma-separated @return bool
[ "Run", "find", "-", "replace", "on", "MySQL", "database" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Mysql/DbFindReplace.php#L34-L60
32,913
doganoo/PHPUtil
src/Util/DateTimeUtil.php
DateTimeUtil.valid
public static function valid(string $date, string $format): bool { return date($format, strtotime($date)) === $date; }
php
public static function valid(string $date, string $format): bool { return date($format, strtotime($date)) === $date; }
[ "public", "static", "function", "valid", "(", "string", "$", "date", ",", "string", "$", "format", ")", ":", "bool", "{", "return", "date", "(", "$", "format", ",", "strtotime", "(", "$", "date", ")", ")", "===", "$", "date", ";", "}" ]
Whether string is a valid date or not @param string $date @param string $format @return bool
[ "Whether", "string", "is", "a", "valid", "date", "or", "not" ]
4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5
https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Util/DateTimeUtil.php#L85-L88
32,914
orchestral/support
src/Support/Transformer.php
Transformer.handle
public function handle($instance) { if ($instance instanceof Paginator) { return $instance->setCollection( $instance->getCollection()->transform($this) ); } elseif ($instance instanceof Transformable || $instance instanceof BaseCollection) { $transformable = $instance; } elseif ($instance instanceof BaseFluent) { $transformable = new Fluent($instance->getAttributes()); } else { throw new InvalidArgumentException("Unable to transform {get_class($instance)}."); } return $transformable->transform($this); }
php
public function handle($instance) { if ($instance instanceof Paginator) { return $instance->setCollection( $instance->getCollection()->transform($this) ); } elseif ($instance instanceof Transformable || $instance instanceof BaseCollection) { $transformable = $instance; } elseif ($instance instanceof BaseFluent) { $transformable = new Fluent($instance->getAttributes()); } else { throw new InvalidArgumentException("Unable to transform {get_class($instance)}."); } return $transformable->transform($this); }
[ "public", "function", "handle", "(", "$", "instance", ")", "{", "if", "(", "$", "instance", "instanceof", "Paginator", ")", "{", "return", "$", "instance", "->", "setCollection", "(", "$", "instance", "->", "getCollection", "(", ")", "->", "transform", "(", "$", "this", ")", ")", ";", "}", "elseif", "(", "$", "instance", "instanceof", "Transformable", "||", "$", "instance", "instanceof", "BaseCollection", ")", "{", "$", "transformable", "=", "$", "instance", ";", "}", "elseif", "(", "$", "instance", "instanceof", "BaseFluent", ")", "{", "$", "transformable", "=", "new", "Fluent", "(", "$", "instance", "->", "getAttributes", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "\"Unable to transform {get_class($instance)}.\"", ")", ";", "}", "return", "$", "transformable", "->", "transform", "(", "$", "this", ")", ";", "}" ]
Handle transformation. @param mixed $instance @return mixed
[ "Handle", "transformation", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Transformer.php#L20-L35
32,915
doganoo/PHPUtil
src/Util/StringUtil.php
StringUtil.stringToArray
public static function stringToArray(?string $string): array { $result = []; $strLen = \strlen($string); if (null === $string) return $result; if (1 === $strLen) { $result[] = $string; return $result; } for ($i = 0; $i < $strLen; $i++) { $result[] = $string[$i]; } return $result; }
php
public static function stringToArray(?string $string): array { $result = []; $strLen = \strlen($string); if (null === $string) return $result; if (1 === $strLen) { $result[] = $string; return $result; } for ($i = 0; $i < $strLen; $i++) { $result[] = $string[$i]; } return $result; }
[ "public", "static", "function", "stringToArray", "(", "?", "string", "$", "string", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "$", "strLen", "=", "\\", "strlen", "(", "$", "string", ")", ";", "if", "(", "null", "===", "$", "string", ")", "return", "$", "result", ";", "if", "(", "1", "===", "$", "strLen", ")", "{", "$", "result", "[", "]", "=", "$", "string", ";", "return", "$", "result", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "strLen", ";", "$", "i", "++", ")", "{", "$", "result", "[", "]", "=", "$", "string", "[", "$", "i", "]", ";", "}", "return", "$", "result", ";", "}" ]
returns an array of elements of the string @param null|string $string @return array
[ "returns", "an", "array", "of", "elements", "of", "the", "string" ]
4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5
https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Util/StringUtil.php#L45-L57
32,916
QoboLtd/qobo-robo
src/Runner.php
Runner.handleError
public function handleError() { // get error info list ($errno, $message, $file, $line) = func_get_args(); // construct error message $msg = "ERROR ($errno): $message"; if ($line !== null) { $file = "$file:$line"; } if ($file !== null) { $msg .= " [$file]"; } static::$lastErrno = $errno; // throw the exception throw new RuntimeException($msg, $errno); }
php
public function handleError() { // get error info list ($errno, $message, $file, $line) = func_get_args(); // construct error message $msg = "ERROR ($errno): $message"; if ($line !== null) { $file = "$file:$line"; } if ($file !== null) { $msg .= " [$file]"; } static::$lastErrno = $errno; // throw the exception throw new RuntimeException($msg, $errno); }
[ "public", "function", "handleError", "(", ")", "{", "// get error info", "list", "(", "$", "errno", ",", "$", "message", ",", "$", "file", ",", "$", "line", ")", "=", "func_get_args", "(", ")", ";", "// construct error message", "$", "msg", "=", "\"ERROR ($errno): $message\"", ";", "if", "(", "$", "line", "!==", "null", ")", "{", "$", "file", "=", "\"$file:$line\"", ";", "}", "if", "(", "$", "file", "!==", "null", ")", "{", "$", "msg", ".=", "\" [$file]\"", ";", "}", "static", "::", "$", "lastErrno", "=", "$", "errno", ";", "// throw the exception", "throw", "new", "RuntimeException", "(", "$", "msg", ",", "$", "errno", ")", ";", "}" ]
Custom error handler that will throw an exception on any errors
[ "Custom", "error", "handler", "that", "will", "throw", "an", "exception", "on", "any", "errors" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Runner.php#L48-L67
32,917
emgiezet/errbitPHP
src/Errbit/Exception/Notice.php
Notice.buildRequestUrl
private function buildRequestUrl() { if (!empty($_SERVER['REQUEST_URI'])) { return sprintf( '%s://%s%s%s', $this->guessProtocol(), $this->guessHost(), $this->guessPort(), $_SERVER['REQUEST_URI'] ); } }
php
private function buildRequestUrl() { if (!empty($_SERVER['REQUEST_URI'])) { return sprintf( '%s://%s%s%s', $this->guessProtocol(), $this->guessHost(), $this->guessPort(), $_SERVER['REQUEST_URI'] ); } }
[ "private", "function", "buildRequestUrl", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "{", "return", "sprintf", "(", "'%s://%s%s%s'", ",", "$", "this", "->", "guessProtocol", "(", ")", ",", "$", "this", "->", "guessHost", "(", ")", ",", "$", "this", "->", "guessPort", "(", ")", ",", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ";", "}", "}" ]
Building request url @return string url
[ "Building", "request", "url" ]
cc634f8d6b0d2cd4a29648662119310afc73fa7b
https://github.com/emgiezet/errbitPHP/blob/cc634f8d6b0d2cd4a29648662119310afc73fa7b/src/Errbit/Exception/Notice.php#L397-L408
32,918
doganoo/PHPUtil
src/FileSystem/DirHandler.php
DirHandler._list
private function _list(string $path): array { $result = []; $scan = glob($path . '/*'); foreach ($scan as $item) { if (is_dir($item)) { $result[basename($item)] = $this->_list($item); } else { $result[] = basename($item); } } return $result; }
php
private function _list(string $path): array { $result = []; $scan = glob($path . '/*'); foreach ($scan as $item) { if (is_dir($item)) { $result[basename($item)] = $this->_list($item); } else { $result[] = basename($item); } } return $result; }
[ "private", "function", "_list", "(", "string", "$", "path", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "$", "scan", "=", "glob", "(", "$", "path", ".", "'/*'", ")", ";", "foreach", "(", "$", "scan", "as", "$", "item", ")", "{", "if", "(", "is_dir", "(", "$", "item", ")", ")", "{", "$", "result", "[", "basename", "(", "$", "item", ")", "]", "=", "$", "this", "->", "_list", "(", "$", "item", ")", ";", "}", "else", "{", "$", "result", "[", "]", "=", "basename", "(", "$", "item", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
lists every item in a given dir see here: https://stackoverflow.com/a/49066335/1966490 @param string $path @return array
[ "lists", "every", "item", "in", "a", "given", "dir" ]
4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5
https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/FileSystem/DirHandler.php#L112-L123
32,919
doganoo/PHPUtil
src/FileSystem/DirHandler.php
DirHandler._findFile
private function _findFile(string $dirName, string $fileName): ?FileHandler { $dirs = glob($dirName . '*'); $file = null; foreach ($dirs as $d) { if (is_file($d)) { $pathInfo = \pathinfo($d); $pathInfo2 = \pathinfo($fileName); if (isset($pathInfo2["extension"])) { $condition = $pathInfo["basename"] === $pathInfo2["basename"]; } else { $condition = $pathInfo["filename"] === $pathInfo2["filename"]; } if ($condition) { return new FileHandler($dirName . "/" . $pathInfo["basename"]); } } else if (is_dir($d)) { $tmp = $this->_findFile($d . "/", $fileName); if (null !== $tmp) { $file = $tmp; } } } return $file; }
php
private function _findFile(string $dirName, string $fileName): ?FileHandler { $dirs = glob($dirName . '*'); $file = null; foreach ($dirs as $d) { if (is_file($d)) { $pathInfo = \pathinfo($d); $pathInfo2 = \pathinfo($fileName); if (isset($pathInfo2["extension"])) { $condition = $pathInfo["basename"] === $pathInfo2["basename"]; } else { $condition = $pathInfo["filename"] === $pathInfo2["filename"]; } if ($condition) { return new FileHandler($dirName . "/" . $pathInfo["basename"]); } } else if (is_dir($d)) { $tmp = $this->_findFile($d . "/", $fileName); if (null !== $tmp) { $file = $tmp; } } } return $file; }
[ "private", "function", "_findFile", "(", "string", "$", "dirName", ",", "string", "$", "fileName", ")", ":", "?", "FileHandler", "{", "$", "dirs", "=", "glob", "(", "$", "dirName", ".", "'*'", ")", ";", "$", "file", "=", "null", ";", "foreach", "(", "$", "dirs", "as", "$", "d", ")", "{", "if", "(", "is_file", "(", "$", "d", ")", ")", "{", "$", "pathInfo", "=", "\\", "pathinfo", "(", "$", "d", ")", ";", "$", "pathInfo2", "=", "\\", "pathinfo", "(", "$", "fileName", ")", ";", "if", "(", "isset", "(", "$", "pathInfo2", "[", "\"extension\"", "]", ")", ")", "{", "$", "condition", "=", "$", "pathInfo", "[", "\"basename\"", "]", "===", "$", "pathInfo2", "[", "\"basename\"", "]", ";", "}", "else", "{", "$", "condition", "=", "$", "pathInfo", "[", "\"filename\"", "]", "===", "$", "pathInfo2", "[", "\"filename\"", "]", ";", "}", "if", "(", "$", "condition", ")", "{", "return", "new", "FileHandler", "(", "$", "dirName", ".", "\"/\"", ".", "$", "pathInfo", "[", "\"basename\"", "]", ")", ";", "}", "}", "else", "if", "(", "is_dir", "(", "$", "d", ")", ")", "{", "$", "tmp", "=", "$", "this", "->", "_findFile", "(", "$", "d", ".", "\"/\"", ",", "$", "fileName", ")", ";", "if", "(", "null", "!==", "$", "tmp", ")", "{", "$", "file", "=", "$", "tmp", ";", "}", "}", "}", "return", "$", "file", ";", "}" ]
finds a file in the given dir @param $dirName @param $fileName @return string
[ "finds", "a", "file", "in", "the", "given", "dir" ]
4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5
https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/FileSystem/DirHandler.php#L193-L218
32,920
doganoo/PHPUtil
src/Util/ArrayUtil.php
ArrayUtil.hasSum
public static function hasSum(array $numbers, int $target): bool { $collection = ArrayUtil::sumCollection($numbers, $target); if (null === $collection) return false; if (0 === \count($collection)) return false; return true; }
php
public static function hasSum(array $numbers, int $target): bool { $collection = ArrayUtil::sumCollection($numbers, $target); if (null === $collection) return false; if (0 === \count($collection)) return false; return true; }
[ "public", "static", "function", "hasSum", "(", "array", "$", "numbers", ",", "int", "$", "target", ")", ":", "bool", "{", "$", "collection", "=", "ArrayUtil", "::", "sumCollection", "(", "$", "numbers", ",", "$", "target", ")", ";", "if", "(", "null", "===", "$", "collection", ")", "return", "false", ";", "if", "(", "0", "===", "\\", "count", "(", "$", "collection", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
returns a boolean that indicates whether a sequence sums up to a value or not @param array $numbers @param int $target @return bool
[ "returns", "a", "boolean", "that", "indicates", "whether", "a", "sequence", "sums", "up", "to", "a", "value", "or", "not" ]
4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5
https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Util/ArrayUtil.php#L67-L72
32,921
nails/module-invoice
src/Factory/ChargeRequest.php
ChargeRequest.setCardNumber
public function setCardNumber($sCardNumber) { // Validate if (preg_match('/[^\d ]/', $sCardNumber)) { throw new ChargeRequestException('Invalid card number; can only contain digits and spaces.', 1); } $this->oCard->number = $sCardNumber; return $this; }
php
public function setCardNumber($sCardNumber) { // Validate if (preg_match('/[^\d ]/', $sCardNumber)) { throw new ChargeRequestException('Invalid card number; can only contain digits and spaces.', 1); } $this->oCard->number = $sCardNumber; return $this; }
[ "public", "function", "setCardNumber", "(", "$", "sCardNumber", ")", "{", "// Validate", "if", "(", "preg_match", "(", "'/[^\\d ]/'", ",", "$", "sCardNumber", ")", ")", "{", "throw", "new", "ChargeRequestException", "(", "'Invalid card number; can only contain digits and spaces.'", ",", "1", ")", ";", "}", "$", "this", "->", "oCard", "->", "number", "=", "$", "sCardNumber", ";", "return", "$", "this", ";", "}" ]
Set the card's number @param string $sCardNumber The card's number @throws ChargeRequestException @return $this
[ "Set", "the", "card", "s", "number" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ChargeRequest.php#L91-L100
32,922
nails/module-invoice
src/Factory/ChargeRequest.php
ChargeRequest.setCardExpMonth
public function setCardExpMonth($sCardExpMonth) { // Validate if (is_numeric($sCardExpMonth)) { $iMonth = (int) $sCardExpMonth; if ($iMonth < 1 || $iMonth > 12) { throw new ChargeRequestException( '"' . $sCardExpMonth . '" is an invalid expiry month; must be in the range 1-12.', 1 ); } else { $this->oCard->exp->month = $iMonth < 10 ? '0' . $iMonth : (string) $iMonth; return $this; } } else { throw new ChargeRequestException( '"' . $sCardExpMonth . '" is an invalid expiry month; must be numeric.', 1 ); } }
php
public function setCardExpMonth($sCardExpMonth) { // Validate if (is_numeric($sCardExpMonth)) { $iMonth = (int) $sCardExpMonth; if ($iMonth < 1 || $iMonth > 12) { throw new ChargeRequestException( '"' . $sCardExpMonth . '" is an invalid expiry month; must be in the range 1-12.', 1 ); } else { $this->oCard->exp->month = $iMonth < 10 ? '0' . $iMonth : (string) $iMonth; return $this; } } else { throw new ChargeRequestException( '"' . $sCardExpMonth . '" is an invalid expiry month; must be numeric.', 1 ); } }
[ "public", "function", "setCardExpMonth", "(", "$", "sCardExpMonth", ")", "{", "// Validate", "if", "(", "is_numeric", "(", "$", "sCardExpMonth", ")", ")", "{", "$", "iMonth", "=", "(", "int", ")", "$", "sCardExpMonth", ";", "if", "(", "$", "iMonth", "<", "1", "||", "$", "iMonth", ">", "12", ")", "{", "throw", "new", "ChargeRequestException", "(", "'\"'", ".", "$", "sCardExpMonth", ".", "'\" is an invalid expiry month; must be in the range 1-12.'", ",", "1", ")", ";", "}", "else", "{", "$", "this", "->", "oCard", "->", "exp", "->", "month", "=", "$", "iMonth", "<", "10", "?", "'0'", ".", "$", "iMonth", ":", "(", "string", ")", "$", "iMonth", ";", "return", "$", "this", ";", "}", "}", "else", "{", "throw", "new", "ChargeRequestException", "(", "'\"'", ".", "$", "sCardExpMonth", ".", "'\" is an invalid expiry month; must be numeric.'", ",", "1", ")", ";", "}", "}" ]
Set the card's expiry month @param string $sCardExpMonth The card's expiry month @throws ChargeRequestException @return $this
[ "Set", "the", "card", "s", "expiry", "month" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ChargeRequest.php#L123-L147
32,923
nails/module-invoice
src/Factory/ChargeRequest.php
ChargeRequest.setCardExpYear
public function setCardExpYear($sCardExpYear) { // Validate if (is_numeric($sCardExpYear)) { // Accept two digits or 4 digits only if (strlen($sCardExpYear) == 2 || strlen($sCardExpYear) == 4) { // Two digit values should be turned into a 4 digit value if (strlen($sCardExpYear) == 2) { // Sorry people living in the 2100's, I'm very sorry everything is broken. $sCardExpYear = '20' . $sCardExpYear; } $iYear = (int) $sCardExpYear; $oNow = Factory::factory('DateTime'); if ($oNow->format('Y') > $iYear) { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be ' . $oNow->format('Y') . ' or later.', 1 ); } $this->oCard->exp->year = (string) $iYear; return $this; } else { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be 2 or 4 digits.', 1 ); } } else { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be numeric.', 1 ); } }
php
public function setCardExpYear($sCardExpYear) { // Validate if (is_numeric($sCardExpYear)) { // Accept two digits or 4 digits only if (strlen($sCardExpYear) == 2 || strlen($sCardExpYear) == 4) { // Two digit values should be turned into a 4 digit value if (strlen($sCardExpYear) == 2) { // Sorry people living in the 2100's, I'm very sorry everything is broken. $sCardExpYear = '20' . $sCardExpYear; } $iYear = (int) $sCardExpYear; $oNow = Factory::factory('DateTime'); if ($oNow->format('Y') > $iYear) { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be ' . $oNow->format('Y') . ' or later.', 1 ); } $this->oCard->exp->year = (string) $iYear; return $this; } else { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be 2 or 4 digits.', 1 ); } } else { throw new ChargeRequestException( '"' . $sCardExpYear . '" is an invalid expiry year; must be numeric.', 1 ); } }
[ "public", "function", "setCardExpYear", "(", "$", "sCardExpYear", ")", "{", "// Validate", "if", "(", "is_numeric", "(", "$", "sCardExpYear", ")", ")", "{", "// Accept two digits or 4 digits only", "if", "(", "strlen", "(", "$", "sCardExpYear", ")", "==", "2", "||", "strlen", "(", "$", "sCardExpYear", ")", "==", "4", ")", "{", "// Two digit values should be turned into a 4 digit value", "if", "(", "strlen", "(", "$", "sCardExpYear", ")", "==", "2", ")", "{", "// Sorry people living in the 2100's, I'm very sorry everything is broken.", "$", "sCardExpYear", "=", "'20'", ".", "$", "sCardExpYear", ";", "}", "$", "iYear", "=", "(", "int", ")", "$", "sCardExpYear", ";", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "if", "(", "$", "oNow", "->", "format", "(", "'Y'", ")", ">", "$", "iYear", ")", "{", "throw", "new", "ChargeRequestException", "(", "'\"'", ".", "$", "sCardExpYear", ".", "'\" is an invalid expiry year; must be '", ".", "$", "oNow", "->", "format", "(", "'Y'", ")", ".", "' or later.'", ",", "1", ")", ";", "}", "$", "this", "->", "oCard", "->", "exp", "->", "year", "=", "(", "string", ")", "$", "iYear", ";", "return", "$", "this", ";", "}", "else", "{", "throw", "new", "ChargeRequestException", "(", "'\"'", ".", "$", "sCardExpYear", ".", "'\" is an invalid expiry year; must be 2 or 4 digits.'", ",", "1", ")", ";", "}", "}", "else", "{", "throw", "new", "ChargeRequestException", "(", "'\"'", ".", "$", "sCardExpYear", ".", "'\" is an invalid expiry year; must be numeric.'", ",", "1", ")", ";", "}", "}" ]
Set the card's expiry year @param string $sCardExpYear The card's expiry year @throws ChargeRequestException @return $this
[ "Set", "the", "card", "s", "expiry", "year" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ChargeRequest.php#L170-L211
32,924
nails/module-invoice
src/Factory/ChargeRequest.php
ChargeRequest.getCustomField
public function getCustomField($sProperty) { return property_exists($this->oCustomField, $sProperty) ? $this->oCustomField->{$sProperty} : null; }
php
public function getCustomField($sProperty) { return property_exists($this->oCustomField, $sProperty) ? $this->oCustomField->{$sProperty} : null; }
[ "public", "function", "getCustomField", "(", "$", "sProperty", ")", "{", "return", "property_exists", "(", "$", "this", "->", "oCustomField", ",", "$", "sProperty", ")", "?", "$", "this", "->", "oCustomField", "->", "{", "$", "sProperty", "}", ":", "null", ";", "}" ]
Retrieve a custom field @param string $sProperty The property to retrieve @return mixed
[ "Retrieve", "a", "custom", "field" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ChargeRequest.php#L276-L279
32,925
nails/module-invoice
src/Factory/ChargeRequest.php
ChargeRequest.getCustomData
public function getCustomData($sProperty) { return property_exists($this->oCustomData, $sProperty) ? $this->oCustomData->{$sProperty} : null; }
php
public function getCustomData($sProperty) { return property_exists($this->oCustomData, $sProperty) ? $this->oCustomData->{$sProperty} : null; }
[ "public", "function", "getCustomData", "(", "$", "sProperty", ")", "{", "return", "property_exists", "(", "$", "this", "->", "oCustomData", ",", "$", "sProperty", ")", "?", "$", "this", "->", "oCustomData", "->", "{", "$", "sProperty", "}", ":", "null", ";", "}" ]
Retrieve a custom value @param string $sProperty The property to retrieve @return mixed
[ "Retrieve", "a", "custom", "value" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ChargeRequest.php#L306-L309
32,926
QoboLtd/qobo-robo
src/App.php
App.getCommands
protected function getCommands() { // construct command classes path depending on grp_cmd flag $cmdPath = rtrim(__DIR__ . "/" . $this->data['cmd_path'], '/') . '/'; $cmdPath .= ($this->data['grp_cmd']) ? "*/*.php" : "*.php"; // construct commad path regex depending on grp_cmd flag $cmdPattern = ($this->data['grp_cmd']) ? '/^.*\/([^\/]+)\/([^\/]+)\.php$/' : '/^.*\/([^\/]+)\.php$/'; // find all command files and commands $commands = []; foreach (glob($cmdPath) as $file) { // match only php files, extract group dir name if (!preg_match($cmdPattern, $file, $matches)) { continue; } // construct a class name from our namespace, optional // command group subdir and actual class file name $className = __NAMESPACE__ . "\\" . str_replace("/", "\\", $this->data['cmd_path']) . $matches[1]; $className .= ($this->data['grp_cmd']) ? "\\" . $matches[2] : ""; // skip if class doesn't exist if (!class_exists($className)) { continue; } // add to our commands list $commands []= $className; } if (!empty($this->data['config']['extra_commands']) && is_array($this->data['config']['extra_commands'])) { $commands = array_merge($commands, $this->data['config']['extra_commands']); } return $commands; }
php
protected function getCommands() { // construct command classes path depending on grp_cmd flag $cmdPath = rtrim(__DIR__ . "/" . $this->data['cmd_path'], '/') . '/'; $cmdPath .= ($this->data['grp_cmd']) ? "*/*.php" : "*.php"; // construct commad path regex depending on grp_cmd flag $cmdPattern = ($this->data['grp_cmd']) ? '/^.*\/([^\/]+)\/([^\/]+)\.php$/' : '/^.*\/([^\/]+)\.php$/'; // find all command files and commands $commands = []; foreach (glob($cmdPath) as $file) { // match only php files, extract group dir name if (!preg_match($cmdPattern, $file, $matches)) { continue; } // construct a class name from our namespace, optional // command group subdir and actual class file name $className = __NAMESPACE__ . "\\" . str_replace("/", "\\", $this->data['cmd_path']) . $matches[1]; $className .= ($this->data['grp_cmd']) ? "\\" . $matches[2] : ""; // skip if class doesn't exist if (!class_exists($className)) { continue; } // add to our commands list $commands []= $className; } if (!empty($this->data['config']['extra_commands']) && is_array($this->data['config']['extra_commands'])) { $commands = array_merge($commands, $this->data['config']['extra_commands']); } return $commands; }
[ "protected", "function", "getCommands", "(", ")", "{", "// construct command classes path depending on grp_cmd flag", "$", "cmdPath", "=", "rtrim", "(", "__DIR__", ".", "\"/\"", ".", "$", "this", "->", "data", "[", "'cmd_path'", "]", ",", "'/'", ")", ".", "'/'", ";", "$", "cmdPath", ".=", "(", "$", "this", "->", "data", "[", "'grp_cmd'", "]", ")", "?", "\"*/*.php\"", ":", "\"*.php\"", ";", "// construct commad path regex depending on grp_cmd flag", "$", "cmdPattern", "=", "(", "$", "this", "->", "data", "[", "'grp_cmd'", "]", ")", "?", "'/^.*\\/([^\\/]+)\\/([^\\/]+)\\.php$/'", ":", "'/^.*\\/([^\\/]+)\\.php$/'", ";", "// find all command files and commands", "$", "commands", "=", "[", "]", ";", "foreach", "(", "glob", "(", "$", "cmdPath", ")", "as", "$", "file", ")", "{", "// match only php files, extract group dir name", "if", "(", "!", "preg_match", "(", "$", "cmdPattern", ",", "$", "file", ",", "$", "matches", ")", ")", "{", "continue", ";", "}", "// construct a class name from our namespace, optional", "// command group subdir and actual class file name", "$", "className", "=", "__NAMESPACE__", ".", "\"\\\\\"", ".", "str_replace", "(", "\"/\"", ",", "\"\\\\\"", ",", "$", "this", "->", "data", "[", "'cmd_path'", "]", ")", ".", "$", "matches", "[", "1", "]", ";", "$", "className", ".=", "(", "$", "this", "->", "data", "[", "'grp_cmd'", "]", ")", "?", "\"\\\\\"", ".", "$", "matches", "[", "2", "]", ":", "\"\"", ";", "// skip if class doesn't exist", "if", "(", "!", "class_exists", "(", "$", "className", ")", ")", "{", "continue", ";", "}", "// add to our commands list", "$", "commands", "[", "]", "=", "$", "className", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "data", "[", "'config'", "]", "[", "'extra_commands'", "]", ")", "&&", "is_array", "(", "$", "this", "->", "data", "[", "'config'", "]", "[", "'extra_commands'", "]", ")", ")", "{", "$", "commands", "=", "array_merge", "(", "$", "commands", ",", "$", "this", "->", "data", "[", "'config'", "]", "[", "'extra_commands'", "]", ")", ";", "}", "return", "$", "commands", ";", "}" ]
Get list of available command classes @return array List of command classes
[ "Get", "list", "of", "available", "command", "classes" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/App.php#L112-L150
32,927
QoboLtd/qobo-robo
src/Command/Project/Branch.php
Branch.projectBranch
public function projectBranch($opts = ['format' => 'table', 'fields' => '']) { $result = $this->taskProjectBranch() ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } $data = $result->getData(); return new PropertyList(['branch' => $data['data'][0]['message']]); }
php
public function projectBranch($opts = ['format' => 'table', 'fields' => '']) { $result = $this->taskProjectBranch() ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } $data = $result->getData(); return new PropertyList(['branch' => $data['data'][0]['message']]); }
[ "public", "function", "projectBranch", "(", "$", "opts", "=", "[", "'format'", "=>", "'table'", ",", "'fields'", "=>", "''", "]", ")", "{", "$", "result", "=", "$", "this", "->", "taskProjectBranch", "(", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "exitError", "(", "\"Failed to run command\"", ")", ";", "}", "$", "data", "=", "$", "result", "->", "getData", "(", ")", ";", "return", "new", "PropertyList", "(", "[", "'branch'", "=>", "$", "data", "[", "'data'", "]", "[", "0", "]", "[", "'message'", "]", "]", ")", ";", "}" ]
Get current project branch @return \Qobo\Robo\Formatter\PropertyList
[ "Get", "current", "project", "branch" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/Branch.php#L24-L35
32,928
hiqdev/hipanel-module-domain
src/models/Domain.php
Domain.isZone
public function isZone($zones) { $zone = $this->getZone(); return is_array($zones) ? in_array($this->getZone(), $zones, true) : $zone === $zones; }
php
public function isZone($zones) { $zone = $this->getZone(); return is_array($zones) ? in_array($this->getZone(), $zones, true) : $zone === $zones; }
[ "public", "function", "isZone", "(", "$", "zones", ")", "{", "$", "zone", "=", "$", "this", "->", "getZone", "(", ")", ";", "return", "is_array", "(", "$", "zones", ")", "?", "in_array", "(", "$", "this", "->", "getZone", "(", ")", ",", "$", "zones", ",", "true", ")", ":", "$", "zone", "===", "$", "zones", ";", "}" ]
a Returns true if the zone is among given list of zones. @param array|string $zones zone or list of zones @return bool
[ "a", "Returns", "true", "if", "the", "zone", "is", "among", "given", "list", "of", "zones", "." ]
b1b02782fcb69970cacafe6c6ead238b14b54209
https://github.com/hiqdev/hipanel-module-domain/blob/b1b02782fcb69970cacafe6c6ead238b14b54209/src/models/Domain.php#L707-L712
32,929
SimpleBus/Serialization
src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php
StandardMessageInEnvelopeSerializer.wrapAndSerialize
public function wrapAndSerialize($message) { $envelope = $this->envelopeFactory->wrapMessageInEnvelope($message); $serializedMessage = $this->objectSerializer->serialize($message); return $this->objectSerializer->serialize($envelope->withSerializedMessage($serializedMessage)); }
php
public function wrapAndSerialize($message) { $envelope = $this->envelopeFactory->wrapMessageInEnvelope($message); $serializedMessage = $this->objectSerializer->serialize($message); return $this->objectSerializer->serialize($envelope->withSerializedMessage($serializedMessage)); }
[ "public", "function", "wrapAndSerialize", "(", "$", "message", ")", "{", "$", "envelope", "=", "$", "this", "->", "envelopeFactory", "->", "wrapMessageInEnvelope", "(", "$", "message", ")", ";", "$", "serializedMessage", "=", "$", "this", "->", "objectSerializer", "->", "serialize", "(", "$", "message", ")", ";", "return", "$", "this", "->", "objectSerializer", "->", "serialize", "(", "$", "envelope", "->", "withSerializedMessage", "(", "$", "serializedMessage", ")", ")", ";", "}" ]
Serialize a Message by wrapping it in an Envelope and serializing the envelope @{inheritdoc}
[ "Serialize", "a", "Message", "by", "wrapping", "it", "in", "an", "Envelope", "and", "serializing", "the", "envelope" ]
b69f896cfdbd798b8e83d79c6c87a051f0469183
https://github.com/SimpleBus/Serialization/blob/b69f896cfdbd798b8e83d79c6c87a051f0469183/src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php#L34-L41
32,930
SimpleBus/Serialization
src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php
StandardMessageInEnvelopeSerializer.unwrapAndDeserialize
public function unwrapAndDeserialize($serializedEnvelope) { $envelope = $this->deserializeEnvelope($serializedEnvelope); $message = $this->deserializeMessage($envelope->serializedMessage(), $envelope->messageType()); return $envelope->withMessage($message); }
php
public function unwrapAndDeserialize($serializedEnvelope) { $envelope = $this->deserializeEnvelope($serializedEnvelope); $message = $this->deserializeMessage($envelope->serializedMessage(), $envelope->messageType()); return $envelope->withMessage($message); }
[ "public", "function", "unwrapAndDeserialize", "(", "$", "serializedEnvelope", ")", "{", "$", "envelope", "=", "$", "this", "->", "deserializeEnvelope", "(", "$", "serializedEnvelope", ")", ";", "$", "message", "=", "$", "this", "->", "deserializeMessage", "(", "$", "envelope", "->", "serializedMessage", "(", ")", ",", "$", "envelope", "->", "messageType", "(", ")", ")", ";", "return", "$", "envelope", "->", "withMessage", "(", "$", "message", ")", ";", "}" ]
Deserialize a Message that was wrapped in an Envelope @{inheritdoc}
[ "Deserialize", "a", "Message", "that", "was", "wrapped", "in", "an", "Envelope" ]
b69f896cfdbd798b8e83d79c6c87a051f0469183
https://github.com/SimpleBus/Serialization/blob/b69f896cfdbd798b8e83d79c6c87a051f0469183/src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php#L48-L55
32,931
SimpleBus/Serialization
src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php
StandardMessageInEnvelopeSerializer.deserializeEnvelope
private function deserializeEnvelope($serializedEnvelope) { $envelopeClass = $this->envelopeFactory->envelopeClass(); $envelope = $this->objectSerializer->deserialize( $serializedEnvelope, $envelopeClass ); if (!($envelope instanceof $envelopeClass)) { throw new \LogicException( sprintf( 'Expected deserialized object to be an instance of "%s"', $envelopeClass ) ); } return $envelope; }
php
private function deserializeEnvelope($serializedEnvelope) { $envelopeClass = $this->envelopeFactory->envelopeClass(); $envelope = $this->objectSerializer->deserialize( $serializedEnvelope, $envelopeClass ); if (!($envelope instanceof $envelopeClass)) { throw new \LogicException( sprintf( 'Expected deserialized object to be an instance of "%s"', $envelopeClass ) ); } return $envelope; }
[ "private", "function", "deserializeEnvelope", "(", "$", "serializedEnvelope", ")", "{", "$", "envelopeClass", "=", "$", "this", "->", "envelopeFactory", "->", "envelopeClass", "(", ")", ";", "$", "envelope", "=", "$", "this", "->", "objectSerializer", "->", "deserialize", "(", "$", "serializedEnvelope", ",", "$", "envelopeClass", ")", ";", "if", "(", "!", "(", "$", "envelope", "instanceof", "$", "envelopeClass", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Expected deserialized object to be an instance of \"%s\"'", ",", "$", "envelopeClass", ")", ")", ";", "}", "return", "$", "envelope", ";", "}" ]
Deserialize the message Envelope @param string $serializedEnvelope @return Envelope
[ "Deserialize", "the", "message", "Envelope" ]
b69f896cfdbd798b8e83d79c6c87a051f0469183
https://github.com/SimpleBus/Serialization/blob/b69f896cfdbd798b8e83d79c6c87a051f0469183/src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php#L63-L81
32,932
SimpleBus/Serialization
src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php
StandardMessageInEnvelopeSerializer.deserializeMessage
private function deserializeMessage($serializedMessage, $messageClass) { $message = $this->objectSerializer->deserialize($serializedMessage, $messageClass); if (!($message instanceof $messageClass)) { throw new \LogicException( sprintf( 'Expected deserialized message to be an instance of "%s"', $messageClass ) ); } return $message; }
php
private function deserializeMessage($serializedMessage, $messageClass) { $message = $this->objectSerializer->deserialize($serializedMessage, $messageClass); if (!($message instanceof $messageClass)) { throw new \LogicException( sprintf( 'Expected deserialized message to be an instance of "%s"', $messageClass ) ); } return $message; }
[ "private", "function", "deserializeMessage", "(", "$", "serializedMessage", ",", "$", "messageClass", ")", "{", "$", "message", "=", "$", "this", "->", "objectSerializer", "->", "deserialize", "(", "$", "serializedMessage", ",", "$", "messageClass", ")", ";", "if", "(", "!", "(", "$", "message", "instanceof", "$", "messageClass", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Expected deserialized message to be an instance of \"%s\"'", ",", "$", "messageClass", ")", ")", ";", "}", "return", "$", "message", ";", "}" ]
Deserialize the Message @param string $serializedMessage @param string $messageClass @return object Of type $messageClass
[ "Deserialize", "the", "Message" ]
b69f896cfdbd798b8e83d79c6c87a051f0469183
https://github.com/SimpleBus/Serialization/blob/b69f896cfdbd798b8e83d79c6c87a051f0469183/src/Envelope/Serializer/StandardMessageInEnvelopeSerializer.php#L90-L104
32,933
canihavesomecoffee/theTVDbAPI
src/MultiLanguageWrapper/Route/SearchRouteLanguageFallback.php
SearchRouteLanguageFallback.getClosureForSearch
public function getClosureForSearch(array $options): Closure { return function ($language) use ($options) { $json = $this->parent->performAPICallWithJsonResponse( 'get', '/search/series', array_merge($options, ['headers' => ['Accept-Language' => $language]]) ); return DataParser::parseDataArray($json, BasicSeries::class); }; }
php
public function getClosureForSearch(array $options): Closure { return function ($language) use ($options) { $json = $this->parent->performAPICallWithJsonResponse( 'get', '/search/series', array_merge($options, ['headers' => ['Accept-Language' => $language]]) ); return DataParser::parseDataArray($json, BasicSeries::class); }; }
[ "public", "function", "getClosureForSearch", "(", "array", "$", "options", ")", ":", "Closure", "{", "return", "function", "(", "$", "language", ")", "use", "(", "$", "options", ")", "{", "$", "json", "=", "$", "this", "->", "parent", "->", "performAPICallWithJsonResponse", "(", "'get'", ",", "'/search/series'", ",", "array_merge", "(", "$", "options", ",", "[", "'headers'", "=>", "[", "'Accept-Language'", "=>", "$", "language", "]", "]", ")", ")", ";", "return", "DataParser", "::", "parseDataArray", "(", "$", "json", ",", "BasicSeries", "::", "class", ")", ";", "}", ";", "}" ]
Returns the closure used to execute a search for a single language. @param array $options The options for the search. @return Closure
[ "Returns", "the", "closure", "used", "to", "execute", "a", "search", "for", "a", "single", "language", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/Route/SearchRouteLanguageFallback.php#L81-L91
32,934
orchestral/support
src/Support/Collection.php
Collection.streamCsv
public function streamCsv() { $delimiter = ','; $enclosure = '"'; $header = $this->resolveCsvHeader(); $stream = \fopen('php://output', 'r+'); \fputcsv($stream, $header, $delimiter, $enclosure); foreach ($this->items as $key => $item) { \fputcsv($stream, Arr::dot($item), $delimiter, $enclosure); } return $stream; }
php
public function streamCsv() { $delimiter = ','; $enclosure = '"'; $header = $this->resolveCsvHeader(); $stream = \fopen('php://output', 'r+'); \fputcsv($stream, $header, $delimiter, $enclosure); foreach ($this->items as $key => $item) { \fputcsv($stream, Arr::dot($item), $delimiter, $enclosure); } return $stream; }
[ "public", "function", "streamCsv", "(", ")", "{", "$", "delimiter", "=", "','", ";", "$", "enclosure", "=", "'\"'", ";", "$", "header", "=", "$", "this", "->", "resolveCsvHeader", "(", ")", ";", "$", "stream", "=", "\\", "fopen", "(", "'php://output'", ",", "'r+'", ")", ";", "\\", "fputcsv", "(", "$", "stream", ",", "$", "header", ",", "$", "delimiter", ",", "$", "enclosure", ")", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "\\", "fputcsv", "(", "$", "stream", ",", "Arr", "::", "dot", "(", "$", "item", ")", ",", "$", "delimiter", ",", "$", "enclosure", ")", ";", "}", "return", "$", "stream", ";", "}" ]
Stream CSV output. @return object
[ "Stream", "CSV", "output", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Collection.php#L29-L44
32,935
QoboLtd/qobo-robo
src/Utility/File.php
File.readLines
public static function readLines($path, $skipEmpty = false) { if (!is_file($path) || !is_readable($path)) { throw new RuntimeException("File '$path' doesn't exist or is not a readable file"); } $lines = ($skipEmpty) ? file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : file($path, FILE_IGNORE_NEW_LINES); if ($lines === false) { throw new RuntimeException("Something went wrong while reading '$path' file content"); } return $lines; }
php
public static function readLines($path, $skipEmpty = false) { if (!is_file($path) || !is_readable($path)) { throw new RuntimeException("File '$path' doesn't exist or is not a readable file"); } $lines = ($skipEmpty) ? file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : file($path, FILE_IGNORE_NEW_LINES); if ($lines === false) { throw new RuntimeException("Something went wrong while reading '$path' file content"); } return $lines; }
[ "public", "static", "function", "readLines", "(", "$", "path", ",", "$", "skipEmpty", "=", "false", ")", "{", "if", "(", "!", "is_file", "(", "$", "path", ")", "||", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"File '$path' doesn't exist or is not a readable file\"", ")", ";", "}", "$", "lines", "=", "(", "$", "skipEmpty", ")", "?", "file", "(", "$", "path", ",", "FILE_IGNORE_NEW_LINES", "|", "FILE_SKIP_EMPTY_LINES", ")", ":", "file", "(", "$", "path", ",", "FILE_IGNORE_NEW_LINES", ")", ";", "if", "(", "$", "lines", "===", "false", ")", "{", "throw", "new", "RuntimeException", "(", "\"Something went wrong while reading '$path' file content\"", ")", ";", "}", "return", "$", "lines", ";", "}" ]
Read file content into array of lines without trailing newlines @param string $path Path to file @param bool $skipEmpty Flag to skip empty lines @return array Lines of file content
[ "Read", "file", "content", "into", "array", "of", "lines", "without", "trailing", "newlines" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/File.php#L29-L45
32,936
QoboLtd/qobo-robo
src/Utility/File.php
File.writeLines
public static function writeLines($path, $lines) { if (is_file($path) && !is_writable($path)) { throw new RuntimeException("File '$path' is not a writable file"); } // make sure every line has only one newline at the end $lines = array_map(function ($line) { return rtrim($line); }, $lines); $bytes = file_put_contents($path, implode("\n", $lines)); if ($bytes === false) { throw new RuntimeException("Something went wrong while writing content to '$path'"); } return true; }
php
public static function writeLines($path, $lines) { if (is_file($path) && !is_writable($path)) { throw new RuntimeException("File '$path' is not a writable file"); } // make sure every line has only one newline at the end $lines = array_map(function ($line) { return rtrim($line); }, $lines); $bytes = file_put_contents($path, implode("\n", $lines)); if ($bytes === false) { throw new RuntimeException("Something went wrong while writing content to '$path'"); } return true; }
[ "public", "static", "function", "writeLines", "(", "$", "path", ",", "$", "lines", ")", "{", "if", "(", "is_file", "(", "$", "path", ")", "&&", "!", "is_writable", "(", "$", "path", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"File '$path' is not a writable file\"", ")", ";", "}", "// make sure every line has only one newline at the end", "$", "lines", "=", "array_map", "(", "function", "(", "$", "line", ")", "{", "return", "rtrim", "(", "$", "line", ")", ";", "}", ",", "$", "lines", ")", ";", "$", "bytes", "=", "file_put_contents", "(", "$", "path", ",", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ")", ";", "if", "(", "$", "bytes", "===", "false", ")", "{", "throw", "new", "RuntimeException", "(", "\"Something went wrong while writing content to '$path'\"", ")", ";", "}", "return", "true", ";", "}" ]
Write array of lines into file @param string $path Path to file @param array $lines Content array @return bool true on success
[ "Write", "array", "of", "lines", "into", "file" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/File.php#L67-L84
32,937
anomalylabs/variables-module
src/Variable/Form/VariableFormBuilder.php
VariableFormBuilder.onReady
public function onReady(Container $container) { /* @var EntryModel $model */ $model = $container->make($this->getModel()); if ($model->isVersionable()) { $this->setButtons( [ 'versions' => [ 'href' => 'admin/variables/versions/{entry.id}?group={request.route.parameters.id}', ], 'cancel', ] ); } }
php
public function onReady(Container $container) { /* @var EntryModel $model */ $model = $container->make($this->getModel()); if ($model->isVersionable()) { $this->setButtons( [ 'versions' => [ 'href' => 'admin/variables/versions/{entry.id}?group={request.route.parameters.id}', ], 'cancel', ] ); } }
[ "public", "function", "onReady", "(", "Container", "$", "container", ")", "{", "/* @var EntryModel $model */", "$", "model", "=", "$", "container", "->", "make", "(", "$", "this", "->", "getModel", "(", ")", ")", ";", "if", "(", "$", "model", "->", "isVersionable", "(", ")", ")", "{", "$", "this", "->", "setButtons", "(", "[", "'versions'", "=>", "[", "'href'", "=>", "'admin/variables/versions/{entry.id}?group={request.route.parameters.id}'", ",", "]", ",", "'cancel'", ",", "]", ")", ";", "}", "}" ]
Fired just before building. @param Container $container
[ "Fired", "just", "before", "building", "." ]
bcd903670471a175f07aba3123693cb3a3c07d0b
https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Variable/Form/VariableFormBuilder.php#L22-L38
32,938
pxgamer/arionum-php
src/Arionum.php
Arionum.sendTransaction
public function sendTransaction(Transaction $transaction): string { $data = array_merge((array)$transaction, [ 'q' => 'send', ]); return $this->getJson($data); }
php
public function sendTransaction(Transaction $transaction): string { $data = array_merge((array)$transaction, [ 'q' => 'send', ]); return $this->getJson($data); }
[ "public", "function", "sendTransaction", "(", "Transaction", "$", "transaction", ")", ":", "string", "{", "$", "data", "=", "array_merge", "(", "(", "array", ")", "$", "transaction", ",", "[", "'q'", "=>", "'send'", ",", "]", ")", ";", "return", "$", "this", "->", "getJson", "(", "$", "data", ")", ";", "}" ]
Send a transaction. @param Transaction $transaction @return string @throws ApiException @api
[ "Send", "a", "transaction", "." ]
1d3e73f7b661878b864b3a910faad540e6af47bb
https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L281-L288
32,939
pxgamer/arionum-php
src/Arionum.php
Arionum.getRandomNumber
public function getRandomNumber(int $height, int $minimum, int $maximum, string $seed = null): int { return $this->getJson([ 'q' => 'randomNumber', 'height' => $height, 'min' => $minimum, 'max' => $maximum, 'seed' => $seed, ]); }
php
public function getRandomNumber(int $height, int $minimum, int $maximum, string $seed = null): int { return $this->getJson([ 'q' => 'randomNumber', 'height' => $height, 'min' => $minimum, 'max' => $maximum, 'seed' => $seed, ]); }
[ "public", "function", "getRandomNumber", "(", "int", "$", "height", ",", "int", "$", "minimum", ",", "int", "$", "maximum", ",", "string", "$", "seed", "=", "null", ")", ":", "int", "{", "return", "$", "this", "->", "getJson", "(", "[", "'q'", "=>", "'randomNumber'", ",", "'height'", "=>", "$", "height", ",", "'min'", "=>", "$", "minimum", ",", "'max'", "=>", "$", "maximum", ",", "'seed'", "=>", "$", "seed", ",", "]", ")", ";", "}" ]
Retrieve a random number based on a specified block. @param int $height @param int $minimum @param int $maximum @param string|null $seed @return int @throws ApiException @api
[ "Retrieve", "a", "random", "number", "based", "on", "a", "specified", "block", "." ]
1d3e73f7b661878b864b3a910faad540e6af47bb
https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L315-L324
32,940
pxgamer/arionum-php
src/Arionum.php
Arionum.checkSignature
public function checkSignature(string $signature, string $data, string $publicKey): bool { return $this->getJson([ 'q' => 'checkSignature', 'signature' => $signature, 'data' => $data, 'public_key' => $publicKey, ]); }
php
public function checkSignature(string $signature, string $data, string $publicKey): bool { return $this->getJson([ 'q' => 'checkSignature', 'signature' => $signature, 'data' => $data, 'public_key' => $publicKey, ]); }
[ "public", "function", "checkSignature", "(", "string", "$", "signature", ",", "string", "$", "data", ",", "string", "$", "publicKey", ")", ":", "bool", "{", "return", "$", "this", "->", "getJson", "(", "[", "'q'", "=>", "'checkSignature'", ",", "'signature'", "=>", "$", "signature", ",", "'data'", "=>", "$", "data", ",", "'public_key'", "=>", "$", "publicKey", ",", "]", ")", ";", "}" ]
Check that a signature is valid against a public key. @param string $signature @param string $data @param string $publicKey @return bool @throws ApiException @api
[ "Check", "that", "a", "signature", "is", "valid", "against", "a", "public", "key", "." ]
1d3e73f7b661878b864b3a910faad540e6af47bb
https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L336-L344
32,941
pxgamer/arionum-php
src/Arionum.php
Arionum.checkAddress
public function checkAddress(string $address, ?string $publicKey = null): bool { return $this->getJson([ 'q' => 'checkAddress', 'account' => $address, 'public_key' => $publicKey, ]); }
php
public function checkAddress(string $address, ?string $publicKey = null): bool { return $this->getJson([ 'q' => 'checkAddress', 'account' => $address, 'public_key' => $publicKey, ]); }
[ "public", "function", "checkAddress", "(", "string", "$", "address", ",", "?", "string", "$", "publicKey", "=", "null", ")", ":", "bool", "{", "return", "$", "this", "->", "getJson", "(", "[", "'q'", "=>", "'checkAddress'", ",", "'account'", "=>", "$", "address", ",", "'public_key'", "=>", "$", "publicKey", ",", "]", ")", ";", "}" ]
Check that an address is valid. Optionally validate it against the corresponding public key. @param string $address @param string|null $publicKey An optional corresponding public key. @return bool @throws ApiException @api
[ "Check", "that", "an", "address", "is", "valid", ".", "Optionally", "validate", "it", "against", "the", "corresponding", "public", "key", "." ]
1d3e73f7b661878b864b3a910faad540e6af47bb
https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L414-L421
32,942
nails/module-invoice
src/Model/Refund.php
Refund.setPending
public function setPending($iRefundId, $aData = []) { $aData['status'] = self::STATUS_PENDING; return $this->update($iRefundId, $aData); }
php
public function setPending($iRefundId, $aData = []) { $aData['status'] = self::STATUS_PENDING; return $this->update($iRefundId, $aData); }
[ "public", "function", "setPending", "(", "$", "iRefundId", ",", "$", "aData", "=", "[", "]", ")", "{", "$", "aData", "[", "'status'", "]", "=", "self", "::", "STATUS_PENDING", ";", "return", "$", "this", "->", "update", "(", "$", "iRefundId", ",", "$", "aData", ")", ";", "}" ]
Set a refund as PENDING @param integer $iRefundId The refund to update @param array $aData Any additional data to save to the transaction @return boolean
[ "Set", "a", "refund", "as", "PENDING" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L222-L226
32,943
nails/module-invoice
src/Model/Refund.php
Refund.setProcessing
public function setProcessing($iRefundId, $aData = []) { $aData['status'] = self::STATUS_PROCESSING; return $this->update($iRefundId, $aData); }
php
public function setProcessing($iRefundId, $aData = []) { $aData['status'] = self::STATUS_PROCESSING; return $this->update($iRefundId, $aData); }
[ "public", "function", "setProcessing", "(", "$", "iRefundId", ",", "$", "aData", "=", "[", "]", ")", "{", "$", "aData", "[", "'status'", "]", "=", "self", "::", "STATUS_PROCESSING", ";", "return", "$", "this", "->", "update", "(", "$", "iRefundId", ",", "$", "aData", ")", ";", "}" ]
Set a refund as PROCESSING @param integer $iRefundId The refund to update @param array $aData Any additional data to save to the transaction @return boolean
[ "Set", "a", "refund", "as", "PROCESSING" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L238-L242
32,944
nails/module-invoice
src/Model/Refund.php
Refund.setFailed
public function setFailed($iRefundId, $aData = []) { $aData['status'] = self::STATUS_FAILED; return $this->update($iRefundId, $aData); }
php
public function setFailed($iRefundId, $aData = []) { $aData['status'] = self::STATUS_FAILED; return $this->update($iRefundId, $aData); }
[ "public", "function", "setFailed", "(", "$", "iRefundId", ",", "$", "aData", "=", "[", "]", ")", "{", "$", "aData", "[", "'status'", "]", "=", "self", "::", "STATUS_FAILED", ";", "return", "$", "this", "->", "update", "(", "$", "iRefundId", ",", "$", "aData", ")", ";", "}" ]
Set a refund as FAILED @param integer $iRefundId The refund to update @param array $aData Any additional data to save to the transaction @return boolean
[ "Set", "a", "refund", "as", "FAILED" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L270-L274
32,945
nails/module-invoice
src/Model/Refund.php
Refund.sendReceipt
public function sendReceipt($iRefundId, $sEmailOverride = null) { try { $oRefund = $this->getById( $iRefundId, [ 'expand' => [ ['invoice', ['expand' => ['customer']]], 'payment', ], ] ); if (empty($oRefund)) { throw new PaymentException('Invalid Payment ID', 1); } if (!in_array($oRefund->status->id, [self::STATUS_PROCESSING, self::STATUS_COMPLETE])) { throw new PaymentException('Refund must be in a paid or processing state to send receipt.', 1); } $oEmail = new \stdClass(); if ($oRefund->status->id == self::STATUS_COMPLETE) { $oEmail->type = 'refund_complete_receipt'; } else { $oEmail->type = 'refund_processing_receipt'; } $oEmail->data = [ 'refund' => $oRefund, ]; if (!empty($sEmailOverride)) { // @todo (Pablo - 2019-01-20) - validate email address (or addresses if an array) $aEmails = explode(',', $sEmailOverride); } elseif (!empty($oRefund->invoice->customer->billing_email)) { $aEmails = explode(',', $oRefund->invoice->customer->billing_email); } elseif (!empty($oRefund->invoice->customer->email)) { $aEmails = [$oRefund->invoice->customer->email]; } else { throw new PaymentException('No email address to send the receipt to.', 1); } $aEmails = array_unique($aEmails); $aEmails = array_filter($aEmails); $oEmailer = Factory::service('Emailer', 'nails/module-email'); $oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice'); foreach ($aEmails as $sEmail) { $oEmail->to_email = $sEmail; $oResult = $oEmailer->send($oEmail); if (!empty($oResult)) { $oInvoiceEmailModel->create( [ 'invoice_id' => $oRefund->invoice->id, 'email_id' => $oResult->id, 'email_type' => $oEmail->type, 'recipient' => $oEmail->to_email, ] ); } else { throw new PaymentException($oEmailer->lastError(), 1); } } } catch (\Exception $e) { $this->setError($e->getMessage()); return false; } return true; }
php
public function sendReceipt($iRefundId, $sEmailOverride = null) { try { $oRefund = $this->getById( $iRefundId, [ 'expand' => [ ['invoice', ['expand' => ['customer']]], 'payment', ], ] ); if (empty($oRefund)) { throw new PaymentException('Invalid Payment ID', 1); } if (!in_array($oRefund->status->id, [self::STATUS_PROCESSING, self::STATUS_COMPLETE])) { throw new PaymentException('Refund must be in a paid or processing state to send receipt.', 1); } $oEmail = new \stdClass(); if ($oRefund->status->id == self::STATUS_COMPLETE) { $oEmail->type = 'refund_complete_receipt'; } else { $oEmail->type = 'refund_processing_receipt'; } $oEmail->data = [ 'refund' => $oRefund, ]; if (!empty($sEmailOverride)) { // @todo (Pablo - 2019-01-20) - validate email address (or addresses if an array) $aEmails = explode(',', $sEmailOverride); } elseif (!empty($oRefund->invoice->customer->billing_email)) { $aEmails = explode(',', $oRefund->invoice->customer->billing_email); } elseif (!empty($oRefund->invoice->customer->email)) { $aEmails = [$oRefund->invoice->customer->email]; } else { throw new PaymentException('No email address to send the receipt to.', 1); } $aEmails = array_unique($aEmails); $aEmails = array_filter($aEmails); $oEmailer = Factory::service('Emailer', 'nails/module-email'); $oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice'); foreach ($aEmails as $sEmail) { $oEmail->to_email = $sEmail; $oResult = $oEmailer->send($oEmail); if (!empty($oResult)) { $oInvoiceEmailModel->create( [ 'invoice_id' => $oRefund->invoice->id, 'email_id' => $oResult->id, 'email_type' => $oEmail->type, 'recipient' => $oEmail->to_email, ] ); } else { throw new PaymentException($oEmailer->lastError(), 1); } } } catch (\Exception $e) { $this->setError($e->getMessage()); return false; } return true; }
[ "public", "function", "sendReceipt", "(", "$", "iRefundId", ",", "$", "sEmailOverride", "=", "null", ")", "{", "try", "{", "$", "oRefund", "=", "$", "this", "->", "getById", "(", "$", "iRefundId", ",", "[", "'expand'", "=>", "[", "[", "'invoice'", ",", "[", "'expand'", "=>", "[", "'customer'", "]", "]", "]", ",", "'payment'", ",", "]", ",", "]", ")", ";", "if", "(", "empty", "(", "$", "oRefund", ")", ")", "{", "throw", "new", "PaymentException", "(", "'Invalid Payment ID'", ",", "1", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "oRefund", "->", "status", "->", "id", ",", "[", "self", "::", "STATUS_PROCESSING", ",", "self", "::", "STATUS_COMPLETE", "]", ")", ")", "{", "throw", "new", "PaymentException", "(", "'Refund must be in a paid or processing state to send receipt.'", ",", "1", ")", ";", "}", "$", "oEmail", "=", "new", "\\", "stdClass", "(", ")", ";", "if", "(", "$", "oRefund", "->", "status", "->", "id", "==", "self", "::", "STATUS_COMPLETE", ")", "{", "$", "oEmail", "->", "type", "=", "'refund_complete_receipt'", ";", "}", "else", "{", "$", "oEmail", "->", "type", "=", "'refund_processing_receipt'", ";", "}", "$", "oEmail", "->", "data", "=", "[", "'refund'", "=>", "$", "oRefund", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "sEmailOverride", ")", ")", "{", "// @todo (Pablo - 2019-01-20) - validate email address (or addresses if an array)", "$", "aEmails", "=", "explode", "(", "','", ",", "$", "sEmailOverride", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "oRefund", "->", "invoice", "->", "customer", "->", "billing_email", ")", ")", "{", "$", "aEmails", "=", "explode", "(", "','", ",", "$", "oRefund", "->", "invoice", "->", "customer", "->", "billing_email", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "oRefund", "->", "invoice", "->", "customer", "->", "email", ")", ")", "{", "$", "aEmails", "=", "[", "$", "oRefund", "->", "invoice", "->", "customer", "->", "email", "]", ";", "}", "else", "{", "throw", "new", "PaymentException", "(", "'No email address to send the receipt to.'", ",", "1", ")", ";", "}", "$", "aEmails", "=", "array_unique", "(", "$", "aEmails", ")", ";", "$", "aEmails", "=", "array_filter", "(", "$", "aEmails", ")", ";", "$", "oEmailer", "=", "Factory", "::", "service", "(", "'Emailer'", ",", "'nails/module-email'", ")", ";", "$", "oInvoiceEmailModel", "=", "Factory", "::", "model", "(", "'InvoiceEmail'", ",", "'nails/module-invoice'", ")", ";", "foreach", "(", "$", "aEmails", "as", "$", "sEmail", ")", "{", "$", "oEmail", "->", "to_email", "=", "$", "sEmail", ";", "$", "oResult", "=", "$", "oEmailer", "->", "send", "(", "$", "oEmail", ")", ";", "if", "(", "!", "empty", "(", "$", "oResult", ")", ")", "{", "$", "oInvoiceEmailModel", "->", "create", "(", "[", "'invoice_id'", "=>", "$", "oRefund", "->", "invoice", "->", "id", ",", "'email_id'", "=>", "$", "oResult", "->", "id", ",", "'email_type'", "=>", "$", "oEmail", "->", "type", ",", "'recipient'", "=>", "$", "oEmail", "->", "to_email", ",", "]", ")", ";", "}", "else", "{", "throw", "new", "PaymentException", "(", "$", "oEmailer", "->", "lastError", "(", ")", ",", "1", ")", ";", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "setError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Sends refund receipt email @param integer $iRefundId The ID of the refund @param string $sEmailOverride The email address to send the email to @return bool
[ "Sends", "refund", "receipt", "email" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L286-L362
32,946
nails/module-invoice
src/Model/Refund.php
Refund.getRefundForEvent
protected function getRefundForEvent(int $iRefundId): Resource { $oRefund = $this->getById($iRefundId); if (empty($oRefund)) { throw new ModelException('Invalid refund ID'); } return $oRefund; }
php
protected function getRefundForEvent(int $iRefundId): Resource { $oRefund = $this->getById($iRefundId); if (empty($oRefund)) { throw new ModelException('Invalid refund ID'); } return $oRefund; }
[ "protected", "function", "getRefundForEvent", "(", "int", "$", "iRefundId", ")", ":", "Resource", "{", "$", "oRefund", "=", "$", "this", "->", "getById", "(", "$", "iRefundId", ")", ";", "if", "(", "empty", "(", "$", "oRefund", ")", ")", "{", "throw", "new", "ModelException", "(", "'Invalid refund ID'", ")", ";", "}", "return", "$", "oRefund", ";", "}" ]
Get a refund in a suitable format for the event triggers @param int $iRefundId The refund ID @return Resource @throws ModelException
[ "Get", "a", "refund", "in", "a", "suitable", "format", "for", "the", "event", "triggers" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L374-L381
32,947
Saritasa/php-laravel-entity-services
src/LaravelEntityServicesServiceProvider.php
LaravelEntityServicesServiceProvider.boot
public function boot(): void { $this->publishes( [ __DIR__ . '/../config/laravel_entity_services.php' => $this->app->make('path.config') . DIRECTORY_SEPARATOR . 'laravel_entity_services.php', ], 'laravel_repositories' ); $this->mergeConfigFrom(__DIR__ . '/../config/laravel_entity_services.php', 'laravel_entity_services'); $this->registerCustomBindings(); }
php
public function boot(): void { $this->publishes( [ __DIR__ . '/../config/laravel_entity_services.php' => $this->app->make('path.config') . DIRECTORY_SEPARATOR . 'laravel_entity_services.php', ], 'laravel_repositories' ); $this->mergeConfigFrom(__DIR__ . '/../config/laravel_entity_services.php', 'laravel_entity_services'); $this->registerCustomBindings(); }
[ "public", "function", "boot", "(", ")", ":", "void", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../config/laravel_entity_services.php'", "=>", "$", "this", "->", "app", "->", "make", "(", "'path.config'", ")", ".", "DIRECTORY_SEPARATOR", ".", "'laravel_entity_services.php'", ",", "]", ",", "'laravel_repositories'", ")", ";", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../config/laravel_entity_services.php'", ",", "'laravel_entity_services'", ")", ";", "$", "this", "->", "registerCustomBindings", "(", ")", ";", "}" ]
Make package settings needed to correct work. @return void @throws BindingResolutionException
[ "Make", "package", "settings", "needed", "to", "correct", "work", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/LaravelEntityServicesServiceProvider.php#L33-L45
32,948
Saritasa/php-laravel-entity-services
src/LaravelEntityServicesServiceProvider.php
LaravelEntityServicesServiceProvider.registerCustomBindings
protected function registerCustomBindings(): void { $entityServiceFactory = $this->app->make(IEntityServiceFactory::class); foreach (config('laravel_entity_services.bindings') as $className => $entityService) { $entityServiceFactory->register($className, $entityService); } }
php
protected function registerCustomBindings(): void { $entityServiceFactory = $this->app->make(IEntityServiceFactory::class); foreach (config('laravel_entity_services.bindings') as $className => $entityService) { $entityServiceFactory->register($className, $entityService); } }
[ "protected", "function", "registerCustomBindings", "(", ")", ":", "void", "{", "$", "entityServiceFactory", "=", "$", "this", "->", "app", "->", "make", "(", "IEntityServiceFactory", "::", "class", ")", ";", "foreach", "(", "config", "(", "'laravel_entity_services.bindings'", ")", "as", "$", "className", "=>", "$", "entityService", ")", "{", "$", "entityServiceFactory", "->", "register", "(", "$", "className", ",", "$", "entityService", ")", ";", "}", "}" ]
Register custom entity services implementations. @return void @throws BindingResolutionException
[ "Register", "custom", "entity", "services", "implementations", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/LaravelEntityServicesServiceProvider.php#L54-L61
32,949
Saritasa/php-laravel-entity-services
src/Services/EntityService.php
EntityService.getValidationRulesForAttributes
protected function getValidationRulesForAttributes(array $modelParams, array $rules = []): array { $modelRules = empty($rules) ? $this->getValidationRules() : $rules; return array_intersect_key($modelRules, $modelParams); }
php
protected function getValidationRulesForAttributes(array $modelParams, array $rules = []): array { $modelRules = empty($rules) ? $this->getValidationRules() : $rules; return array_intersect_key($modelRules, $modelParams); }
[ "protected", "function", "getValidationRulesForAttributes", "(", "array", "$", "modelParams", ",", "array", "$", "rules", "=", "[", "]", ")", ":", "array", "{", "$", "modelRules", "=", "empty", "(", "$", "rules", ")", "?", "$", "this", "->", "getValidationRules", "(", ")", ":", "$", "rules", ";", "return", "array_intersect_key", "(", "$", "modelRules", ",", "$", "modelParams", ")", ";", "}" ]
Return rules for given attributes. @param array $modelParams Updating fields @param array $rules Custom validation rules @return array
[ "Return", "rules", "for", "given", "attributes", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L120-L124
32,950
Saritasa/php-laravel-entity-services
src/Services/EntityService.php
EntityService.validate
protected function validate(array $data, array $rules = null): void { $validator = $this->validatorFactory->make($data, $rules ?? $this->getValidationRules()); if ($validator->fails()) { throw new ValidationException($validator); } }
php
protected function validate(array $data, array $rules = null): void { $validator = $this->validatorFactory->make($data, $rules ?? $this->getValidationRules()); if ($validator->fails()) { throw new ValidationException($validator); } }
[ "protected", "function", "validate", "(", "array", "$", "data", ",", "array", "$", "rules", "=", "null", ")", ":", "void", "{", "$", "validator", "=", "$", "this", "->", "validatorFactory", "->", "make", "(", "$", "data", ",", "$", "rules", "??", "$", "this", "->", "getValidationRules", "(", ")", ")", ";", "if", "(", "$", "validator", "->", "fails", "(", ")", ")", "{", "throw", "new", "ValidationException", "(", "$", "validator", ")", ";", "}", "}" ]
Validates data. @param array $data Data to validate @param array|null $rules Validation rules @throws ValidationException @return void
[ "Validates", "data", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L163-L169
32,951
Saritasa/php-laravel-entity-services
src/Services/EntityService.php
EntityService.getValidationRules
protected function getValidationRules(): array { $validationRulesFromRepository = $this->repository->getModelValidationRules(); return !empty($validationRulesFromRepository) ? $validationRulesFromRepository : $this->validationRules; }
php
protected function getValidationRules(): array { $validationRulesFromRepository = $this->repository->getModelValidationRules(); return !empty($validationRulesFromRepository) ? $validationRulesFromRepository : $this->validationRules; }
[ "protected", "function", "getValidationRules", "(", ")", ":", "array", "{", "$", "validationRulesFromRepository", "=", "$", "this", "->", "repository", "->", "getModelValidationRules", "(", ")", ";", "return", "!", "empty", "(", "$", "validationRulesFromRepository", ")", "?", "$", "validationRulesFromRepository", ":", "$", "this", "->", "validationRules", ";", "}" ]
Returns validation rules. @return array
[ "Returns", "validation", "rules", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L176-L181
32,952
canihavesomecoffee/theTVDbAPI
src/MultiLanguageWrapper/Route/EpisodesRouteLanguageFallback.php
EpisodesRouteLanguageFallback.getClosureById
public function getClosureById(int $episodeId): Closure { return function ($language) use ($episodeId) { $json = $this->parent->performAPICallWithJsonResponse( 'get', '/episodes/'.$episodeId, [ 'headers' => ['Accept-Language' => $language] ] ); return DataParser::parseData($json, Episode::class); }; }
php
public function getClosureById(int $episodeId): Closure { return function ($language) use ($episodeId) { $json = $this->parent->performAPICallWithJsonResponse( 'get', '/episodes/'.$episodeId, [ 'headers' => ['Accept-Language' => $language] ] ); return DataParser::parseData($json, Episode::class); }; }
[ "public", "function", "getClosureById", "(", "int", "$", "episodeId", ")", ":", "Closure", "{", "return", "function", "(", "$", "language", ")", "use", "(", "$", "episodeId", ")", "{", "$", "json", "=", "$", "this", "->", "parent", "->", "performAPICallWithJsonResponse", "(", "'get'", ",", "'/episodes/'", ".", "$", "episodeId", ",", "[", "'headers'", "=>", "[", "'Accept-Language'", "=>", "$", "language", "]", "]", ")", ";", "return", "DataParser", "::", "parseData", "(", "$", "json", ",", "Episode", "::", "class", ")", ";", "}", ";", "}" ]
Returns the closure used to fetch an episode by id for a single language. @param int $episodeId The episode to fetch. @return Closure
[ "Returns", "the", "closure", "used", "to", "fetch", "an", "episode", "by", "id", "for", "a", "single", "language", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/Route/EpisodesRouteLanguageFallback.php#L79-L91
32,953
QoboLtd/qobo-robo
src/AbstractTask.php
AbstractTask.printInfo
protected function printInfo($msg, $data = null) { // pass-through when no 'name' found in data if ($data == null || !isset($data['name'])) { return $this->printTaskInfo($msg, $data); } // doubt someone will use this ever in data $key = 'print_task_info_name_replacement_macro'; // replace 'name' with above key both in data // and in msg placeholders $data[$key] = $data['name']; unset($data['name']); $msg = str_replace('{name}', '{' . $key . '}', $msg); // print nice message $result = $this->printTaskInfo($msg, $data); return $result; }
php
protected function printInfo($msg, $data = null) { // pass-through when no 'name' found in data if ($data == null || !isset($data['name'])) { return $this->printTaskInfo($msg, $data); } // doubt someone will use this ever in data $key = 'print_task_info_name_replacement_macro'; // replace 'name' with above key both in data // and in msg placeholders $data[$key] = $data['name']; unset($data['name']); $msg = str_replace('{name}', '{' . $key . '}', $msg); // print nice message $result = $this->printTaskInfo($msg, $data); return $result; }
[ "protected", "function", "printInfo", "(", "$", "msg", ",", "$", "data", "=", "null", ")", "{", "// pass-through when no 'name' found in data", "if", "(", "$", "data", "==", "null", "||", "!", "isset", "(", "$", "data", "[", "'name'", "]", ")", ")", "{", "return", "$", "this", "->", "printTaskInfo", "(", "$", "msg", ",", "$", "data", ")", ";", "}", "// doubt someone will use this ever in data", "$", "key", "=", "'print_task_info_name_replacement_macro'", ";", "// replace 'name' with above key both in data", "// and in msg placeholders", "$", "data", "[", "$", "key", "]", "=", "$", "data", "[", "'name'", "]", ";", "unset", "(", "$", "data", "[", "'name'", "]", ")", ";", "$", "msg", "=", "str_replace", "(", "'{name}'", ",", "'{'", ".", "$", "key", ".", "'}'", ",", "$", "msg", ")", ";", "// print nice message", "$", "result", "=", "$", "this", "->", "printTaskInfo", "(", "$", "msg", ",", "$", "data", ")", ";", "return", "$", "result", ";", "}" ]
A quick fix on printInfo, as it is not very friendly when you use 'name' placeholders or even just have 'name' set in the data
[ "A", "quick", "fix", "on", "printInfo", "as", "it", "is", "not", "very", "friendly", "when", "you", "use", "name", "placeholders", "or", "even", "just", "have", "name", "set", "in", "the", "data" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/AbstractTask.php#L156-L176
32,954
byjg/restserver
src/HttpResponse.php
HttpResponse.addCookie
public function addCookie($name, $value, $expire = null, $path = null, $domain = null) { if (!is_null($expire)) { $expire = time() + $expire; } setcookie($name, $value, $expire, $path, $domain); }
php
public function addCookie($name, $value, $expire = null, $path = null, $domain = null) { if (!is_null($expire)) { $expire = time() + $expire; } setcookie($name, $value, $expire, $path, $domain); }
[ "public", "function", "addCookie", "(", "$", "name", ",", "$", "value", ",", "$", "expire", "=", "null", ",", "$", "path", "=", "null", ",", "$", "domain", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "expire", ")", ")", "{", "$", "expire", "=", "time", "(", ")", "+", "$", "expire", ";", "}", "setcookie", "(", "$", "name", ",", "$", "value", ",", "$", "expire", ",", "$", "path", ",", "$", "domain", ")", ";", "}" ]
Add a cookie value @param string $name @param string $value @param int $expire (seconds from now) @param int $path (directory into domain in which the cookie will be available on ) @param string $domain
[ "Add", "a", "cookie", "value" ]
1fdbd58f414f5d9958de0873d67eea961dc52fda
https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpResponse.php#L63-L69
32,955
byjg/restserver
src/HttpResponse.php
HttpResponse.writeDebug
public function writeDebug($key, $string) { if (is_null($this->responseDebug)) { $this->responseDebug = new ResponseBag(); $this->response->add($this->responseDebug); } $this->responseDebug->add(['debug' => [$key => $string]]); ErrorHandler::getInstance()->addExtraInfo($key, serialize($string)); }
php
public function writeDebug($key, $string) { if (is_null($this->responseDebug)) { $this->responseDebug = new ResponseBag(); $this->response->add($this->responseDebug); } $this->responseDebug->add(['debug' => [$key => $string]]); ErrorHandler::getInstance()->addExtraInfo($key, serialize($string)); }
[ "public", "function", "writeDebug", "(", "$", "key", ",", "$", "string", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "responseDebug", ")", ")", "{", "$", "this", "->", "responseDebug", "=", "new", "ResponseBag", "(", ")", ";", "$", "this", "->", "response", "->", "add", "(", "$", "this", "->", "responseDebug", ")", ";", "}", "$", "this", "->", "responseDebug", "->", "add", "(", "[", "'debug'", "=>", "[", "$", "key", "=>", "$", "string", "]", "]", ")", ";", "ErrorHandler", "::", "getInstance", "(", ")", "->", "addExtraInfo", "(", "$", "key", ",", "serialize", "(", "$", "string", ")", ")", ";", "}" ]
Added informations for debug purposes only. In case the error it will showed and the result a node called "debug" will be added. @param string $key @param mixed $string
[ "Added", "informations", "for", "debug", "purposes", "only", ".", "In", "case", "the", "error", "it", "will", "showed", "and", "the", "result", "a", "node", "called", "debug", "will", "be", "added", "." ]
1fdbd58f414f5d9958de0873d67eea961dc52fda
https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpResponse.php#L110-L118
32,956
wikimedia/mediawiki-oauthclient-php
src/Client.php
Client.makeOAuthCall
public function makeOAuthCall( /*Token*/ $token, $url, $isPost = false, array $postFields = null ) { // Figure out if there is a file in postFields $hasFile = false; if ( is_array( $postFields ) ) { foreach ( $postFields as $field ) { if ( is_a( $field, 'CurlFile' ) ) { $hasFile = true; break; } } } $params = []; // Get any params from the url if ( strpos( $url, '?' ) ) { $parsed = parse_url( $url ); parse_str( $parsed['query'], $params ); } $params += $this->extraParams; if ( $isPost && $postFields && !$hasFile ) { $params += $postFields; } $method = $isPost ? 'POST' : 'GET'; $req = Request::fromConsumerAndToken( $this->config->consumer, $token, $method, $url, $params ); $req->signRequest( new HmacSha1(), $this->config->consumer, $token ); $this->lastNonce = $req->getParameter( 'oauth_nonce' ); return $this->makeCurlCall( $url, $req->toHeader(), $isPost, $postFields, $hasFile ); }
php
public function makeOAuthCall( /*Token*/ $token, $url, $isPost = false, array $postFields = null ) { // Figure out if there is a file in postFields $hasFile = false; if ( is_array( $postFields ) ) { foreach ( $postFields as $field ) { if ( is_a( $field, 'CurlFile' ) ) { $hasFile = true; break; } } } $params = []; // Get any params from the url if ( strpos( $url, '?' ) ) { $parsed = parse_url( $url ); parse_str( $parsed['query'], $params ); } $params += $this->extraParams; if ( $isPost && $postFields && !$hasFile ) { $params += $postFields; } $method = $isPost ? 'POST' : 'GET'; $req = Request::fromConsumerAndToken( $this->config->consumer, $token, $method, $url, $params ); $req->signRequest( new HmacSha1(), $this->config->consumer, $token ); $this->lastNonce = $req->getParameter( 'oauth_nonce' ); return $this->makeCurlCall( $url, $req->toHeader(), $isPost, $postFields, $hasFile ); }
[ "public", "function", "makeOAuthCall", "(", "/*Token*/", "$", "token", ",", "$", "url", ",", "$", "isPost", "=", "false", ",", "array", "$", "postFields", "=", "null", ")", "{", "// Figure out if there is a file in postFields", "$", "hasFile", "=", "false", ";", "if", "(", "is_array", "(", "$", "postFields", ")", ")", "{", "foreach", "(", "$", "postFields", "as", "$", "field", ")", "{", "if", "(", "is_a", "(", "$", "field", ",", "'CurlFile'", ")", ")", "{", "$", "hasFile", "=", "true", ";", "break", ";", "}", "}", "}", "$", "params", "=", "[", "]", ";", "// Get any params from the url", "if", "(", "strpos", "(", "$", "url", ",", "'?'", ")", ")", "{", "$", "parsed", "=", "parse_url", "(", "$", "url", ")", ";", "parse_str", "(", "$", "parsed", "[", "'query'", "]", ",", "$", "params", ")", ";", "}", "$", "params", "+=", "$", "this", "->", "extraParams", ";", "if", "(", "$", "isPost", "&&", "$", "postFields", "&&", "!", "$", "hasFile", ")", "{", "$", "params", "+=", "$", "postFields", ";", "}", "$", "method", "=", "$", "isPost", "?", "'POST'", ":", "'GET'", ";", "$", "req", "=", "Request", "::", "fromConsumerAndToken", "(", "$", "this", "->", "config", "->", "consumer", ",", "$", "token", ",", "$", "method", ",", "$", "url", ",", "$", "params", ")", ";", "$", "req", "->", "signRequest", "(", "new", "HmacSha1", "(", ")", ",", "$", "this", "->", "config", "->", "consumer", ",", "$", "token", ")", ";", "$", "this", "->", "lastNonce", "=", "$", "req", "->", "getParameter", "(", "'oauth_nonce'", ")", ";", "return", "$", "this", "->", "makeCurlCall", "(", "$", "url", ",", "$", "req", "->", "toHeader", "(", ")", ",", "$", "isPost", ",", "$", "postFields", ",", "$", "hasFile", ")", ";", "}" ]
Make a signed request to MediaWiki @param Token $token additional token to use in signature, besides the consumer token. In most cases, this will be the access token you got from complete(), but we set it to the request token when finishing the handshake. @param string $url URL to call @param bool $isPost true if this should be a POST request @param array|null $postFields POST parameters, only if $isPost is also true @return string Body from the curl request @throws Exception On curl failure
[ "Make", "a", "signed", "request", "to", "MediaWiki" ]
1c8b33ff91273ba50e987d380724add7051d31ea
https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L224-L269
32,957
wikimedia/mediawiki-oauthclient-php
src/Client.php
Client.compareHash
private function compareHash( $hash1, $hash2 ) { $result = strlen( $hash1 ) ^ strlen( $hash2 ); $len = min( strlen( $hash1 ), strlen( $hash2 ) ) - 1; for ( $i = 0; $i < $len; $i++ ) { $result |= ord( $hash1{$i} ) ^ ord( $hash2{$i} ); } return $result == 0; }
php
private function compareHash( $hash1, $hash2 ) { $result = strlen( $hash1 ) ^ strlen( $hash2 ); $len = min( strlen( $hash1 ), strlen( $hash2 ) ) - 1; for ( $i = 0; $i < $len; $i++ ) { $result |= ord( $hash1{$i} ) ^ ord( $hash2{$i} ); } return $result == 0; }
[ "private", "function", "compareHash", "(", "$", "hash1", ",", "$", "hash2", ")", "{", "$", "result", "=", "strlen", "(", "$", "hash1", ")", "^", "strlen", "(", "$", "hash2", ")", ";", "$", "len", "=", "min", "(", "strlen", "(", "$", "hash1", ")", ",", "strlen", "(", "$", "hash2", ")", ")", "-", "1", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "$", "i", "++", ")", "{", "$", "result", "|=", "ord", "(", "$", "hash1", "{", "$", "i", "}", ")", "^", "ord", "(", "$", "hash2", "{", "$", "i", "}", ")", ";", "}", "return", "$", "result", "==", "0", ";", "}" ]
Constant time comparison @param string $hash1 @param string $hash2 @return bool
[ "Constant", "time", "comparison" ]
1c8b33ff91273ba50e987d380724add7051d31ea
https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L410-L417
32,958
wikimedia/mediawiki-oauthclient-php
src/Client.php
Client.decodeJson
private function decodeJson( $json ) { $error = $errorMsg = null; $return = json_decode( $json ); if ( $return === null && trim( $json ) !== 'null' ) { $error = json_last_error(); $errorMsg = json_last_error_msg(); } elseif ( !$return || !is_object( $return ) ) { $error = 128; $errorMsg = 'Response must be an object'; } if ( $error ) { $this->logger->error( 'Failed to decode server response as JSON: {message}', [ 'response' => $json, 'code' => json_last_error(), 'message' => json_last_error_msg(), ] ); throw new Exception( 'Decoding server response failed: ' . json_last_error_msg() . " (Raw response: $json)" ); } return $return; }
php
private function decodeJson( $json ) { $error = $errorMsg = null; $return = json_decode( $json ); if ( $return === null && trim( $json ) !== 'null' ) { $error = json_last_error(); $errorMsg = json_last_error_msg(); } elseif ( !$return || !is_object( $return ) ) { $error = 128; $errorMsg = 'Response must be an object'; } if ( $error ) { $this->logger->error( 'Failed to decode server response as JSON: {message}', [ 'response' => $json, 'code' => json_last_error(), 'message' => json_last_error_msg(), ] ); throw new Exception( 'Decoding server response failed: ' . json_last_error_msg() . " (Raw response: $json)" ); } return $return; }
[ "private", "function", "decodeJson", "(", "$", "json", ")", "{", "$", "error", "=", "$", "errorMsg", "=", "null", ";", "$", "return", "=", "json_decode", "(", "$", "json", ")", ";", "if", "(", "$", "return", "===", "null", "&&", "trim", "(", "$", "json", ")", "!==", "'null'", ")", "{", "$", "error", "=", "json_last_error", "(", ")", ";", "$", "errorMsg", "=", "json_last_error_msg", "(", ")", ";", "}", "elseif", "(", "!", "$", "return", "||", "!", "is_object", "(", "$", "return", ")", ")", "{", "$", "error", "=", "128", ";", "$", "errorMsg", "=", "'Response must be an object'", ";", "}", "if", "(", "$", "error", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "'Failed to decode server response as JSON: {message}'", ",", "[", "'response'", "=>", "$", "json", ",", "'code'", "=>", "json_last_error", "(", ")", ",", "'message'", "=>", "json_last_error_msg", "(", ")", ",", "]", ")", ";", "throw", "new", "Exception", "(", "'Decoding server response failed: '", ".", "json_last_error_msg", "(", ")", ".", "\" (Raw response: $json)\"", ")", ";", "}", "return", "$", "return", ";", "}" ]
Like json_decode but with sane error handling. Assumes that null is not a valid value for the JSON string. @param string $json @return mixed @throws Exception On invalid JSON
[ "Like", "json_decode", "but", "with", "sane", "error", "handling", ".", "Assumes", "that", "null", "is", "not", "a", "valid", "value", "for", "the", "JSON", "string", "." ]
1c8b33ff91273ba50e987d380724add7051d31ea
https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L426-L450
32,959
QoboLtd/qobo-robo
src/Command/Project/Version.php
Version.projectVersion
public function projectVersion($opts = ['format' => 'table', 'fields' => '']) { $result = $this->taskDotenvReload()->run(); $envVersion = getenv('GIT_BRANCH'); if (!empty($envVersion)) { return new PropertyList(['version' => $envVersion]); } $result = $this->taskGitHash()->run(); if ($result->wasSuccessful()) { return new PropertyList(['version' => $result->getData()['data'][0]['message'] ]); } return new PropertyList(['version' => 'Unknown']); }
php
public function projectVersion($opts = ['format' => 'table', 'fields' => '']) { $result = $this->taskDotenvReload()->run(); $envVersion = getenv('GIT_BRANCH'); if (!empty($envVersion)) { return new PropertyList(['version' => $envVersion]); } $result = $this->taskGitHash()->run(); if ($result->wasSuccessful()) { return new PropertyList(['version' => $result->getData()['data'][0]['message'] ]); } return new PropertyList(['version' => 'Unknown']); }
[ "public", "function", "projectVersion", "(", "$", "opts", "=", "[", "'format'", "=>", "'table'", ",", "'fields'", "=>", "''", "]", ")", "{", "$", "result", "=", "$", "this", "->", "taskDotenvReload", "(", ")", "->", "run", "(", ")", ";", "$", "envVersion", "=", "getenv", "(", "'GIT_BRANCH'", ")", ";", "if", "(", "!", "empty", "(", "$", "envVersion", ")", ")", "{", "return", "new", "PropertyList", "(", "[", "'version'", "=>", "$", "envVersion", "]", ")", ";", "}", "$", "result", "=", "$", "this", "->", "taskGitHash", "(", ")", "->", "run", "(", ")", ";", "if", "(", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "return", "new", "PropertyList", "(", "[", "'version'", "=>", "$", "result", "->", "getData", "(", ")", "[", "'data'", "]", "[", "0", "]", "[", "'message'", "]", "]", ")", ";", "}", "return", "new", "PropertyList", "(", "[", "'version'", "=>", "'Unknown'", "]", ")", ";", "}" ]
Get project version @option string $format Output format (table, list, csv, json, xml) @option string $fields Limit output to given fields, comma-separated @return PropertyList result
[ "Get", "project", "version" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/Version.php#L27-L42
32,960
nails/module-invoice
src/Model/Invoice.php
Invoice.getStates
public function getStates(): array { return [ self::STATE_DRAFT => 'Draft', self::STATE_OPEN => 'Open', self::STATE_PAID_PARTIAL => 'Partially Paid', self::STATE_PAID_PROCESSING => 'Paid (payments processing)', self::STATE_PAID => 'Paid', self::STATE_WRITTEN_OFF => 'Written Off', self::STATE_CANCELLED => 'Cancelled', ]; }
php
public function getStates(): array { return [ self::STATE_DRAFT => 'Draft', self::STATE_OPEN => 'Open', self::STATE_PAID_PARTIAL => 'Partially Paid', self::STATE_PAID_PROCESSING => 'Paid (payments processing)', self::STATE_PAID => 'Paid', self::STATE_WRITTEN_OFF => 'Written Off', self::STATE_CANCELLED => 'Cancelled', ]; }
[ "public", "function", "getStates", "(", ")", ":", "array", "{", "return", "[", "self", "::", "STATE_DRAFT", "=>", "'Draft'", ",", "self", "::", "STATE_OPEN", "=>", "'Open'", ",", "self", "::", "STATE_PAID_PARTIAL", "=>", "'Partially Paid'", ",", "self", "::", "STATE_PAID_PROCESSING", "=>", "'Paid (payments processing)'", ",", "self", "::", "STATE_PAID", "=>", "'Paid'", ",", "self", "::", "STATE_WRITTEN_OFF", "=>", "'Written Off'", ",", "self", "::", "STATE_CANCELLED", "=>", "'Cancelled'", ",", "]", ";", "}" ]
Returns the invoice states with human friendly names @return array
[ "Returns", "the", "invoice", "states", "with", "human", "friendly", "names" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L120-L131
32,961
nails/module-invoice
src/Model/Invoice.php
Invoice.update
public function update($mIds, array $aData = []): bool { // @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent $oDb = Factory::service('Database'); try { $sKeyExistsCustomerId = array_key_exists('customer_id', $aData); $sKeyExistsEmail = array_key_exists('email', $aData); if ($sKeyExistsCustomerId && $sKeyExistsEmail) { throw new InvoiceException('An invoice cannot be assigned to both an email and a customer.', 1); } if ($sKeyExistsCustomerId && empty($aData['customer_id'])) { throw new InvoiceException('If supplied, "customer_id" cannot be empty.', 1); } elseif ($sKeyExistsCustomerId && $sKeyExistsEmail) { // Ensure the email field is empty if it has been supplied $aData['email'] = null; } if ($sKeyExistsEmail && empty($aData['email'])) { throw new InvoiceException('If supplied, "email" cannot be empty.', 1); } elseif ($sKeyExistsEmail && $sKeyExistsCustomerId) { // Ensure the customer_id field is empty if it has been supplied $aData['customer_id'] = null; } $oDb->trans_begin(); $this->prepareInvoice($aData, $mIds); if (array_key_exists('items', $aData)) { $aItems = $aData['items']; unset($aData['items']); } unset($aData['ref']); unset($aData['token']); $bResult = parent::update($mIds, $aData); if (!$bResult) { throw new InvoiceException('Failed to update invoice.', 1); } if (!empty($aItems)) { $this->updateLineItems($mIds, $aItems); } $oDb->trans_commit(); $this->triggerEvent( Events::INVOICE_UPDATED, [$this->getInvoiceForEvent($mIds)] ); return $bResult; } catch (\Exception $e) { $oDb->trans_rollback(); $this->setError($e->getMessage()); return false; } }
php
public function update($mIds, array $aData = []): bool { // @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent $oDb = Factory::service('Database'); try { $sKeyExistsCustomerId = array_key_exists('customer_id', $aData); $sKeyExistsEmail = array_key_exists('email', $aData); if ($sKeyExistsCustomerId && $sKeyExistsEmail) { throw new InvoiceException('An invoice cannot be assigned to both an email and a customer.', 1); } if ($sKeyExistsCustomerId && empty($aData['customer_id'])) { throw new InvoiceException('If supplied, "customer_id" cannot be empty.', 1); } elseif ($sKeyExistsCustomerId && $sKeyExistsEmail) { // Ensure the email field is empty if it has been supplied $aData['email'] = null; } if ($sKeyExistsEmail && empty($aData['email'])) { throw new InvoiceException('If supplied, "email" cannot be empty.', 1); } elseif ($sKeyExistsEmail && $sKeyExistsCustomerId) { // Ensure the customer_id field is empty if it has been supplied $aData['customer_id'] = null; } $oDb->trans_begin(); $this->prepareInvoice($aData, $mIds); if (array_key_exists('items', $aData)) { $aItems = $aData['items']; unset($aData['items']); } unset($aData['ref']); unset($aData['token']); $bResult = parent::update($mIds, $aData); if (!$bResult) { throw new InvoiceException('Failed to update invoice.', 1); } if (!empty($aItems)) { $this->updateLineItems($mIds, $aItems); } $oDb->trans_commit(); $this->triggerEvent( Events::INVOICE_UPDATED, [$this->getInvoiceForEvent($mIds)] ); return $bResult; } catch (\Exception $e) { $oDb->trans_rollback(); $this->setError($e->getMessage()); return false; } }
[ "public", "function", "update", "(", "$", "mIds", ",", "array", "$", "aData", "=", "[", "]", ")", ":", "bool", "{", "// @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "try", "{", "$", "sKeyExistsCustomerId", "=", "array_key_exists", "(", "'customer_id'", ",", "$", "aData", ")", ";", "$", "sKeyExistsEmail", "=", "array_key_exists", "(", "'email'", ",", "$", "aData", ")", ";", "if", "(", "$", "sKeyExistsCustomerId", "&&", "$", "sKeyExistsEmail", ")", "{", "throw", "new", "InvoiceException", "(", "'An invoice cannot be assigned to both an email and a customer.'", ",", "1", ")", ";", "}", "if", "(", "$", "sKeyExistsCustomerId", "&&", "empty", "(", "$", "aData", "[", "'customer_id'", "]", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'If supplied, \"customer_id\" cannot be empty.'", ",", "1", ")", ";", "}", "elseif", "(", "$", "sKeyExistsCustomerId", "&&", "$", "sKeyExistsEmail", ")", "{", "// Ensure the email field is empty if it has been supplied", "$", "aData", "[", "'email'", "]", "=", "null", ";", "}", "if", "(", "$", "sKeyExistsEmail", "&&", "empty", "(", "$", "aData", "[", "'email'", "]", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'If supplied, \"email\" cannot be empty.'", ",", "1", ")", ";", "}", "elseif", "(", "$", "sKeyExistsEmail", "&&", "$", "sKeyExistsCustomerId", ")", "{", "// Ensure the customer_id field is empty if it has been supplied", "$", "aData", "[", "'customer_id'", "]", "=", "null", ";", "}", "$", "oDb", "->", "trans_begin", "(", ")", ";", "$", "this", "->", "prepareInvoice", "(", "$", "aData", ",", "$", "mIds", ")", ";", "if", "(", "array_key_exists", "(", "'items'", ",", "$", "aData", ")", ")", "{", "$", "aItems", "=", "$", "aData", "[", "'items'", "]", ";", "unset", "(", "$", "aData", "[", "'items'", "]", ")", ";", "}", "unset", "(", "$", "aData", "[", "'ref'", "]", ")", ";", "unset", "(", "$", "aData", "[", "'token'", "]", ")", ";", "$", "bResult", "=", "parent", "::", "update", "(", "$", "mIds", ",", "$", "aData", ")", ";", "if", "(", "!", "$", "bResult", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to update invoice.'", ",", "1", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "aItems", ")", ")", "{", "$", "this", "->", "updateLineItems", "(", "$", "mIds", ",", "$", "aItems", ")", ";", "}", "$", "oDb", "->", "trans_commit", "(", ")", ";", "$", "this", "->", "triggerEvent", "(", "Events", "::", "INVOICE_UPDATED", ",", "[", "$", "this", "->", "getInvoiceForEvent", "(", "$", "mIds", ")", "]", ")", ";", "return", "$", "bResult", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "oDb", "->", "trans_rollback", "(", ")", ";", "$", "this", "->", "setError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "}" ]
Update an invoice @param int|array $mIds The ID (or array of IDs) of the object(s) to update @param array $aData The data to update the object(s) with @return bool @throws FactoryException
[ "Update", "an", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L341-L405
32,962
nails/module-invoice
src/Model/Invoice.php
Invoice.updateLineItems
protected function updateLineItems(int $iInvoiceId, array $aItems): void { $oItemModel = Factory::model('InvoiceItem', 'nails/module-invoice'); $aTouchedIds = []; // Update/insert all known items foreach ($aItems as $aItem) { $aData = [ 'label' => getFromArray('label', $aItem, null), 'body' => getFromArray('body', $aItem, null), 'order' => getFromArray('order', $aItem, 0), 'currency' => getFromArray('currency', $aItem, null), 'unit' => getFromArray('unit', $aItem, null), 'tax_id' => getFromArray('tax_id', $aItem, null), 'quantity' => getFromArray('quantity', $aItem, 1), 'unit_cost' => getFromArray('unit_cost', $aItem, 0), 'sub_total' => getFromArray('sub_total', $aItem, 0), 'tax_total' => getFromArray('tax_total', $aItem, 0), 'grand_total' => getFromArray('grand_total', $aItem, 0), 'callback_data' => getFromArray('callback_data', $aItem, null), ]; // Ensure callback data is encoded as JSON if (array_key_exists('callback_data', $aData)) { $aData['callback_data'] = json_encode($aData['callback_data']); } if (!empty($aItem['id'])) { // Update if (!$oItemModel->update($aItem['id'], $aData)) { throw new InvoiceException('Failed to update invoice item.', 1); } else { $aTouchedIds[] = $aItem['id']; } } else { // Insert $aData['invoice_id'] = $iInvoiceId; $iItemId = $oItemModel->create($aData); if (!$iItemId) { throw new InvoiceException('Failed to create invoice item.', 1); } else { $aTouchedIds[] = $iItemId; } } } // Delete those we no longer require if (!empty($aTouchedIds)) { $oDb = Factory::service('Database'); $oDb->where_not_in('id', $aTouchedIds); $oDb->where('invoice_id', $iInvoiceId); if (!$oDb->delete($oItemModel->getTableName())) { throw new InvoiceException('Failed to delete old invoice items.', 1); } } }
php
protected function updateLineItems(int $iInvoiceId, array $aItems): void { $oItemModel = Factory::model('InvoiceItem', 'nails/module-invoice'); $aTouchedIds = []; // Update/insert all known items foreach ($aItems as $aItem) { $aData = [ 'label' => getFromArray('label', $aItem, null), 'body' => getFromArray('body', $aItem, null), 'order' => getFromArray('order', $aItem, 0), 'currency' => getFromArray('currency', $aItem, null), 'unit' => getFromArray('unit', $aItem, null), 'tax_id' => getFromArray('tax_id', $aItem, null), 'quantity' => getFromArray('quantity', $aItem, 1), 'unit_cost' => getFromArray('unit_cost', $aItem, 0), 'sub_total' => getFromArray('sub_total', $aItem, 0), 'tax_total' => getFromArray('tax_total', $aItem, 0), 'grand_total' => getFromArray('grand_total', $aItem, 0), 'callback_data' => getFromArray('callback_data', $aItem, null), ]; // Ensure callback data is encoded as JSON if (array_key_exists('callback_data', $aData)) { $aData['callback_data'] = json_encode($aData['callback_data']); } if (!empty($aItem['id'])) { // Update if (!$oItemModel->update($aItem['id'], $aData)) { throw new InvoiceException('Failed to update invoice item.', 1); } else { $aTouchedIds[] = $aItem['id']; } } else { // Insert $aData['invoice_id'] = $iInvoiceId; $iItemId = $oItemModel->create($aData); if (!$iItemId) { throw new InvoiceException('Failed to create invoice item.', 1); } else { $aTouchedIds[] = $iItemId; } } } // Delete those we no longer require if (!empty($aTouchedIds)) { $oDb = Factory::service('Database'); $oDb->where_not_in('id', $aTouchedIds); $oDb->where('invoice_id', $iInvoiceId); if (!$oDb->delete($oItemModel->getTableName())) { throw new InvoiceException('Failed to delete old invoice items.', 1); } } }
[ "protected", "function", "updateLineItems", "(", "int", "$", "iInvoiceId", ",", "array", "$", "aItems", ")", ":", "void", "{", "$", "oItemModel", "=", "Factory", "::", "model", "(", "'InvoiceItem'", ",", "'nails/module-invoice'", ")", ";", "$", "aTouchedIds", "=", "[", "]", ";", "// Update/insert all known items", "foreach", "(", "$", "aItems", "as", "$", "aItem", ")", "{", "$", "aData", "=", "[", "'label'", "=>", "getFromArray", "(", "'label'", ",", "$", "aItem", ",", "null", ")", ",", "'body'", "=>", "getFromArray", "(", "'body'", ",", "$", "aItem", ",", "null", ")", ",", "'order'", "=>", "getFromArray", "(", "'order'", ",", "$", "aItem", ",", "0", ")", ",", "'currency'", "=>", "getFromArray", "(", "'currency'", ",", "$", "aItem", ",", "null", ")", ",", "'unit'", "=>", "getFromArray", "(", "'unit'", ",", "$", "aItem", ",", "null", ")", ",", "'tax_id'", "=>", "getFromArray", "(", "'tax_id'", ",", "$", "aItem", ",", "null", ")", ",", "'quantity'", "=>", "getFromArray", "(", "'quantity'", ",", "$", "aItem", ",", "1", ")", ",", "'unit_cost'", "=>", "getFromArray", "(", "'unit_cost'", ",", "$", "aItem", ",", "0", ")", ",", "'sub_total'", "=>", "getFromArray", "(", "'sub_total'", ",", "$", "aItem", ",", "0", ")", ",", "'tax_total'", "=>", "getFromArray", "(", "'tax_total'", ",", "$", "aItem", ",", "0", ")", ",", "'grand_total'", "=>", "getFromArray", "(", "'grand_total'", ",", "$", "aItem", ",", "0", ")", ",", "'callback_data'", "=>", "getFromArray", "(", "'callback_data'", ",", "$", "aItem", ",", "null", ")", ",", "]", ";", "// Ensure callback data is encoded as JSON", "if", "(", "array_key_exists", "(", "'callback_data'", ",", "$", "aData", ")", ")", "{", "$", "aData", "[", "'callback_data'", "]", "=", "json_encode", "(", "$", "aData", "[", "'callback_data'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "aItem", "[", "'id'", "]", ")", ")", "{", "// Update", "if", "(", "!", "$", "oItemModel", "->", "update", "(", "$", "aItem", "[", "'id'", "]", ",", "$", "aData", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to update invoice item.'", ",", "1", ")", ";", "}", "else", "{", "$", "aTouchedIds", "[", "]", "=", "$", "aItem", "[", "'id'", "]", ";", "}", "}", "else", "{", "// Insert", "$", "aData", "[", "'invoice_id'", "]", "=", "$", "iInvoiceId", ";", "$", "iItemId", "=", "$", "oItemModel", "->", "create", "(", "$", "aData", ")", ";", "if", "(", "!", "$", "iItemId", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to create invoice item.'", ",", "1", ")", ";", "}", "else", "{", "$", "aTouchedIds", "[", "]", "=", "$", "iItemId", ";", "}", "}", "}", "// Delete those we no longer require", "if", "(", "!", "empty", "(", "$", "aTouchedIds", ")", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "where_not_in", "(", "'id'", ",", "$", "aTouchedIds", ")", ";", "$", "oDb", "->", "where", "(", "'invoice_id'", ",", "$", "iInvoiceId", ")", ";", "if", "(", "!", "$", "oDb", "->", "delete", "(", "$", "oItemModel", "->", "getTableName", "(", ")", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to delete old invoice items.'", ",", "1", ")", ";", "}", "}", "}" ]
Update the line items of an invoice @param int $iInvoiceId The invoice ID @param array $aItems The items to update @throws FactoryException @throws InvoiceException
[ "Update", "the", "line", "items", "of", "an", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L638-L699
32,963
nails/module-invoice
src/Model/Invoice.php
Invoice.generateValidRef
public function generateValidRef(): string { Factory::helper('string'); $oDb = Factory::service('Database'); $oNow = Factory::factory('DateTime'); do { $sRef = $oNow->format('Ym') . '-' . strtoupper(random_string('alnum')); $oDb->where('ref', $sRef); $bRefExists = (bool) $oDb->count_all_results($this->table); } while ($bRefExists); return $sRef; }
php
public function generateValidRef(): string { Factory::helper('string'); $oDb = Factory::service('Database'); $oNow = Factory::factory('DateTime'); do { $sRef = $oNow->format('Ym') . '-' . strtoupper(random_string('alnum')); $oDb->where('ref', $sRef); $bRefExists = (bool) $oDb->count_all_results($this->table); } while ($bRefExists); return $sRef; }
[ "public", "function", "generateValidRef", "(", ")", ":", "string", "{", "Factory", "::", "helper", "(", "'string'", ")", ";", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "do", "{", "$", "sRef", "=", "$", "oNow", "->", "format", "(", "'Ym'", ")", ".", "'-'", ".", "strtoupper", "(", "random_string", "(", "'alnum'", ")", ")", ";", "$", "oDb", "->", "where", "(", "'ref'", ",", "$", "sRef", ")", ";", "$", "bRefExists", "=", "(", "bool", ")", "$", "oDb", "->", "count_all_results", "(", "$", "this", "->", "table", ")", ";", "}", "while", "(", "$", "bRefExists", ")", ";", "return", "$", "sRef", ";", "}" ]
Generates a valid invoice ref @return string @throws FactoryException
[ "Generates", "a", "valid", "invoice", "ref" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L725-L741
32,964
nails/module-invoice
src/Model/Invoice.php
Invoice.isPaid
public function isPaid(int $iInvoiceId, bool $bIncludeProcessing = false): bool { $oInvoice = $this->getById($iInvoiceId); if (!empty($oInvoice)) { $iPaid = $oInvoice->totals->raw->paid; if ($bIncludeProcessing) { $iPaid += $oInvoice->totals->raw->processing; } return $iPaid >= $oInvoice->totals->raw->grand; } return false; }
php
public function isPaid(int $iInvoiceId, bool $bIncludeProcessing = false): bool { $oInvoice = $this->getById($iInvoiceId); if (!empty($oInvoice)) { $iPaid = $oInvoice->totals->raw->paid; if ($bIncludeProcessing) { $iPaid += $oInvoice->totals->raw->processing; } return $iPaid >= $oInvoice->totals->raw->grand; } return false; }
[ "public", "function", "isPaid", "(", "int", "$", "iInvoiceId", ",", "bool", "$", "bIncludeProcessing", "=", "false", ")", ":", "bool", "{", "$", "oInvoice", "=", "$", "this", "->", "getById", "(", "$", "iInvoiceId", ")", ";", "if", "(", "!", "empty", "(", "$", "oInvoice", ")", ")", "{", "$", "iPaid", "=", "$", "oInvoice", "->", "totals", "->", "raw", "->", "paid", ";", "if", "(", "$", "bIncludeProcessing", ")", "{", "$", "iPaid", "+=", "$", "oInvoice", "->", "totals", "->", "raw", "->", "processing", ";", "}", "return", "$", "iPaid", ">=", "$", "oInvoice", "->", "totals", "->", "raw", "->", "grand", ";", "}", "return", "false", ";", "}" ]
Whether an invoice has been fully paid or not @param int $iInvoiceId The Invoice to query @param bool $bIncludeProcessing Whether to include payments which are still processing @return bool @throws ModelException
[ "Whether", "an", "invoice", "has", "been", "fully", "paid", "or", "not" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L838-L853
32,965
nails/module-invoice
src/Model/Invoice.php
Invoice.setPaid
public function setPaid($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_PAID, 'paid' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_PAID, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
php
public function setPaid($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_PAID, 'paid' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_PAID, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
[ "public", "function", "setPaid", "(", "$", "iInvoiceId", ")", ":", "bool", "{", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "$", "bResult", "=", "$", "this", "->", "update", "(", "$", "iInvoiceId", ",", "[", "'state'", "=>", "self", "::", "STATE_PAID", ",", "'paid'", "=>", "$", "oNow", "->", "format", "(", "'Y-m-d H:i:s'", ")", ",", "]", ")", ";", "if", "(", "$", "bResult", ")", "{", "$", "this", "->", "triggerEvent", "(", "Events", "::", "INVOICE_PAID", ",", "[", "$", "this", "->", "getInvoiceForEvent", "(", "$", "iInvoiceId", ")", "]", ")", ";", "}", "return", "$", "bResult", ";", "}" ]
Set an invoice as paid @param int $iInvoiceId The Invoice to query @return bool @throws ModelException @throws FactoryException
[ "Set", "an", "invoice", "as", "paid" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L866-L885
32,966
nails/module-invoice
src/Model/Invoice.php
Invoice.setPaidProcessing
public function setPaidProcessing($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_PAID_PROCESSING, 'paid' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_PAID_PROCESSING, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
php
public function setPaidProcessing($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_PAID_PROCESSING, 'paid' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_PAID_PROCESSING, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
[ "public", "function", "setPaidProcessing", "(", "$", "iInvoiceId", ")", ":", "bool", "{", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "$", "bResult", "=", "$", "this", "->", "update", "(", "$", "iInvoiceId", ",", "[", "'state'", "=>", "self", "::", "STATE_PAID_PROCESSING", ",", "'paid'", "=>", "$", "oNow", "->", "format", "(", "'Y-m-d H:i:s'", ")", ",", "]", ")", ";", "if", "(", "$", "bResult", ")", "{", "$", "this", "->", "triggerEvent", "(", "Events", "::", "INVOICE_PAID_PROCESSING", ",", "[", "$", "this", "->", "getInvoiceForEvent", "(", "$", "iInvoiceId", ")", "]", ")", ";", "}", "return", "$", "bResult", ";", "}" ]
Set an invoice as paid but with processing payments @param int $iInvoiceId The Invoice to query @return bool @throws ModelException @throws FactoryException
[ "Set", "an", "invoice", "as", "paid", "but", "with", "processing", "payments" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L898-L917
32,967
nails/module-invoice
src/Model/Invoice.php
Invoice.setWrittenOff
public function setWrittenOff($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_WRITTEN_OFF, 'written_off' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_WRITTEN_OFF, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
php
public function setWrittenOff($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_WRITTEN_OFF, 'written_off' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_WRITTEN_OFF, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
[ "public", "function", "setWrittenOff", "(", "$", "iInvoiceId", ")", ":", "bool", "{", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "$", "bResult", "=", "$", "this", "->", "update", "(", "$", "iInvoiceId", ",", "[", "'state'", "=>", "self", "::", "STATE_WRITTEN_OFF", ",", "'written_off'", "=>", "$", "oNow", "->", "format", "(", "'Y-m-d H:i:s'", ")", ",", "]", ")", ";", "if", "(", "$", "bResult", ")", "{", "$", "this", "->", "triggerEvent", "(", "Events", "::", "INVOICE_WRITTEN_OFF", ",", "[", "$", "this", "->", "getInvoiceForEvent", "(", "$", "iInvoiceId", ")", "]", ")", ";", "}", "return", "$", "bResult", ";", "}" ]
Set an invoice as written off @param int $iInvoiceId The Invoice to query @return bool @throws ModelException @throws FactoryException
[ "Set", "an", "invoice", "as", "written", "off" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L930-L949
32,968
nails/module-invoice
src/Model/Invoice.php
Invoice.setCancelled
public function setCancelled($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_CANCELLED, 'written_off' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_CANCELLED, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
php
public function setCancelled($iInvoiceId): bool { $oNow = Factory::factory('DateTime'); $bResult = $this->update( $iInvoiceId, [ 'state' => self::STATE_CANCELLED, 'written_off' => $oNow->format('Y-m-d H:i:s'), ] ); if ($bResult) { $this->triggerEvent( Events::INVOICE_CANCELLED, [$this->getInvoiceForEvent($iInvoiceId)] ); } return $bResult; }
[ "public", "function", "setCancelled", "(", "$", "iInvoiceId", ")", ":", "bool", "{", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "$", "bResult", "=", "$", "this", "->", "update", "(", "$", "iInvoiceId", ",", "[", "'state'", "=>", "self", "::", "STATE_CANCELLED", ",", "'written_off'", "=>", "$", "oNow", "->", "format", "(", "'Y-m-d H:i:s'", ")", ",", "]", ")", ";", "if", "(", "$", "bResult", ")", "{", "$", "this", "->", "triggerEvent", "(", "Events", "::", "INVOICE_CANCELLED", ",", "[", "$", "this", "->", "getInvoiceForEvent", "(", "$", "iInvoiceId", ")", "]", ")", ";", "}", "return", "$", "bResult", ";", "}" ]
Set an invoice as cancelled @param int $iInvoiceId The Invoice to query @return bool @throws ModelException @throws FactoryException
[ "Set", "an", "invoice", "as", "cancelled" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L962-L981
32,969
nails/module-invoice
src/Model/Invoice.php
Invoice.getInvoiceForEvent
protected function getInvoiceForEvent(int $iInvoiceId): Resource { $oInvoice = $this->getById($iInvoiceId, ['expand' => ['customer', 'items']]); if (empty($oInvoice)) { throw new ModelException('Invalid invoice ID'); } return $oInvoice; }
php
protected function getInvoiceForEvent(int $iInvoiceId): Resource { $oInvoice = $this->getById($iInvoiceId, ['expand' => ['customer', 'items']]); if (empty($oInvoice)) { throw new ModelException('Invalid invoice ID'); } return $oInvoice; }
[ "protected", "function", "getInvoiceForEvent", "(", "int", "$", "iInvoiceId", ")", ":", "Resource", "{", "$", "oInvoice", "=", "$", "this", "->", "getById", "(", "$", "iInvoiceId", ",", "[", "'expand'", "=>", "[", "'customer'", ",", "'items'", "]", "]", ")", ";", "if", "(", "empty", "(", "$", "oInvoice", ")", ")", "{", "throw", "new", "ModelException", "(", "'Invalid invoice ID'", ")", ";", "}", "return", "$", "oInvoice", ";", "}" ]
Get an invoice in a suitable format for the event triggers @param int $iInvoiceId The invoice ID @return Resource @throws ModelException
[ "Get", "an", "invoice", "in", "a", "suitable", "format", "for", "the", "event", "triggers" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L993-L1000
32,970
canihavesomecoffee/theTVDbAPI
src/DataParser.php
DataParser.parseDataArray
public static function parseDataArray($json, string $returnClass): array { $result = []; if (is_array($json)) { foreach ($json as $entry) { $result[] = static::parseData($entry, $returnClass); } } return $result; }
php
public static function parseDataArray($json, string $returnClass): array { $result = []; if (is_array($json)) { foreach ($json as $entry) { $result[] = static::parseData($entry, $returnClass); } } return $result; }
[ "public", "static", "function", "parseDataArray", "(", "$", "json", ",", "string", "$", "returnClass", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "json", ")", ")", "{", "foreach", "(", "$", "json", "as", "$", "entry", ")", "{", "$", "result", "[", "]", "=", "static", "::", "parseData", "(", "$", "entry", ",", "$", "returnClass", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Parses the given JSON data into an array of return_class instances. @param object $json The JSON data. Must be valid @param string $returnClass The expected return class @return array
[ "Parses", "the", "given", "JSON", "data", "into", "an", "array", "of", "return_class", "instances", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/DataParser.php#L75-L84
32,971
canihavesomecoffee/theTVDbAPI
src/DataParser.php
DataParser.getSerializer
private static function getSerializer(): Serializer { if (static::$serializer === null) { $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); static::$serializer = new Serializer( [new ObjectNormalizer(null, null, null, $extractor)], [new JsonEncoder()] ); } return static::$serializer; }
php
private static function getSerializer(): Serializer { if (static::$serializer === null) { $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); static::$serializer = new Serializer( [new ObjectNormalizer(null, null, null, $extractor)], [new JsonEncoder()] ); } return static::$serializer; }
[ "private", "static", "function", "getSerializer", "(", ")", ":", "Serializer", "{", "if", "(", "static", "::", "$", "serializer", "===", "null", ")", "{", "$", "extractor", "=", "new", "PropertyInfoExtractor", "(", "[", "]", ",", "[", "new", "PhpDocExtractor", "(", ")", ",", "new", "ReflectionExtractor", "(", ")", "]", ")", ";", "static", "::", "$", "serializer", "=", "new", "Serializer", "(", "[", "new", "ObjectNormalizer", "(", "null", ",", "null", ",", "null", ",", "$", "extractor", ")", "]", ",", "[", "new", "JsonEncoder", "(", ")", "]", ")", ";", "}", "return", "static", "::", "$", "serializer", ";", "}" ]
Gets the serializer instance. @return Serializer An instance of the Serializer.
[ "Gets", "the", "serializer", "instance", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/DataParser.php#L91-L101
32,972
nails/module-invoice
src/Factory/ResponseBase.php
ResponseBase.setStatus
public function setStatus($sStatus) { if (!$this->bIsLocked) { $aStatuses = $this->getStatuses(); if (!in_array($sStatus, $aStatuses)) { throw new ResponseException('"' . $sStatus . '" is an invalid response status.', 1); } $this->sStatus = $sStatus; } return $this; }
php
public function setStatus($sStatus) { if (!$this->bIsLocked) { $aStatuses = $this->getStatuses(); if (!in_array($sStatus, $aStatuses)) { throw new ResponseException('"' . $sStatus . '" is an invalid response status.', 1); } $this->sStatus = $sStatus; } return $this; }
[ "public", "function", "setStatus", "(", "$", "sStatus", ")", "{", "if", "(", "!", "$", "this", "->", "bIsLocked", ")", "{", "$", "aStatuses", "=", "$", "this", "->", "getStatuses", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "sStatus", ",", "$", "aStatuses", ")", ")", "{", "throw", "new", "ResponseException", "(", "'\"'", ".", "$", "sStatus", ".", "'\" is an invalid response status.'", ",", "1", ")", ";", "}", "$", "this", "->", "sStatus", "=", "$", "sStatus", ";", "}", "return", "$", "this", ";", "}" ]
Returns the current status of the response @param string $sStatus The status to set @throws ResponseException @return string
[ "Returns", "the", "current", "status", "of", "the", "response" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ResponseBase.php#L94-L107
32,973
nails/module-invoice
src/Factory/ResponseBase.php
ResponseBase.setStatusFailed
public function setStatusFailed($sReasonMsg, $sReasonCode, $sUserFeedback = '') { $this->sErrorMsg = trim($sReasonMsg); $this->sErrorCode = trim($sReasonCode); $this->sErrorUser = trim($sUserFeedback); return $this->setStatus(self::STATUS_FAILED); }
php
public function setStatusFailed($sReasonMsg, $sReasonCode, $sUserFeedback = '') { $this->sErrorMsg = trim($sReasonMsg); $this->sErrorCode = trim($sReasonCode); $this->sErrorUser = trim($sUserFeedback); return $this->setStatus(self::STATUS_FAILED); }
[ "public", "function", "setStatusFailed", "(", "$", "sReasonMsg", ",", "$", "sReasonCode", ",", "$", "sUserFeedback", "=", "''", ")", "{", "$", "this", "->", "sErrorMsg", "=", "trim", "(", "$", "sReasonMsg", ")", ";", "$", "this", "->", "sErrorCode", "=", "trim", "(", "$", "sReasonCode", ")", ";", "$", "this", "->", "sErrorUser", "=", "trim", "(", "$", "sUserFeedback", ")", ";", "return", "$", "this", "->", "setStatus", "(", "self", "::", "STATUS_FAILED", ")", ";", "}" ]
Set the status as FAILED @param string $sReasonMsg The exception message, logged against the payment and not shown to the customer @param string $sReasonCode The exception code, logged against the payment and not shown to the customer @param string $sUserFeedback The message to show to the user explaining the error @return string
[ "Set", "the", "status", "as", "FAILED" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ResponseBase.php#L153-L160
32,974
anomalylabs/variables-module
src/Http/Controller/Admin/VersionsController.php
VersionsController.index
public function index(VersionTableBuilder $table) { /** * Mimic the parent controllers method. */ $table ->setType($this->getModel()) ->setId($this->request->route('id')); $versionable = $table->getVersionableInstance(); if ($current = $versionable->getCurrentVersion()) { $table->setCurrent($current); } /* @var ControlPanelBuilder $controlPanel */ $controlPanel = $this->container->make(ControlPanelBuilder::class); $section = $controlPanel->getControlPanelActiveSection(); /** * Mimic the default table buttons handler * and override the href so that we edit * the group and not the versionable ID. */ $table->setButtons( [ 'load' => [ 'href' => $section->getHref( 'edit/{request.input.group}?version={entry.version}&versionable={entry.versionable_type}' ), 'disabled' => function (VersionInterface $entry) use ($current) { if ($current->getVersion() !== $entry->getVersion()) { return false; } return true; }, ], ] ); return $table->render(); }
php
public function index(VersionTableBuilder $table) { /** * Mimic the parent controllers method. */ $table ->setType($this->getModel()) ->setId($this->request->route('id')); $versionable = $table->getVersionableInstance(); if ($current = $versionable->getCurrentVersion()) { $table->setCurrent($current); } /* @var ControlPanelBuilder $controlPanel */ $controlPanel = $this->container->make(ControlPanelBuilder::class); $section = $controlPanel->getControlPanelActiveSection(); /** * Mimic the default table buttons handler * and override the href so that we edit * the group and not the versionable ID. */ $table->setButtons( [ 'load' => [ 'href' => $section->getHref( 'edit/{request.input.group}?version={entry.version}&versionable={entry.versionable_type}' ), 'disabled' => function (VersionInterface $entry) use ($current) { if ($current->getVersion() !== $entry->getVersion()) { return false; } return true; }, ], ] ); return $table->render(); }
[ "public", "function", "index", "(", "VersionTableBuilder", "$", "table", ")", "{", "/**\n * Mimic the parent controllers method.\n */", "$", "table", "->", "setType", "(", "$", "this", "->", "getModel", "(", ")", ")", "->", "setId", "(", "$", "this", "->", "request", "->", "route", "(", "'id'", ")", ")", ";", "$", "versionable", "=", "$", "table", "->", "getVersionableInstance", "(", ")", ";", "if", "(", "$", "current", "=", "$", "versionable", "->", "getCurrentVersion", "(", ")", ")", "{", "$", "table", "->", "setCurrent", "(", "$", "current", ")", ";", "}", "/* @var ControlPanelBuilder $controlPanel */", "$", "controlPanel", "=", "$", "this", "->", "container", "->", "make", "(", "ControlPanelBuilder", "::", "class", ")", ";", "$", "section", "=", "$", "controlPanel", "->", "getControlPanelActiveSection", "(", ")", ";", "/**\n * Mimic the default table buttons handler\n * and override the href so that we edit\n * the group and not the versionable ID.\n */", "$", "table", "->", "setButtons", "(", "[", "'load'", "=>", "[", "'href'", "=>", "$", "section", "->", "getHref", "(", "'edit/{request.input.group}?version={entry.version}&versionable={entry.versionable_type}'", ")", ",", "'disabled'", "=>", "function", "(", "VersionInterface", "$", "entry", ")", "use", "(", "$", "current", ")", "{", "if", "(", "$", "current", "->", "getVersion", "(", ")", "!==", "$", "entry", "->", "getVersion", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ",", "]", ",", "]", ")", ";", "return", "$", "table", "->", "render", "(", ")", ";", "}" ]
Return a list of versions for the variable group. @param VersionTableBuilder $table @param $id @return \Symfony\Component\HttpFoundation\Response
[ "Return", "a", "list", "of", "versions", "for", "the", "variable", "group", "." ]
bcd903670471a175f07aba3123693cb3a3c07d0b
https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Http/Controller/Admin/VersionsController.php#L45-L90
32,975
canihavesomecoffee/theTVDbAPI
src/MultiLanguageWrapper/ClassValidator.php
ClassValidator.isValid
public function isValid(string $returnTypeClass, $instance): bool { if (array_key_exists($returnTypeClass, $this->getRequiredFields()) === false) { return false; } foreach ($this->getRequiredFields()[$returnTypeClass] as $property) { if (is_array($instance)) { foreach ($instance as $item) { if ($item->{$property} === null) { return false; } } } elseif ($instance->{$property} === null) { return false; } } return true; }
php
public function isValid(string $returnTypeClass, $instance): bool { if (array_key_exists($returnTypeClass, $this->getRequiredFields()) === false) { return false; } foreach ($this->getRequiredFields()[$returnTypeClass] as $property) { if (is_array($instance)) { foreach ($instance as $item) { if ($item->{$property} === null) { return false; } } } elseif ($instance->{$property} === null) { return false; } } return true; }
[ "public", "function", "isValid", "(", "string", "$", "returnTypeClass", ",", "$", "instance", ")", ":", "bool", "{", "if", "(", "array_key_exists", "(", "$", "returnTypeClass", ",", "$", "this", "->", "getRequiredFields", "(", ")", ")", "===", "false", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "getRequiredFields", "(", ")", "[", "$", "returnTypeClass", "]", "as", "$", "property", ")", "{", "if", "(", "is_array", "(", "$", "instance", ")", ")", "{", "foreach", "(", "$", "instance", "as", "$", "item", ")", "{", "if", "(", "$", "item", "->", "{", "$", "property", "}", "===", "null", ")", "{", "return", "false", ";", "}", "}", "}", "elseif", "(", "$", "instance", "->", "{", "$", "property", "}", "===", "null", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if for a given instance the required fields are not null. @param string $returnTypeClass The class type of the instance. @param object|array $instance The instance to check. @return bool
[ "Checks", "if", "for", "a", "given", "instance", "the", "required", "fields", "are", "not", "null", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/ClassValidator.php#L52-L69
32,976
canihavesomecoffee/theTVDbAPI
src/MultiLanguageWrapper/ClassValidator.php
ClassValidator.merge
public function merge(string $returnTypeClass, $existingInstance, $newInstance) { if ($existingInstance === null) { return $newInstance; } if (array_key_exists($returnTypeClass, $this->getRequiredFields()) && $newInstance !== null) { foreach ($this->getRequiredFields()[$returnTypeClass] as $property) { if (is_array($existingInstance)) { $existingInstanceSize = sizeof($existingInstance); for ($index = 0; $index < $existingInstanceSize; $index++) { if ($existingInstance[$index]->{$property} === null) { $existingInstance[$index]->{$property} = $newInstance[$index]->{$property}; } } } elseif ($existingInstance->{$property} === null) { $existingInstance->{$property} = $newInstance->{$property}; } } } return $existingInstance; }
php
public function merge(string $returnTypeClass, $existingInstance, $newInstance) { if ($existingInstance === null) { return $newInstance; } if (array_key_exists($returnTypeClass, $this->getRequiredFields()) && $newInstance !== null) { foreach ($this->getRequiredFields()[$returnTypeClass] as $property) { if (is_array($existingInstance)) { $existingInstanceSize = sizeof($existingInstance); for ($index = 0; $index < $existingInstanceSize; $index++) { if ($existingInstance[$index]->{$property} === null) { $existingInstance[$index]->{$property} = $newInstance[$index]->{$property}; } } } elseif ($existingInstance->{$property} === null) { $existingInstance->{$property} = $newInstance->{$property}; } } } return $existingInstance; }
[ "public", "function", "merge", "(", "string", "$", "returnTypeClass", ",", "$", "existingInstance", ",", "$", "newInstance", ")", "{", "if", "(", "$", "existingInstance", "===", "null", ")", "{", "return", "$", "newInstance", ";", "}", "if", "(", "array_key_exists", "(", "$", "returnTypeClass", ",", "$", "this", "->", "getRequiredFields", "(", ")", ")", "&&", "$", "newInstance", "!==", "null", ")", "{", "foreach", "(", "$", "this", "->", "getRequiredFields", "(", ")", "[", "$", "returnTypeClass", "]", "as", "$", "property", ")", "{", "if", "(", "is_array", "(", "$", "existingInstance", ")", ")", "{", "$", "existingInstanceSize", "=", "sizeof", "(", "$", "existingInstance", ")", ";", "for", "(", "$", "index", "=", "0", ";", "$", "index", "<", "$", "existingInstanceSize", ";", "$", "index", "++", ")", "{", "if", "(", "$", "existingInstance", "[", "$", "index", "]", "->", "{", "$", "property", "}", "===", "null", ")", "{", "$", "existingInstance", "[", "$", "index", "]", "->", "{", "$", "property", "}", "=", "$", "newInstance", "[", "$", "index", "]", "->", "{", "$", "property", "}", ";", "}", "}", "}", "elseif", "(", "$", "existingInstance", "->", "{", "$", "property", "}", "===", "null", ")", "{", "$", "existingInstance", "->", "{", "$", "property", "}", "=", "$", "newInstance", "->", "{", "$", "property", "}", ";", "}", "}", "}", "return", "$", "existingInstance", ";", "}" ]
Merges two instances together by replacing missing values that are required. @param string $returnTypeClass The class type of the instances. @param object|array $existingInstance The instance that already exists. @param object|array $newInstance The instance to be merged. @return mixed
[ "Merges", "two", "instances", "together", "by", "replacing", "missing", "values", "that", "are", "required", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/ClassValidator.php#L80-L100
32,977
nails/module-invoice
admin/controllers/Customer.php
Customer.edit
public function edit() { if (!userHasPermission('admin:invoice:customer:edit')) { unauthorised(); } $oCustomerModel = Factory::model('Customer', 'nails/module-invoice'); $oUri = Factory::service('Uri'); $itemId = (int) $oUri->segment(5); $this->data['item'] = $oCustomerModel->getById( $itemId, ['expand' => $oCustomerModel::EXPAND_ALL] ); if (empty($this->data['item'])) { show404(); } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); if ($oInput->post()) { try { $this->formValidation(); if (!$oCustomerModel->update($itemId, $this->prepPostData())) { throw new NailsException('Failed to update item. ' . $oCustomerModel->lastError(), 1); } $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->setFlashData('success', 'Item updated successfully.'); redirect('admin/invoice/customer'); } catch (\Exception $e) { $this->data['error'] = $e->getMessage(); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Edit customer'; Helper::loadView('edit'); }
php
public function edit() { if (!userHasPermission('admin:invoice:customer:edit')) { unauthorised(); } $oCustomerModel = Factory::model('Customer', 'nails/module-invoice'); $oUri = Factory::service('Uri'); $itemId = (int) $oUri->segment(5); $this->data['item'] = $oCustomerModel->getById( $itemId, ['expand' => $oCustomerModel::EXPAND_ALL] ); if (empty($this->data['item'])) { show404(); } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); if ($oInput->post()) { try { $this->formValidation(); if (!$oCustomerModel->update($itemId, $this->prepPostData())) { throw new NailsException('Failed to update item. ' . $oCustomerModel->lastError(), 1); } $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->setFlashData('success', 'Item updated successfully.'); redirect('admin/invoice/customer'); } catch (\Exception $e) { $this->data['error'] = $e->getMessage(); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Edit customer'; Helper::loadView('edit'); }
[ "public", "function", "edit", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:invoice:customer:edit'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "$", "oCustomerModel", "=", "Factory", "::", "model", "(", "'Customer'", ",", "'nails/module-invoice'", ")", ";", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", "itemId", "=", "(", "int", ")", "$", "oUri", "->", "segment", "(", "5", ")", ";", "$", "this", "->", "data", "[", "'item'", "]", "=", "$", "oCustomerModel", "->", "getById", "(", "$", "itemId", ",", "[", "'expand'", "=>", "$", "oCustomerModel", "::", "EXPAND_ALL", "]", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "data", "[", "'item'", "]", ")", ")", "{", "show404", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "if", "(", "$", "oInput", "->", "post", "(", ")", ")", "{", "try", "{", "$", "this", "->", "formValidation", "(", ")", ";", "if", "(", "!", "$", "oCustomerModel", "->", "update", "(", "$", "itemId", ",", "$", "this", "->", "prepPostData", "(", ")", ")", ")", "{", "throw", "new", "NailsException", "(", "'Failed to update item. '", ".", "$", "oCustomerModel", "->", "lastError", "(", ")", ",", "1", ")", ";", "}", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "oSession", "->", "setFlashData", "(", "'success'", ",", "'Item updated successfully.'", ")", ";", "redirect", "(", "'admin/invoice/customer'", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "data", "[", "'error'", "]", "=", "$", "e", "->", "getMessage", "(", ")", ";", "}", "}", "// --------------------------------------------------------------------------", "$", "this", "->", "data", "[", "'page'", "]", "->", "title", "=", "'Edit customer'", ";", "Helper", "::", "loadView", "(", "'edit'", ")", ";", "}" ]
Edit an existing customer @return void
[ "Edit", "an", "existing", "customer" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Customer.php#L189-L234
32,978
nails/module-invoice
admin/controllers/Customer.php
Customer.formValidation
protected function formValidation() { $aRules = [ 'first_name' => 'max_length[255]', 'last_name' => 'max_length[255]', 'organisation' => 'max_length[255]', 'email' => 'max_length[255]|valid_email|required', 'billing_email' => 'max_length[255]|valid_email', 'telephone' => 'max_length[25]', 'vat_number' => 'max_length[25]', 'billing_address_line_1' => 'max_length[255]', 'billing_address_line_2' => 'max_length[255]', 'billing_address_town' => 'max_length[255]', 'billing_address_county' => 'max_length[255]', 'billing_address_postcode' => 'max_length[255]', 'billing_address_country' => 'max_length[255]', ]; $oFormValidation = Factory::service('FormValidation'); foreach ($aRules as $sKey => $sRule) { $oFormValidation->set_rules($sKey, '', $sRule); } $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('max_length', lang('fv_max_length')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if (!$oFormValidation->run()) { throw new NailsException(lang('fv_there_were_errors'), 1); } // First/Last name is required if no organisation is provided $oInput = Factory::service('Input'); $sOrganisation = $oInput->post('organisation'); $sFirstName = $oInput->post('first_name'); $sLastName = $oInput->post('last_name'); if (empty($sOrganisation) && (empty($sFirstName) || empty($sLastName))) { throw new NailsException('First name and surname are required if not providing an organisation.', 1); } }
php
protected function formValidation() { $aRules = [ 'first_name' => 'max_length[255]', 'last_name' => 'max_length[255]', 'organisation' => 'max_length[255]', 'email' => 'max_length[255]|valid_email|required', 'billing_email' => 'max_length[255]|valid_email', 'telephone' => 'max_length[25]', 'vat_number' => 'max_length[25]', 'billing_address_line_1' => 'max_length[255]', 'billing_address_line_2' => 'max_length[255]', 'billing_address_town' => 'max_length[255]', 'billing_address_county' => 'max_length[255]', 'billing_address_postcode' => 'max_length[255]', 'billing_address_country' => 'max_length[255]', ]; $oFormValidation = Factory::service('FormValidation'); foreach ($aRules as $sKey => $sRule) { $oFormValidation->set_rules($sKey, '', $sRule); } $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('max_length', lang('fv_max_length')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if (!$oFormValidation->run()) { throw new NailsException(lang('fv_there_were_errors'), 1); } // First/Last name is required if no organisation is provided $oInput = Factory::service('Input'); $sOrganisation = $oInput->post('organisation'); $sFirstName = $oInput->post('first_name'); $sLastName = $oInput->post('last_name'); if (empty($sOrganisation) && (empty($sFirstName) || empty($sLastName))) { throw new NailsException('First name and surname are required if not providing an organisation.', 1); } }
[ "protected", "function", "formValidation", "(", ")", "{", "$", "aRules", "=", "[", "'first_name'", "=>", "'max_length[255]'", ",", "'last_name'", "=>", "'max_length[255]'", ",", "'organisation'", "=>", "'max_length[255]'", ",", "'email'", "=>", "'max_length[255]|valid_email|required'", ",", "'billing_email'", "=>", "'max_length[255]|valid_email'", ",", "'telephone'", "=>", "'max_length[25]'", ",", "'vat_number'", "=>", "'max_length[25]'", ",", "'billing_address_line_1'", "=>", "'max_length[255]'", ",", "'billing_address_line_2'", "=>", "'max_length[255]'", ",", "'billing_address_town'", "=>", "'max_length[255]'", ",", "'billing_address_county'", "=>", "'max_length[255]'", ",", "'billing_address_postcode'", "=>", "'max_length[255]'", ",", "'billing_address_country'", "=>", "'max_length[255]'", ",", "]", ";", "$", "oFormValidation", "=", "Factory", "::", "service", "(", "'FormValidation'", ")", ";", "foreach", "(", "$", "aRules", "as", "$", "sKey", "=>", "$", "sRule", ")", "{", "$", "oFormValidation", "->", "set_rules", "(", "$", "sKey", ",", "''", ",", "$", "sRule", ")", ";", "}", "$", "oFormValidation", "->", "set_message", "(", "'required'", ",", "lang", "(", "'fv_required'", ")", ")", ";", "$", "oFormValidation", "->", "set_message", "(", "'max_length'", ",", "lang", "(", "'fv_max_length'", ")", ")", ";", "$", "oFormValidation", "->", "set_message", "(", "'valid_email'", ",", "lang", "(", "'fv_valid_email'", ")", ")", ";", "if", "(", "!", "$", "oFormValidation", "->", "run", "(", ")", ")", "{", "throw", "new", "NailsException", "(", "lang", "(", "'fv_there_were_errors'", ")", ",", "1", ")", ";", "}", "// First/Last name is required if no organisation is provided", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "$", "sOrganisation", "=", "$", "oInput", "->", "post", "(", "'organisation'", ")", ";", "$", "sFirstName", "=", "$", "oInput", "->", "post", "(", "'first_name'", ")", ";", "$", "sLastName", "=", "$", "oInput", "->", "post", "(", "'last_name'", ")", ";", "if", "(", "empty", "(", "$", "sOrganisation", ")", "&&", "(", "empty", "(", "$", "sFirstName", ")", "||", "empty", "(", "$", "sLastName", ")", ")", ")", "{", "throw", "new", "NailsException", "(", "'First name and surname are required if not providing an organisation.'", ",", "1", ")", ";", "}", "}" ]
Runs form validation @return void
[ "Runs", "form", "validation" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Customer.php#L242-L281
32,979
canihavesomecoffee/theTVDbAPI
src/Route/UsersRoute.php
UsersRoute.removeFavorite
public function removeFavorite(int $seriesId): bool { $response = $this->parent->performAPICall('delete', '/user/favorites/'.$seriesId); return $response->getStatusCode() === 200; }
php
public function removeFavorite(int $seriesId): bool { $response = $this->parent->performAPICall('delete', '/user/favorites/'.$seriesId); return $response->getStatusCode() === 200; }
[ "public", "function", "removeFavorite", "(", "int", "$", "seriesId", ")", ":", "bool", "{", "$", "response", "=", "$", "this", "->", "parent", "->", "performAPICall", "(", "'delete'", ",", "'/user/favorites/'", ".", "$", "seriesId", ")", ";", "return", "$", "response", "->", "getStatusCode", "(", ")", "===", "200", ";", "}" ]
Remove series from favorites. @param int $seriesId The id of the series to remove. @return bool True if the series was removed from the user's favourites.
[ "Remove", "series", "from", "favorites", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Route/UsersRoute.php#L76-L80
32,980
canihavesomecoffee/theTVDbAPI
src/Route/UsersRoute.php
UsersRoute.addRating
public function addRating(Rating $rating): bool { $response = $this->parent->performAPICall( 'put', 'user/ratings/'.$rating->getRatingType().'/'.$rating->ratingItemId.'/'.$rating->rating ); return $response->getStatusCode() === 200; }
php
public function addRating(Rating $rating): bool { $response = $this->parent->performAPICall( 'put', 'user/ratings/'.$rating->getRatingType().'/'.$rating->ratingItemId.'/'.$rating->rating ); return $response->getStatusCode() === 200; }
[ "public", "function", "addRating", "(", "Rating", "$", "rating", ")", ":", "bool", "{", "$", "response", "=", "$", "this", "->", "parent", "->", "performAPICall", "(", "'put'", ",", "'user/ratings/'", ".", "$", "rating", "->", "getRatingType", "(", ")", ".", "'/'", ".", "$", "rating", "->", "ratingItemId", ".", "'/'", ".", "$", "rating", "->", "rating", ")", ";", "return", "$", "response", "->", "getStatusCode", "(", ")", "===", "200", ";", "}" ]
Adds a user rating. @param Rating $rating The rating to add. @return bool True on success, false on failure.
[ "Adds", "a", "user", "rating", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Route/UsersRoute.php#L127-L134
32,981
canihavesomecoffee/theTVDbAPI
src/Model/PaginatedResults.php
PaginatedResults.getLinkElement
private function getLinkElement(string $key): int { $link = -1; if (array_key_exists($key, $this->links)) { $link = intval($this->links[$key], 10); } return $link; }
php
private function getLinkElement(string $key): int { $link = -1; if (array_key_exists($key, $this->links)) { $link = intval($this->links[$key], 10); } return $link; }
[ "private", "function", "getLinkElement", "(", "string", "$", "key", ")", ":", "int", "{", "$", "link", "=", "-", "1", ";", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "links", ")", ")", "{", "$", "link", "=", "intval", "(", "$", "this", "->", "links", "[", "$", "key", "]", ",", "10", ")", ";", "}", "return", "$", "link", ";", "}" ]
Fetches a link element from the array. @param string $key The element to retrieve. @return int The element if found, or -1 if not.
[ "Fetches", "a", "link", "element", "from", "the", "array", "." ]
f23f544029269fe2a244818209b060d08654eca6
https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Model/PaginatedResults.php#L123-L130
32,982
Saritasa/php-laravel-entity-services
src/Services/EntityServiceFactory.php
EntityServiceFactory.buildEntityService
protected function buildEntityService(string $modelClass): IEntityService { try { if (isset($this->registeredServices[$modelClass])) { return $this->container->make($this->registeredServices[$modelClass]); } return $this->container->make(EntityService::class, [ 'className' => $modelClass, 'repository' => $this->repositoryFactory->getRepository($modelClass), ]); } catch (RepositoryException $exception) { throw new EntityServiceException($exception->getMessage(), $exception->getCode(), $exception); } }
php
protected function buildEntityService(string $modelClass): IEntityService { try { if (isset($this->registeredServices[$modelClass])) { return $this->container->make($this->registeredServices[$modelClass]); } return $this->container->make(EntityService::class, [ 'className' => $modelClass, 'repository' => $this->repositoryFactory->getRepository($modelClass), ]); } catch (RepositoryException $exception) { throw new EntityServiceException($exception->getMessage(), $exception->getCode(), $exception); } }
[ "protected", "function", "buildEntityService", "(", "string", "$", "modelClass", ")", ":", "IEntityService", "{", "try", "{", "if", "(", "isset", "(", "$", "this", "->", "registeredServices", "[", "$", "modelClass", "]", ")", ")", "{", "return", "$", "this", "->", "container", "->", "make", "(", "$", "this", "->", "registeredServices", "[", "$", "modelClass", "]", ")", ";", "}", "return", "$", "this", "->", "container", "->", "make", "(", "EntityService", "::", "class", ",", "[", "'className'", "=>", "$", "modelClass", ",", "'repository'", "=>", "$", "this", "->", "repositoryFactory", "->", "getRepository", "(", "$", "modelClass", ")", ",", "]", ")", ";", "}", "catch", "(", "RepositoryException", "$", "exception", ")", "{", "throw", "new", "EntityServiceException", "(", "$", "exception", "->", "getMessage", "(", ")", ",", "$", "exception", "->", "getCode", "(", ")", ",", "$", "exception", ")", ";", "}", "}" ]
Build entity service by model class from registered instances or creates default. @param string $modelClass Model class to build entity service @return IEntityService @throws EntityServiceException @throws BindingResolutionException
[ "Build", "entity", "service", "by", "model", "class", "from", "registered", "instances", "or", "creates", "default", "." ]
7cac8e05d8a067ac269ce141e94b18b8b89e5493
https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityServiceFactory.php#L83-L97
32,983
wikimedia/mediawiki-oauthclient-php
src/Request.php
Request.fromRequest
public static function fromRequest( $method = null, $url = null, array $params = null ) { $scheme = ( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] != 'on' ) ? 'http' : 'https'; $url = ( $url ?: $scheme ) . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']; $method = $method ?: $_SERVER['REQUEST_METHOD']; // We weren't handed any params, so let's find the ones relevant // to this request. If you run XML-RPC or similar you should use this // to provide your own parsed parameter-list if ( !$params ) { // Find request headers $headers = Util::getHeaders(); // Parse the query-string to find GET params $params = Util::parseParameters( $_SERVER['QUERY_STRING'] ); // It's a POST request of the proper content-type, so parse POST // params and add those overriding any duplicates from GET if ( $method === 'POST' && isset( $headers['Content-Type'] ) && strstr( $headers['Content-Type'], 'application/x-www-form-urlencoded' ) ) { $post_data = Util::parseParameters( file_get_contents( self::$POST_INPUT ) ); $params = array_merge( $params, $post_data ); } // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if ( isset( $headers['Authorization'] ) && substr( $headers['Authorization'], 0, 6 ) === 'OAuth ' ) { $header_params = Util::splitHeader( $headers['Authorization'] ); $params = array_merge( $params, $header_params ); } } return new Request( $method, $url, $params ); }
php
public static function fromRequest( $method = null, $url = null, array $params = null ) { $scheme = ( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] != 'on' ) ? 'http' : 'https'; $url = ( $url ?: $scheme ) . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']; $method = $method ?: $_SERVER['REQUEST_METHOD']; // We weren't handed any params, so let's find the ones relevant // to this request. If you run XML-RPC or similar you should use this // to provide your own parsed parameter-list if ( !$params ) { // Find request headers $headers = Util::getHeaders(); // Parse the query-string to find GET params $params = Util::parseParameters( $_SERVER['QUERY_STRING'] ); // It's a POST request of the proper content-type, so parse POST // params and add those overriding any duplicates from GET if ( $method === 'POST' && isset( $headers['Content-Type'] ) && strstr( $headers['Content-Type'], 'application/x-www-form-urlencoded' ) ) { $post_data = Util::parseParameters( file_get_contents( self::$POST_INPUT ) ); $params = array_merge( $params, $post_data ); } // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if ( isset( $headers['Authorization'] ) && substr( $headers['Authorization'], 0, 6 ) === 'OAuth ' ) { $header_params = Util::splitHeader( $headers['Authorization'] ); $params = array_merge( $params, $header_params ); } } return new Request( $method, $url, $params ); }
[ "public", "static", "function", "fromRequest", "(", "$", "method", "=", "null", ",", "$", "url", "=", "null", ",", "array", "$", "params", "=", "null", ")", "{", "$", "scheme", "=", "(", "!", "isset", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "||", "$", "_SERVER", "[", "'HTTPS'", "]", "!=", "'on'", ")", "?", "'http'", ":", "'https'", ";", "$", "url", "=", "(", "$", "url", "?", ":", "$", "scheme", ")", ".", "'://'", ".", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ".", "':'", ".", "$", "_SERVER", "[", "'SERVER_PORT'", "]", ".", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "$", "method", "=", "$", "method", "?", ":", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ";", "// We weren't handed any params, so let's find the ones relevant", "// to this request. If you run XML-RPC or similar you should use this", "// to provide your own parsed parameter-list", "if", "(", "!", "$", "params", ")", "{", "// Find request headers", "$", "headers", "=", "Util", "::", "getHeaders", "(", ")", ";", "// Parse the query-string to find GET params", "$", "params", "=", "Util", "::", "parseParameters", "(", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ")", ";", "// It's a POST request of the proper content-type, so parse POST", "// params and add those overriding any duplicates from GET", "if", "(", "$", "method", "===", "'POST'", "&&", "isset", "(", "$", "headers", "[", "'Content-Type'", "]", ")", "&&", "strstr", "(", "$", "headers", "[", "'Content-Type'", "]", ",", "'application/x-www-form-urlencoded'", ")", ")", "{", "$", "post_data", "=", "Util", "::", "parseParameters", "(", "file_get_contents", "(", "self", "::", "$", "POST_INPUT", ")", ")", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "post_data", ")", ";", "}", "// We have a Authorization-header with OAuth data. Parse the header", "// and add those overriding any duplicates from GET or POST", "if", "(", "isset", "(", "$", "headers", "[", "'Authorization'", "]", ")", "&&", "substr", "(", "$", "headers", "[", "'Authorization'", "]", ",", "0", ",", "6", ")", "===", "'OAuth '", ")", "{", "$", "header_params", "=", "Util", "::", "splitHeader", "(", "$", "headers", "[", "'Authorization'", "]", ")", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "header_params", ")", ";", "}", "}", "return", "new", "Request", "(", "$", "method", ",", "$", "url", ",", "$", "params", ")", ";", "}" ]
Attempt to build up a request from what was passed to the server @param string|null $method @param string|null $url @param array|null $params @return Request
[ "Attempt", "to", "build", "up", "a", "request", "from", "what", "was", "passed", "to", "the", "server" ]
1c8b33ff91273ba50e987d380724add7051d31ea
https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Request.php#L84-L133
32,984
wikimedia/mediawiki-oauthclient-php
src/Request.php
Request.toUrl
public function toUrl() { $post_data = $this->toPostData(); $out = $this->getNormalizedUrl(); if ( $post_data ) { $out .= '?' . $post_data; } return $out; }
php
public function toUrl() { $post_data = $this->toPostData(); $out = $this->getNormalizedUrl(); if ( $post_data ) { $out .= '?' . $post_data; } return $out; }
[ "public", "function", "toUrl", "(", ")", "{", "$", "post_data", "=", "$", "this", "->", "toPostData", "(", ")", ";", "$", "out", "=", "$", "this", "->", "getNormalizedUrl", "(", ")", ";", "if", "(", "$", "post_data", ")", "{", "$", "out", ".=", "'?'", ".", "$", "post_data", ";", "}", "return", "$", "out", ";", "}" ]
Builds a url usable for a GET request @return string
[ "Builds", "a", "url", "usable", "for", "a", "GET", "request" ]
1c8b33ff91273ba50e987d380724add7051d31ea
https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Request.php#L278-L285
32,985
anomalylabs/variables-module
src/Http/Controller/Admin/VariablesController.php
VariablesController.edit
public function edit(StreamRepositoryInterface $streams, VariableFormBuilder $form, $id) { /* @var StreamInterface $group */ $group = $streams->find($id); $entry = $group->getEntryModel()->firstOrNew([]); return $form->setModel($group->getEntryModelName())->render($entry); }
php
public function edit(StreamRepositoryInterface $streams, VariableFormBuilder $form, $id) { /* @var StreamInterface $group */ $group = $streams->find($id); $entry = $group->getEntryModel()->firstOrNew([]); return $form->setModel($group->getEntryModelName())->render($entry); }
[ "public", "function", "edit", "(", "StreamRepositoryInterface", "$", "streams", ",", "VariableFormBuilder", "$", "form", ",", "$", "id", ")", "{", "/* @var StreamInterface $group */", "$", "group", "=", "$", "streams", "->", "find", "(", "$", "id", ")", ";", "$", "entry", "=", "$", "group", "->", "getEntryModel", "(", ")", "->", "firstOrNew", "(", "[", "]", ")", ";", "return", "$", "form", "->", "setModel", "(", "$", "group", "->", "getEntryModelName", "(", ")", ")", "->", "render", "(", "$", "entry", ")", ";", "}" ]
Return a form to edit the variables. @param StreamRepositoryInterface $streams @param VariableFormBuilder $form @param $id @return \Symfony\Component\HttpFoundation\Response
[ "Return", "a", "form", "to", "edit", "the", "variables", "." ]
bcd903670471a175f07aba3123693cb3a3c07d0b
https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Http/Controller/Admin/VariablesController.php#L40-L48
32,986
orchestral/support
src/Providers/Concerns/AliasesProvider.php
AliasesProvider.registerFacadesAliases
protected function registerFacadesAliases(): void { $loader = AliasLoader::getInstance(); foreach ((array) $this->facades as $facade => $aliases) { foreach ((array) $aliases as $alias) { $loader->alias($alias, $facade); } } }
php
protected function registerFacadesAliases(): void { $loader = AliasLoader::getInstance(); foreach ((array) $this->facades as $facade => $aliases) { foreach ((array) $aliases as $alias) { $loader->alias($alias, $facade); } } }
[ "protected", "function", "registerFacadesAliases", "(", ")", ":", "void", "{", "$", "loader", "=", "AliasLoader", "::", "getInstance", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "this", "->", "facades", "as", "$", "facade", "=>", "$", "aliases", ")", "{", "foreach", "(", "(", "array", ")", "$", "aliases", "as", "$", "alias", ")", "{", "$", "loader", "->", "alias", "(", "$", "alias", ",", "$", "facade", ")", ";", "}", "}", "}" ]
Register facades aliases. @return void
[ "Register", "facades", "aliases", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Providers/Concerns/AliasesProvider.php#L14-L23
32,987
nails/module-invoice
src/Factory/Invoice.php
Invoice.addItem
public function addItem(Item $oItem) { if (empty(!$this->iId)) { throw new InvoiceException('Invoice has been saved and cannot be modified.'); } $this->aItems[] = $oItem; return $this; }
php
public function addItem(Item $oItem) { if (empty(!$this->iId)) { throw new InvoiceException('Invoice has been saved and cannot be modified.'); } $this->aItems[] = $oItem; return $this; }
[ "public", "function", "addItem", "(", "Item", "$", "oItem", ")", "{", "if", "(", "empty", "(", "!", "$", "this", "->", "iId", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'Invoice has been saved and cannot be modified.'", ")", ";", "}", "$", "this", "->", "aItems", "[", "]", "=", "$", "oItem", ";", "return", "$", "this", ";", "}" ]
Add an item to the invoice @param Item $oItem the item to add @return $this @throws InvoiceException
[ "Add", "an", "item", "to", "the", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L153-L160
32,988
nails/module-invoice
src/Factory/Invoice.php
Invoice.save
public function save() { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (empty($this->iId)) { $oInvoice = $oInvoiceModel->create($this->toArray(), true); if (empty($oInvoice)) { throw new InvoiceException($oInvoiceModel->lastError()); } $this->iId = $oInvoice->id; $this->sRef = $oInvoice->ref; } else { $oInvoice = $oInvoiceModel->getById($this->iId); } return $oInvoice; }
php
public function save() { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (empty($this->iId)) { $oInvoice = $oInvoiceModel->create($this->toArray(), true); if (empty($oInvoice)) { throw new InvoiceException($oInvoiceModel->lastError()); } $this->iId = $oInvoice->id; $this->sRef = $oInvoice->ref; } else { $oInvoice = $oInvoiceModel->getById($this->iId); } return $oInvoice; }
[ "public", "function", "save", "(", ")", "{", "$", "oInvoiceModel", "=", "Factory", "::", "model", "(", "'Invoice'", ",", "'nails/module-invoice'", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "iId", ")", ")", "{", "$", "oInvoice", "=", "$", "oInvoiceModel", "->", "create", "(", "$", "this", "->", "toArray", "(", ")", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "oInvoice", ")", ")", "{", "throw", "new", "InvoiceException", "(", "$", "oInvoiceModel", "->", "lastError", "(", ")", ")", ";", "}", "$", "this", "->", "iId", "=", "$", "oInvoice", "->", "id", ";", "$", "this", "->", "sRef", "=", "$", "oInvoice", "->", "ref", ";", "}", "else", "{", "$", "oInvoice", "=", "$", "oInvoiceModel", "->", "getById", "(", "$", "this", "->", "iId", ")", ";", "}", "return", "$", "oInvoice", ";", "}" ]
Saves a new invoice @return \stdClass @throws InvoiceException
[ "Saves", "a", "new", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L186-L200
32,989
nails/module-invoice
src/Factory/Invoice.php
Invoice.delete
public function delete() { if (!empty($this->iId)) { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (!$oInvoiceModel->delete($this->iId)) { throw new InvoiceException('Failed to delete invoice.'); } } return $this; }
php
public function delete() { if (!empty($this->iId)) { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (!$oInvoiceModel->delete($this->iId)) { throw new InvoiceException('Failed to delete invoice.'); } } return $this; }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "iId", ")", ")", "{", "$", "oInvoiceModel", "=", "Factory", "::", "model", "(", "'Invoice'", ",", "'nails/module-invoice'", ")", ";", "if", "(", "!", "$", "oInvoiceModel", "->", "delete", "(", "$", "this", "->", "iId", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to delete invoice.'", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Deletes an invoice @return $this @throws InvoiceException
[ "Deletes", "an", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L209-L219
32,990
nails/module-invoice
src/Factory/Invoice.php
Invoice.writeOff
public function writeOff() { if (!empty($this->iId)) { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (!$oInvoiceModel->setWrittenOff($this->iId)) { throw new InvoiceException('Failed to write off invoice.'); } } return $this; }
php
public function writeOff() { if (!empty($this->iId)) { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); if (!$oInvoiceModel->setWrittenOff($this->iId)) { throw new InvoiceException('Failed to write off invoice.'); } } return $this; }
[ "public", "function", "writeOff", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "iId", ")", ")", "{", "$", "oInvoiceModel", "=", "Factory", "::", "model", "(", "'Invoice'", ",", "'nails/module-invoice'", ")", ";", "if", "(", "!", "$", "oInvoiceModel", "->", "setWrittenOff", "(", "$", "this", "->", "iId", ")", ")", "{", "throw", "new", "InvoiceException", "(", "'Failed to write off invoice.'", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Writes an invoice off @return $this @throws InvoiceException
[ "Writes", "an", "invoice", "off" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L228-L238
32,991
nails/module-invoice
src/Factory/Invoice.php
Invoice.charge
public function charge(ChargeRequest $oChargeRequest) { if (empty($this->iId)) { $oInvoice = $this->save(); } else { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); $oInvoice = $oInvoiceModel->getById($this->iId); } $oChargeRequest->setInvoice($this->iId); $oChargeRequest->setDescription('Payment for invoice ' . $this->sRef); return $oChargeRequest->execute( $oInvoice->totals->raw->grand, $oInvoice->currency->code ); }
php
public function charge(ChargeRequest $oChargeRequest) { if (empty($this->iId)) { $oInvoice = $this->save(); } else { $oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice'); $oInvoice = $oInvoiceModel->getById($this->iId); } $oChargeRequest->setInvoice($this->iId); $oChargeRequest->setDescription('Payment for invoice ' . $this->sRef); return $oChargeRequest->execute( $oInvoice->totals->raw->grand, $oInvoice->currency->code ); }
[ "public", "function", "charge", "(", "ChargeRequest", "$", "oChargeRequest", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "iId", ")", ")", "{", "$", "oInvoice", "=", "$", "this", "->", "save", "(", ")", ";", "}", "else", "{", "$", "oInvoiceModel", "=", "Factory", "::", "model", "(", "'Invoice'", ",", "'nails/module-invoice'", ")", ";", "$", "oInvoice", "=", "$", "oInvoiceModel", "->", "getById", "(", "$", "this", "->", "iId", ")", ";", "}", "$", "oChargeRequest", "->", "setInvoice", "(", "$", "this", "->", "iId", ")", ";", "$", "oChargeRequest", "->", "setDescription", "(", "'Payment for invoice '", ".", "$", "this", "->", "sRef", ")", ";", "return", "$", "oChargeRequest", "->", "execute", "(", "$", "oInvoice", "->", "totals", "->", "raw", "->", "grand", ",", "$", "oInvoice", "->", "currency", "->", "code", ")", ";", "}" ]
Charges an invoice @param ChargeRequest $oChargeRequest @return ChargeResponse @throws InvoiceException
[ "Charges", "an", "invoice" ]
3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716
https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L250-L265
32,992
QoboLtd/qobo-robo
src/Utility/Template.php
Template.getTokens
public static function getTokens($template, $pre = '%%', $post = '%%') { $tokens = []; $regex = "/$pre(.*?)$post/"; if (preg_match_all($regex, $template, $matches)) { $tokens = array_unique($matches[1]); } natsort($tokens); return $tokens; }
php
public static function getTokens($template, $pre = '%%', $post = '%%') { $tokens = []; $regex = "/$pre(.*?)$post/"; if (preg_match_all($regex, $template, $matches)) { $tokens = array_unique($matches[1]); } natsort($tokens); return $tokens; }
[ "public", "static", "function", "getTokens", "(", "$", "template", ",", "$", "pre", "=", "'%%'", ",", "$", "post", "=", "'%%'", ")", "{", "$", "tokens", "=", "[", "]", ";", "$", "regex", "=", "\"/$pre(.*?)$post/\"", ";", "if", "(", "preg_match_all", "(", "$", "regex", ",", "$", "template", ",", "$", "matches", ")", ")", "{", "$", "tokens", "=", "array_unique", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "natsort", "(", "$", "tokens", ")", ";", "return", "$", "tokens", ";", "}" ]
Returns a list of unique tokens found in a given template @param string $template Template content @param string $pre Token prefix @param string $post Token postfix @return array List of tokens
[ "Returns", "a", "list", "of", "unique", "tokens", "found", "in", "a", "given", "template" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/Template.php#L40-L51
32,993
QoboLtd/qobo-robo
src/Utility/Template.php
Template.parse
public static function parse( $template, array $tokens, $pre = '%%', $post = '%%', $flags = self::FLAG_RECURSIVE | self::FLAG_STRICT ) { // nothing to do with empty templates or when no tokens given if (empty($template) || empty($tokens)) { return $template; } // FLAG_EMPTY_MISSING and FLAG_STRICT are mutually exclusive if (($flags & self::FLAG_EMPTY_MISSING) && ($flags & self::FLAG_STRICT)) { throw new InvalidArgumentException("Can't use FLAG_EMPTY_MISSING and FLAG_STRICT together"); } // replace the tokens with their values $result = $template; foreach ($tokens as $token => $replacement) { $token = "$pre$token$post"; $result = str_replace($token, $replacement, $result); } if ($flags & self::FLAG_RECURSIVE) { $recursiveResult = self::parse($result, $tokens, $pre, $post, $flags xor self::FLAG_RECURSIVE); if ($result <> $recursiveResult) { $result = self::parse($result, $pre, $post, $flags); } } // check for any tokens left in the result $remainingTokens = self::getTokens($result, $pre, $post); // ok if no tokens left if (empty($remainingTokens)) { return $result; } // throw exception if in strict mode if ($flags & self::FLAG_STRICT) { throw new RuntimeException("Missing values for [" . implode(", ", $remainingTokens) . "] tokens"); } // replace unknown tokens with empty string if FLAG_EMPTY_MISSING if ($flags & self::FLAG_EMPTY_MISSING) { $tokens = []; foreach ($remainingTokens as $token) { $tokens[$token] = ""; } return self::parse($result, $tokens, $pre, $post); } return $result; }
php
public static function parse( $template, array $tokens, $pre = '%%', $post = '%%', $flags = self::FLAG_RECURSIVE | self::FLAG_STRICT ) { // nothing to do with empty templates or when no tokens given if (empty($template) || empty($tokens)) { return $template; } // FLAG_EMPTY_MISSING and FLAG_STRICT are mutually exclusive if (($flags & self::FLAG_EMPTY_MISSING) && ($flags & self::FLAG_STRICT)) { throw new InvalidArgumentException("Can't use FLAG_EMPTY_MISSING and FLAG_STRICT together"); } // replace the tokens with their values $result = $template; foreach ($tokens as $token => $replacement) { $token = "$pre$token$post"; $result = str_replace($token, $replacement, $result); } if ($flags & self::FLAG_RECURSIVE) { $recursiveResult = self::parse($result, $tokens, $pre, $post, $flags xor self::FLAG_RECURSIVE); if ($result <> $recursiveResult) { $result = self::parse($result, $pre, $post, $flags); } } // check for any tokens left in the result $remainingTokens = self::getTokens($result, $pre, $post); // ok if no tokens left if (empty($remainingTokens)) { return $result; } // throw exception if in strict mode if ($flags & self::FLAG_STRICT) { throw new RuntimeException("Missing values for [" . implode(", ", $remainingTokens) . "] tokens"); } // replace unknown tokens with empty string if FLAG_EMPTY_MISSING if ($flags & self::FLAG_EMPTY_MISSING) { $tokens = []; foreach ($remainingTokens as $token) { $tokens[$token] = ""; } return self::parse($result, $tokens, $pre, $post); } return $result; }
[ "public", "static", "function", "parse", "(", "$", "template", ",", "array", "$", "tokens", ",", "$", "pre", "=", "'%%'", ",", "$", "post", "=", "'%%'", ",", "$", "flags", "=", "self", "::", "FLAG_RECURSIVE", "|", "self", "::", "FLAG_STRICT", ")", "{", "// nothing to do with empty templates or when no tokens given", "if", "(", "empty", "(", "$", "template", ")", "||", "empty", "(", "$", "tokens", ")", ")", "{", "return", "$", "template", ";", "}", "// FLAG_EMPTY_MISSING and FLAG_STRICT are mutually exclusive", "if", "(", "(", "$", "flags", "&", "self", "::", "FLAG_EMPTY_MISSING", ")", "&&", "(", "$", "flags", "&", "self", "::", "FLAG_STRICT", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Can't use FLAG_EMPTY_MISSING and FLAG_STRICT together\"", ")", ";", "}", "// replace the tokens with their values", "$", "result", "=", "$", "template", ";", "foreach", "(", "$", "tokens", "as", "$", "token", "=>", "$", "replacement", ")", "{", "$", "token", "=", "\"$pre$token$post\"", ";", "$", "result", "=", "str_replace", "(", "$", "token", ",", "$", "replacement", ",", "$", "result", ")", ";", "}", "if", "(", "$", "flags", "&", "self", "::", "FLAG_RECURSIVE", ")", "{", "$", "recursiveResult", "=", "self", "::", "parse", "(", "$", "result", ",", "$", "tokens", ",", "$", "pre", ",", "$", "post", ",", "$", "flags", "xor", "self", "::", "FLAG_RECURSIVE", ")", ";", "if", "(", "$", "result", "<>", "$", "recursiveResult", ")", "{", "$", "result", "=", "self", "::", "parse", "(", "$", "result", ",", "$", "pre", ",", "$", "post", ",", "$", "flags", ")", ";", "}", "}", "// check for any tokens left in the result", "$", "remainingTokens", "=", "self", "::", "getTokens", "(", "$", "result", ",", "$", "pre", ",", "$", "post", ")", ";", "// ok if no tokens left", "if", "(", "empty", "(", "$", "remainingTokens", ")", ")", "{", "return", "$", "result", ";", "}", "// throw exception if in strict mode", "if", "(", "$", "flags", "&", "self", "::", "FLAG_STRICT", ")", "{", "throw", "new", "RuntimeException", "(", "\"Missing values for [\"", ".", "implode", "(", "\", \"", ",", "$", "remainingTokens", ")", ".", "\"] tokens\"", ")", ";", "}", "// replace unknown tokens with empty string if FLAG_EMPTY_MISSING", "if", "(", "$", "flags", "&", "self", "::", "FLAG_EMPTY_MISSING", ")", "{", "$", "tokens", "=", "[", "]", ";", "foreach", "(", "$", "remainingTokens", "as", "$", "token", ")", "{", "$", "tokens", "[", "$", "token", "]", "=", "\"\"", ";", "}", "return", "self", "::", "parse", "(", "$", "result", ",", "$", "tokens", ",", "$", "pre", ",", "$", "post", ")", ";", "}", "return", "$", "result", ";", "}" ]
Parse template with given tokens @param string $template Template content @param array $tokens List of key value tokens array @param string $pre Token prefix @param string $post Token postfix @param int $flags Additianal flags for parsing @return string Parsed template
[ "Parse", "template", "with", "given", "tokens" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/Template.php#L64-L120
32,994
QoboLtd/qobo-robo
src/Command/Project/DotenvCreate.php
DotenvCreate.projectDotenvCreate
public function projectDotenvCreate( $envPath = '.env', $templatePath = '.env.example', $env = '', $opts = ['format' => 'table', 'fields' => ''] ) { $task = $this->taskProjectDotenvCreate() ->env($envPath) ->template($templatePath); $vars = explode(',', $env); foreach ($vars as $var) { $var = trim($var); if (preg_match('/^(.*?)=(.*?)$/', $var, $matches)) { $task->set($matches[1], $matches[2]); } } $result = $task->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } $data = $result->getData()['data']; $lines = array_map(function ($k, $v) { return "$k=$v"; }, array_keys($data), $data); $result = $this->taskWriteToFile($envPath) ->lines($lines) ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } return new PropertyList($data); }
php
public function projectDotenvCreate( $envPath = '.env', $templatePath = '.env.example', $env = '', $opts = ['format' => 'table', 'fields' => ''] ) { $task = $this->taskProjectDotenvCreate() ->env($envPath) ->template($templatePath); $vars = explode(',', $env); foreach ($vars as $var) { $var = trim($var); if (preg_match('/^(.*?)=(.*?)$/', $var, $matches)) { $task->set($matches[1], $matches[2]); } } $result = $task->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } $data = $result->getData()['data']; $lines = array_map(function ($k, $v) { return "$k=$v"; }, array_keys($data), $data); $result = $this->taskWriteToFile($envPath) ->lines($lines) ->run(); if (!$result->wasSuccessful()) { $this->exitError("Failed to run command"); } return new PropertyList($data); }
[ "public", "function", "projectDotenvCreate", "(", "$", "envPath", "=", "'.env'", ",", "$", "templatePath", "=", "'.env.example'", ",", "$", "env", "=", "''", ",", "$", "opts", "=", "[", "'format'", "=>", "'table'", ",", "'fields'", "=>", "''", "]", ")", "{", "$", "task", "=", "$", "this", "->", "taskProjectDotenvCreate", "(", ")", "->", "env", "(", "$", "envPath", ")", "->", "template", "(", "$", "templatePath", ")", ";", "$", "vars", "=", "explode", "(", "','", ",", "$", "env", ")", ";", "foreach", "(", "$", "vars", "as", "$", "var", ")", "{", "$", "var", "=", "trim", "(", "$", "var", ")", ";", "if", "(", "preg_match", "(", "'/^(.*?)=(.*?)$/'", ",", "$", "var", ",", "$", "matches", ")", ")", "{", "$", "task", "->", "set", "(", "$", "matches", "[", "1", "]", ",", "$", "matches", "[", "2", "]", ")", ";", "}", "}", "$", "result", "=", "$", "task", "->", "run", "(", ")", ";", "if", "(", "!", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "exitError", "(", "\"Failed to run command\"", ")", ";", "}", "$", "data", "=", "$", "result", "->", "getData", "(", ")", "[", "'data'", "]", ";", "$", "lines", "=", "array_map", "(", "function", "(", "$", "k", ",", "$", "v", ")", "{", "return", "\"$k=$v\"", ";", "}", ",", "array_keys", "(", "$", "data", ")", ",", "$", "data", ")", ";", "$", "result", "=", "$", "this", "->", "taskWriteToFile", "(", "$", "envPath", ")", "->", "lines", "(", "$", "lines", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "exitError", "(", "\"Failed to run command\"", ")", ";", "}", "return", "new", "PropertyList", "(", "$", "data", ")", ";", "}" ]
Create dotenv file @param string $envPath Path to dotenv file @param string $templatePath Path to dotenv template @param string $env Custom dotenv in KEY1=VALUE1,KEY2=VALUE2 format @option string $format Output format (table, list, csv, json, xml) @option string $fields Limit output to given fields, comma-separated @return PropertyList
[ "Create", "dotenv", "file" ]
ea10f778bb046ad41324d22b27fce5a2fb8915ce
https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/DotenvCreate.php#L32-L71
32,995
orchestral/support
src/Support/Concerns/DataContainer.php
DataContainer.get
public function get(string $key, $default = null) { $value = Arr::get($this->items, $key); if (\is_null($value)) { return \value($default); } return $value; }
php
public function get(string $key, $default = null) { $value = Arr::get($this->items, $key); if (\is_null($value)) { return \value($default); } return $value; }
[ "public", "function", "get", "(", "string", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "value", "=", "Arr", "::", "get", "(", "$", "this", "->", "items", ",", "$", "key", ")", ";", "if", "(", "\\", "is_null", "(", "$", "value", ")", ")", "{", "return", "\\", "value", "(", "$", "default", ")", ";", "}", "return", "$", "value", ";", "}" ]
Get a item value. @param string $key @param mixed $default @return mixed
[ "Get", "a", "item", "value", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L41-L50
32,996
orchestral/support
src/Support/Concerns/DataContainer.php
DataContainer.secureGet
public function secureGet(string $key, $default = null) { $value = $this->get($key, $default); if ($this->encrypter instanceof Encrypter) { try { return $this->encrypter->decrypt($value); } catch (DecryptException $e) { // } } return $value; }
php
public function secureGet(string $key, $default = null) { $value = $this->get($key, $default); if ($this->encrypter instanceof Encrypter) { try { return $this->encrypter->decrypt($value); } catch (DecryptException $e) { // } } return $value; }
[ "public", "function", "secureGet", "(", "string", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "if", "(", "$", "this", "->", "encrypter", "instanceof", "Encrypter", ")", "{", "try", "{", "return", "$", "this", "->", "encrypter", "->", "decrypt", "(", "$", "value", ")", ";", "}", "catch", "(", "DecryptException", "$", "e", ")", "{", "//", "}", "}", "return", "$", "value", ";", "}" ]
Get an encrypted item value. @param string $key @param mixed $default @return mixed
[ "Get", "an", "encrypted", "item", "value", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L60-L73
32,997
orchestral/support
src/Support/Concerns/DataContainer.php
DataContainer.set
public function set(string $key, $value = null) { return Arr::set($this->items, $key, \value($value)); }
php
public function set(string $key, $value = null) { return Arr::set($this->items, $key, \value($value)); }
[ "public", "function", "set", "(", "string", "$", "key", ",", "$", "value", "=", "null", ")", "{", "return", "Arr", "::", "set", "(", "$", "this", "->", "items", ",", "$", "key", ",", "\\", "value", "(", "$", "value", ")", ")", ";", "}" ]
Set a item value. @param string $key @param mixed $value @return mixed
[ "Set", "a", "item", "value", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L83-L86
32,998
orchestral/support
src/Support/Concerns/DataContainer.php
DataContainer.secureSet
public function secureSet(string $key, $value = null) { try { if ($this->encrypter instanceof Encrypter) { $value = $this->encrypter->encrypt($value); } } catch (EncryptException $e) { // } return $this->set($key, $value); }
php
public function secureSet(string $key, $value = null) { try { if ($this->encrypter instanceof Encrypter) { $value = $this->encrypter->encrypt($value); } } catch (EncryptException $e) { // } return $this->set($key, $value); }
[ "public", "function", "secureSet", "(", "string", "$", "key", ",", "$", "value", "=", "null", ")", "{", "try", "{", "if", "(", "$", "this", "->", "encrypter", "instanceof", "Encrypter", ")", "{", "$", "value", "=", "$", "this", "->", "encrypter", "->", "encrypt", "(", "$", "value", ")", ";", "}", "}", "catch", "(", "EncryptException", "$", "e", ")", "{", "//", "}", "return", "$", "this", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}" ]
Set an ecrypted item value. @param string $key @param mixed $value @return mixed
[ "Set", "an", "ecrypted", "item", "value", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L96-L107
32,999
orchestral/support
src/Support/Concerns/DataContainer.php
DataContainer.forget
public function forget(string $key): bool { $items = $this->items; \array_push($this->removedItems, $key); Arr::forget($items, $key); $this->items = $items; return true; }
php
public function forget(string $key): bool { $items = $this->items; \array_push($this->removedItems, $key); Arr::forget($items, $key); $this->items = $items; return true; }
[ "public", "function", "forget", "(", "string", "$", "key", ")", ":", "bool", "{", "$", "items", "=", "$", "this", "->", "items", ";", "\\", "array_push", "(", "$", "this", "->", "removedItems", ",", "$", "key", ")", ";", "Arr", "::", "forget", "(", "$", "items", ",", "$", "key", ")", ";", "$", "this", "->", "items", "=", "$", "items", ";", "return", "true", ";", "}" ]
Remove a item key. @param string $key @return bool
[ "Remove", "a", "item", "key", "." ]
b56f0469f967737e39fc9a33d40ae7439f4f6884
https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L128-L138