repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
bobthecow/psysh
src/Input/ShellInput.php
ShellInput.addLongOption
private function addLongOption($name, $value) { if (!$this->definition->hasOption($name)) { throw new \RuntimeException(\sprintf('The "--%s" option does not exist.', $name)); } $option = $this->definition->getOption($name); if (null !== $value && !$option->acceptValue()) { throw new \RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name)); } if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) { // if option accepts an optional or mandatory argument // let's see if there is one provided $next = \array_shift($this->parsed); $nextToken = $next[0]; if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || \in_array($nextToken, ['', null], true)) { $value = $nextToken; } else { \array_unshift($this->parsed, $next); } } if (null === $value) { if ($option->isValueRequired()) { throw new \RuntimeException(\sprintf('The "--%s" option requires a value.', $name)); } if (!$option->isArray() && !$option->isValueOptional()) { $value = true; } } if ($option->isArray()) { $this->options[$name][] = $value; } else { $this->options[$name] = $value; } }
php
private function addLongOption($name, $value) { if (!$this->definition->hasOption($name)) { throw new \RuntimeException(\sprintf('The "--%s" option does not exist.', $name)); } $option = $this->definition->getOption($name); if (null !== $value && !$option->acceptValue()) { throw new \RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name)); } if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) { $next = \array_shift($this->parsed); $nextToken = $next[0]; if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || \in_array($nextToken, ['', null], true)) { $value = $nextToken; } else { \array_unshift($this->parsed, $next); } } if (null === $value) { if ($option->isValueRequired()) { throw new \RuntimeException(\sprintf('The "--%s" option requires a value.', $name)); } if (!$option->isArray() && !$option->isValueOptional()) { $value = true; } } if ($option->isArray()) { $this->options[$name][] = $value; } else { $this->options[$name] = $value; } }
[ "private", "function", "addLongOption", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "definition", "->", "hasOption", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\\", "sprintf", "(", "'The \"--%s\" option does not exist.'", ",", "$", "name", ")", ")", ";", "}", "$", "option", "=", "$", "this", "->", "definition", "->", "getOption", "(", "$", "name", ")", ";", "if", "(", "null", "!==", "$", "value", "&&", "!", "$", "option", "->", "acceptValue", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\\", "sprintf", "(", "'The \"--%s\" option does not accept a value.'", ",", "$", "name", ")", ")", ";", "}", "if", "(", "\\", "in_array", "(", "$", "value", ",", "[", "''", ",", "null", "]", ",", "true", ")", "&&", "$", "option", "->", "acceptValue", "(", ")", "&&", "\\", "count", "(", "$", "this", "->", "parsed", ")", ")", "{", "// if option accepts an optional or mandatory argument", "// let's see if there is one provided", "$", "next", "=", "\\", "array_shift", "(", "$", "this", "->", "parsed", ")", ";", "$", "nextToken", "=", "$", "next", "[", "0", "]", ";", "if", "(", "(", "isset", "(", "$", "nextToken", "[", "0", "]", ")", "&&", "'-'", "!==", "$", "nextToken", "[", "0", "]", ")", "||", "\\", "in_array", "(", "$", "nextToken", ",", "[", "''", ",", "null", "]", ",", "true", ")", ")", "{", "$", "value", "=", "$", "nextToken", ";", "}", "else", "{", "\\", "array_unshift", "(", "$", "this", "->", "parsed", ",", "$", "next", ")", ";", "}", "}", "if", "(", "null", "===", "$", "value", ")", "{", "if", "(", "$", "option", "->", "isValueRequired", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\\", "sprintf", "(", "'The \"--%s\" option requires a value.'", ",", "$", "name", ")", ")", ";", "}", "if", "(", "!", "$", "option", "->", "isArray", "(", ")", "&&", "!", "$", "option", "->", "isValueOptional", "(", ")", ")", "{", "$", "value", "=", "true", ";", "}", "}", "if", "(", "$", "option", "->", "isArray", "(", ")", ")", "{", "$", "this", "->", "options", "[", "$", "name", "]", "[", "]", "=", "$", "value", ";", "}", "else", "{", "$", "this", "->", "options", "[", "$", "name", "]", "=", "$", "value", ";", "}", "}" ]
Adds a long option value. @param string $name The long option key @param mixed $value The value for the option @throws \RuntimeException When option given doesn't exist
[ "Adds", "a", "long", "option", "value", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/ShellInput.php#L294-L333
bobthecow/psysh
src/CodeCleaner/RequirePass.php
RequirePass.enterNode
public function enterNode(Node $origNode) { if (!$this->isRequireNode($origNode)) { return; } $node = clone $origNode; /* * rewrite * * $foo = require $bar * * to * * $foo = require \Psy\CodeCleaner\RequirePass::resolve($bar) */ $node->expr = new StaticCall( new FullyQualifiedName('Psy\CodeCleaner\RequirePass'), 'resolve', [new Arg($origNode->expr), new Arg(new LNumber($origNode->getLine()))], $origNode->getAttributes() ); return $node; }
php
public function enterNode(Node $origNode) { if (!$this->isRequireNode($origNode)) { return; } $node = clone $origNode; $node->expr = new StaticCall( new FullyQualifiedName('Psy\CodeCleaner\RequirePass'), 'resolve', [new Arg($origNode->expr), new Arg(new LNumber($origNode->getLine()))], $origNode->getAttributes() ); return $node; }
[ "public", "function", "enterNode", "(", "Node", "$", "origNode", ")", "{", "if", "(", "!", "$", "this", "->", "isRequireNode", "(", "$", "origNode", ")", ")", "{", "return", ";", "}", "$", "node", "=", "clone", "$", "origNode", ";", "/*\n * rewrite\n *\n * $foo = require $bar\n *\n * to\n *\n * $foo = require \\Psy\\CodeCleaner\\RequirePass::resolve($bar)\n */", "$", "node", "->", "expr", "=", "new", "StaticCall", "(", "new", "FullyQualifiedName", "(", "'Psy\\CodeCleaner\\RequirePass'", ")", ",", "'resolve'", ",", "[", "new", "Arg", "(", "$", "origNode", "->", "expr", ")", ",", "new", "Arg", "(", "new", "LNumber", "(", "$", "origNode", "->", "getLine", "(", ")", ")", ")", "]", ",", "$", "origNode", "->", "getAttributes", "(", ")", ")", ";", "return", "$", "node", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/RequirePass.php#L34-L59
bobthecow/psysh
src/CodeCleaner/RequirePass.php
RequirePass.resolve
public static function resolve($file, $lineNumber = null) { $file = (string) $file; if ($file === '') { // @todo Shell::handleError would be better here, because we could // fake the file and line number, but we can't call it statically. // So we're duplicating some of the logics here. if (E_WARNING & \error_reporting()) { ErrorException::throwException(E_WARNING, 'Filename cannot be empty', null, $lineNumber); } // @todo trigger an error as fallback? this is pretty ugly… // trigger_error('Filename cannot be empty', E_USER_WARNING); } if ($file === '' || !\stream_resolve_include_path($file)) { $msg = \sprintf("Failed opening required '%s'", $file); throw new FatalErrorException($msg, 0, E_ERROR, null, $lineNumber); } return $file; }
php
public static function resolve($file, $lineNumber = null) { $file = (string) $file; if ($file === '') { if (E_WARNING & \error_reporting()) { ErrorException::throwException(E_WARNING, 'Filename cannot be empty', null, $lineNumber); } } if ($file === '' || !\stream_resolve_include_path($file)) { $msg = \sprintf("Failed opening required '%s'", $file); throw new FatalErrorException($msg, 0, E_ERROR, null, $lineNumber); } return $file; }
[ "public", "static", "function", "resolve", "(", "$", "file", ",", "$", "lineNumber", "=", "null", ")", "{", "$", "file", "=", "(", "string", ")", "$", "file", ";", "if", "(", "$", "file", "===", "''", ")", "{", "// @todo Shell::handleError would be better here, because we could", "// fake the file and line number, but we can't call it statically.", "// So we're duplicating some of the logics here.", "if", "(", "E_WARNING", "&", "\\", "error_reporting", "(", ")", ")", "{", "ErrorException", "::", "throwException", "(", "E_WARNING", ",", "'Filename cannot be empty'", ",", "null", ",", "$", "lineNumber", ")", ";", "}", "// @todo trigger an error as fallback? this is pretty ugly…", "// trigger_error('Filename cannot be empty', E_USER_WARNING);", "}", "if", "(", "$", "file", "===", "''", "||", "!", "\\", "stream_resolve_include_path", "(", "$", "file", ")", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "\"Failed opening required '%s'\"", ",", "$", "file", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "lineNumber", ")", ";", "}", "return", "$", "file", ";", "}" ]
Runtime validation that $file can be resolved as an include path. If $file can be resolved, return $file. Otherwise throw a fatal error exception. @throws FatalErrorException when unable to resolve include path for $file @throws ErrorException if $file is empty and E_WARNING is included in error_reporting level @param string $file @param int $lineNumber Line number of the original require expression @return string Exactly the same as $file
[ "Runtime", "validation", "that", "$file", "can", "be", "resolved", "as", "an", "include", "path", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/RequirePass.php#L74-L95
bobthecow/psysh
src/Command/DumpCommand.php
DumpCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $depth = $input->getOption('depth'); $target = $this->resolveCode($input->getArgument('target')); $output->page($this->presenter->present($target, $depth, $input->getOption('all') ? Presenter::VERBOSE : 0)); if (\is_object($target)) { $this->setCommandScopeVariables(new \ReflectionObject($target)); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $depth = $input->getOption('depth'); $target = $this->resolveCode($input->getArgument('target')); $output->page($this->presenter->present($target, $depth, $input->getOption('all') ? Presenter::VERBOSE : 0)); if (\is_object($target)) { $this->setCommandScopeVariables(new \ReflectionObject($target)); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "depth", "=", "$", "input", "->", "getOption", "(", "'depth'", ")", ";", "$", "target", "=", "$", "this", "->", "resolveCode", "(", "$", "input", "->", "getArgument", "(", "'target'", ")", ")", ";", "$", "output", "->", "page", "(", "$", "this", "->", "presenter", "->", "present", "(", "$", "target", ",", "$", "depth", ",", "$", "input", "->", "getOption", "(", "'all'", ")", "?", "Presenter", "::", "VERBOSE", ":", "0", ")", ")", ";", "if", "(", "\\", "is_object", "(", "$", "target", ")", ")", "{", "$", "this", "->", "setCommandScopeVariables", "(", "new", "\\", "ReflectionObject", "(", "$", "target", ")", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/DumpCommand.php#L70-L79
bobthecow/psysh
src/CodeCleaner/InstanceOfPass.php
InstanceOfPass.enterNode
public function enterNode(Node $node) { if (!$node instanceof Instanceof_) { return; } if (($node->expr instanceof Scalar && !$node->expr instanceof Encapsed) || $node->expr instanceof ConstFetch) { throw new FatalErrorException(self::EXCEPTION_MSG, 0, E_ERROR, null, $node->getLine()); } }
php
public function enterNode(Node $node) { if (!$node instanceof Instanceof_) { return; } if (($node->expr instanceof Scalar && !$node->expr instanceof Encapsed) || $node->expr instanceof ConstFetch) { throw new FatalErrorException(self::EXCEPTION_MSG, 0, E_ERROR, null, $node->getLine()); } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "if", "(", "!", "$", "node", "instanceof", "Instanceof_", ")", "{", "return", ";", "}", "if", "(", "(", "$", "node", "->", "expr", "instanceof", "Scalar", "&&", "!", "$", "node", "->", "expr", "instanceof", "Encapsed", ")", "||", "$", "node", "->", "expr", "instanceof", "ConstFetch", ")", "{", "throw", "new", "FatalErrorException", "(", "self", "::", "EXCEPTION_MSG", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}" ]
Validate that the instanceof statement does not receive a scalar value or a non-class constant. @throws FatalErrorException if a scalar or a non-class constant is given @param Node $node
[ "Validate", "that", "the", "instanceof", "statement", "does", "not", "receive", "a", "scalar", "value", "or", "a", "non", "-", "class", "constant", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/InstanceOfPass.php#L37-L46
bobthecow/psysh
src/Command/TimeitCommand.php
TimeitCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $code = $input->getArgument('code'); $num = $input->getOption('num') ?: 1; $shell = $this->getApplication(); $instrumentedCode = $this->instrumentCode($code); self::$times = []; for ($i = 0; $i < $num; $i++) { $_ = $shell->execute($instrumentedCode); $this->ensureEndMarked(); } $shell->writeReturnValue($_); $times = self::$times; self::$times = []; if ($num === 1) { $output->writeln(\sprintf(self::RESULT_MSG, $times[0])); } else { $total = \array_sum($times); \rsort($times); $median = $times[\round($num / 2)]; $output->writeln(\sprintf(self::AVG_RESULT_MSG, $total / $num, $median, $total)); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $code = $input->getArgument('code'); $num = $input->getOption('num') ?: 1; $shell = $this->getApplication(); $instrumentedCode = $this->instrumentCode($code); self::$times = []; for ($i = 0; $i < $num; $i++) { $_ = $shell->execute($instrumentedCode); $this->ensureEndMarked(); } $shell->writeReturnValue($_); $times = self::$times; self::$times = []; if ($num === 1) { $output->writeln(\sprintf(self::RESULT_MSG, $times[0])); } else { $total = \array_sum($times); \rsort($times); $median = $times[\round($num / 2)]; $output->writeln(\sprintf(self::AVG_RESULT_MSG, $total / $num, $median, $total)); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "code", "=", "$", "input", "->", "getArgument", "(", "'code'", ")", ";", "$", "num", "=", "$", "input", "->", "getOption", "(", "'num'", ")", "?", ":", "1", ";", "$", "shell", "=", "$", "this", "->", "getApplication", "(", ")", ";", "$", "instrumentedCode", "=", "$", "this", "->", "instrumentCode", "(", "$", "code", ")", ";", "self", "::", "$", "times", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "num", ";", "$", "i", "++", ")", "{", "$", "_", "=", "$", "shell", "->", "execute", "(", "$", "instrumentedCode", ")", ";", "$", "this", "->", "ensureEndMarked", "(", ")", ";", "}", "$", "shell", "->", "writeReturnValue", "(", "$", "_", ")", ";", "$", "times", "=", "self", "::", "$", "times", ";", "self", "::", "$", "times", "=", "[", "]", ";", "if", "(", "$", "num", "===", "1", ")", "{", "$", "output", "->", "writeln", "(", "\\", "sprintf", "(", "self", "::", "RESULT_MSG", ",", "$", "times", "[", "0", "]", ")", ")", ";", "}", "else", "{", "$", "total", "=", "\\", "array_sum", "(", "$", "times", ")", ";", "\\", "rsort", "(", "$", "times", ")", ";", "$", "median", "=", "$", "times", "[", "\\", "round", "(", "$", "num", "/", "2", ")", "]", ";", "$", "output", "->", "writeln", "(", "\\", "sprintf", "(", "self", "::", "AVG_RESULT_MSG", ",", "$", "total", "/", "$", "num", ",", "$", "median", ",", "$", "total", ")", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand.php#L80-L109
bobthecow/psysh
src/Command/TimeitCommand.php
TimeitCommand.markEnd
public static function markEnd($ret = null) { self::$times[] = \microtime(true) - self::$start; self::$start = null; return $ret; }
php
public static function markEnd($ret = null) { self::$times[] = \microtime(true) - self::$start; self::$start = null; return $ret; }
[ "public", "static", "function", "markEnd", "(", "$", "ret", "=", "null", ")", "{", "self", "::", "$", "times", "[", "]", "=", "\\", "microtime", "(", "true", ")", "-", "self", "::", "$", "start", ";", "self", "::", "$", "start", "=", "null", ";", "return", "$", "ret", ";", "}" ]
Internal method for marking the end of timeit execution. A static call to this method is injected by TimeitVisitor at the end of the timeit input code to instrument the call. Note that this accepts an optional $ret parameter, which is used to pass the return value of the last statement back out of timeit. This saves us a bunch of code rewriting shenanigans. @param mixed $ret @return mixed it just passes $ret right back
[ "Internal", "method", "for", "marking", "the", "end", "of", "timeit", "execution", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand.php#L137-L143
bobthecow/psysh
src/Command/TimeitCommand.php
TimeitCommand.instrumentCode
private function instrumentCode($code) { return $this->printer->prettyPrint($this->traverser->traverse($this->parse($code))); }
php
private function instrumentCode($code) { return $this->printer->prettyPrint($this->traverser->traverse($this->parse($code))); }
[ "private", "function", "instrumentCode", "(", "$", "code", ")", "{", "return", "$", "this", "->", "printer", "->", "prettyPrint", "(", "$", "this", "->", "traverser", "->", "traverse", "(", "$", "this", "->", "parse", "(", "$", "code", ")", ")", ")", ";", "}" ]
Instrument code for timeit execution. This inserts `markStart` and `markEnd` calls to ensure that (reasonably) accurate times are recorded for just the code being executed. @param string $code @return string
[ "Instrument", "code", "for", "timeit", "execution", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand.php#L168-L171
bobthecow/psysh
src/TabCompletion/Matcher/AbstractMatcher.php
AbstractMatcher.getInput
protected function getInput(array $tokens) { $var = ''; $firstToken = \array_pop($tokens); if (self::tokenIs($firstToken, self::T_STRING)) { $var = $firstToken[1]; } return $var; }
php
protected function getInput(array $tokens) { $var = ''; $firstToken = \array_pop($tokens); if (self::tokenIs($firstToken, self::T_STRING)) { $var = $firstToken[1]; } return $var; }
[ "protected", "function", "getInput", "(", "array", "$", "tokens", ")", "{", "$", "var", "=", "''", ";", "$", "firstToken", "=", "\\", "array_pop", "(", "$", "tokens", ")", ";", "if", "(", "self", "::", "tokenIs", "(", "$", "firstToken", ",", "self", "::", "T_STRING", ")", ")", "{", "$", "var", "=", "$", "firstToken", "[", "1", "]", ";", "}", "return", "$", "var", ";", "}" ]
Get current readline input word. @param array $tokens Tokenized readline input (see token_get_all) @return string
[ "Get", "current", "readline", "input", "word", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L64-L73
bobthecow/psysh
src/TabCompletion/Matcher/AbstractMatcher.php
AbstractMatcher.getNamespaceAndClass
protected function getNamespaceAndClass($tokens) { $class = ''; while (self::hasToken( [self::T_NS_SEPARATOR, self::T_STRING], $token = \array_pop($tokens) )) { if (self::needCompleteClass($token)) { continue; } $class = $token[1] . $class; } return $class; }
php
protected function getNamespaceAndClass($tokens) { $class = ''; while (self::hasToken( [self::T_NS_SEPARATOR, self::T_STRING], $token = \array_pop($tokens) )) { if (self::needCompleteClass($token)) { continue; } $class = $token[1] . $class; } return $class; }
[ "protected", "function", "getNamespaceAndClass", "(", "$", "tokens", ")", "{", "$", "class", "=", "''", ";", "while", "(", "self", "::", "hasToken", "(", "[", "self", "::", "T_NS_SEPARATOR", ",", "self", "::", "T_STRING", "]", ",", "$", "token", "=", "\\", "array_pop", "(", "$", "tokens", ")", ")", ")", "{", "if", "(", "self", "::", "needCompleteClass", "(", "$", "token", ")", ")", "{", "continue", ";", "}", "$", "class", "=", "$", "token", "[", "1", "]", ".", "$", "class", ";", "}", "return", "$", "class", ";", "}" ]
Get current namespace and class (if any) from readline input. @param array $tokens Tokenized readline input (see token_get_all) @return string
[ "Get", "current", "namespace", "and", "class", "(", "if", "any", ")", "from", "readline", "input", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L82-L97
bobthecow/psysh
src/TabCompletion/Matcher/AbstractMatcher.php
AbstractMatcher.hasSyntax
public static function hasSyntax($token, $syntax = self::VAR_SYNTAX) { if (!\is_array($token)) { return false; } $regexp = \sprintf('#%s#', $syntax); return (bool) \preg_match($regexp, $token[1]); }
php
public static function hasSyntax($token, $syntax = self::VAR_SYNTAX) { if (!\is_array($token)) { return false; } $regexp = \sprintf(' return (bool) \preg_match($regexp, $token[1]); }
[ "public", "static", "function", "hasSyntax", "(", "$", "token", ",", "$", "syntax", "=", "self", "::", "VAR_SYNTAX", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "$", "regexp", "=", "\\", "sprintf", "(", "'#%s#'", ",", "$", "syntax", ")", ";", "return", "(", "bool", ")", "\\", "preg_match", "(", "$", "regexp", ",", "$", "token", "[", "1", "]", ")", ";", "}" ]
Check whether $token matches a given syntax pattern. @param mixed $token A PHP token (see token_get_all) @param string $syntax A syntax pattern (default: variable pattern) @return bool
[ "Check", "whether", "$token", "matches", "a", "given", "syntax", "pattern", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L130-L139
bobthecow/psysh
src/TabCompletion/Matcher/AbstractMatcher.php
AbstractMatcher.isOperator
public static function isOperator($token) { if (!\is_string($token)) { return false; } return \strpos(self::MISC_OPERATORS, $token) !== false; }
php
public static function isOperator($token) { if (!\is_string($token)) { return false; } return \strpos(self::MISC_OPERATORS, $token) !== false; }
[ "public", "static", "function", "isOperator", "(", "$", "token", ")", "{", "if", "(", "!", "\\", "is_string", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "return", "\\", "strpos", "(", "self", "::", "MISC_OPERATORS", ",", "$", "token", ")", "!==", "false", ";", "}" ]
Check whether $token is an operator. @param mixed $token A PHP token (see token_get_all) @return bool
[ "Check", "whether", "$token", "is", "an", "operator", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L165-L172
bobthecow/psysh
src/TabCompletion/Matcher/AbstractMatcher.php
AbstractMatcher.hasToken
public static function hasToken(array $coll, $token) { if (!\is_array($token)) { return false; } return \in_array(\token_name($token[0]), $coll); }
php
public static function hasToken(array $coll, $token) { if (!\is_array($token)) { return false; } return \in_array(\token_name($token[0]), $coll); }
[ "public", "static", "function", "hasToken", "(", "array", "$", "coll", ",", "$", "token", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "return", "\\", "in_array", "(", "\\", "token_name", "(", "$", "token", "[", "0", "]", ")", ",", "$", "coll", ")", ";", "}" ]
Check whether $token type is present in $coll. @param array $coll A list of token types @param mixed $token A PHP token (see token_get_all) @return bool
[ "Check", "whether", "$token", "type", "is", "present", "in", "$coll", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L187-L194
bobthecow/psysh
src/Reflection/ReflectionLanguageConstruct.php
ReflectionLanguageConstruct.getParameters
public function getParameters() { $params = []; foreach (self::$languageConstructs[$this->keyword] as $parameter => $opts) { \array_push($params, new ReflectionLanguageConstructParameter($this->keyword, $parameter, $opts)); } return $params; }
php
public function getParameters() { $params = []; foreach (self::$languageConstructs[$this->keyword] as $parameter => $opts) { \array_push($params, new ReflectionLanguageConstructParameter($this->keyword, $parameter, $opts)); } return $params; }
[ "public", "function", "getParameters", "(", ")", "{", "$", "params", "=", "[", "]", ";", "foreach", "(", "self", "::", "$", "languageConstructs", "[", "$", "this", "->", "keyword", "]", "as", "$", "parameter", "=>", "$", "opts", ")", "{", "\\", "array_push", "(", "$", "params", ",", "new", "ReflectionLanguageConstructParameter", "(", "$", "this", "->", "keyword", ",", "$", "parameter", ",", "$", "opts", ")", ")", ";", "}", "return", "$", "params", ";", "}" ]
Get language construct params. @return array
[ "Get", "language", "construct", "params", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Reflection/ReflectionLanguageConstruct.php#L121-L129
bobthecow/psysh
src/VarDumper/Presenter.php
Presenter.present
public function present($value, $depth = null, $options = 0) { $data = $this->cloner->cloneVar($value, !($options & self::VERBOSE) ? Caster::EXCLUDE_VERBOSE : 0); if (null !== $depth) { $data = $data->withMaxDepth($depth); } // Work around https://github.com/symfony/symfony/issues/23572 $oldLocale = \setlocale(LC_NUMERIC, 0); \setlocale(LC_NUMERIC, 'C'); $output = ''; $this->dumper->dump($data, function ($line, $depth) use (&$output) { if ($depth >= 0) { if ('' !== $output) { $output .= PHP_EOL; } $output .= \str_repeat(' ', $depth) . $line; } }); // Now put the locale back \setlocale(LC_NUMERIC, $oldLocale); return OutputFormatter::escape($output); }
php
public function present($value, $depth = null, $options = 0) { $data = $this->cloner->cloneVar($value, !($options & self::VERBOSE) ? Caster::EXCLUDE_VERBOSE : 0); if (null !== $depth) { $data = $data->withMaxDepth($depth); } $oldLocale = \setlocale(LC_NUMERIC, 0); \setlocale(LC_NUMERIC, 'C'); $output = ''; $this->dumper->dump($data, function ($line, $depth) use (&$output) { if ($depth >= 0) { if ('' !== $output) { $output .= PHP_EOL; } $output .= \str_repeat(' ', $depth) . $line; } }); \setlocale(LC_NUMERIC, $oldLocale); return OutputFormatter::escape($output); }
[ "public", "function", "present", "(", "$", "value", ",", "$", "depth", "=", "null", ",", "$", "options", "=", "0", ")", "{", "$", "data", "=", "$", "this", "->", "cloner", "->", "cloneVar", "(", "$", "value", ",", "!", "(", "$", "options", "&", "self", "::", "VERBOSE", ")", "?", "Caster", "::", "EXCLUDE_VERBOSE", ":", "0", ")", ";", "if", "(", "null", "!==", "$", "depth", ")", "{", "$", "data", "=", "$", "data", "->", "withMaxDepth", "(", "$", "depth", ")", ";", "}", "// Work around https://github.com/symfony/symfony/issues/23572", "$", "oldLocale", "=", "\\", "setlocale", "(", "LC_NUMERIC", ",", "0", ")", ";", "\\", "setlocale", "(", "LC_NUMERIC", ",", "'C'", ")", ";", "$", "output", "=", "''", ";", "$", "this", "->", "dumper", "->", "dump", "(", "$", "data", ",", "function", "(", "$", "line", ",", "$", "depth", ")", "use", "(", "&", "$", "output", ")", "{", "if", "(", "$", "depth", ">=", "0", ")", "{", "if", "(", "''", "!==", "$", "output", ")", "{", "$", "output", ".=", "PHP_EOL", ";", "}", "$", "output", ".=", "\\", "str_repeat", "(", "' '", ",", "$", "depth", ")", ".", "$", "line", ";", "}", "}", ")", ";", "// Now put the locale back", "\\", "setlocale", "(", "LC_NUMERIC", ",", "$", "oldLocale", ")", ";", "return", "OutputFormatter", "::", "escape", "(", "$", "output", ")", ";", "}" ]
Present a full representation of the value. If $depth is 0, the value will be presented as a ref instead. @param mixed $value @param int $depth (default: null) @param int $options One of Presenter constants @return string
[ "Present", "a", "full", "representation", "of", "the", "value", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/VarDumper/Presenter.php#L110-L136
bobthecow/psysh
src/Command/ListCommand/ClassEnumerator.php
ClassEnumerator.listItems
protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null) { // only list classes when no Reflector is present. // // @todo make a NamespaceReflector and pass that in for commands like: // // ls --classes Foo // // ... for listing classes in the Foo namespace if ($reflector !== null || $target !== null) { return; } $user = $input->getOption('user'); $internal = $input->getOption('internal'); $ret = []; // only list classes, interfaces and traits if we are specifically asked if ($input->getOption('classes')) { $ret = \array_merge($ret, $this->filterClasses('Classes', \get_declared_classes(), $internal, $user)); } if ($input->getOption('interfaces')) { $ret = \array_merge($ret, $this->filterClasses('Interfaces', \get_declared_interfaces(), $internal, $user)); } if ($input->getOption('traits')) { $ret = \array_merge($ret, $this->filterClasses('Traits', \get_declared_traits(), $internal, $user)); } return \array_map([$this, 'prepareClasses'], \array_filter($ret)); }
php
protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null) { if ($reflector !== null || $target !== null) { return; } $user = $input->getOption('user'); $internal = $input->getOption('internal'); $ret = []; if ($input->getOption('classes')) { $ret = \array_merge($ret, $this->filterClasses('Classes', \get_declared_classes(), $internal, $user)); } if ($input->getOption('interfaces')) { $ret = \array_merge($ret, $this->filterClasses('Interfaces', \get_declared_interfaces(), $internal, $user)); } if ($input->getOption('traits')) { $ret = \array_merge($ret, $this->filterClasses('Traits', \get_declared_traits(), $internal, $user)); } return \array_map([$this, 'prepareClasses'], \array_filter($ret)); }
[ "protected", "function", "listItems", "(", "InputInterface", "$", "input", ",", "\\", "Reflector", "$", "reflector", "=", "null", ",", "$", "target", "=", "null", ")", "{", "// only list classes when no Reflector is present.", "//", "// @todo make a NamespaceReflector and pass that in for commands like:", "//", "// ls --classes Foo", "//", "// ... for listing classes in the Foo namespace", "if", "(", "$", "reflector", "!==", "null", "||", "$", "target", "!==", "null", ")", "{", "return", ";", "}", "$", "user", "=", "$", "input", "->", "getOption", "(", "'user'", ")", ";", "$", "internal", "=", "$", "input", "->", "getOption", "(", "'internal'", ")", ";", "$", "ret", "=", "[", "]", ";", "// only list classes, interfaces and traits if we are specifically asked", "if", "(", "$", "input", "->", "getOption", "(", "'classes'", ")", ")", "{", "$", "ret", "=", "\\", "array_merge", "(", "$", "ret", ",", "$", "this", "->", "filterClasses", "(", "'Classes'", ",", "\\", "get_declared_classes", "(", ")", ",", "$", "internal", ",", "$", "user", ")", ")", ";", "}", "if", "(", "$", "input", "->", "getOption", "(", "'interfaces'", ")", ")", "{", "$", "ret", "=", "\\", "array_merge", "(", "$", "ret", ",", "$", "this", "->", "filterClasses", "(", "'Interfaces'", ",", "\\", "get_declared_interfaces", "(", ")", ",", "$", "internal", ",", "$", "user", ")", ")", ";", "}", "if", "(", "$", "input", "->", "getOption", "(", "'traits'", ")", ")", "{", "$", "ret", "=", "\\", "array_merge", "(", "$", "ret", ",", "$", "this", "->", "filterClasses", "(", "'Traits'", ",", "\\", "get_declared_traits", "(", ")", ",", "$", "internal", ",", "$", "user", ")", ")", ";", "}", "return", "\\", "array_map", "(", "[", "$", "this", ",", "'prepareClasses'", "]", ",", "\\", "array_filter", "(", "$", "ret", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/ClassEnumerator.php#L24-L58
bobthecow/psysh
src/Command/ListCommand/ClassEnumerator.php
ClassEnumerator.filterClasses
protected function filterClasses($key, $classes, $internal, $user) { $ret = []; if ($internal) { $ret['Internal ' . $key] = \array_filter($classes, function ($class) { $refl = new \ReflectionClass($class); return $refl->isInternal(); }); } if ($user) { $ret['User ' . $key] = \array_filter($classes, function ($class) { $refl = new \ReflectionClass($class); return !$refl->isInternal(); }); } if (!$user && !$internal) { $ret[$key] = $classes; } return $ret; }
php
protected function filterClasses($key, $classes, $internal, $user) { $ret = []; if ($internal) { $ret['Internal ' . $key] = \array_filter($classes, function ($class) { $refl = new \ReflectionClass($class); return $refl->isInternal(); }); } if ($user) { $ret['User ' . $key] = \array_filter($classes, function ($class) { $refl = new \ReflectionClass($class); return !$refl->isInternal(); }); } if (!$user && !$internal) { $ret[$key] = $classes; } return $ret; }
[ "protected", "function", "filterClasses", "(", "$", "key", ",", "$", "classes", ",", "$", "internal", ",", "$", "user", ")", "{", "$", "ret", "=", "[", "]", ";", "if", "(", "$", "internal", ")", "{", "$", "ret", "[", "'Internal '", ".", "$", "key", "]", "=", "\\", "array_filter", "(", "$", "classes", ",", "function", "(", "$", "class", ")", "{", "$", "refl", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "return", "$", "refl", "->", "isInternal", "(", ")", ";", "}", ")", ";", "}", "if", "(", "$", "user", ")", "{", "$", "ret", "[", "'User '", ".", "$", "key", "]", "=", "\\", "array_filter", "(", "$", "classes", ",", "function", "(", "$", "class", ")", "{", "$", "refl", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "return", "!", "$", "refl", "->", "isInternal", "(", ")", ";", "}", ")", ";", "}", "if", "(", "!", "$", "user", "&&", "!", "$", "internal", ")", "{", "$", "ret", "[", "$", "key", "]", "=", "$", "classes", ";", "}", "return", "$", "ret", ";", "}" ]
Filter a list of classes, interfaces or traits. If $internal or $user is defined, results will be limited to internal or user-defined classes as appropriate. @param string $key @param array $classes @param bool $internal @param bool $user @return array
[ "Filter", "a", "list", "of", "classes", "interfaces", "or", "traits", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/ClassEnumerator.php#L73-L98
bobthecow/psysh
src/Command/ListCommand/ClassEnumerator.php
ClassEnumerator.prepareClasses
protected function prepareClasses(array $classes) { \natcasesort($classes); // My kingdom for a generator. $ret = []; foreach ($classes as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
php
protected function prepareClasses(array $classes) { \natcasesort($classes); $ret = []; foreach ($classes as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
[ "protected", "function", "prepareClasses", "(", "array", "$", "classes", ")", "{", "\\", "natcasesort", "(", "$", "classes", ")", ";", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "classes", "as", "$", "name", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "ret", "[", "$", "name", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'style'", "=>", "self", "::", "IS_CLASS", ",", "'value'", "=>", "$", "this", "->", "presentSignature", "(", "$", "name", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted class array. @param array $classes @return array
[ "Prepare", "formatted", "class", "array", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/ClassEnumerator.php#L107-L125
bobthecow/psysh
src/TabCompletion/AutoCompleter.php
AutoCompleter.processCallback
public function processCallback($input, $index, $info = []) { // Some (Windows?) systems provide incomplete `readline_info`, so let's // try to work around it. $line = $info['line_buffer']; if (isset($info['end'])) { $line = \substr($line, 0, $info['end']); } if ($line === '' && $input !== '') { $line = $input; } $tokens = \token_get_all('<?php ' . $line); // remove whitespaces $tokens = \array_filter($tokens, function ($token) { return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE); }); $matches = []; foreach ($this->matchers as $matcher) { if ($matcher->hasMatched($tokens)) { $matches = \array_merge($matcher->getMatches($tokens), $matches); } } $matches = \array_unique($matches); return !empty($matches) ? $matches : ['']; }
php
public function processCallback($input, $index, $info = []) { $line = $info['line_buffer']; if (isset($info['end'])) { $line = \substr($line, 0, $info['end']); } if ($line === '' && $input !== '') { $line = $input; } $tokens = \token_get_all('<?php ' . $line); $tokens = \array_filter($tokens, function ($token) { return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE); }); $matches = []; foreach ($this->matchers as $matcher) { if ($matcher->hasMatched($tokens)) { $matches = \array_merge($matcher->getMatches($tokens), $matches); } } $matches = \array_unique($matches); return !empty($matches) ? $matches : ['']; }
[ "public", "function", "processCallback", "(", "$", "input", ",", "$", "index", ",", "$", "info", "=", "[", "]", ")", "{", "// Some (Windows?) systems provide incomplete `readline_info`, so let's", "// try to work around it.", "$", "line", "=", "$", "info", "[", "'line_buffer'", "]", ";", "if", "(", "isset", "(", "$", "info", "[", "'end'", "]", ")", ")", "{", "$", "line", "=", "\\", "substr", "(", "$", "line", ",", "0", ",", "$", "info", "[", "'end'", "]", ")", ";", "}", "if", "(", "$", "line", "===", "''", "&&", "$", "input", "!==", "''", ")", "{", "$", "line", "=", "$", "input", ";", "}", "$", "tokens", "=", "\\", "token_get_all", "(", "'<?php '", ".", "$", "line", ")", ";", "// remove whitespaces", "$", "tokens", "=", "\\", "array_filter", "(", "$", "tokens", ",", "function", "(", "$", "token", ")", "{", "return", "!", "AbstractMatcher", "::", "tokenIs", "(", "$", "token", ",", "AbstractMatcher", "::", "T_WHITESPACE", ")", ";", "}", ")", ";", "$", "matches", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "matchers", "as", "$", "matcher", ")", "{", "if", "(", "$", "matcher", "->", "hasMatched", "(", "$", "tokens", ")", ")", "{", "$", "matches", "=", "\\", "array_merge", "(", "$", "matcher", "->", "getMatches", "(", "$", "tokens", ")", ",", "$", "matches", ")", ";", "}", "}", "$", "matches", "=", "\\", "array_unique", "(", "$", "matches", ")", ";", "return", "!", "empty", "(", "$", "matches", ")", "?", "$", "matches", ":", "[", "''", "]", ";", "}" ]
Handle readline completion. @param string $input Readline current word @param int $index Current word index @param array $info readline_info() data @return array
[ "Handle", "readline", "completion", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/AutoCompleter.php#L53-L82
bobthecow/psysh
src/CodeCleaner/PassableByReferencePass.php
PassableByReferencePass.enterNode
public function enterNode(Node $node) { // @todo support MethodCall and StaticCall as well. if ($node instanceof FuncCall) { // if function name is an expression or a variable, give it a pass for now. if ($node->name instanceof Expr || $node->name instanceof Variable) { return; } $name = (string) $node->name; if ($name === 'array_multisort') { return $this->validateArrayMultisort($node); } try { $refl = new \ReflectionFunction($name); } catch (\ReflectionException $e) { // Well, we gave it a shot! return; } foreach ($refl->getParameters() as $key => $param) { if (\array_key_exists($key, $node->args)) { $arg = $node->args[$key]; if ($param->isPassedByReference() && !$this->isPassableByReference($arg)) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } } } }
php
public function enterNode(Node $node) { if ($node instanceof FuncCall) { if ($node->name instanceof Expr || $node->name instanceof Variable) { return; } $name = (string) $node->name; if ($name === 'array_multisort') { return $this->validateArrayMultisort($node); } try { $refl = new \ReflectionFunction($name); } catch (\ReflectionException $e) { return; } foreach ($refl->getParameters() as $key => $param) { if (\array_key_exists($key, $node->args)) { $arg = $node->args[$key]; if ($param->isPassedByReference() && !$this->isPassableByReference($arg)) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } } } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "// @todo support MethodCall and StaticCall as well.", "if", "(", "$", "node", "instanceof", "FuncCall", ")", "{", "// if function name is an expression or a variable, give it a pass for now.", "if", "(", "$", "node", "->", "name", "instanceof", "Expr", "||", "$", "node", "->", "name", "instanceof", "Variable", ")", "{", "return", ";", "}", "$", "name", "=", "(", "string", ")", "$", "node", "->", "name", ";", "if", "(", "$", "name", "===", "'array_multisort'", ")", "{", "return", "$", "this", "->", "validateArrayMultisort", "(", "$", "node", ")", ";", "}", "try", "{", "$", "refl", "=", "new", "\\", "ReflectionFunction", "(", "$", "name", ")", ";", "}", "catch", "(", "\\", "ReflectionException", "$", "e", ")", "{", "// Well, we gave it a shot!", "return", ";", "}", "foreach", "(", "$", "refl", "->", "getParameters", "(", ")", "as", "$", "key", "=>", "$", "param", ")", "{", "if", "(", "\\", "array_key_exists", "(", "$", "key", ",", "$", "node", "->", "args", ")", ")", "{", "$", "arg", "=", "$", "node", "->", "args", "[", "$", "key", "]", ";", "if", "(", "$", "param", "->", "isPassedByReference", "(", ")", "&&", "!", "$", "this", "->", "isPassableByReference", "(", "$", "arg", ")", ")", "{", "throw", "new", "FatalErrorException", "(", "self", "::", "EXCEPTION_MESSAGE", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}", "}", "}" ]
@throws FatalErrorException if non-variables are passed by reference @param Node $node
[ "@throws", "FatalErrorException", "if", "non", "-", "variables", "are", "passed", "by", "reference" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/PassableByReferencePass.php#L36-L67
bobthecow/psysh
src/CodeCleaner/PassableByReferencePass.php
PassableByReferencePass.validateArrayMultisort
private function validateArrayMultisort(Node $node) { $nonPassable = 2; // start with 2 because the first one has to be passable by reference foreach ($node->args as $arg) { if ($this->isPassableByReference($arg)) { $nonPassable = 0; } elseif (++$nonPassable > 2) { // There can be *at most* two non-passable-by-reference args in a row. This is about // as close as we can get to validating the arguments for this function :-/ throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } }
php
private function validateArrayMultisort(Node $node) { $nonPassable = 2; foreach ($node->args as $arg) { if ($this->isPassableByReference($arg)) { $nonPassable = 0; } elseif (++$nonPassable > 2) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } }
[ "private", "function", "validateArrayMultisort", "(", "Node", "$", "node", ")", "{", "$", "nonPassable", "=", "2", ";", "// start with 2 because the first one has to be passable by reference", "foreach", "(", "$", "node", "->", "args", "as", "$", "arg", ")", "{", "if", "(", "$", "this", "->", "isPassableByReference", "(", "$", "arg", ")", ")", "{", "$", "nonPassable", "=", "0", ";", "}", "elseif", "(", "++", "$", "nonPassable", ">", "2", ")", "{", "// There can be *at most* two non-passable-by-reference args in a row. This is about", "// as close as we can get to validating the arguments for this function :-/", "throw", "new", "FatalErrorException", "(", "self", "::", "EXCEPTION_MESSAGE", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}" ]
Because array_multisort has a problematic signature... The argument order is all sorts of wonky, and whether something is passed by reference or not depends on the values of the two arguments before it. We'll do a good faith attempt at validating this, but err on the side of permissive. This is why you don't design languages where core code and extensions can implement APIs that wouldn't be possible in userland code. @throws FatalErrorException for clearly invalid arguments @param Node $node
[ "Because", "array_multisort", "has", "a", "problematic", "signature", "..." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/PassableByReferencePass.php#L96-L108
bobthecow/psysh
src/Output/ShellOutput.php
ShellOutput.page
public function page($messages, $type = 0) { if (\is_string($messages)) { $messages = (array) $messages; } if (!\is_array($messages) && !\is_callable($messages)) { throw new \InvalidArgumentException('Paged output requires a string, array or callback'); } $this->startPaging(); if (\is_callable($messages)) { $messages($this); } else { $this->write($messages, true, $type); } $this->stopPaging(); }
php
public function page($messages, $type = 0) { if (\is_string($messages)) { $messages = (array) $messages; } if (!\is_array($messages) && !\is_callable($messages)) { throw new \InvalidArgumentException('Paged output requires a string, array or callback'); } $this->startPaging(); if (\is_callable($messages)) { $messages($this); } else { $this->write($messages, true, $type); } $this->stopPaging(); }
[ "public", "function", "page", "(", "$", "messages", ",", "$", "type", "=", "0", ")", "{", "if", "(", "\\", "is_string", "(", "$", "messages", ")", ")", "{", "$", "messages", "=", "(", "array", ")", "$", "messages", ";", "}", "if", "(", "!", "\\", "is_array", "(", "$", "messages", ")", "&&", "!", "\\", "is_callable", "(", "$", "messages", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Paged output requires a string, array or callback'", ")", ";", "}", "$", "this", "->", "startPaging", "(", ")", ";", "if", "(", "\\", "is_callable", "(", "$", "messages", ")", ")", "{", "$", "messages", "(", "$", "this", ")", ";", "}", "else", "{", "$", "this", "->", "write", "(", "$", "messages", ",", "true", ",", "$", "type", ")", ";", "}", "$", "this", "->", "stopPaging", "(", ")", ";", "}" ]
Page multiple lines of output. The output pager is started If $messages is callable, it will be called, passing this output instance for rendering. Otherwise, all passed $messages are paged to output. Upon completion, the output pager is flushed. @param string|array|\Closure $messages A string, array of strings or a callback @param int $type (default: 0)
[ "Page", "multiple", "lines", "of", "output", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L66-L85
bobthecow/psysh
src/Output/ShellOutput.php
ShellOutput.write
public function write($messages, $newline = false, $type = 0) { if ($this->getVerbosity() === self::VERBOSITY_QUIET) { return; } $messages = (array) $messages; if ($type & self::NUMBER_LINES) { $pad = \strlen((string) \count($messages)); $template = $this->isDecorated() ? "<aside>%{$pad}s</aside>: %s" : "%{$pad}s: %s"; if ($type & self::OUTPUT_RAW) { $messages = \array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $messages); } foreach ($messages as $i => $line) { $messages[$i] = \sprintf($template, $i, $line); } // clean this up for super. $type = $type & ~self::NUMBER_LINES & ~self::OUTPUT_RAW; } parent::write($messages, $newline, $type); }
php
public function write($messages, $newline = false, $type = 0) { if ($this->getVerbosity() === self::VERBOSITY_QUIET) { return; } $messages = (array) $messages; if ($type & self::NUMBER_LINES) { $pad = \strlen((string) \count($messages)); $template = $this->isDecorated() ? "<aside>%{$pad}s</aside>: %s" : "%{$pad}s: %s"; if ($type & self::OUTPUT_RAW) { $messages = \array_map(['Symfony\Component\Console\Formatter\OutputFormatter', 'escape'], $messages); } foreach ($messages as $i => $line) { $messages[$i] = \sprintf($template, $i, $line); } $type = $type & ~self::NUMBER_LINES & ~self::OUTPUT_RAW; } parent::write($messages, $newline, $type); }
[ "public", "function", "write", "(", "$", "messages", ",", "$", "newline", "=", "false", ",", "$", "type", "=", "0", ")", "{", "if", "(", "$", "this", "->", "getVerbosity", "(", ")", "===", "self", "::", "VERBOSITY_QUIET", ")", "{", "return", ";", "}", "$", "messages", "=", "(", "array", ")", "$", "messages", ";", "if", "(", "$", "type", "&", "self", "::", "NUMBER_LINES", ")", "{", "$", "pad", "=", "\\", "strlen", "(", "(", "string", ")", "\\", "count", "(", "$", "messages", ")", ")", ";", "$", "template", "=", "$", "this", "->", "isDecorated", "(", ")", "?", "\"<aside>%{$pad}s</aside>: %s\"", ":", "\"%{$pad}s: %s\"", ";", "if", "(", "$", "type", "&", "self", "::", "OUTPUT_RAW", ")", "{", "$", "messages", "=", "\\", "array_map", "(", "[", "'Symfony\\Component\\Console\\Formatter\\OutputFormatter'", ",", "'escape'", "]", ",", "$", "messages", ")", ";", "}", "foreach", "(", "$", "messages", "as", "$", "i", "=>", "$", "line", ")", "{", "$", "messages", "[", "$", "i", "]", "=", "\\", "sprintf", "(", "$", "template", ",", "$", "i", ",", "$", "line", ")", ";", "}", "// clean this up for super.", "$", "type", "=", "$", "type", "&", "~", "self", "::", "NUMBER_LINES", "&", "~", "self", "::", "OUTPUT_RAW", ";", "}", "parent", "::", "write", "(", "$", "messages", ",", "$", "newline", ",", "$", "type", ")", ";", "}" ]
Writes a message to the output. Optionally, pass `$type | self::NUMBER_LINES` as the $type parameter to number the lines of output. @throws \InvalidArgumentException When unknown output type is given @param string|array $messages The message as an array of lines or a single string @param bool $newline Whether to add a newline or not @param int $type The type of output
[ "Writes", "a", "message", "to", "the", "output", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L116-L141
bobthecow/psysh
src/Output/ShellOutput.php
ShellOutput.doWrite
public function doWrite($message, $newline) { if ($this->paging > 0) { $this->pager->doWrite($message, $newline); } else { parent::doWrite($message, $newline); } }
php
public function doWrite($message, $newline) { if ($this->paging > 0) { $this->pager->doWrite($message, $newline); } else { parent::doWrite($message, $newline); } }
[ "public", "function", "doWrite", "(", "$", "message", ",", "$", "newline", ")", "{", "if", "(", "$", "this", "->", "paging", ">", "0", ")", "{", "$", "this", "->", "pager", "->", "doWrite", "(", "$", "message", ",", "$", "newline", ")", ";", "}", "else", "{", "parent", "::", "doWrite", "(", "$", "message", ",", "$", "newline", ")", ";", "}", "}" ]
Writes a message to the output. Handles paged output, or writes directly to the output stream. @param string $message A message to write to the output @param bool $newline Whether to add a newline or not
[ "Writes", "a", "message", "to", "the", "output", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L151-L158
bobthecow/psysh
src/Output/ShellOutput.php
ShellOutput.initFormatters
private function initFormatters() { $formatter = $this->getFormatter(); $formatter->setStyle('warning', new OutputFormatterStyle('black', 'yellow')); $formatter->setStyle('error', new OutputFormatterStyle('black', 'red', ['bold'])); $formatter->setStyle('aside', new OutputFormatterStyle('blue')); $formatter->setStyle('strong', new OutputFormatterStyle(null, null, ['bold'])); $formatter->setStyle('return', new OutputFormatterStyle('cyan')); $formatter->setStyle('urgent', new OutputFormatterStyle('red')); $formatter->setStyle('hidden', new OutputFormatterStyle('black')); // Visibility $formatter->setStyle('public', new OutputFormatterStyle(null, null, ['bold'])); $formatter->setStyle('protected', new OutputFormatterStyle('yellow')); $formatter->setStyle('private', new OutputFormatterStyle('red')); $formatter->setStyle('global', new OutputFormatterStyle('cyan', null, ['bold'])); $formatter->setStyle('const', new OutputFormatterStyle('cyan')); $formatter->setStyle('class', new OutputFormatterStyle('blue', null, ['underscore'])); $formatter->setStyle('function', new OutputFormatterStyle(null)); $formatter->setStyle('default', new OutputFormatterStyle(null)); // Types $formatter->setStyle('number', new OutputFormatterStyle('magenta')); $formatter->setStyle('string', new OutputFormatterStyle('green')); $formatter->setStyle('bool', new OutputFormatterStyle('cyan')); $formatter->setStyle('keyword', new OutputFormatterStyle('yellow')); $formatter->setStyle('comment', new OutputFormatterStyle('blue')); $formatter->setStyle('object', new OutputFormatterStyle('blue')); $formatter->setStyle('resource', new OutputFormatterStyle('yellow')); }
php
private function initFormatters() { $formatter = $this->getFormatter(); $formatter->setStyle('warning', new OutputFormatterStyle('black', 'yellow')); $formatter->setStyle('error', new OutputFormatterStyle('black', 'red', ['bold'])); $formatter->setStyle('aside', new OutputFormatterStyle('blue')); $formatter->setStyle('strong', new OutputFormatterStyle(null, null, ['bold'])); $formatter->setStyle('return', new OutputFormatterStyle('cyan')); $formatter->setStyle('urgent', new OutputFormatterStyle('red')); $formatter->setStyle('hidden', new OutputFormatterStyle('black')); $formatter->setStyle('public', new OutputFormatterStyle(null, null, ['bold'])); $formatter->setStyle('protected', new OutputFormatterStyle('yellow')); $formatter->setStyle('private', new OutputFormatterStyle('red')); $formatter->setStyle('global', new OutputFormatterStyle('cyan', null, ['bold'])); $formatter->setStyle('const', new OutputFormatterStyle('cyan')); $formatter->setStyle('class', new OutputFormatterStyle('blue', null, ['underscore'])); $formatter->setStyle('function', new OutputFormatterStyle(null)); $formatter->setStyle('default', new OutputFormatterStyle(null)); $formatter->setStyle('number', new OutputFormatterStyle('magenta')); $formatter->setStyle('string', new OutputFormatterStyle('green')); $formatter->setStyle('bool', new OutputFormatterStyle('cyan')); $formatter->setStyle('keyword', new OutputFormatterStyle('yellow')); $formatter->setStyle('comment', new OutputFormatterStyle('blue')); $formatter->setStyle('object', new OutputFormatterStyle('blue')); $formatter->setStyle('resource', new OutputFormatterStyle('yellow')); }
[ "private", "function", "initFormatters", "(", ")", "{", "$", "formatter", "=", "$", "this", "->", "getFormatter", "(", ")", ";", "$", "formatter", "->", "setStyle", "(", "'warning'", ",", "new", "OutputFormatterStyle", "(", "'black'", ",", "'yellow'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'error'", ",", "new", "OutputFormatterStyle", "(", "'black'", ",", "'red'", ",", "[", "'bold'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'aside'", ",", "new", "OutputFormatterStyle", "(", "'blue'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'strong'", ",", "new", "OutputFormatterStyle", "(", "null", ",", "null", ",", "[", "'bold'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'return'", ",", "new", "OutputFormatterStyle", "(", "'cyan'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'urgent'", ",", "new", "OutputFormatterStyle", "(", "'red'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'hidden'", ",", "new", "OutputFormatterStyle", "(", "'black'", ")", ")", ";", "// Visibility", "$", "formatter", "->", "setStyle", "(", "'public'", ",", "new", "OutputFormatterStyle", "(", "null", ",", "null", ",", "[", "'bold'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'protected'", ",", "new", "OutputFormatterStyle", "(", "'yellow'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'private'", ",", "new", "OutputFormatterStyle", "(", "'red'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'global'", ",", "new", "OutputFormatterStyle", "(", "'cyan'", ",", "null", ",", "[", "'bold'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'const'", ",", "new", "OutputFormatterStyle", "(", "'cyan'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'class'", ",", "new", "OutputFormatterStyle", "(", "'blue'", ",", "null", ",", "[", "'underscore'", "]", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'function'", ",", "new", "OutputFormatterStyle", "(", "null", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'default'", ",", "new", "OutputFormatterStyle", "(", "null", ")", ")", ";", "// Types", "$", "formatter", "->", "setStyle", "(", "'number'", ",", "new", "OutputFormatterStyle", "(", "'magenta'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'string'", ",", "new", "OutputFormatterStyle", "(", "'green'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'bool'", ",", "new", "OutputFormatterStyle", "(", "'cyan'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'keyword'", ",", "new", "OutputFormatterStyle", "(", "'yellow'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'comment'", ",", "new", "OutputFormatterStyle", "(", "'blue'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'object'", ",", "new", "OutputFormatterStyle", "(", "'blue'", ")", ")", ";", "$", "formatter", "->", "setStyle", "(", "'resource'", ",", "new", "OutputFormatterStyle", "(", "'yellow'", ")", ")", ";", "}" ]
Initialize output formatter styles.
[ "Initialize", "output", "formatter", "styles", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L173-L203
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.getDefaultPasses
private function getDefaultPasses() { $useStatementPass = new UseStatementPass(); $namespacePass = new NamespacePass($this); // Try to add implicit `use` statements and an implicit namespace, // based on the file in which the `debug` call was made. $this->addImplicitDebugContext([$useStatementPass, $namespacePass]); return [ // Validation passes new AbstractClassPass(), new AssignThisVariablePass(), new CalledClassPass(), new CallTimePassByReferencePass(), new FinalClassPass(), new FunctionContextPass(), new FunctionReturnInWriteContextPass(), new InstanceOfPass(), new LeavePsyshAlonePass(), new LegacyEmptyPass(), new ListPass(), new LoopContextPass(), new PassableByReferencePass(), new ValidConstructorPass(), // Rewriting shenanigans $useStatementPass, // must run before the namespace pass new ExitPass(), new ImplicitReturnPass(), new MagicConstantsPass(), $namespacePass, // must run after the implicit return pass new RequirePass(), new StrictTypesPass(), // Namespace-aware validation (which depends on aforementioned shenanigans) new ValidClassNamePass(), new ValidConstantPass(), new ValidFunctionNamePass(), ]; }
php
private function getDefaultPasses() { $useStatementPass = new UseStatementPass(); $namespacePass = new NamespacePass($this); $this->addImplicitDebugContext([$useStatementPass, $namespacePass]); return [ new AbstractClassPass(), new AssignThisVariablePass(), new CalledClassPass(), new CallTimePassByReferencePass(), new FinalClassPass(), new FunctionContextPass(), new FunctionReturnInWriteContextPass(), new InstanceOfPass(), new LeavePsyshAlonePass(), new LegacyEmptyPass(), new ListPass(), new LoopContextPass(), new PassableByReferencePass(), new ValidConstructorPass(), $useStatementPass, new ExitPass(), new ImplicitReturnPass(), new MagicConstantsPass(), $namespacePass, new RequirePass(), new StrictTypesPass(), new ValidClassNamePass(), new ValidConstantPass(), new ValidFunctionNamePass(), ]; }
[ "private", "function", "getDefaultPasses", "(", ")", "{", "$", "useStatementPass", "=", "new", "UseStatementPass", "(", ")", ";", "$", "namespacePass", "=", "new", "NamespacePass", "(", "$", "this", ")", ";", "// Try to add implicit `use` statements and an implicit namespace,", "// based on the file in which the `debug` call was made.", "$", "this", "->", "addImplicitDebugContext", "(", "[", "$", "useStatementPass", ",", "$", "namespacePass", "]", ")", ";", "return", "[", "// Validation passes", "new", "AbstractClassPass", "(", ")", ",", "new", "AssignThisVariablePass", "(", ")", ",", "new", "CalledClassPass", "(", ")", ",", "new", "CallTimePassByReferencePass", "(", ")", ",", "new", "FinalClassPass", "(", ")", ",", "new", "FunctionContextPass", "(", ")", ",", "new", "FunctionReturnInWriteContextPass", "(", ")", ",", "new", "InstanceOfPass", "(", ")", ",", "new", "LeavePsyshAlonePass", "(", ")", ",", "new", "LegacyEmptyPass", "(", ")", ",", "new", "ListPass", "(", ")", ",", "new", "LoopContextPass", "(", ")", ",", "new", "PassableByReferencePass", "(", ")", ",", "new", "ValidConstructorPass", "(", ")", ",", "// Rewriting shenanigans", "$", "useStatementPass", ",", "// must run before the namespace pass", "new", "ExitPass", "(", ")", ",", "new", "ImplicitReturnPass", "(", ")", ",", "new", "MagicConstantsPass", "(", ")", ",", "$", "namespacePass", ",", "// must run after the implicit return pass", "new", "RequirePass", "(", ")", ",", "new", "StrictTypesPass", "(", ")", ",", "// Namespace-aware validation (which depends on aforementioned shenanigans)", "new", "ValidClassNamePass", "(", ")", ",", "new", "ValidConstantPass", "(", ")", ",", "new", "ValidFunctionNamePass", "(", ")", ",", "]", ";", "}" ]
Get default CodeCleaner passes. @return array
[ "Get", "default", "CodeCleaner", "passes", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L82-L122
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.addImplicitDebugContext
private function addImplicitDebugContext(array $passes) { $file = $this->getDebugFile(); if ($file === null) { return; } try { $code = @\file_get_contents($file); if (!$code) { return; } $stmts = $this->parse($code, true); if ($stmts === false) { return; } // Set up a clean traverser for just these code cleaner passes $traverser = new NodeTraverser(); foreach ($passes as $pass) { $traverser->addVisitor($pass); } $traverser->traverse($stmts); } catch (\Throwable $e) { // Don't care. } catch (\Exception $e) { // Still don't care. } }
php
private function addImplicitDebugContext(array $passes) { $file = $this->getDebugFile(); if ($file === null) { return; } try { $code = @\file_get_contents($file); if (!$code) { return; } $stmts = $this->parse($code, true); if ($stmts === false) { return; } $traverser = new NodeTraverser(); foreach ($passes as $pass) { $traverser->addVisitor($pass); } $traverser->traverse($stmts); } catch (\Throwable $e) { } catch (\Exception $e) { } }
[ "private", "function", "addImplicitDebugContext", "(", "array", "$", "passes", ")", "{", "$", "file", "=", "$", "this", "->", "getDebugFile", "(", ")", ";", "if", "(", "$", "file", "===", "null", ")", "{", "return", ";", "}", "try", "{", "$", "code", "=", "@", "\\", "file_get_contents", "(", "$", "file", ")", ";", "if", "(", "!", "$", "code", ")", "{", "return", ";", "}", "$", "stmts", "=", "$", "this", "->", "parse", "(", "$", "code", ",", "true", ")", ";", "if", "(", "$", "stmts", "===", "false", ")", "{", "return", ";", "}", "// Set up a clean traverser for just these code cleaner passes", "$", "traverser", "=", "new", "NodeTraverser", "(", ")", ";", "foreach", "(", "$", "passes", "as", "$", "pass", ")", "{", "$", "traverser", "->", "addVisitor", "(", "$", "pass", ")", ";", "}", "$", "traverser", "->", "traverse", "(", "$", "stmts", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "// Don't care.", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Still don't care.", "}", "}" ]
"Warm up" code cleaner passes when we're coming from a debug call. This is useful, for example, for `UseStatementPass` and `NamespacePass` which keep track of state between calls, to maintain the current namespace and a map of use statements. @param array $passes
[ "Warm", "up", "code", "cleaner", "passes", "when", "we", "re", "coming", "from", "a", "debug", "call", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L133-L163
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.getDebugFile
private static function getDebugFile() { $trace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach (\array_reverse($trace) as $stackFrame) { if (!self::isDebugCall($stackFrame)) { continue; } if (\preg_match('/eval\(/', $stackFrame['file'])) { \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); return $matches[1][0]; } return $stackFrame['file']; } }
php
private static function getDebugFile() { $trace = \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach (\array_reverse($trace) as $stackFrame) { if (!self::isDebugCall($stackFrame)) { continue; } if (\preg_match('/eval\(/', $stackFrame['file'])) { \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); return $matches[1][0]; } return $stackFrame['file']; } }
[ "private", "static", "function", "getDebugFile", "(", ")", "{", "$", "trace", "=", "\\", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "foreach", "(", "\\", "array_reverse", "(", "$", "trace", ")", "as", "$", "stackFrame", ")", "{", "if", "(", "!", "self", "::", "isDebugCall", "(", "$", "stackFrame", ")", ")", "{", "continue", ";", "}", "if", "(", "\\", "preg_match", "(", "'/eval\\(/'", ",", "$", "stackFrame", "[", "'file'", "]", ")", ")", "{", "\\", "preg_match_all", "(", "'/([^\\(]+)\\((\\d+)/'", ",", "$", "stackFrame", "[", "'file'", "]", ",", "$", "matches", ")", ";", "return", "$", "matches", "[", "1", "]", "[", "0", "]", ";", "}", "return", "$", "stackFrame", "[", "'file'", "]", ";", "}", "}" ]
Search the stack trace for a file in which the user called Psy\debug. @return string|null
[ "Search", "the", "stack", "trace", "for", "a", "file", "in", "which", "the", "user", "called", "Psy", "\\", "debug", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L170-L187
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.clean
public function clean(array $codeLines, $requireSemicolons = false) { $stmts = $this->parse('<?php ' . \implode(PHP_EOL, $codeLines) . PHP_EOL, $requireSemicolons); if ($stmts === false) { return false; } // Catch fatal errors before they happen $stmts = $this->traverser->traverse($stmts); // Work around https://github.com/nikic/PHP-Parser/issues/399 $oldLocale = \setlocale(LC_NUMERIC, 0); \setlocale(LC_NUMERIC, 'C'); $code = $this->printer->prettyPrint($stmts); // Now put the locale back \setlocale(LC_NUMERIC, $oldLocale); return $code; }
php
public function clean(array $codeLines, $requireSemicolons = false) { $stmts = $this->parse('<?php ' . \implode(PHP_EOL, $codeLines) . PHP_EOL, $requireSemicolons); if ($stmts === false) { return false; } $stmts = $this->traverser->traverse($stmts); $oldLocale = \setlocale(LC_NUMERIC, 0); \setlocale(LC_NUMERIC, 'C'); $code = $this->printer->prettyPrint($stmts); \setlocale(LC_NUMERIC, $oldLocale); return $code; }
[ "public", "function", "clean", "(", "array", "$", "codeLines", ",", "$", "requireSemicolons", "=", "false", ")", "{", "$", "stmts", "=", "$", "this", "->", "parse", "(", "'<?php '", ".", "\\", "implode", "(", "PHP_EOL", ",", "$", "codeLines", ")", ".", "PHP_EOL", ",", "$", "requireSemicolons", ")", ";", "if", "(", "$", "stmts", "===", "false", ")", "{", "return", "false", ";", "}", "// Catch fatal errors before they happen", "$", "stmts", "=", "$", "this", "->", "traverser", "->", "traverse", "(", "$", "stmts", ")", ";", "// Work around https://github.com/nikic/PHP-Parser/issues/399", "$", "oldLocale", "=", "\\", "setlocale", "(", "LC_NUMERIC", ",", "0", ")", ";", "\\", "setlocale", "(", "LC_NUMERIC", ",", "'C'", ")", ";", "$", "code", "=", "$", "this", "->", "printer", "->", "prettyPrint", "(", "$", "stmts", ")", ";", "// Now put the locale back", "\\", "setlocale", "(", "LC_NUMERIC", ",", "$", "oldLocale", ")", ";", "return", "$", "code", ";", "}" ]
Clean the given array of code. @throws ParseErrorException if the code is invalid PHP, and cannot be coerced into valid PHP @param array $codeLines @param bool $requireSemicolons @return string|false Cleaned PHP code, False if the input is incomplete
[ "Clean", "the", "given", "array", "of", "code", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L215-L235
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.parse
protected function parse($code, $requireSemicolons = false) { try { return $this->parser->parse($code); } catch (\PhpParser\Error $e) { if ($this->parseErrorIsUnclosedString($e, $code)) { return false; } if ($this->parseErrorIsUnterminatedComment($e, $code)) { return false; } if ($this->parseErrorIsTrailingComma($e, $code)) { return false; } if (!$this->parseErrorIsEOF($e)) { throw ParseErrorException::fromParseError($e); } if ($requireSemicolons) { return false; } try { // Unexpected EOF, try again with an implicit semicolon return $this->parser->parse($code . ';'); } catch (\PhpParser\Error $e) { return false; } } }
php
protected function parse($code, $requireSemicolons = false) { try { return $this->parser->parse($code); } catch (\PhpParser\Error $e) { if ($this->parseErrorIsUnclosedString($e, $code)) { return false; } if ($this->parseErrorIsUnterminatedComment($e, $code)) { return false; } if ($this->parseErrorIsTrailingComma($e, $code)) { return false; } if (!$this->parseErrorIsEOF($e)) { throw ParseErrorException::fromParseError($e); } if ($requireSemicolons) { return false; } try { return $this->parser->parse($code . ';'); } catch (\PhpParser\Error $e) { return false; } } }
[ "protected", "function", "parse", "(", "$", "code", ",", "$", "requireSemicolons", "=", "false", ")", "{", "try", "{", "return", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ")", ";", "}", "catch", "(", "\\", "PhpParser", "\\", "Error", "$", "e", ")", "{", "if", "(", "$", "this", "->", "parseErrorIsUnclosedString", "(", "$", "e", ",", "$", "code", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "parseErrorIsUnterminatedComment", "(", "$", "e", ",", "$", "code", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "parseErrorIsTrailingComma", "(", "$", "e", ",", "$", "code", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "this", "->", "parseErrorIsEOF", "(", "$", "e", ")", ")", "{", "throw", "ParseErrorException", "::", "fromParseError", "(", "$", "e", ")", ";", "}", "if", "(", "$", "requireSemicolons", ")", "{", "return", "false", ";", "}", "try", "{", "// Unexpected EOF, try again with an implicit semicolon", "return", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ".", "';'", ")", ";", "}", "catch", "(", "\\", "PhpParser", "\\", "Error", "$", "e", ")", "{", "return", "false", ";", "}", "}", "}" ]
Lex and parse a block of code. @see Parser::parse @throws ParseErrorException for parse errors that can't be resolved by waiting a line to see what comes next @param string $code @param bool $requireSemicolons @return array|false A set of statements, or false if incomplete
[ "Lex", "and", "parse", "a", "block", "of", "code", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L272-L304
bobthecow/psysh
src/CodeCleaner.php
CodeCleaner.parseErrorIsUnclosedString
private function parseErrorIsUnclosedString(\PhpParser\Error $e, $code) { if ($e->getRawMessage() !== 'Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE') { return false; } try { $this->parser->parse($code . "';"); } catch (\Exception $e) { return false; } return true; }
php
private function parseErrorIsUnclosedString(\PhpParser\Error $e, $code) { if ($e->getRawMessage() !== 'Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE') { return false; } try { $this->parser->parse($code . "';"); } catch (\Exception $e) { return false; } return true; }
[ "private", "function", "parseErrorIsUnclosedString", "(", "\\", "PhpParser", "\\", "Error", "$", "e", ",", "$", "code", ")", "{", "if", "(", "$", "e", "->", "getRawMessage", "(", ")", "!==", "'Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE'", ")", "{", "return", "false", ";", "}", "try", "{", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ".", "\"';\"", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
A special test for unclosed single-quoted strings. Unlike (all?) other unclosed statements, single quoted strings have their own special beautiful snowflake syntax error just for themselves. @param \PhpParser\Error $e @param string $code @return bool
[ "A", "special", "test", "for", "unclosed", "single", "-", "quoted", "strings", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L325-L338
bobthecow/psysh
src/CodeCleaner/ValidFunctionNamePass.php
ValidFunctionNamePass.enterNode
public function enterNode(Node $node) { parent::enterNode($node); if (self::isConditional($node)) { $this->conditionalScopes++; } elseif ($node instanceof Function_) { $name = $this->getFullyQualifiedName($node->name); // @todo add an "else" here which adds a runtime check for instances where we can't tell // whether a function is being redefined by static analysis alone. if ($this->conditionalScopes === 0) { if (\function_exists($name) || isset($this->currentScope[\strtolower($name)])) { $msg = \sprintf('Cannot redeclare %s()', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } $this->currentScope[\strtolower($name)] = true; } }
php
public function enterNode(Node $node) { parent::enterNode($node); if (self::isConditional($node)) { $this->conditionalScopes++; } elseif ($node instanceof Function_) { $name = $this->getFullyQualifiedName($node->name); if ($this->conditionalScopes === 0) { if (\function_exists($name) || isset($this->currentScope[\strtolower($name)])) { $msg = \sprintf('Cannot redeclare %s()', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } $this->currentScope[\strtolower($name)] = true; } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "parent", "::", "enterNode", "(", "$", "node", ")", ";", "if", "(", "self", "::", "isConditional", "(", "$", "node", ")", ")", "{", "$", "this", "->", "conditionalScopes", "++", ";", "}", "elseif", "(", "$", "node", "instanceof", "Function_", ")", "{", "$", "name", "=", "$", "this", "->", "getFullyQualifiedName", "(", "$", "node", "->", "name", ")", ";", "// @todo add an \"else\" here which adds a runtime check for instances where we can't tell", "// whether a function is being redefined by static analysis alone.", "if", "(", "$", "this", "->", "conditionalScopes", "===", "0", ")", "{", "if", "(", "\\", "function_exists", "(", "$", "name", ")", "||", "isset", "(", "$", "this", "->", "currentScope", "[", "\\", "strtolower", "(", "$", "name", ")", "]", ")", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Cannot redeclare %s()'", ",", "$", "name", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "$", "this", "->", "currentScope", "[", "\\", "strtolower", "(", "$", "name", ")", "]", "=", "true", ";", "}", "}" ]
Store newly defined function names on the way in, to allow recursion. @param Node $node
[ "Store", "newly", "defined", "function", "names", "on", "the", "way", "in", "to", "allow", "recursion", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidFunctionNamePass.php#L40-L61
bobthecow/psysh
src/CodeCleaner/ValidFunctionNamePass.php
ValidFunctionNamePass.leaveNode
public function leaveNode(Node $node) { if (self::isConditional($node)) { $this->conditionalScopes--; } elseif ($node instanceof FuncCall) { // if function name is an expression or a variable, give it a pass for now. $name = $node->name; if (!$name instanceof Expr && !$name instanceof Variable) { $shortName = \implode('\\', $name->parts); $fullName = $this->getFullyQualifiedName($name); $inScope = isset($this->currentScope[\strtolower($fullName)]); if (!$inScope && !\function_exists($shortName) && !\function_exists($fullName)) { $message = \sprintf('Call to undefined function %s()', $name); throw new FatalErrorException($message, 0, E_ERROR, null, $node->getLine()); } } } }
php
public function leaveNode(Node $node) { if (self::isConditional($node)) { $this->conditionalScopes--; } elseif ($node instanceof FuncCall) { $name = $node->name; if (!$name instanceof Expr && !$name instanceof Variable) { $shortName = \implode('\\', $name->parts); $fullName = $this->getFullyQualifiedName($name); $inScope = isset($this->currentScope[\strtolower($fullName)]); if (!$inScope && !\function_exists($shortName) && !\function_exists($fullName)) { $message = \sprintf('Call to undefined function %s()', $name); throw new FatalErrorException($message, 0, E_ERROR, null, $node->getLine()); } } } }
[ "public", "function", "leaveNode", "(", "Node", "$", "node", ")", "{", "if", "(", "self", "::", "isConditional", "(", "$", "node", ")", ")", "{", "$", "this", "->", "conditionalScopes", "--", ";", "}", "elseif", "(", "$", "node", "instanceof", "FuncCall", ")", "{", "// if function name is an expression or a variable, give it a pass for now.", "$", "name", "=", "$", "node", "->", "name", ";", "if", "(", "!", "$", "name", "instanceof", "Expr", "&&", "!", "$", "name", "instanceof", "Variable", ")", "{", "$", "shortName", "=", "\\", "implode", "(", "'\\\\'", ",", "$", "name", "->", "parts", ")", ";", "$", "fullName", "=", "$", "this", "->", "getFullyQualifiedName", "(", "$", "name", ")", ";", "$", "inScope", "=", "isset", "(", "$", "this", "->", "currentScope", "[", "\\", "strtolower", "(", "$", "fullName", ")", "]", ")", ";", "if", "(", "!", "$", "inScope", "&&", "!", "\\", "function_exists", "(", "$", "shortName", ")", "&&", "!", "\\", "function_exists", "(", "$", "fullName", ")", ")", "{", "$", "message", "=", "\\", "sprintf", "(", "'Call to undefined function %s()'", ",", "$", "name", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "message", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}", "}" ]
Validate that function calls will succeed. @throws FatalErrorException if a function is redefined @throws FatalErrorException if the function name is a string (not an expression) and is not defined @param Node $node
[ "Validate", "that", "function", "calls", "will", "succeed", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidFunctionNamePass.php#L71-L88
bobthecow/psysh
src/CodeCleaner/ValidConstantPass.php
ValidConstantPass.leaveNode
public function leaveNode(Node $node) { if ($node instanceof ConstFetch && \count($node->name->parts) > 1) { $name = $this->getFullyQualifiedName($node->name); if (!\defined($name)) { $msg = \sprintf('Undefined constant %s', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } elseif ($node instanceof ClassConstFetch) { $this->validateClassConstFetchExpression($node); } }
php
public function leaveNode(Node $node) { if ($node instanceof ConstFetch && \count($node->name->parts) > 1) { $name = $this->getFullyQualifiedName($node->name); if (!\defined($name)) { $msg = \sprintf('Undefined constant %s', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } elseif ($node instanceof ClassConstFetch) { $this->validateClassConstFetchExpression($node); } }
[ "public", "function", "leaveNode", "(", "Node", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "ConstFetch", "&&", "\\", "count", "(", "$", "node", "->", "name", "->", "parts", ")", ">", "1", ")", "{", "$", "name", "=", "$", "this", "->", "getFullyQualifiedName", "(", "$", "node", "->", "name", ")", ";", "if", "(", "!", "\\", "defined", "(", "$", "name", ")", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Undefined constant %s'", ",", "$", "name", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "elseif", "(", "$", "node", "instanceof", "ClassConstFetch", ")", "{", "$", "this", "->", "validateClassConstFetchExpression", "(", "$", "node", ")", ";", "}", "}" ]
Validate that namespaced constant references will succeed. Note that this does not (yet) detect constants defined in the current code snippet. It won't happen very often, so we'll punt for now. @throws FatalErrorException if a constant reference is not defined @param Node $node
[ "Validate", "that", "namespaced", "constant", "references", "will", "succeed", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidConstantPass.php#L44-L55
bobthecow/psysh
src/CodeCleaner/ValidConstantPass.php
ValidConstantPass.validateClassConstFetchExpression
protected function validateClassConstFetchExpression(ClassConstFetch $stmt) { // For PHP Parser 4.x $constName = $stmt->name instanceof Identifier ? $stmt->name->toString() : $stmt->name; // give the `class` pseudo-constant a pass if ($constName === 'class') { return; } // if class name is an expression, give it a pass for now if (!$stmt->class instanceof Expr) { $className = $this->getFullyQualifiedName($stmt->class); // if the class doesn't exist, don't throw an exception… it might be // defined in the same line it's used or something stupid like that. if (\class_exists($className) || \interface_exists($className)) { $refl = new \ReflectionClass($className); if (!$refl->hasConstant($constName)) { $constType = \class_exists($className) ? 'Class' : 'Interface'; $msg = \sprintf('%s constant \'%s::%s\' not found', $constType, $className, $constName); throw new FatalErrorException($msg, 0, E_ERROR, null, $stmt->getLine()); } } } }
php
protected function validateClassConstFetchExpression(ClassConstFetch $stmt) { $constName = $stmt->name instanceof Identifier ? $stmt->name->toString() : $stmt->name; if ($constName === 'class') { return; } if (!$stmt->class instanceof Expr) { $className = $this->getFullyQualifiedName($stmt->class); if (\class_exists($className) || \interface_exists($className)) { $refl = new \ReflectionClass($className); if (!$refl->hasConstant($constName)) { $constType = \class_exists($className) ? 'Class' : 'Interface'; $msg = \sprintf('%s constant \'%s::%s\' not found', $constType, $className, $constName); throw new FatalErrorException($msg, 0, E_ERROR, null, $stmt->getLine()); } } } }
[ "protected", "function", "validateClassConstFetchExpression", "(", "ClassConstFetch", "$", "stmt", ")", "{", "// For PHP Parser 4.x", "$", "constName", "=", "$", "stmt", "->", "name", "instanceof", "Identifier", "?", "$", "stmt", "->", "name", "->", "toString", "(", ")", ":", "$", "stmt", "->", "name", ";", "// give the `class` pseudo-constant a pass", "if", "(", "$", "constName", "===", "'class'", ")", "{", "return", ";", "}", "// if class name is an expression, give it a pass for now", "if", "(", "!", "$", "stmt", "->", "class", "instanceof", "Expr", ")", "{", "$", "className", "=", "$", "this", "->", "getFullyQualifiedName", "(", "$", "stmt", "->", "class", ")", ";", "// if the class doesn't exist, don't throw an exception… it might be", "// defined in the same line it's used or something stupid like that.", "if", "(", "\\", "class_exists", "(", "$", "className", ")", "||", "\\", "interface_exists", "(", "$", "className", ")", ")", "{", "$", "refl", "=", "new", "\\", "ReflectionClass", "(", "$", "className", ")", ";", "if", "(", "!", "$", "refl", "->", "hasConstant", "(", "$", "constName", ")", ")", "{", "$", "constType", "=", "\\", "class_exists", "(", "$", "className", ")", "?", "'Class'", ":", "'Interface'", ";", "$", "msg", "=", "\\", "sprintf", "(", "'%s constant \\'%s::%s\\' not found'", ",", "$", "constType", ",", "$", "className", ",", "$", "constName", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "stmt", "->", "getLine", "(", ")", ")", ";", "}", "}", "}", "}" ]
Validate a class constant fetch expression. @throws FatalErrorException if a class constant is not defined @param ClassConstFetch $stmt
[ "Validate", "a", "class", "constant", "fetch", "expression", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidConstantPass.php#L64-L89
bobthecow/psysh
src/ConfigPaths.php
ConfigPaths.getCurrentConfigDir
public static function getCurrentConfigDir() { $configDirs = self::getHomeConfigDirs(); foreach ($configDirs as $configDir) { if (@\is_dir($configDir)) { return $configDir; } } return $configDirs[0]; }
php
public static function getCurrentConfigDir() { $configDirs = self::getHomeConfigDirs(); foreach ($configDirs as $configDir) { if (@\is_dir($configDir)) { return $configDir; } } return $configDirs[0]; }
[ "public", "static", "function", "getCurrentConfigDir", "(", ")", "{", "$", "configDirs", "=", "self", "::", "getHomeConfigDirs", "(", ")", ";", "foreach", "(", "$", "configDirs", "as", "$", "configDir", ")", "{", "if", "(", "@", "\\", "is_dir", "(", "$", "configDir", ")", ")", "{", "return", "$", "configDir", ";", "}", "}", "return", "$", "configDirs", "[", "0", "]", ";", "}" ]
Get the current home config directory. Returns the highest precedence home config directory which actually exists. If none of them exists, returns the highest precedence home config directory (`%APPDATA%/PsySH` on Windows, `~/.config/psysh` everywhere else). @see self::getHomeConfigDirs @return string
[ "Get", "the", "current", "home", "config", "directory", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L67-L77
bobthecow/psysh
src/ConfigPaths.php
ConfigPaths.getConfigFiles
public static function getConfigFiles(array $names, $configDir = null) { $dirs = ($configDir === null) ? self::getConfigDirs() : [$configDir]; return self::getRealFiles($dirs, $names); }
php
public static function getConfigFiles(array $names, $configDir = null) { $dirs = ($configDir === null) ? self::getConfigDirs() : [$configDir]; return self::getRealFiles($dirs, $names); }
[ "public", "static", "function", "getConfigFiles", "(", "array", "$", "names", ",", "$", "configDir", "=", "null", ")", "{", "$", "dirs", "=", "(", "$", "configDir", "===", "null", ")", "?", "self", "::", "getConfigDirs", "(", ")", ":", "[", "$", "configDir", "]", ";", "return", "self", "::", "getRealFiles", "(", "$", "dirs", ",", "$", "names", ")", ";", "}" ]
Find real config files in config directories. @param string[] $names Config file names @param string $configDir Optionally use a specific config directory @return string[]
[ "Find", "real", "config", "files", "in", "config", "directories", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L87-L92
bobthecow/psysh
src/ConfigPaths.php
ConfigPaths.getDataFiles
public static function getDataFiles(array $names, $dataDir = null) { $dirs = ($dataDir === null) ? self::getDataDirs() : [$dataDir]; return self::getRealFiles($dirs, $names); }
php
public static function getDataFiles(array $names, $dataDir = null) { $dirs = ($dataDir === null) ? self::getDataDirs() : [$dataDir]; return self::getRealFiles($dirs, $names); }
[ "public", "static", "function", "getDataFiles", "(", "array", "$", "names", ",", "$", "dataDir", "=", "null", ")", "{", "$", "dirs", "=", "(", "$", "dataDir", "===", "null", ")", "?", "self", "::", "getDataDirs", "(", ")", ":", "[", "$", "dataDir", "]", ";", "return", "self", "::", "getRealFiles", "(", "$", "dirs", ",", "$", "names", ")", ";", "}" ]
Find real data files in config directories. @param string[] $names Config file names @param string $dataDir Optionally use a specific config directory @return string[]
[ "Find", "real", "data", "files", "in", "config", "directories", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L121-L126
bobthecow/psysh
src/ConfigPaths.php
ConfigPaths.getRuntimeDir
public static function getRuntimeDir() { $xdg = new Xdg(); \set_error_handler(['Psy\Exception\ErrorException', 'throwException']); try { // XDG doesn't really work on Windows, sometimes complains about // permissions, sometimes tries to remove non-empty directories. // It's a bit flaky. So we'll give this a shot first... $runtimeDir = $xdg->getRuntimeDir(false); } catch (\Exception $e) { // Well. That didn't work. Fall back to a boring old folder in the // system temp dir. $runtimeDir = \sys_get_temp_dir(); } \restore_error_handler(); return \strtr($runtimeDir, '\\', '/') . '/psysh'; }
php
public static function getRuntimeDir() { $xdg = new Xdg(); \set_error_handler(['Psy\Exception\ErrorException', 'throwException']); try { $runtimeDir = $xdg->getRuntimeDir(false); } catch (\Exception $e) { $runtimeDir = \sys_get_temp_dir(); } \restore_error_handler(); return \strtr($runtimeDir, '\\', '/') . '/psysh'; }
[ "public", "static", "function", "getRuntimeDir", "(", ")", "{", "$", "xdg", "=", "new", "Xdg", "(", ")", ";", "\\", "set_error_handler", "(", "[", "'Psy\\Exception\\ErrorException'", ",", "'throwException'", "]", ")", ";", "try", "{", "// XDG doesn't really work on Windows, sometimes complains about", "// permissions, sometimes tries to remove non-empty directories.", "// It's a bit flaky. So we'll give this a shot first...", "$", "runtimeDir", "=", "$", "xdg", "->", "getRuntimeDir", "(", "false", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Well. That didn't work. Fall back to a boring old folder in the", "// system temp dir.", "$", "runtimeDir", "=", "\\", "sys_get_temp_dir", "(", ")", ";", "}", "\\", "restore_error_handler", "(", ")", ";", "return", "\\", "strtr", "(", "$", "runtimeDir", ",", "'\\\\'", ",", "'/'", ")", ".", "'/psysh'", ";", "}" ]
Get a runtime directory. Defaults to `/psysh` inside the system's temp dir. @return string
[ "Get", "a", "runtime", "directory", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L135-L155
bobthecow/psysh
src/ConfigPaths.php
ConfigPaths.touchFileWithMkdir
public static function touchFileWithMkdir($file) { if (\file_exists($file)) { if (\is_writable($file)) { return $file; } \trigger_error(\sprintf('Writing to %s is not allowed.', $file), E_USER_NOTICE); return false; } $dir = \dirname($file); if (!\is_dir($dir)) { // Just try making it and see if it works @\mkdir($dir, 0700, true); } if (!\is_dir($dir) || !\is_writable($dir)) { \trigger_error(\sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE); return false; } \touch($file); return $file; }
php
public static function touchFileWithMkdir($file) { if (\file_exists($file)) { if (\is_writable($file)) { return $file; } \trigger_error(\sprintf('Writing to %s is not allowed.', $file), E_USER_NOTICE); return false; } $dir = \dirname($file); if (!\is_dir($dir)) { @\mkdir($dir, 0700, true); } if (!\is_dir($dir) || !\is_writable($dir)) { \trigger_error(\sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE); return false; } \touch($file); return $file; }
[ "public", "static", "function", "touchFileWithMkdir", "(", "$", "file", ")", "{", "if", "(", "\\", "file_exists", "(", "$", "file", ")", ")", "{", "if", "(", "\\", "is_writable", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "\\", "trigger_error", "(", "\\", "sprintf", "(", "'Writing to %s is not allowed.'", ",", "$", "file", ")", ",", "E_USER_NOTICE", ")", ";", "return", "false", ";", "}", "$", "dir", "=", "\\", "dirname", "(", "$", "file", ")", ";", "if", "(", "!", "\\", "is_dir", "(", "$", "dir", ")", ")", "{", "// Just try making it and see if it works", "@", "\\", "mkdir", "(", "$", "dir", ",", "0700", ",", "true", ")", ";", "}", "if", "(", "!", "\\", "is_dir", "(", "$", "dir", ")", "||", "!", "\\", "is_writable", "(", "$", "dir", ")", ")", "{", "\\", "trigger_error", "(", "\\", "sprintf", "(", "'Writing to %s is not allowed.'", ",", "$", "dir", ")", ",", "E_USER_NOTICE", ")", ";", "return", "false", ";", "}", "\\", "touch", "(", "$", "file", ")", ";", "return", "$", "file", ";", "}" ]
Ensure that $file exists and is writable, make the parent directory if necessary. Generates E_USER_NOTICE error if either $file or its directory is not writable. @param string $file @return string|false Full path to $file, or false if file is not writable
[ "Ensure", "that", "$file", "exists", "and", "is", "writable", "make", "the", "parent", "directory", "if", "necessary", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L208-L236
bobthecow/psysh
src/Command/ListCommand/TraitEnumerator.php
TraitEnumerator.listItems
protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null) { // only list traits when no Reflector is present. // // @todo make a NamespaceReflector and pass that in for commands like: // // ls --traits Foo // // ... for listing traits in the Foo namespace if ($reflector !== null || $target !== null) { return; } // only list traits if we are specifically asked if (!$input->getOption('traits')) { return; } $traits = $this->prepareTraits(\get_declared_traits()); if (empty($traits)) { return; } return [ 'Traits' => $traits, ]; }
php
protected function listItems(InputInterface $input, \Reflector $reflector = null, $target = null) { if ($reflector !== null || $target !== null) { return; } if (!$input->getOption('traits')) { return; } $traits = $this->prepareTraits(\get_declared_traits()); if (empty($traits)) { return; } return [ 'Traits' => $traits, ]; }
[ "protected", "function", "listItems", "(", "InputInterface", "$", "input", ",", "\\", "Reflector", "$", "reflector", "=", "null", ",", "$", "target", "=", "null", ")", "{", "// only list traits when no Reflector is present.", "//", "// @todo make a NamespaceReflector and pass that in for commands like:", "//", "// ls --traits Foo", "//", "// ... for listing traits in the Foo namespace", "if", "(", "$", "reflector", "!==", "null", "||", "$", "target", "!==", "null", ")", "{", "return", ";", "}", "// only list traits if we are specifically asked", "if", "(", "!", "$", "input", "->", "getOption", "(", "'traits'", ")", ")", "{", "return", ";", "}", "$", "traits", "=", "$", "this", "->", "prepareTraits", "(", "\\", "get_declared_traits", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "traits", ")", ")", "{", "return", ";", "}", "return", "[", "'Traits'", "=>", "$", "traits", ",", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/TraitEnumerator.php#L33-L61
bobthecow/psysh
src/Command/ListCommand/TraitEnumerator.php
TraitEnumerator.prepareTraits
protected function prepareTraits(array $traits) { \natcasesort($traits); // My kingdom for a generator. $ret = []; foreach ($traits as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
php
protected function prepareTraits(array $traits) { \natcasesort($traits); $ret = []; foreach ($traits as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
[ "protected", "function", "prepareTraits", "(", "array", "$", "traits", ")", "{", "\\", "natcasesort", "(", "$", "traits", ")", ";", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "traits", "as", "$", "name", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "ret", "[", "$", "name", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'style'", "=>", "self", "::", "IS_CLASS", ",", "'value'", "=>", "$", "this", "->", "presentSignature", "(", "$", "name", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted trait array. @param array $traits @return array
[ "Prepare", "formatted", "trait", "array", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/TraitEnumerator.php#L70-L88
bobthecow/psysh
src/ParserFactory.php
ParserFactory.createParser
public function createParser($kind = null) { if ($this->hasKindsSupport()) { $originalFactory = new OriginalParserFactory(); $kind = $kind ?: $this->getDefaultKind(); if (!\in_array($kind, static::getPossibleKinds())) { throw new \InvalidArgumentException('Unknown parser kind'); } $parser = $originalFactory->create(\constant('PhpParser\ParserFactory::' . $kind)); } else { if ($kind !== null) { throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind'); } $parser = new Parser(new Lexer()); } return $parser; }
php
public function createParser($kind = null) { if ($this->hasKindsSupport()) { $originalFactory = new OriginalParserFactory(); $kind = $kind ?: $this->getDefaultKind(); if (!\in_array($kind, static::getPossibleKinds())) { throw new \InvalidArgumentException('Unknown parser kind'); } $parser = $originalFactory->create(\constant('PhpParser\ParserFactory::' . $kind)); } else { if ($kind !== null) { throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind'); } $parser = new Parser(new Lexer()); } return $parser; }
[ "public", "function", "createParser", "(", "$", "kind", "=", "null", ")", "{", "if", "(", "$", "this", "->", "hasKindsSupport", "(", ")", ")", "{", "$", "originalFactory", "=", "new", "OriginalParserFactory", "(", ")", ";", "$", "kind", "=", "$", "kind", "?", ":", "$", "this", "->", "getDefaultKind", "(", ")", ";", "if", "(", "!", "\\", "in_array", "(", "$", "kind", ",", "static", "::", "getPossibleKinds", "(", ")", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown parser kind'", ")", ";", "}", "$", "parser", "=", "$", "originalFactory", "->", "create", "(", "\\", "constant", "(", "'PhpParser\\ParserFactory::'", ".", "$", "kind", ")", ")", ";", "}", "else", "{", "if", "(", "$", "kind", "!==", "null", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Install PHP Parser v2.x to specify parser kind'", ")", ";", "}", "$", "parser", "=", "new", "Parser", "(", "new", "Lexer", "(", ")", ")", ";", "}", "return", "$", "parser", ";", "}" ]
New parser instance with given kind. @param string|null $kind One of class constants (only for PHP parser 2.0 and above) @return Parser
[ "New", "parser", "instance", "with", "given", "kind", "." ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ParserFactory.php#L69-L90
bobthecow/psysh
src/CodeCleaner/AbstractClassPass.php
AbstractClassPass.enterNode
public function enterNode(Node $node) { if ($node instanceof Class_) { $this->class = $node; $this->abstractMethods = []; } elseif ($node instanceof ClassMethod) { if ($node->isAbstract()) { $name = \sprintf('%s::%s', $this->class->name, $node->name); $this->abstractMethods[] = $name; if ($node->stmts !== null) { $msg = \sprintf('Abstract function %s cannot contain body', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } } }
php
public function enterNode(Node $node) { if ($node instanceof Class_) { $this->class = $node; $this->abstractMethods = []; } elseif ($node instanceof ClassMethod) { if ($node->isAbstract()) { $name = \sprintf('%s::%s', $this->class->name, $node->name); $this->abstractMethods[] = $name; if ($node->stmts !== null) { $msg = \sprintf('Abstract function %s cannot contain body', $name); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "Class_", ")", "{", "$", "this", "->", "class", "=", "$", "node", ";", "$", "this", "->", "abstractMethods", "=", "[", "]", ";", "}", "elseif", "(", "$", "node", "instanceof", "ClassMethod", ")", "{", "if", "(", "$", "node", "->", "isAbstract", "(", ")", ")", "{", "$", "name", "=", "\\", "sprintf", "(", "'%s::%s'", ",", "$", "this", "->", "class", "->", "name", ",", "$", "node", "->", "name", ")", ";", "$", "this", "->", "abstractMethods", "[", "]", "=", "$", "name", ";", "if", "(", "$", "node", "->", "stmts", "!==", "null", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Abstract function %s cannot contain body'", ",", "$", "name", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}", "}" ]
@throws RuntimeException if the node is an abstract function with a body @param Node $node
[ "@throws", "RuntimeException", "if", "the", "node", "is", "an", "abstract", "function", "with", "a", "body" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/AbstractClassPass.php#L32-L48
bobthecow/psysh
src/CodeCleaner/AbstractClassPass.php
AbstractClassPass.leaveNode
public function leaveNode(Node $node) { if ($node instanceof Class_) { $count = \count($this->abstractMethods); if ($count > 0 && !$node->isAbstract()) { $msg = \sprintf( 'Class %s contains %d abstract method%s must therefore be declared abstract or implement the remaining methods (%s)', $node->name, $count, ($count === 1) ? '' : 's', \implode(', ', $this->abstractMethods) ); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } }
php
public function leaveNode(Node $node) { if ($node instanceof Class_) { $count = \count($this->abstractMethods); if ($count > 0 && !$node->isAbstract()) { $msg = \sprintf( 'Class %s contains %d abstract method%s must therefore be declared abstract or implement the remaining methods (%s)', $node->name, $count, ($count === 1) ? '' : 's', \implode(', ', $this->abstractMethods) ); throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine()); } } }
[ "public", "function", "leaveNode", "(", "Node", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "Class_", ")", "{", "$", "count", "=", "\\", "count", "(", "$", "this", "->", "abstractMethods", ")", ";", "if", "(", "$", "count", ">", "0", "&&", "!", "$", "node", "->", "isAbstract", "(", ")", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Class %s contains %d abstract method%s must therefore be declared abstract or implement the remaining methods (%s)'", ",", "$", "node", "->", "name", ",", "$", "count", ",", "(", "$", "count", "===", "1", ")", "?", "''", ":", "'s'", ",", "\\", "implode", "(", "', '", ",", "$", "this", "->", "abstractMethods", ")", ")", ";", "throw", "new", "FatalErrorException", "(", "$", "msg", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}" ]
@throws RuntimeException if the node is a non-abstract class with abstract methods @param Node $node
[ "@throws", "RuntimeException", "if", "the", "node", "is", "a", "non", "-", "abstract", "class", "with", "abstract", "methods" ]
train
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/AbstractClassPass.php#L55-L70
jeremykenedy/laravel-logger
src/app/Http/Middleware/LogActivity.php
LogActivity.handle
public function handle($request, Closure $next, $description = null) { if (config('LaravelLogger.loggerMiddlewareEnabled') && $this->shouldLog($request)) { ActivityLogger::activity($description); } return $next($request); }
php
public function handle($request, Closure $next, $description = null) { if (config('LaravelLogger.loggerMiddlewareEnabled') && $this->shouldLog($request)) { ActivityLogger::activity($description); } return $next($request); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ",", "$", "description", "=", "null", ")", "{", "if", "(", "config", "(", "'LaravelLogger.loggerMiddlewareEnabled'", ")", "&&", "$", "this", "->", "shouldLog", "(", "$", "request", ")", ")", "{", "ActivityLogger", "::", "activity", "(", "$", "description", ")", ";", "}", "return", "$", "next", "(", "$", "request", ")", ";", "}" ]
Handle an incoming request. @param Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Middleware/LogActivity.php#L21-L28
jeremykenedy/laravel-logger
src/app/Http/Middleware/LogActivity.php
LogActivity.shouldLog
protected function shouldLog($request) { foreach (config('LaravelLogger.loggerMiddlewareExcept', []) as $except) { if ($except !== '/') { $except = trim($except, '/'); } if ($request->is($except)) { return false; } } return true; }
php
protected function shouldLog($request) { foreach (config('LaravelLogger.loggerMiddlewareExcept', []) as $except) { if ($except !== '/') { $except = trim($except, '/'); } if ($request->is($except)) { return false; } } return true; }
[ "protected", "function", "shouldLog", "(", "$", "request", ")", "{", "foreach", "(", "config", "(", "'LaravelLogger.loggerMiddlewareExcept'", ",", "[", "]", ")", "as", "$", "except", ")", "{", "if", "(", "$", "except", "!==", "'/'", ")", "{", "$", "except", "=", "trim", "(", "$", "except", ",", "'/'", ")", ";", "}", "if", "(", "$", "request", "->", "is", "(", "$", "except", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determine if the request has a URI that should log. @param \Illuminate\Http\Request $request @return bool
[ "Determine", "if", "the", "request", "has", "a", "URI", "that", "should", "log", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Middleware/LogActivity.php#L37-L50
jeremykenedy/laravel-logger
src/LaravelLoggerServiceProvider.php
LaravelLoggerServiceProvider.register
public function register() { $this->loadRoutesFrom(__DIR__.'/routes/web.php'); $this->loadViewsFrom(__DIR__.'/resources/views/', 'LaravelLogger'); $this->loadMigrationsFrom(__DIR__.'/database/migrations'); if (file_exists(config_path('laravel-logger.php'))) { $this->mergeConfigFrom(config_path('laravel-logger.php'), 'LaravelLogger'); } else { $this->mergeConfigFrom(__DIR__.'/config/laravel-logger.php', 'LaravelLogger'); } $this->registerEventListeners(); $this->publishFiles(); }
php
public function register() { $this->loadRoutesFrom(__DIR__.'/routes/web.php'); $this->loadViewsFrom(__DIR__.'/resources/views/', 'LaravelLogger'); $this->loadMigrationsFrom(__DIR__.'/database/migrations'); if (file_exists(config_path('laravel-logger.php'))) { $this->mergeConfigFrom(config_path('laravel-logger.php'), 'LaravelLogger'); } else { $this->mergeConfigFrom(__DIR__.'/config/laravel-logger.php', 'LaravelLogger'); } $this->registerEventListeners(); $this->publishFiles(); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "loadRoutesFrom", "(", "__DIR__", ".", "'/routes/web.php'", ")", ";", "$", "this", "->", "loadViewsFrom", "(", "__DIR__", ".", "'/resources/views/'", ",", "'LaravelLogger'", ")", ";", "$", "this", "->", "loadMigrationsFrom", "(", "__DIR__", ".", "'/database/migrations'", ")", ";", "if", "(", "file_exists", "(", "config_path", "(", "'laravel-logger.php'", ")", ")", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "config_path", "(", "'laravel-logger.php'", ")", ",", "'LaravelLogger'", ")", ";", "}", "else", "{", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/config/laravel-logger.php'", ",", "'LaravelLogger'", ")", ";", "}", "$", "this", "->", "registerEventListeners", "(", ")", ";", "$", "this", "->", "publishFiles", "(", ")", ";", "}" ]
Register the application services. @return void
[ "Register", "the", "application", "services", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/LaravelLoggerServiceProvider.php#L71-L83
jeremykenedy/laravel-logger
src/LaravelLoggerServiceProvider.php
LaravelLoggerServiceProvider.registerEventListeners
private function registerEventListeners() { $listeners = $this->getListeners(); foreach ($listeners as $listenerKey => $listenerValues) { foreach ($listenerValues as $listenerValue) { \Event::listen($listenerKey, $listenerValue ); } } }
php
private function registerEventListeners() { $listeners = $this->getListeners(); foreach ($listeners as $listenerKey => $listenerValues) { foreach ($listenerValues as $listenerValue) { \Event::listen($listenerKey, $listenerValue ); } } }
[ "private", "function", "registerEventListeners", "(", ")", "{", "$", "listeners", "=", "$", "this", "->", "getListeners", "(", ")", ";", "foreach", "(", "$", "listeners", "as", "$", "listenerKey", "=>", "$", "listenerValues", ")", "{", "foreach", "(", "$", "listenerValues", "as", "$", "listenerValue", ")", "{", "\\", "Event", "::", "listen", "(", "$", "listenerKey", ",", "$", "listenerValue", ")", ";", "}", "}", "}" ]
Register the list of listeners and events. @return void
[ "Register", "the", "list", "of", "listeners", "and", "events", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/LaravelLoggerServiceProvider.php#L100-L110
jeremykenedy/laravel-logger
src/LaravelLoggerServiceProvider.php
LaravelLoggerServiceProvider.publishFiles
private function publishFiles() { $publishTag = 'LaravelLogger'; $this->publishes([ __DIR__.'/config/laravel-logger.php' => base_path('config/laravel-logger.php'), ], $publishTag); $this->publishes([ __DIR__.'/resources/views' => base_path('resources/views/vendor/'.$publishTag), ], $publishTag); $this->publishes([ __DIR__.'/resources/lang' => base_path('resources/lang/vendor/'.$publishTag), ], $publishTag); }
php
private function publishFiles() { $publishTag = 'LaravelLogger'; $this->publishes([ __DIR__.'/config/laravel-logger.php' => base_path('config/laravel-logger.php'), ], $publishTag); $this->publishes([ __DIR__.'/resources/views' => base_path('resources/views/vendor/'.$publishTag), ], $publishTag); $this->publishes([ __DIR__.'/resources/lang' => base_path('resources/lang/vendor/'.$publishTag), ], $publishTag); }
[ "private", "function", "publishFiles", "(", ")", "{", "$", "publishTag", "=", "'LaravelLogger'", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/config/laravel-logger.php'", "=>", "base_path", "(", "'config/laravel-logger.php'", ")", ",", "]", ",", "$", "publishTag", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/resources/views'", "=>", "base_path", "(", "'resources/views/vendor/'", ".", "$", "publishTag", ")", ",", "]", ",", "$", "publishTag", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/resources/lang'", "=>", "base_path", "(", "'resources/lang/vendor/'", ".", "$", "publishTag", ")", ",", "]", ",", "$", "publishTag", ")", ";", "}" ]
Publish files for Laravel Logger. @return void
[ "Publish", "files", "for", "Laravel", "Logger", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/LaravelLoggerServiceProvider.php#L117-L132
jeremykenedy/laravel-logger
src/database/migrations/2017_11_04_103444_create_laravel_logger_activity_table.php
CreateLaravelLoggerActivityTable.up
public function up() { $activity = new Activity(); $connection = $activity->getConnectionName(); $table = $activity->getTableName(); $tableCheck = Schema::connection($connection)->hasTable($table); if (!$tableCheck) { Schema::connection($connection)->create($table, function (Blueprint $table) { $table->increments('id'); $table->longText('description'); $table->string('userType'); $table->integer('userId')->nullable(); $table->longText('route')->nullable(); $table->ipAddress('ipAddress')->nullable(); $table->text('userAgent')->nullable(); $table->string('locale')->nullable(); $table->longText('referer')->nullable(); $table->string('methodType')->nullable(); $table->timestamps(); $table->softDeletes(); }); } }
php
public function up() { $activity = new Activity(); $connection = $activity->getConnectionName(); $table = $activity->getTableName(); $tableCheck = Schema::connection($connection)->hasTable($table); if (!$tableCheck) { Schema::connection($connection)->create($table, function (Blueprint $table) { $table->increments('id'); $table->longText('description'); $table->string('userType'); $table->integer('userId')->nullable(); $table->longText('route')->nullable(); $table->ipAddress('ipAddress')->nullable(); $table->text('userAgent')->nullable(); $table->string('locale')->nullable(); $table->longText('referer')->nullable(); $table->string('methodType')->nullable(); $table->timestamps(); $table->softDeletes(); }); } }
[ "public", "function", "up", "(", ")", "{", "$", "activity", "=", "new", "Activity", "(", ")", ";", "$", "connection", "=", "$", "activity", "->", "getConnectionName", "(", ")", ";", "$", "table", "=", "$", "activity", "->", "getTableName", "(", ")", ";", "$", "tableCheck", "=", "Schema", "::", "connection", "(", "$", "connection", ")", "->", "hasTable", "(", "$", "table", ")", ";", "if", "(", "!", "$", "tableCheck", ")", "{", "Schema", "::", "connection", "(", "$", "connection", ")", "->", "create", "(", "$", "table", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "increments", "(", "'id'", ")", ";", "$", "table", "->", "longText", "(", "'description'", ")", ";", "$", "table", "->", "string", "(", "'userType'", ")", ";", "$", "table", "->", "integer", "(", "'userId'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "longText", "(", "'route'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "ipAddress", "(", "'ipAddress'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "text", "(", "'userAgent'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "string", "(", "'locale'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "longText", "(", "'referer'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "string", "(", "'methodType'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "timestamps", "(", ")", ";", "$", "table", "->", "softDeletes", "(", ")", ";", "}", ")", ";", "}", "}" ]
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/database/migrations/2017_11_04_103444_create_laravel_logger_activity_table.php#L15-L38
jeremykenedy/laravel-logger
src/database/migrations/2017_11_04_103444_create_laravel_logger_activity_table.php
CreateLaravelLoggerActivityTable.down
public function down() { $activity = new Activity(); $connection = $activity->getConnectionName(); $table = $activity->getTableName(); Schema::connection($connection)->dropIfExists($table); }
php
public function down() { $activity = new Activity(); $connection = $activity->getConnectionName(); $table = $activity->getTableName(); Schema::connection($connection)->dropIfExists($table); }
[ "public", "function", "down", "(", ")", "{", "$", "activity", "=", "new", "Activity", "(", ")", ";", "$", "connection", "=", "$", "activity", "->", "getConnectionName", "(", ")", ";", "$", "table", "=", "$", "activity", "->", "getTableName", "(", ")", ";", "Schema", "::", "connection", "(", "$", "connection", ")", "->", "dropIfExists", "(", "$", "table", ")", ";", "}" ]
Reverse the migrations. @return void
[ "Reverse", "the", "migrations", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/database/migrations/2017_11_04_103444_create_laravel_logger_activity_table.php#L45-L52
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.mapAdditionalDetails
private function mapAdditionalDetails($collectionItems) { $collectionItems->map(function ($collectionItem) { $eventTime = Carbon::parse($collectionItem->updated_at); $collectionItem['timePassed'] = $eventTime->diffForHumans(); $collectionItem['userAgentDetails'] = UserAgentDetails::details($collectionItem->useragent); $collectionItem['langDetails'] = UserAgentDetails::localeLang($collectionItem->locale); $collectionItem['userDetails'] = config('LaravelLogger.defaultUserModel')::find($collectionItem->userId); return $collectionItem; }); return $collectionItems; }
php
private function mapAdditionalDetails($collectionItems) { $collectionItems->map(function ($collectionItem) { $eventTime = Carbon::parse($collectionItem->updated_at); $collectionItem['timePassed'] = $eventTime->diffForHumans(); $collectionItem['userAgentDetails'] = UserAgentDetails::details($collectionItem->useragent); $collectionItem['langDetails'] = UserAgentDetails::localeLang($collectionItem->locale); $collectionItem['userDetails'] = config('LaravelLogger.defaultUserModel')::find($collectionItem->userId); return $collectionItem; }); return $collectionItems; }
[ "private", "function", "mapAdditionalDetails", "(", "$", "collectionItems", ")", "{", "$", "collectionItems", "->", "map", "(", "function", "(", "$", "collectionItem", ")", "{", "$", "eventTime", "=", "Carbon", "::", "parse", "(", "$", "collectionItem", "->", "updated_at", ")", ";", "$", "collectionItem", "[", "'timePassed'", "]", "=", "$", "eventTime", "->", "diffForHumans", "(", ")", ";", "$", "collectionItem", "[", "'userAgentDetails'", "]", "=", "UserAgentDetails", "::", "details", "(", "$", "collectionItem", "->", "useragent", ")", ";", "$", "collectionItem", "[", "'langDetails'", "]", "=", "UserAgentDetails", "::", "localeLang", "(", "$", "collectionItem", "->", "locale", ")", ";", "$", "collectionItem", "[", "'userDetails'", "]", "=", "config", "(", "'LaravelLogger.defaultUserModel'", ")", "::", "find", "(", "$", "collectionItem", "->", "userId", ")", ";", "return", "$", "collectionItem", ";", "}", ")", ";", "return", "$", "collectionItems", ";", "}" ]
Add additional details to a collections. @param collection $collectionItems @return collection
[ "Add", "additional", "details", "to", "a", "collections", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L46-L59
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.showAccessLogEntry
public function showAccessLogEntry(Request $request, $id) { $activity = Activity::findOrFail($id); $userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId); $userAgentDetails = UserAgentDetails::details($activity->useragent); $ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress); $langDetails = UserAgentDetails::localeLang($activity->locale); $eventTime = Carbon::parse($activity->created_at); $timePassed = $eventTime->diffForHumans(); if (config('LaravelLogger.loggerPaginationEnabled')) { $userActivities = Activity::where('userId', $activity->userId) ->orderBy('created_at', 'desc') ->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalUserActivities = $userActivities->total(); } else { $userActivities = Activity::where('userId', $activity->userId) ->orderBy('created_at', 'desc') ->get(); $totalUserActivities = $userActivities->count(); } self::mapAdditionalDetails($userActivities); $data = [ 'activity' => $activity, 'userDetails' => $userDetails, 'ipAddressDetails' => $ipAddressDetails, 'timePassed' => $timePassed, 'userAgentDetails' => $userAgentDetails, 'langDetails' => $langDetails, 'userActivities' => $userActivities, 'totalUserActivities' => $totalUserActivities, 'isClearedEntry' => false, ]; return View('LaravelLogger::logger.activity-log-item', $data); }
php
public function showAccessLogEntry(Request $request, $id) { $activity = Activity::findOrFail($id); $userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId); $userAgentDetails = UserAgentDetails::details($activity->useragent); $ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress); $langDetails = UserAgentDetails::localeLang($activity->locale); $eventTime = Carbon::parse($activity->created_at); $timePassed = $eventTime->diffForHumans(); if (config('LaravelLogger.loggerPaginationEnabled')) { $userActivities = Activity::where('userId', $activity->userId) ->orderBy('created_at', 'desc') ->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalUserActivities = $userActivities->total(); } else { $userActivities = Activity::where('userId', $activity->userId) ->orderBy('created_at', 'desc') ->get(); $totalUserActivities = $userActivities->count(); } self::mapAdditionalDetails($userActivities); $data = [ 'activity' => $activity, 'userDetails' => $userDetails, 'ipAddressDetails' => $ipAddressDetails, 'timePassed' => $timePassed, 'userAgentDetails' => $userAgentDetails, 'langDetails' => $langDetails, 'userActivities' => $userActivities, 'totalUserActivities' => $totalUserActivities, 'isClearedEntry' => false, ]; return View('LaravelLogger::logger.activity-log-item', $data); }
[ "public", "function", "showAccessLogEntry", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "activity", "=", "Activity", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "userDetails", "=", "config", "(", "'LaravelLogger.defaultUserModel'", ")", "::", "find", "(", "$", "activity", "->", "userId", ")", ";", "$", "userAgentDetails", "=", "UserAgentDetails", "::", "details", "(", "$", "activity", "->", "useragent", ")", ";", "$", "ipAddressDetails", "=", "IpAddressDetails", "::", "checkIP", "(", "$", "activity", "->", "ipAddress", ")", ";", "$", "langDetails", "=", "UserAgentDetails", "::", "localeLang", "(", "$", "activity", "->", "locale", ")", ";", "$", "eventTime", "=", "Carbon", "::", "parse", "(", "$", "activity", "->", "created_at", ")", ";", "$", "timePassed", "=", "$", "eventTime", "->", "diffForHumans", "(", ")", ";", "if", "(", "config", "(", "'LaravelLogger.loggerPaginationEnabled'", ")", ")", "{", "$", "userActivities", "=", "Activity", "::", "where", "(", "'userId'", ",", "$", "activity", "->", "userId", ")", "->", "orderBy", "(", "'created_at'", ",", "'desc'", ")", "->", "paginate", "(", "config", "(", "'LaravelLogger.loggerPaginationPerPage'", ")", ")", ";", "$", "totalUserActivities", "=", "$", "userActivities", "->", "total", "(", ")", ";", "}", "else", "{", "$", "userActivities", "=", "Activity", "::", "where", "(", "'userId'", ",", "$", "activity", "->", "userId", ")", "->", "orderBy", "(", "'created_at'", ",", "'desc'", ")", "->", "get", "(", ")", ";", "$", "totalUserActivities", "=", "$", "userActivities", "->", "count", "(", ")", ";", "}", "self", "::", "mapAdditionalDetails", "(", "$", "userActivities", ")", ";", "$", "data", "=", "[", "'activity'", "=>", "$", "activity", ",", "'userDetails'", "=>", "$", "userDetails", ",", "'ipAddressDetails'", "=>", "$", "ipAddressDetails", ",", "'timePassed'", "=>", "$", "timePassed", ",", "'userAgentDetails'", "=>", "$", "userAgentDetails", ",", "'langDetails'", "=>", "$", "langDetails", ",", "'userActivities'", "=>", "$", "userActivities", ",", "'totalUserActivities'", "=>", "$", "totalUserActivities", ",", "'isClearedEntry'", "=>", "false", ",", "]", ";", "return", "View", "(", "'LaravelLogger::logger.activity-log-item'", ",", "$", "data", ")", ";", "}" ]
Show an individual activity log entry. @param Request $request @param int $id @return \Illuminate\Http\Response
[ "Show", "an", "individual", "activity", "log", "entry", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L94-L132
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.clearActivityLog
public function clearActivityLog(Request $request) { $activities = Activity::all(); foreach ($activities as $activity) { $activity->delete(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logClearedSuccessfuly')); }
php
public function clearActivityLog(Request $request) { $activities = Activity::all(); foreach ($activities as $activity) { $activity->delete(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logClearedSuccessfuly')); }
[ "public", "function", "clearActivityLog", "(", "Request", "$", "request", ")", "{", "$", "activities", "=", "Activity", "::", "all", "(", ")", ";", "foreach", "(", "$", "activities", "as", "$", "activity", ")", "{", "$", "activity", "->", "delete", "(", ")", ";", "}", "return", "redirect", "(", "'activity'", ")", "->", "with", "(", "'success'", ",", "trans", "(", "'LaravelLogger::laravel-logger.messages.logClearedSuccessfuly'", ")", ")", ";", "}" ]
Remove the specified resource from storage. @param Request $request @return \Illuminate\Http\Response
[ "Remove", "the", "specified", "resource", "from", "storage", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L141-L149
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.showClearedActivityLog
public function showClearedActivityLog() { if (config('LaravelLogger.loggerPaginationEnabled')) { $activities = Activity::onlyTrashed() ->orderBy('created_at', 'desc') ->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalActivities = $activities->total(); } else { $activities = Activity::onlyTrashed() ->orderBy('created_at', 'desc') ->get(); $totalActivities = $activities->count(); } self::mapAdditionalDetails($activities); $data = [ 'activities' => $activities, 'totalActivities' => $totalActivities, ]; return View('LaravelLogger::logger.activity-log-cleared', $data); }
php
public function showClearedActivityLog() { if (config('LaravelLogger.loggerPaginationEnabled')) { $activities = Activity::onlyTrashed() ->orderBy('created_at', 'desc') ->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalActivities = $activities->total(); } else { $activities = Activity::onlyTrashed() ->orderBy('created_at', 'desc') ->get(); $totalActivities = $activities->count(); } self::mapAdditionalDetails($activities); $data = [ 'activities' => $activities, 'totalActivities' => $totalActivities, ]; return View('LaravelLogger::logger.activity-log-cleared', $data); }
[ "public", "function", "showClearedActivityLog", "(", ")", "{", "if", "(", "config", "(", "'LaravelLogger.loggerPaginationEnabled'", ")", ")", "{", "$", "activities", "=", "Activity", "::", "onlyTrashed", "(", ")", "->", "orderBy", "(", "'created_at'", ",", "'desc'", ")", "->", "paginate", "(", "config", "(", "'LaravelLogger.loggerPaginationPerPage'", ")", ")", ";", "$", "totalActivities", "=", "$", "activities", "->", "total", "(", ")", ";", "}", "else", "{", "$", "activities", "=", "Activity", "::", "onlyTrashed", "(", ")", "->", "orderBy", "(", "'created_at'", ",", "'desc'", ")", "->", "get", "(", ")", ";", "$", "totalActivities", "=", "$", "activities", "->", "count", "(", ")", ";", "}", "self", "::", "mapAdditionalDetails", "(", "$", "activities", ")", ";", "$", "data", "=", "[", "'activities'", "=>", "$", "activities", ",", "'totalActivities'", "=>", "$", "totalActivities", ",", "]", ";", "return", "View", "(", "'LaravelLogger::logger.activity-log-cleared'", ",", "$", "data", ")", ";", "}" ]
Show the cleared activity log - softdeleted records. @return \Illuminate\Http\Response
[ "Show", "the", "cleared", "activity", "log", "-", "softdeleted", "records", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L156-L178
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.showClearedAccessLogEntry
public function showClearedAccessLogEntry(Request $request, $id) { $activity = self::getClearedActvity($id); $userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId); $userAgentDetails = UserAgentDetails::details($activity->useragent); $ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress); $langDetails = UserAgentDetails::localeLang($activity->locale); $eventTime = Carbon::parse($activity->created_at); $timePassed = $eventTime->diffForHumans(); $data = [ 'activity' => $activity, 'userDetails' => $userDetails, 'ipAddressDetails' => $ipAddressDetails, 'timePassed' => $timePassed, 'userAgentDetails' => $userAgentDetails, 'langDetails' => $langDetails, 'isClearedEntry' => true, ]; return View('LaravelLogger::logger.activity-log-item', $data); }
php
public function showClearedAccessLogEntry(Request $request, $id) { $activity = self::getClearedActvity($id); $userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId); $userAgentDetails = UserAgentDetails::details($activity->useragent); $ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress); $langDetails = UserAgentDetails::localeLang($activity->locale); $eventTime = Carbon::parse($activity->created_at); $timePassed = $eventTime->diffForHumans(); $data = [ 'activity' => $activity, 'userDetails' => $userDetails, 'ipAddressDetails' => $ipAddressDetails, 'timePassed' => $timePassed, 'userAgentDetails' => $userAgentDetails, 'langDetails' => $langDetails, 'isClearedEntry' => true, ]; return View('LaravelLogger::logger.activity-log-item', $data); }
[ "public", "function", "showClearedAccessLogEntry", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "activity", "=", "self", "::", "getClearedActvity", "(", "$", "id", ")", ";", "$", "userDetails", "=", "config", "(", "'LaravelLogger.defaultUserModel'", ")", "::", "find", "(", "$", "activity", "->", "userId", ")", ";", "$", "userAgentDetails", "=", "UserAgentDetails", "::", "details", "(", "$", "activity", "->", "useragent", ")", ";", "$", "ipAddressDetails", "=", "IpAddressDetails", "::", "checkIP", "(", "$", "activity", "->", "ipAddress", ")", ";", "$", "langDetails", "=", "UserAgentDetails", "::", "localeLang", "(", "$", "activity", "->", "locale", ")", ";", "$", "eventTime", "=", "Carbon", "::", "parse", "(", "$", "activity", "->", "created_at", ")", ";", "$", "timePassed", "=", "$", "eventTime", "->", "diffForHumans", "(", ")", ";", "$", "data", "=", "[", "'activity'", "=>", "$", "activity", ",", "'userDetails'", "=>", "$", "userDetails", ",", "'ipAddressDetails'", "=>", "$", "ipAddressDetails", ",", "'timePassed'", "=>", "$", "timePassed", ",", "'userAgentDetails'", "=>", "$", "userAgentDetails", ",", "'langDetails'", "=>", "$", "langDetails", ",", "'isClearedEntry'", "=>", "true", ",", "]", ";", "return", "View", "(", "'LaravelLogger::logger.activity-log-item'", ",", "$", "data", ")", ";", "}" ]
Show an individual cleared (soft deleted) activity log entry. @param Request $request @param int $id @return \Illuminate\Http\Response
[ "Show", "an", "individual", "cleared", "(", "soft", "deleted", ")", "activity", "log", "entry", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L188-L210
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.getClearedActvity
private static function getClearedActvity($id) { $activity = Activity::onlyTrashed()->where('id', $id)->get(); if (count($activity) != 1) { return abort(404); } return $activity[0]; }
php
private static function getClearedActvity($id) { $activity = Activity::onlyTrashed()->where('id', $id)->get(); if (count($activity) != 1) { return abort(404); } return $activity[0]; }
[ "private", "static", "function", "getClearedActvity", "(", "$", "id", ")", "{", "$", "activity", "=", "Activity", "::", "onlyTrashed", "(", ")", "->", "where", "(", "'id'", ",", "$", "id", ")", "->", "get", "(", ")", ";", "if", "(", "count", "(", "$", "activity", ")", "!=", "1", ")", "{", "return", "abort", "(", "404", ")", ";", "}", "return", "$", "activity", "[", "0", "]", ";", "}" ]
Get Cleared (Soft Deleted) Activity - Helper Method. @param int $id @return \Illuminate\Http\Response
[ "Get", "Cleared", "(", "Soft", "Deleted", ")", "Activity", "-", "Helper", "Method", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L219-L227
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.destroyActivityLog
public function destroyActivityLog(Request $request) { $activities = Activity::onlyTrashed()->get(); foreach ($activities as $activity) { $activity->forceDelete(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly')); }
php
public function destroyActivityLog(Request $request) { $activities = Activity::onlyTrashed()->get(); foreach ($activities as $activity) { $activity->forceDelete(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly')); }
[ "public", "function", "destroyActivityLog", "(", "Request", "$", "request", ")", "{", "$", "activities", "=", "Activity", "::", "onlyTrashed", "(", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "activities", "as", "$", "activity", ")", "{", "$", "activity", "->", "forceDelete", "(", ")", ";", "}", "return", "redirect", "(", "'activity'", ")", "->", "with", "(", "'success'", ",", "trans", "(", "'LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly'", ")", ")", ";", "}" ]
Destroy the specified resource from storage. @param Request $request @return \Illuminate\Http\Response
[ "Destroy", "the", "specified", "resource", "from", "storage", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L236-L244
jeremykenedy/laravel-logger
src/app/Http/Controllers/LaravelLoggerController.php
LaravelLoggerController.restoreClearedActivityLog
public function restoreClearedActivityLog(Request $request) { $activities = Activity::onlyTrashed()->get(); foreach ($activities as $activity) { $activity->restore(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly')); }
php
public function restoreClearedActivityLog(Request $request) { $activities = Activity::onlyTrashed()->get(); foreach ($activities as $activity) { $activity->restore(); } return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly')); }
[ "public", "function", "restoreClearedActivityLog", "(", "Request", "$", "request", ")", "{", "$", "activities", "=", "Activity", "::", "onlyTrashed", "(", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "activities", "as", "$", "activity", ")", "{", "$", "activity", "->", "restore", "(", ")", ";", "}", "return", "redirect", "(", "'activity'", ")", "->", "with", "(", "'success'", ",", "trans", "(", "'LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly'", ")", ")", ";", "}" ]
Restore the specified resource from soft deleted storage. @param Request $request @return \Illuminate\Http\Response
[ "Restore", "the", "specified", "resource", "from", "soft", "deleted", "storage", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L253-L261
jeremykenedy/laravel-logger
src/app/Http/Traits/UserAgentDetails.php
UserAgentDetails.details
public static function details($ua) { $ua = is_null($ua) ? $_SERVER['HTTP_USER_AGENT'] : $ua; // Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..) $platforms = 'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux'; // All browsers except MSIE/Trident and.. // NOT for browsers that use this syntax: Version/0.xx Browsername $browsers = 'Firefox|Chrome|Opera'; // Specifically for browsers that use this syntax: Version/0.xx Browername $browsers_v = 'Safari|Mobile'; // Mobile is mentioned in Android and BlackBerry UA's // Fill in your most common engines.. $engines = 'Gecko|Trident|Webkit|Presto'; // Regex the crap out of the user agent, making multiple selections and.. $regex_pat = "/((Mozilla)\/[\d\.]+|(Opera)\/[\d\.]+)\s\(.*?((MSIE)\s([\d\.]+).*?(Windows)|({$platforms})).*?\s.*?({$engines})[\/\s]+[\d\.]+(\;\srv\:([\d\.]+)|.*?).*?(Version[\/\s]([\d\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\/\s]+([\d\.]+))|$).*/i"; // .. placing them in this order, delimited by | $replace_pat = '$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}'; // Run the preg_replace .. and explode on | $ua_array = explode('|', preg_replace($regex_pat, $replace_pat, $ua, PREG_PATTERN_ORDER)); if (count($ua_array) > 1) { $return['platform'] = $ua_array[0]; // Windows / iPad / MacOS / BlackBerry $return['type'] = $ua_array[1]; // Mozilla / Opera etc. $return['renderer'] = $ua_array[2]; // WebKit / Presto / Trident / Gecko etc. $return['browser'] = $ua_array[3]; // Chrome / Safari / MSIE / Firefox /* Not necessary but this will filter out Chromes ridiculously long version numbers 31.0.1234.122 becomes 31.0, while a "normal" 3 digit version number like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is. */ if (preg_match("/^[\d]+\.[\d]+(?:\.[\d]{0,2}$)?/", $ua_array[4], $matches)) { $return['version'] = $matches[0]; } else { $return['version'] = $ua_array[4]; } } else { return false; } // Replace some browsernames e.g. MSIE -> Internet Explorer switch (strtolower($return['browser'])) { case 'msie': case 'trident': $return['browser'] = 'Internet Explorer'; break; case '': // IE 11 is a steamy turd (thanks Microsoft...) if (strtolower($return['renderer']) == 'trident') { $return['browser'] = 'Internet Explorer'; } break; } switch (strtolower($return['platform'])) { case 'android': // These browsers claim to be Safari but are BB Mobile case 'blackberry': // and Android Mobile if ($return['browser'] == 'Safari' || $return['browser'] == 'Mobile' || $return['browser'] == '') { $return['browser'] = "{$return['platform']} mobile"; } break; } return $return; }
php
public static function details($ua) { $ua = is_null($ua) ? $_SERVER['HTTP_USER_AGENT'] : $ua; $platforms = 'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux'; $browsers = 'Firefox|Chrome|Opera'; $browsers_v = 'Safari|Mobile'; $engines = 'Gecko|Trident|Webkit|Presto'; $regex_pat = "/((Mozilla)\/[\d\.]+|(Opera)\/[\d\.]+)\s\(.*?((MSIE)\s([\d\.]+).*?(Windows)|({$platforms})).*?\s.*?({$engines})[\/\s]+[\d\.]+(\;\srv\:([\d\.]+)|.*?).*?(Version[\/\s]([\d\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\/\s]+([\d\.]+))|$).*/i"; $replace_pat = '$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}'; $ua_array = explode('|', preg_replace($regex_pat, $replace_pat, $ua, PREG_PATTERN_ORDER)); if (count($ua_array) > 1) { $return['platform'] = $ua_array[0]; $return['type'] = $ua_array[1]; $return['renderer'] = $ua_array[2]; $return['browser'] = $ua_array[3]; if (preg_match("/^[\d]+\.[\d]+(?:\.[\d]{0,2}$)?/", $ua_array[4], $matches)) { $return['version'] = $matches[0]; } else { $return['version'] = $ua_array[4]; } } else { return false; } switch (strtolower($return['browser'])) { case 'msie': case 'trident': $return['browser'] = 'Internet Explorer'; break; case '': if (strtolower($return['renderer']) == 'trident') { $return['browser'] = 'Internet Explorer'; } break; } switch (strtolower($return['platform'])) { case 'android': case 'blackberry': if ($return['browser'] == 'Safari' || $return['browser'] == 'Mobile' || $return['browser'] == '') { $return['browser'] = "{$return['platform']} mobile"; } break; } return $return; }
[ "public", "static", "function", "details", "(", "$", "ua", ")", "{", "$", "ua", "=", "is_null", "(", "$", "ua", ")", "?", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ":", "$", "ua", ";", "// Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..)", "$", "platforms", "=", "'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux'", ";", "// All browsers except MSIE/Trident and..", "// NOT for browsers that use this syntax: Version/0.xx Browsername", "$", "browsers", "=", "'Firefox|Chrome|Opera'", ";", "// Specifically for browsers that use this syntax: Version/0.xx Browername", "$", "browsers_v", "=", "'Safari|Mobile'", ";", "// Mobile is mentioned in Android and BlackBerry UA's", "// Fill in your most common engines..", "$", "engines", "=", "'Gecko|Trident|Webkit|Presto'", ";", "// Regex the crap out of the user agent, making multiple selections and..", "$", "regex_pat", "=", "\"/((Mozilla)\\/[\\d\\.]+|(Opera)\\/[\\d\\.]+)\\s\\(.*?((MSIE)\\s([\\d\\.]+).*?(Windows)|({$platforms})).*?\\s.*?({$engines})[\\/\\s]+[\\d\\.]+(\\;\\srv\\:([\\d\\.]+)|.*?).*?(Version[\\/\\s]([\\d\\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\\/\\s]+([\\d\\.]+))|$).*/i\"", ";", "// .. placing them in this order, delimited by |", "$", "replace_pat", "=", "'$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}'", ";", "// Run the preg_replace .. and explode on |", "$", "ua_array", "=", "explode", "(", "'|'", ",", "preg_replace", "(", "$", "regex_pat", ",", "$", "replace_pat", ",", "$", "ua", ",", "PREG_PATTERN_ORDER", ")", ")", ";", "if", "(", "count", "(", "$", "ua_array", ")", ">", "1", ")", "{", "$", "return", "[", "'platform'", "]", "=", "$", "ua_array", "[", "0", "]", ";", "// Windows / iPad / MacOS / BlackBerry", "$", "return", "[", "'type'", "]", "=", "$", "ua_array", "[", "1", "]", ";", "// Mozilla / Opera etc.", "$", "return", "[", "'renderer'", "]", "=", "$", "ua_array", "[", "2", "]", ";", "// WebKit / Presto / Trident / Gecko etc.", "$", "return", "[", "'browser'", "]", "=", "$", "ua_array", "[", "3", "]", ";", "// Chrome / Safari / MSIE / Firefox", "/*\n Not necessary but this will filter out Chromes ridiculously long version\n numbers 31.0.1234.122 becomes 31.0, while a \"normal\" 3 digit version number\n like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is.\n */", "if", "(", "preg_match", "(", "\"/^[\\d]+\\.[\\d]+(?:\\.[\\d]{0,2}$)?/\"", ",", "$", "ua_array", "[", "4", "]", ",", "$", "matches", ")", ")", "{", "$", "return", "[", "'version'", "]", "=", "$", "matches", "[", "0", "]", ";", "}", "else", "{", "$", "return", "[", "'version'", "]", "=", "$", "ua_array", "[", "4", "]", ";", "}", "}", "else", "{", "return", "false", ";", "}", "// Replace some browsernames e.g. MSIE -> Internet Explorer", "switch", "(", "strtolower", "(", "$", "return", "[", "'browser'", "]", ")", ")", "{", "case", "'msie'", ":", "case", "'trident'", ":", "$", "return", "[", "'browser'", "]", "=", "'Internet Explorer'", ";", "break", ";", "case", "''", ":", "// IE 11 is a steamy turd (thanks Microsoft...)", "if", "(", "strtolower", "(", "$", "return", "[", "'renderer'", "]", ")", "==", "'trident'", ")", "{", "$", "return", "[", "'browser'", "]", "=", "'Internet Explorer'", ";", "}", "break", ";", "}", "switch", "(", "strtolower", "(", "$", "return", "[", "'platform'", "]", ")", ")", "{", "case", "'android'", ":", "// These browsers claim to be Safari but are BB Mobile", "case", "'blackberry'", ":", "// and Android Mobile", "if", "(", "$", "return", "[", "'browser'", "]", "==", "'Safari'", "||", "$", "return", "[", "'browser'", "]", "==", "'Mobile'", "||", "$", "return", "[", "'browser'", "]", "==", "''", ")", "{", "$", "return", "[", "'browser'", "]", "=", "\"{$return['platform']} mobile\"", ";", "}", "break", ";", "}", "return", "$", "return", ";", "}" ]
Get the user's agents details. @param $ua @return array
[ "Get", "the", "user", "s", "agents", "details", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/UserAgentDetails.php#L14-L82
jeremykenedy/laravel-logger
src/app/Http/Traits/IpAddressDetails.php
IpAddressDetails.checkIP
public static function checkIP($ip = null, $purpose = 'location', $deep_detect = true) { $output = null; if (filter_var($ip, FILTER_VALIDATE_IP) === false) { $ip = $_SERVER['REMOTE_ADDR']; if ($deep_detect) { if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) { $ip = $_SERVER['HTTP_CLIENT_IP']; } } } $purpose = str_replace(['name', "\n", "\t", ' ', '-', '_'], null, strtolower(trim($purpose))); $support = ['country', 'countrycode', 'state', 'region', 'city', 'location', 'address']; $continents = [ 'AF' => 'Africa', 'AN' => 'Antarctica', 'AS' => 'Asia', 'EU' => 'Europe', 'OC' => 'Australia (Oceania)', 'NA' => 'North America', 'SA' => 'South America', ]; if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) { $ipdat = @json_decode(file_get_contents('http://www.geoplugin.net/json.gp?ip='.$ip)); if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) { switch ($purpose) { case 'location': $output = [ 'city' => @$ipdat->geoplugin_city, 'state' => @$ipdat->geoplugin_regionName, 'country' => @$ipdat->geoplugin_countryName, 'countryCode' => @$ipdat->geoplugin_countryCode, 'continent' => @$continents[strtoupper($ipdat->geoplugin_continentCode)], 'continent_code' => @$ipdat->geoplugin_continentCode, 'latitude' => @$ipdat->geoplugin_latitude, 'longitude' => @$ipdat->geoplugin_longitude, 'currencyCode' => @$ipdat->geoplugin_currencyCode, 'areaCode' => @$ipdat->geoplugin_areaCode, 'dmaCode' => @$ipdat->geoplugin_dmaCode, 'region' => @$ipdat->geoplugin_region, ]; break; case 'address': $address = [$ipdat->geoplugin_countryName]; if (@strlen($ipdat->geoplugin_regionName) >= 1) { $address[] = $ipdat->geoplugin_regionName; } if (@strlen($ipdat->geoplugin_city) >= 1) { $address[] = $ipdat->geoplugin_city; } $output = implode(', ', array_reverse($address)); break; case 'city': $output = @$ipdat->geoplugin_city; break; case 'state': $output = @$ipdat->geoplugin_regionName; break; case 'region': $output = @$ipdat->geoplugin_regionName; break; case 'country': $output = @$ipdat->geoplugin_countryName; break; case 'countrycode': $output = @$ipdat->geoplugin_countryCode; break; } } } return $output; }
php
public static function checkIP($ip = null, $purpose = 'location', $deep_detect = true) { $output = null; if (filter_var($ip, FILTER_VALIDATE_IP) === false) { $ip = $_SERVER['REMOTE_ADDR']; if ($deep_detect) { if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) { $ip = $_SERVER['HTTP_CLIENT_IP']; } } } $purpose = str_replace(['name', "\n", "\t", ' ', '-', '_'], null, strtolower(trim($purpose))); $support = ['country', 'countrycode', 'state', 'region', 'city', 'location', 'address']; $continents = [ 'AF' => 'Africa', 'AN' => 'Antarctica', 'AS' => 'Asia', 'EU' => 'Europe', 'OC' => 'Australia (Oceania)', 'NA' => 'North America', 'SA' => 'South America', ]; if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) { $ipdat = @json_decode(file_get_contents('http: if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) { switch ($purpose) { case 'location': $output = [ 'city' => @$ipdat->geoplugin_city, 'state' => @$ipdat->geoplugin_regionName, 'country' => @$ipdat->geoplugin_countryName, 'countryCode' => @$ipdat->geoplugin_countryCode, 'continent' => @$continents[strtoupper($ipdat->geoplugin_continentCode)], 'continent_code' => @$ipdat->geoplugin_continentCode, 'latitude' => @$ipdat->geoplugin_latitude, 'longitude' => @$ipdat->geoplugin_longitude, 'currencyCode' => @$ipdat->geoplugin_currencyCode, 'areaCode' => @$ipdat->geoplugin_areaCode, 'dmaCode' => @$ipdat->geoplugin_dmaCode, 'region' => @$ipdat->geoplugin_region, ]; break; case 'address': $address = [$ipdat->geoplugin_countryName]; if (@strlen($ipdat->geoplugin_regionName) >= 1) { $address[] = $ipdat->geoplugin_regionName; } if (@strlen($ipdat->geoplugin_city) >= 1) { $address[] = $ipdat->geoplugin_city; } $output = implode(', ', array_reverse($address)); break; case 'city': $output = @$ipdat->geoplugin_city; break; case 'state': $output = @$ipdat->geoplugin_regionName; break; case 'region': $output = @$ipdat->geoplugin_regionName; break; case 'country': $output = @$ipdat->geoplugin_countryName; break; case 'countrycode': $output = @$ipdat->geoplugin_countryCode; break; } } } return $output; }
[ "public", "static", "function", "checkIP", "(", "$", "ip", "=", "null", ",", "$", "purpose", "=", "'location'", ",", "$", "deep_detect", "=", "true", ")", "{", "$", "output", "=", "null", ";", "if", "(", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP", ")", "===", "false", ")", "{", "$", "ip", "=", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", ";", "if", "(", "$", "deep_detect", ")", "{", "if", "(", "filter_var", "(", "@", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ",", "FILTER_VALIDATE_IP", ")", ")", "{", "$", "ip", "=", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_FOR'", "]", ";", "}", "if", "(", "filter_var", "(", "@", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ",", "FILTER_VALIDATE_IP", ")", ")", "{", "$", "ip", "=", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ";", "}", "}", "}", "$", "purpose", "=", "str_replace", "(", "[", "'name'", ",", "\"\\n\"", ",", "\"\\t\"", ",", "' '", ",", "'-'", ",", "'_'", "]", ",", "null", ",", "strtolower", "(", "trim", "(", "$", "purpose", ")", ")", ")", ";", "$", "support", "=", "[", "'country'", ",", "'countrycode'", ",", "'state'", ",", "'region'", ",", "'city'", ",", "'location'", ",", "'address'", "]", ";", "$", "continents", "=", "[", "'AF'", "=>", "'Africa'", ",", "'AN'", "=>", "'Antarctica'", ",", "'AS'", "=>", "'Asia'", ",", "'EU'", "=>", "'Europe'", ",", "'OC'", "=>", "'Australia (Oceania)'", ",", "'NA'", "=>", "'North America'", ",", "'SA'", "=>", "'South America'", ",", "]", ";", "if", "(", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP", ")", "&&", "in_array", "(", "$", "purpose", ",", "$", "support", ")", ")", "{", "$", "ipdat", "=", "@", "json_decode", "(", "file_get_contents", "(", "'http://www.geoplugin.net/json.gp?ip='", ".", "$", "ip", ")", ")", ";", "if", "(", "@", "strlen", "(", "trim", "(", "$", "ipdat", "->", "geoplugin_countryCode", ")", ")", "==", "2", ")", "{", "switch", "(", "$", "purpose", ")", "{", "case", "'location'", ":", "$", "output", "=", "[", "'city'", "=>", "@", "$", "ipdat", "->", "geoplugin_city", ",", "'state'", "=>", "@", "$", "ipdat", "->", "geoplugin_regionName", ",", "'country'", "=>", "@", "$", "ipdat", "->", "geoplugin_countryName", ",", "'countryCode'", "=>", "@", "$", "ipdat", "->", "geoplugin_countryCode", ",", "'continent'", "=>", "@", "$", "continents", "[", "strtoupper", "(", "$", "ipdat", "->", "geoplugin_continentCode", ")", "]", ",", "'continent_code'", "=>", "@", "$", "ipdat", "->", "geoplugin_continentCode", ",", "'latitude'", "=>", "@", "$", "ipdat", "->", "geoplugin_latitude", ",", "'longitude'", "=>", "@", "$", "ipdat", "->", "geoplugin_longitude", ",", "'currencyCode'", "=>", "@", "$", "ipdat", "->", "geoplugin_currencyCode", ",", "'areaCode'", "=>", "@", "$", "ipdat", "->", "geoplugin_areaCode", ",", "'dmaCode'", "=>", "@", "$", "ipdat", "->", "geoplugin_dmaCode", ",", "'region'", "=>", "@", "$", "ipdat", "->", "geoplugin_region", ",", "]", ";", "break", ";", "case", "'address'", ":", "$", "address", "=", "[", "$", "ipdat", "->", "geoplugin_countryName", "]", ";", "if", "(", "@", "strlen", "(", "$", "ipdat", "->", "geoplugin_regionName", ")", ">=", "1", ")", "{", "$", "address", "[", "]", "=", "$", "ipdat", "->", "geoplugin_regionName", ";", "}", "if", "(", "@", "strlen", "(", "$", "ipdat", "->", "geoplugin_city", ")", ">=", "1", ")", "{", "$", "address", "[", "]", "=", "$", "ipdat", "->", "geoplugin_city", ";", "}", "$", "output", "=", "implode", "(", "', '", ",", "array_reverse", "(", "$", "address", ")", ")", ";", "break", ";", "case", "'city'", ":", "$", "output", "=", "@", "$", "ipdat", "->", "geoplugin_city", ";", "break", ";", "case", "'state'", ":", "$", "output", "=", "@", "$", "ipdat", "->", "geoplugin_regionName", ";", "break", ";", "case", "'region'", ":", "$", "output", "=", "@", "$", "ipdat", "->", "geoplugin_regionName", ";", "break", ";", "case", "'country'", ":", "$", "output", "=", "@", "$", "ipdat", "->", "geoplugin_countryName", ";", "break", ";", "case", "'countrycode'", ":", "$", "output", "=", "@", "$", "ipdat", "->", "geoplugin_countryCode", ";", "break", ";", "}", "}", "}", "return", "$", "output", ";", "}" ]
Get the Location of the IP Address. @param string $ip (optional, no value will always return NULL) @param string $purpose (optional) @param bool $deep_detect (optional) @return string
[ "Get", "the", "Location", "of", "the", "IP", "Address", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/IpAddressDetails.php#L16-L91
jeremykenedy/laravel-logger
src/app/Http/Traits/ActivityLogger.php
ActivityLogger.activity
public static function activity($description = null) { $userType = trans('LaravelLogger::laravel-logger.userTypes.guest'); $userId = null; if (\Auth::check()) { $userType = trans('LaravelLogger::laravel-logger.userTypes.registered'); $userId = \Request::user()->id; } if (Crawler::isCrawler()) { $userType = trans('LaravelLogger::laravel-logger.userTypes.crawler'); $description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.\Request::fullUrl(); } if (!$description) { switch (strtolower(\Request::method())) { case 'post': $verb = trans('LaravelLogger::laravel-logger.verbTypes.created'); break; case 'patch': case 'put': $verb = trans('LaravelLogger::laravel-logger.verbTypes.edited'); break; case 'delete': $verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted'); break; case 'get': default: $verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed'); break; } $description = $verb.' '.\Request::path(); } $data = [ 'description' => $description, 'userType' => $userType, 'userId' => $userId, 'route' => \Request::fullUrl(), 'ipAddress' => \Request::ip(), 'userAgent' => \Request::header('user-agent'), 'locale' => \Request::header('accept-language'), 'referer' => \Request::header('referer'), 'methodType' => \Request::method(), ]; // Validation Instance $validator = Validator::make($data, Activity::Rules([])); if ($validator->fails()) { $errors = self::prepareErrorMessage($validator->errors(), $data); if (config('LaravelLogger.logDBActivityLogFailuresToFile')) { Log::error('Failed to record activity event. Failed Validation: '.$errors); } } else { self::storeActivity($data); } }
php
public static function activity($description = null) { $userType = trans('LaravelLogger::laravel-logger.userTypes.guest'); $userId = null; if (\Auth::check()) { $userType = trans('LaravelLogger::laravel-logger.userTypes.registered'); $userId = \Request::user()->id; } if (Crawler::isCrawler()) { $userType = trans('LaravelLogger::laravel-logger.userTypes.crawler'); $description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.\Request::fullUrl(); } if (!$description) { switch (strtolower(\Request::method())) { case 'post': $verb = trans('LaravelLogger::laravel-logger.verbTypes.created'); break; case 'patch': case 'put': $verb = trans('LaravelLogger::laravel-logger.verbTypes.edited'); break; case 'delete': $verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted'); break; case 'get': default: $verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed'); break; } $description = $verb.' '.\Request::path(); } $data = [ 'description' => $description, 'userType' => $userType, 'userId' => $userId, 'route' => \Request::fullUrl(), 'ipAddress' => \Request::ip(), 'userAgent' => \Request::header('user-agent'), 'locale' => \Request::header('accept-language'), 'referer' => \Request::header('referer'), 'methodType' => \Request::method(), ]; $validator = Validator::make($data, Activity::Rules([])); if ($validator->fails()) { $errors = self::prepareErrorMessage($validator->errors(), $data); if (config('LaravelLogger.logDBActivityLogFailuresToFile')) { Log::error('Failed to record activity event. Failed Validation: '.$errors); } } else { self::storeActivity($data); } }
[ "public", "static", "function", "activity", "(", "$", "description", "=", "null", ")", "{", "$", "userType", "=", "trans", "(", "'LaravelLogger::laravel-logger.userTypes.guest'", ")", ";", "$", "userId", "=", "null", ";", "if", "(", "\\", "Auth", "::", "check", "(", ")", ")", "{", "$", "userType", "=", "trans", "(", "'LaravelLogger::laravel-logger.userTypes.registered'", ")", ";", "$", "userId", "=", "\\", "Request", "::", "user", "(", ")", "->", "id", ";", "}", "if", "(", "Crawler", "::", "isCrawler", "(", ")", ")", "{", "$", "userType", "=", "trans", "(", "'LaravelLogger::laravel-logger.userTypes.crawler'", ")", ";", "$", "description", "=", "$", "userType", ".", "' '", ".", "trans", "(", "'LaravelLogger::laravel-logger.verbTypes.crawled'", ")", ".", "' '", ".", "\\", "Request", "::", "fullUrl", "(", ")", ";", "}", "if", "(", "!", "$", "description", ")", "{", "switch", "(", "strtolower", "(", "\\", "Request", "::", "method", "(", ")", ")", ")", "{", "case", "'post'", ":", "$", "verb", "=", "trans", "(", "'LaravelLogger::laravel-logger.verbTypes.created'", ")", ";", "break", ";", "case", "'patch'", ":", "case", "'put'", ":", "$", "verb", "=", "trans", "(", "'LaravelLogger::laravel-logger.verbTypes.edited'", ")", ";", "break", ";", "case", "'delete'", ":", "$", "verb", "=", "trans", "(", "'LaravelLogger::laravel-logger.verbTypes.deleted'", ")", ";", "break", ";", "case", "'get'", ":", "default", ":", "$", "verb", "=", "trans", "(", "'LaravelLogger::laravel-logger.verbTypes.viewed'", ")", ";", "break", ";", "}", "$", "description", "=", "$", "verb", ".", "' '", ".", "\\", "Request", "::", "path", "(", ")", ";", "}", "$", "data", "=", "[", "'description'", "=>", "$", "description", ",", "'userType'", "=>", "$", "userType", ",", "'userId'", "=>", "$", "userId", ",", "'route'", "=>", "\\", "Request", "::", "fullUrl", "(", ")", ",", "'ipAddress'", "=>", "\\", "Request", "::", "ip", "(", ")", ",", "'userAgent'", "=>", "\\", "Request", "::", "header", "(", "'user-agent'", ")", ",", "'locale'", "=>", "\\", "Request", "::", "header", "(", "'accept-language'", ")", ",", "'referer'", "=>", "\\", "Request", "::", "header", "(", "'referer'", ")", ",", "'methodType'", "=>", "\\", "Request", "::", "method", "(", ")", ",", "]", ";", "// Validation Instance", "$", "validator", "=", "Validator", "::", "make", "(", "$", "data", ",", "Activity", "::", "Rules", "(", "[", "]", ")", ")", ";", "if", "(", "$", "validator", "->", "fails", "(", ")", ")", "{", "$", "errors", "=", "self", "::", "prepareErrorMessage", "(", "$", "validator", "->", "errors", "(", ")", ",", "$", "data", ")", ";", "if", "(", "config", "(", "'LaravelLogger.logDBActivityLogFailuresToFile'", ")", ")", "{", "Log", "::", "error", "(", "'Failed to record activity event. Failed Validation: '", ".", "$", "errors", ")", ";", "}", "}", "else", "{", "self", "::", "storeActivity", "(", "$", "data", ")", ";", "}", "}" ]
Laravel Logger Log Activity. @param string $description @return void
[ "Laravel", "Logger", "Log", "Activity", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/ActivityLogger.php#L19-L80
jeremykenedy/laravel-logger
src/app/Http/Traits/ActivityLogger.php
ActivityLogger.storeActivity
private static function storeActivity($data) { Activity::create([ 'description' => $data['description'], 'userType' => $data['userType'], 'userId' => $data['userId'], 'route' => $data['route'], 'ipAddress' => $data['ipAddress'], 'userAgent' => $data['userAgent'], 'locale' => $data['locale'], 'referer' => $data['referer'], 'methodType' => $data['methodType'], ]); }
php
private static function storeActivity($data) { Activity::create([ 'description' => $data['description'], 'userType' => $data['userType'], 'userId' => $data['userId'], 'route' => $data['route'], 'ipAddress' => $data['ipAddress'], 'userAgent' => $data['userAgent'], 'locale' => $data['locale'], 'referer' => $data['referer'], 'methodType' => $data['methodType'], ]); }
[ "private", "static", "function", "storeActivity", "(", "$", "data", ")", "{", "Activity", "::", "create", "(", "[", "'description'", "=>", "$", "data", "[", "'description'", "]", ",", "'userType'", "=>", "$", "data", "[", "'userType'", "]", ",", "'userId'", "=>", "$", "data", "[", "'userId'", "]", ",", "'route'", "=>", "$", "data", "[", "'route'", "]", ",", "'ipAddress'", "=>", "$", "data", "[", "'ipAddress'", "]", ",", "'userAgent'", "=>", "$", "data", "[", "'userAgent'", "]", ",", "'locale'", "=>", "$", "data", "[", "'locale'", "]", ",", "'referer'", "=>", "$", "data", "[", "'referer'", "]", ",", "'methodType'", "=>", "$", "data", "[", "'methodType'", "]", ",", "]", ")", ";", "}" ]
Store activity entry to database. @param array $data @return void
[ "Store", "activity", "entry", "to", "database", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/ActivityLogger.php#L89-L102
jeremykenedy/laravel-logger
src/app/Http/Traits/ActivityLogger.php
ActivityLogger.prepareErrorMessage
private static function prepareErrorMessage($validatorErrors, $data) { $errors = json_decode(json_encode($validatorErrors, true)); array_walk($errors, function (&$value, $key) use ($data) { array_push($value, "Value: $data[$key]"); }); return json_encode($errors, true); }
php
private static function prepareErrorMessage($validatorErrors, $data) { $errors = json_decode(json_encode($validatorErrors, true)); array_walk($errors, function (&$value, $key) use ($data) { array_push($value, "Value: $data[$key]"); }); return json_encode($errors, true); }
[ "private", "static", "function", "prepareErrorMessage", "(", "$", "validatorErrors", ",", "$", "data", ")", "{", "$", "errors", "=", "json_decode", "(", "json_encode", "(", "$", "validatorErrors", ",", "true", ")", ")", ";", "array_walk", "(", "$", "errors", ",", "function", "(", "&", "$", "value", ",", "$", "key", ")", "use", "(", "$", "data", ")", "{", "array_push", "(", "$", "value", ",", "\"Value: $data[$key]\"", ")", ";", "}", ")", ";", "return", "json_encode", "(", "$", "errors", ",", "true", ")", ";", "}" ]
Prepare Error Message (add the actual value of the error field). @param $validator @param $data @return string
[ "Prepare", "Error", "Message", "(", "add", "the", "actual", "value", "of", "the", "error", "field", ")", "." ]
train
https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/ActivityLogger.php#L112-L120
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.process
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $scheme = $request->getUri()->getScheme(); $host = $request->getUri()->getHost(); /* If rules say we should not authenticate call next and return. */ if (false === $this->shouldAuthenticate($request)) { return $handler->handle($request); } /* HTTP allowed only if secure is false or server is in relaxed array. */ if ("https" !== $scheme && true === $this->options["secure"]) { if (!in_array($host, $this->options["relaxed"])) { $message = sprintf( "Insecure use of middleware over %s denied by configuration.", strtoupper($scheme) ); throw new RuntimeException($message); } } /* If token cannot be found or decoded return with 401 Unauthorized. */ try { $token = $this->fetchToken($request); $decoded = $this->decodeToken($token); } catch (RuntimeException | DomainException $exception) { $response = (new ResponseFactory)->createResponse(401); return $this->processError($response, [ "message" => $exception->getMessage(), "uri" => (string)$request->getUri() ]); } $params = ["decoded" => $decoded]; /* Add decoded token to request as attribute when requested. */ if ($this->options["attribute"]) { $request = $request->withAttribute($this->options["attribute"], $decoded); } /* Modify $request before calling next middleware. */ if (is_callable($this->options["before"])) { $response = (new ResponseFactory)->createResponse(200); $beforeRequest = $this->options["before"]($request, $params); if ($beforeRequest instanceof ServerRequestInterface) { $request = $beforeRequest; } } /* Everything ok, call next middleware. */ $response = $handler->handle($request); /* Modify $response before returning. */ if (is_callable($this->options["after"])) { $afterResponse = $this->options["after"]($response, $params); if ($afterResponse instanceof ResponseInterface) { return $afterResponse; } } return $response; }
php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $scheme = $request->getUri()->getScheme(); $host = $request->getUri()->getHost(); if (false === $this->shouldAuthenticate($request)) { return $handler->handle($request); } if ("https" !== $scheme && true === $this->options["secure"]) { if (!in_array($host, $this->options["relaxed"])) { $message = sprintf( "Insecure use of middleware over %s denied by configuration.", strtoupper($scheme) ); throw new RuntimeException($message); } } try { $token = $this->fetchToken($request); $decoded = $this->decodeToken($token); } catch (RuntimeException | DomainException $exception) { $response = (new ResponseFactory)->createResponse(401); return $this->processError($response, [ "message" => $exception->getMessage(), "uri" => (string)$request->getUri() ]); } $params = ["decoded" => $decoded]; if ($this->options["attribute"]) { $request = $request->withAttribute($this->options["attribute"], $decoded); } if (is_callable($this->options["before"])) { $response = (new ResponseFactory)->createResponse(200); $beforeRequest = $this->options["before"]($request, $params); if ($beforeRequest instanceof ServerRequestInterface) { $request = $beforeRequest; } } $response = $handler->handle($request); if (is_callable($this->options["after"])) { $afterResponse = $this->options["after"]($response, $params); if ($afterResponse instanceof ResponseInterface) { return $afterResponse; } } return $response; }
[ "public", "function", "process", "(", "ServerRequestInterface", "$", "request", ",", "RequestHandlerInterface", "$", "handler", ")", ":", "ResponseInterface", "{", "$", "scheme", "=", "$", "request", "->", "getUri", "(", ")", "->", "getScheme", "(", ")", ";", "$", "host", "=", "$", "request", "->", "getUri", "(", ")", "->", "getHost", "(", ")", ";", "/* If rules say we should not authenticate call next and return. */", "if", "(", "false", "===", "$", "this", "->", "shouldAuthenticate", "(", "$", "request", ")", ")", "{", "return", "$", "handler", "->", "handle", "(", "$", "request", ")", ";", "}", "/* HTTP allowed only if secure is false or server is in relaxed array. */", "if", "(", "\"https\"", "!==", "$", "scheme", "&&", "true", "===", "$", "this", "->", "options", "[", "\"secure\"", "]", ")", "{", "if", "(", "!", "in_array", "(", "$", "host", ",", "$", "this", "->", "options", "[", "\"relaxed\"", "]", ")", ")", "{", "$", "message", "=", "sprintf", "(", "\"Insecure use of middleware over %s denied by configuration.\"", ",", "strtoupper", "(", "$", "scheme", ")", ")", ";", "throw", "new", "RuntimeException", "(", "$", "message", ")", ";", "}", "}", "/* If token cannot be found or decoded return with 401 Unauthorized. */", "try", "{", "$", "token", "=", "$", "this", "->", "fetchToken", "(", "$", "request", ")", ";", "$", "decoded", "=", "$", "this", "->", "decodeToken", "(", "$", "token", ")", ";", "}", "catch", "(", "RuntimeException", "|", "DomainException", "$", "exception", ")", "{", "$", "response", "=", "(", "new", "ResponseFactory", ")", "->", "createResponse", "(", "401", ")", ";", "return", "$", "this", "->", "processError", "(", "$", "response", ",", "[", "\"message\"", "=>", "$", "exception", "->", "getMessage", "(", ")", ",", "\"uri\"", "=>", "(", "string", ")", "$", "request", "->", "getUri", "(", ")", "]", ")", ";", "}", "$", "params", "=", "[", "\"decoded\"", "=>", "$", "decoded", "]", ";", "/* Add decoded token to request as attribute when requested. */", "if", "(", "$", "this", "->", "options", "[", "\"attribute\"", "]", ")", "{", "$", "request", "=", "$", "request", "->", "withAttribute", "(", "$", "this", "->", "options", "[", "\"attribute\"", "]", ",", "$", "decoded", ")", ";", "}", "/* Modify $request before calling next middleware. */", "if", "(", "is_callable", "(", "$", "this", "->", "options", "[", "\"before\"", "]", ")", ")", "{", "$", "response", "=", "(", "new", "ResponseFactory", ")", "->", "createResponse", "(", "200", ")", ";", "$", "beforeRequest", "=", "$", "this", "->", "options", "[", "\"before\"", "]", "(", "$", "request", ",", "$", "params", ")", ";", "if", "(", "$", "beforeRequest", "instanceof", "ServerRequestInterface", ")", "{", "$", "request", "=", "$", "beforeRequest", ";", "}", "}", "/* Everything ok, call next middleware. */", "$", "response", "=", "$", "handler", "->", "handle", "(", "$", "request", ")", ";", "/* Modify $response before returning. */", "if", "(", "is_callable", "(", "$", "this", "->", "options", "[", "\"after\"", "]", ")", ")", "{", "$", "afterResponse", "=", "$", "this", "->", "options", "[", "\"after\"", "]", "(", "$", "response", ",", "$", "params", ")", ";", "if", "(", "$", "afterResponse", "instanceof", "ResponseInterface", ")", "{", "return", "$", "afterResponse", ";", "}", "}", "return", "$", "response", ";", "}" ]
Process a request in PSR-15 style and return a response.
[ "Process", "a", "request", "in", "PSR", "-", "15", "style", "and", "return", "a", "response", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L116-L177
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.withRules
public function withRules(array $rules): self { $new = clone $this; /* Clear the stack */ unset($new->rules); $new->rules = new \SplStack; /* Add the rules */ foreach ($rules as $callable) { $new = $new->addRule($callable); } return $new; }
php
public function withRules(array $rules): self { $new = clone $this; unset($new->rules); $new->rules = new \SplStack; foreach ($rules as $callable) { $new = $new->addRule($callable); } return $new; }
[ "public", "function", "withRules", "(", "array", "$", "rules", ")", ":", "self", "{", "$", "new", "=", "clone", "$", "this", ";", "/* Clear the stack */", "unset", "(", "$", "new", "->", "rules", ")", ";", "$", "new", "->", "rules", "=", "new", "\\", "SplStack", ";", "/* Add the rules */", "foreach", "(", "$", "rules", "as", "$", "callable", ")", "{", "$", "new", "=", "$", "new", "->", "addRule", "(", "$", "callable", ")", ";", "}", "return", "$", "new", ";", "}" ]
Set all rules in the stack.
[ "Set", "all", "rules", "in", "the", "stack", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L182-L193
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.shouldAuthenticate
private function shouldAuthenticate(ServerRequestInterface $request): bool { /* If any of the rules in stack return false will not authenticate */ foreach ($this->rules as $callable) { if (false === $callable($request)) { return false; } } return true; }
php
private function shouldAuthenticate(ServerRequestInterface $request): bool { foreach ($this->rules as $callable) { if (false === $callable($request)) { return false; } } return true; }
[ "private", "function", "shouldAuthenticate", "(", "ServerRequestInterface", "$", "request", ")", ":", "bool", "{", "/* If any of the rules in stack return false will not authenticate */", "foreach", "(", "$", "this", "->", "rules", "as", "$", "callable", ")", "{", "if", "(", "false", "===", "$", "callable", "(", "$", "request", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if middleware should authenticate.
[ "Check", "if", "middleware", "should", "authenticate", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L209-L218
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.processError
private function processError(ResponseInterface $response, array $arguments): ResponseInterface { if (is_callable($this->options["error"])) { $handlerResponse = $this->options["error"]($response, $arguments); if ($handlerResponse instanceof ResponseInterface) { return $handlerResponse; } } return $response; }
php
private function processError(ResponseInterface $response, array $arguments): ResponseInterface { if (is_callable($this->options["error"])) { $handlerResponse = $this->options["error"]($response, $arguments); if ($handlerResponse instanceof ResponseInterface) { return $handlerResponse; } } return $response; }
[ "private", "function", "processError", "(", "ResponseInterface", "$", "response", ",", "array", "$", "arguments", ")", ":", "ResponseInterface", "{", "if", "(", "is_callable", "(", "$", "this", "->", "options", "[", "\"error\"", "]", ")", ")", "{", "$", "handlerResponse", "=", "$", "this", "->", "options", "[", "\"error\"", "]", "(", "$", "response", ",", "$", "arguments", ")", ";", "if", "(", "$", "handlerResponse", "instanceof", "ResponseInterface", ")", "{", "return", "$", "handlerResponse", ";", "}", "}", "return", "$", "response", ";", "}" ]
Call the error handler if it exists.
[ "Call", "the", "error", "handler", "if", "it", "exists", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L223-L232
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.fetchToken
private function fetchToken(ServerRequestInterface $request): string { /* Check for token in header. */ $header = $request->getHeaderLine($this->options["header"]); if (false === empty($header)) { if (preg_match($this->options["regexp"], $header, $matches)) { $this->log(LogLevel::DEBUG, "Using token from request header"); return $matches[1]; } } /* Token not found in header try a cookie. */ $cookieParams = $request->getCookieParams(); if (isset($cookieParams[$this->options["cookie"]])) { $this->log(LogLevel::DEBUG, "Using token from cookie"); return $cookieParams[$this->options["cookie"]]; }; /* If everything fails log and throw. */ $this->log(LogLevel::WARNING, "Token not found"); throw new RuntimeException("Token not found."); }
php
private function fetchToken(ServerRequestInterface $request): string { $header = $request->getHeaderLine($this->options["header"]); if (false === empty($header)) { if (preg_match($this->options["regexp"], $header, $matches)) { $this->log(LogLevel::DEBUG, "Using token from request header"); return $matches[1]; } } $cookieParams = $request->getCookieParams(); if (isset($cookieParams[$this->options["cookie"]])) { $this->log(LogLevel::DEBUG, "Using token from cookie"); return $cookieParams[$this->options["cookie"]]; }; $this->log(LogLevel::WARNING, "Token not found"); throw new RuntimeException("Token not found."); }
[ "private", "function", "fetchToken", "(", "ServerRequestInterface", "$", "request", ")", ":", "string", "{", "/* Check for token in header. */", "$", "header", "=", "$", "request", "->", "getHeaderLine", "(", "$", "this", "->", "options", "[", "\"header\"", "]", ")", ";", "if", "(", "false", "===", "empty", "(", "$", "header", ")", ")", "{", "if", "(", "preg_match", "(", "$", "this", "->", "options", "[", "\"regexp\"", "]", ",", "$", "header", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "DEBUG", ",", "\"Using token from request header\"", ")", ";", "return", "$", "matches", "[", "1", "]", ";", "}", "}", "/* Token not found in header try a cookie. */", "$", "cookieParams", "=", "$", "request", "->", "getCookieParams", "(", ")", ";", "if", "(", "isset", "(", "$", "cookieParams", "[", "$", "this", "->", "options", "[", "\"cookie\"", "]", "]", ")", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "DEBUG", ",", "\"Using token from cookie\"", ")", ";", "return", "$", "cookieParams", "[", "$", "this", "->", "options", "[", "\"cookie\"", "]", "]", ";", "}", ";", "/* If everything fails log and throw. */", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "\"Token not found\"", ")", ";", "throw", "new", "RuntimeException", "(", "\"Token not found.\"", ")", ";", "}" ]
Fetch the access token.
[ "Fetch", "the", "access", "token", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L237-L260
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.decodeToken
private function decodeToken(string $token): array { try { $decoded = JWT::decode( $token, $this->options["secret"], (array) $this->options["algorithm"] ); return (array) $decoded; } catch (Exception $exception) { $this->log(LogLevel::WARNING, $exception->getMessage(), [$token]); throw $exception; } }
php
private function decodeToken(string $token): array { try { $decoded = JWT::decode( $token, $this->options["secret"], (array) $this->options["algorithm"] ); return (array) $decoded; } catch (Exception $exception) { $this->log(LogLevel::WARNING, $exception->getMessage(), [$token]); throw $exception; } }
[ "private", "function", "decodeToken", "(", "string", "$", "token", ")", ":", "array", "{", "try", "{", "$", "decoded", "=", "JWT", "::", "decode", "(", "$", "token", ",", "$", "this", "->", "options", "[", "\"secret\"", "]", ",", "(", "array", ")", "$", "this", "->", "options", "[", "\"algorithm\"", "]", ")", ";", "return", "(", "array", ")", "$", "decoded", ";", "}", "catch", "(", "Exception", "$", "exception", ")", "{", "$", "this", "->", "log", "(", "LogLevel", "::", "WARNING", ",", "$", "exception", "->", "getMessage", "(", ")", ",", "[", "$", "token", "]", ")", ";", "throw", "$", "exception", ";", "}", "}" ]
Decode the token.
[ "Decode", "the", "token", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L265-L278
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.secret
private function secret($secret): void { if (false === is_array($secret) && false === is_string($secret)) { throw new InvalidArgumentException( 'Secret must be either a string or an array of "kid" => "secret" pairs' ); } $this->options["secret"] = $secret; }
php
private function secret($secret): void { if (false === is_array($secret) && false === is_string($secret)) { throw new InvalidArgumentException( 'Secret must be either a string or an array of "kid" => "secret" pairs' ); } $this->options["secret"] = $secret; }
[ "private", "function", "secret", "(", "$", "secret", ")", ":", "void", "{", "if", "(", "false", "===", "is_array", "(", "$", "secret", ")", "&&", "false", "===", "is_string", "(", "$", "secret", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Secret must be either a string or an array of \"kid\" => \"secret\" pairs'", ")", ";", "}", "$", "this", "->", "options", "[", "\"secret\"", "]", "=", "$", "secret", ";", "}" ]
Set the secret key.
[ "Set", "the", "secret", "key", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L343-L351
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.error
private function error(callable $error): void { if ($error instanceof Closure) { $this->options["error"] = $error->bindTo($this); } else { $this->options["error"] = $error; } }
php
private function error(callable $error): void { if ($error instanceof Closure) { $this->options["error"] = $error->bindTo($this); } else { $this->options["error"] = $error; } }
[ "private", "function", "error", "(", "callable", "$", "error", ")", ":", "void", "{", "if", "(", "$", "error", "instanceof", "Closure", ")", "{", "$", "this", "->", "options", "[", "\"error\"", "]", "=", "$", "error", "->", "bindTo", "(", "$", "this", ")", ";", "}", "else", "{", "$", "this", "->", "options", "[", "\"error\"", "]", "=", "$", "error", ";", "}", "}" ]
Set the error handler.
[ "Set", "the", "error", "handler", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L356-L363
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.before
private function before(callable $before): void { if ($before instanceof Closure) { $this->options["before"] = $before->bindTo($this); } else { $this->options["before"] = $before; } }
php
private function before(callable $before): void { if ($before instanceof Closure) { $this->options["before"] = $before->bindTo($this); } else { $this->options["before"] = $before; } }
[ "private", "function", "before", "(", "callable", "$", "before", ")", ":", "void", "{", "if", "(", "$", "before", "instanceof", "Closure", ")", "{", "$", "this", "->", "options", "[", "\"before\"", "]", "=", "$", "before", "->", "bindTo", "(", "$", "this", ")", ";", "}", "else", "{", "$", "this", "->", "options", "[", "\"before\"", "]", "=", "$", "before", ";", "}", "}" ]
Set the before handler.
[ "Set", "the", "before", "handler", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L419-L426
tuupola/slim-jwt-auth
src/JwtAuthentication.php
JwtAuthentication.after
private function after(callable $after): void { if ($after instanceof Closure) { $this->options["after"] = $after->bindTo($this); } else { $this->options["after"] = $after; } }
php
private function after(callable $after): void { if ($after instanceof Closure) { $this->options["after"] = $after->bindTo($this); } else { $this->options["after"] = $after; } }
[ "private", "function", "after", "(", "callable", "$", "after", ")", ":", "void", "{", "if", "(", "$", "after", "instanceof", "Closure", ")", "{", "$", "this", "->", "options", "[", "\"after\"", "]", "=", "$", "after", "->", "bindTo", "(", "$", "this", ")", ";", "}", "else", "{", "$", "this", "->", "options", "[", "\"after\"", "]", "=", "$", "after", ";", "}", "}" ]
Set the after handler.
[ "Set", "the", "after", "handler", "." ]
train
https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L431-L438
Imangazaliev/DiDOM
src/DiDom/Errors.php
Errors.restore
public static function restore($clear = true) { if ($clear) { libxml_clear_errors(); } libxml_use_internal_errors(self::$internalErrors); libxml_disable_entity_loader(self::$disableEntities); }
php
public static function restore($clear = true) { if ($clear) { libxml_clear_errors(); } libxml_use_internal_errors(self::$internalErrors); libxml_disable_entity_loader(self::$disableEntities); }
[ "public", "static", "function", "restore", "(", "$", "clear", "=", "true", ")", "{", "if", "(", "$", "clear", ")", "{", "libxml_clear_errors", "(", ")", ";", "}", "libxml_use_internal_errors", "(", "self", "::", "$", "internalErrors", ")", ";", "libxml_disable_entity_loader", "(", "self", "::", "$", "disableEntities", ")", ";", "}" ]
Restore error reporting. @param bool $clear
[ "Restore", "error", "reporting", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Errors.php#L31-L39
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.parseStyleAttribute
protected function parseStyleAttribute() { if (!$this->element->hasAttribute('style')) { // possible if style attribute has been removed if ($this->styleString !== '') { $this->styleString = ''; $this->properties = []; } return; } // if style attribute is not changed if ($this->element->getAttribute('style') === $this->styleString) { return; } // save style attribute as is (without trimming) $this->styleString = $this->element->getAttribute('style'); $styleString = trim($this->styleString, ' ;'); if ($styleString === '') { $this->properties = []; return; } $properties = explode(';', $styleString); foreach ($properties as $property) { list($name, $value) = explode(':', $property); $name = trim($name); $value = trim($value); $this->properties[$name] = $value; } }
php
protected function parseStyleAttribute() { if (!$this->element->hasAttribute('style')) { if ($this->styleString !== '') { $this->styleString = ''; $this->properties = []; } return; } if ($this->element->getAttribute('style') === $this->styleString) { return; } $this->styleString = $this->element->getAttribute('style'); $styleString = trim($this->styleString, ' ;'); if ($styleString === '') { $this->properties = []; return; } $properties = explode(';', $styleString); foreach ($properties as $property) { list($name, $value) = explode(':', $property); $name = trim($name); $value = trim($value); $this->properties[$name] = $value; } }
[ "protected", "function", "parseStyleAttribute", "(", ")", "{", "if", "(", "!", "$", "this", "->", "element", "->", "hasAttribute", "(", "'style'", ")", ")", "{", "// possible if style attribute has been removed", "if", "(", "$", "this", "->", "styleString", "!==", "''", ")", "{", "$", "this", "->", "styleString", "=", "''", ";", "$", "this", "->", "properties", "=", "[", "]", ";", "}", "return", ";", "}", "// if style attribute is not changed", "if", "(", "$", "this", "->", "element", "->", "getAttribute", "(", "'style'", ")", "===", "$", "this", "->", "styleString", ")", "{", "return", ";", "}", "// save style attribute as is (without trimming)", "$", "this", "->", "styleString", "=", "$", "this", "->", "element", "->", "getAttribute", "(", "'style'", ")", ";", "$", "styleString", "=", "trim", "(", "$", "this", "->", "styleString", ",", "' ;'", ")", ";", "if", "(", "$", "styleString", "===", "''", ")", "{", "$", "this", "->", "properties", "=", "[", "]", ";", "return", ";", "}", "$", "properties", "=", "explode", "(", "';'", ",", "$", "styleString", ")", ";", "foreach", "(", "$", "properties", "as", "$", "property", ")", "{", "list", "(", "$", "name", ",", "$", "value", ")", "=", "explode", "(", "':'", ",", "$", "property", ")", ";", "$", "name", "=", "trim", "(", "$", "name", ")", ";", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "$", "this", "->", "properties", "[", "$", "name", "]", "=", "$", "value", ";", "}", "}" ]
Parses style attribute of the element.
[ "Parses", "style", "attribute", "of", "the", "element", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L47-L85
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.updateStyleAttribute
protected function updateStyleAttribute() { $this->styleString = $this->buildStyleString(); $this->element->setAttribute('style', $this->styleString); }
php
protected function updateStyleAttribute() { $this->styleString = $this->buildStyleString(); $this->element->setAttribute('style', $this->styleString); }
[ "protected", "function", "updateStyleAttribute", "(", ")", "{", "$", "this", "->", "styleString", "=", "$", "this", "->", "buildStyleString", "(", ")", ";", "$", "this", "->", "element", "->", "setAttribute", "(", "'style'", ",", "$", "this", "->", "styleString", ")", ";", "}" ]
Updates style attribute of the element.
[ "Updates", "style", "attribute", "of", "the", "element", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L90-L95
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.setProperty
public function setProperty($name, $value) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } if (!is_string($value)) { throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value)))); } $this->parseStyleAttribute(); $this->properties[$name] = $value; $this->updateStyleAttribute(); return $this; }
php
public function setProperty($name, $value) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } if (!is_string($value)) { throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value)))); } $this->parseStyleAttribute(); $this->properties[$name] = $value; $this->updateStyleAttribute(); return $this; }
[ "public", "function", "setProperty", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 1 to be string, %s given'", ",", "__METHOD__", ",", "(", "is_object", "(", "$", "name", ")", "?", "get_class", "(", "$", "name", ")", ":", "gettype", "(", "$", "name", ")", ")", ")", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 2 to be string, %s given'", ",", "__METHOD__", ",", "(", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ")", ")", ")", ";", "}", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "$", "this", "->", "properties", "[", "$", "name", "]", "=", "$", "value", ";", "$", "this", "->", "updateStyleAttribute", "(", ")", ";", "return", "$", "this", ";", "}" ]
@param string $name @param string $value @return \DiDom\StyleAttribute @throws \InvalidArgumentException if property name is not a string @throws \InvalidArgumentException if property value is not a string
[ "@param", "string", "$name", "@param", "string", "$value" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L120-L137
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.setMultipleProperties
public function setMultipleProperties(array $properties) { $this->parseStyleAttribute(); foreach ($properties as $propertyName => $value) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (!is_string($value)) { throw new InvalidArgumentException(sprintf('Property value must be a string, %s given', (is_object($value) ? get_class($value) : gettype($value)))); } $this->properties[$propertyName] = $value; } $this->updateStyleAttribute(); return $this; }
php
public function setMultipleProperties(array $properties) { $this->parseStyleAttribute(); foreach ($properties as $propertyName => $value) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (!is_string($value)) { throw new InvalidArgumentException(sprintf('Property value must be a string, %s given', (is_object($value) ? get_class($value) : gettype($value)))); } $this->properties[$propertyName] = $value; } $this->updateStyleAttribute(); return $this; }
[ "public", "function", "setMultipleProperties", "(", "array", "$", "properties", ")", "{", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "foreach", "(", "$", "properties", "as", "$", "propertyName", "=>", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "propertyName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property name must be a string, %s given'", ",", "(", "is_object", "(", "$", "propertyName", ")", "?", "get_class", "(", "$", "propertyName", ")", ":", "gettype", "(", "$", "propertyName", ")", ")", ")", ")", ";", "}", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property value must be a string, %s given'", ",", "(", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ")", ")", ")", ";", "}", "$", "this", "->", "properties", "[", "$", "propertyName", "]", "=", "$", "value", ";", "}", "$", "this", "->", "updateStyleAttribute", "(", ")", ";", "return", "$", "this", ";", "}" ]
@param array $properties @return \DiDom\StyleAttribute @throws \InvalidArgumentException if property name is not a string @throws \InvalidArgumentException if property value is not a string
[ "@param", "array", "$properties" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L147-L166
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.getProperty
public function getProperty($name, $default = null) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } $this->parseStyleAttribute(); if (!array_key_exists($name, $this->properties)) { return $default; } return $this->properties[$name]; }
php
public function getProperty($name, $default = null) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } $this->parseStyleAttribute(); if (!array_key_exists($name, $this->properties)) { return $default; } return $this->properties[$name]; }
[ "public", "function", "getProperty", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 1 to be string, %s given'", ",", "__METHOD__", ",", "(", "is_object", "(", "$", "name", ")", "?", "get_class", "(", "$", "name", ")", ":", "gettype", "(", "$", "name", ")", ")", ")", ")", ";", "}", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "properties", ")", ")", "{", "return", "$", "default", ";", "}", "return", "$", "this", "->", "properties", "[", "$", "name", "]", ";", "}" ]
@param string $name @param mixed $default @return mixed
[ "@param", "string", "$name", "@param", "mixed", "$default" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L174-L187
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.getMultipleProperties
public function getMultipleProperties(array $propertyNames) { $this->parseStyleAttribute(); $result = []; foreach ($propertyNames as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (array_key_exists($propertyName, $this->properties)) { $result[$propertyName] = $this->properties[$propertyName]; } } return $result; }
php
public function getMultipleProperties(array $propertyNames) { $this->parseStyleAttribute(); $result = []; foreach ($propertyNames as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (array_key_exists($propertyName, $this->properties)) { $result[$propertyName] = $this->properties[$propertyName]; } } return $result; }
[ "public", "function", "getMultipleProperties", "(", "array", "$", "propertyNames", ")", "{", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "propertyNames", "as", "$", "propertyName", ")", "{", "if", "(", "!", "is_string", "(", "$", "propertyName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property name must be a string, %s given'", ",", "(", "is_object", "(", "$", "propertyName", ")", "?", "get_class", "(", "$", "propertyName", ")", ":", "gettype", "(", "$", "propertyName", ")", ")", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", "propertyName", ",", "$", "this", "->", "properties", ")", ")", "{", "$", "result", "[", "$", "propertyName", "]", "=", "$", "this", "->", "properties", "[", "$", "propertyName", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
@param array $propertyNames @return mixed @throws \InvalidArgumentException if property name is not a string
[ "@param", "array", "$propertyNames" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L196-L213
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.removeProperty
public function removeProperty($name) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } $this->parseStyleAttribute(); unset($this->properties[$name]); $this->updateStyleAttribute(); return $this; }
php
public function removeProperty($name) { if (!is_string($name)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($name) ? get_class($name) : gettype($name)))); } $this->parseStyleAttribute(); unset($this->properties[$name]); $this->updateStyleAttribute(); return $this; }
[ "public", "function", "removeProperty", "(", "$", "name", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 1 to be string, %s given'", ",", "__METHOD__", ",", "(", "is_object", "(", "$", "name", ")", "?", "get_class", "(", "$", "name", ")", ":", "gettype", "(", "$", "name", ")", ")", ")", ")", ";", "}", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "unset", "(", "$", "this", "->", "properties", "[", "$", "name", "]", ")", ";", "$", "this", "->", "updateStyleAttribute", "(", ")", ";", "return", "$", "this", ";", "}" ]
@param string $name @return \DiDom\StyleAttribute @throws \InvalidArgumentException if property name is not a string
[ "@param", "string", "$name" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L248-L261
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.removeMultipleProperties
public function removeMultipleProperties(array $propertyNames) { $this->parseStyleAttribute(); foreach ($propertyNames as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } unset($this->properties[$propertyName]); } $this->updateStyleAttribute(); return $this; }
php
public function removeMultipleProperties(array $propertyNames) { $this->parseStyleAttribute(); foreach ($propertyNames as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } unset($this->properties[$propertyName]); } $this->updateStyleAttribute(); return $this; }
[ "public", "function", "removeMultipleProperties", "(", "array", "$", "propertyNames", ")", "{", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "foreach", "(", "$", "propertyNames", "as", "$", "propertyName", ")", "{", "if", "(", "!", "is_string", "(", "$", "propertyName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property name must be a string, %s given'", ",", "(", "is_object", "(", "$", "propertyName", ")", "?", "get_class", "(", "$", "propertyName", ")", ":", "gettype", "(", "$", "propertyName", ")", ")", ")", ")", ";", "}", "unset", "(", "$", "this", "->", "properties", "[", "$", "propertyName", "]", ")", ";", "}", "$", "this", "->", "updateStyleAttribute", "(", ")", ";", "return", "$", "this", ";", "}" ]
@param array $propertyNames @return \DiDom\StyleAttribute @throws \InvalidArgumentException if property name is not a string
[ "@param", "array", "$propertyNames" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L270-L285
Imangazaliev/DiDOM
src/DiDom/StyleAttribute.php
StyleAttribute.removeAllProperties
public function removeAllProperties(array $exclusions = []) { $this->parseStyleAttribute(); $preservedProperties = []; foreach ($exclusions as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (!array_key_exists($propertyName, $this->properties)) { continue; } $preservedProperties[$propertyName] = $this->properties[$propertyName]; } $this->properties = $preservedProperties; $this->updateStyleAttribute(); return $this; }
php
public function removeAllProperties(array $exclusions = []) { $this->parseStyleAttribute(); $preservedProperties = []; foreach ($exclusions as $propertyName) { if (!is_string($propertyName)) { throw new InvalidArgumentException(sprintf('Property name must be a string, %s given', (is_object($propertyName) ? get_class($propertyName) : gettype($propertyName)))); } if (!array_key_exists($propertyName, $this->properties)) { continue; } $preservedProperties[$propertyName] = $this->properties[$propertyName]; } $this->properties = $preservedProperties; $this->updateStyleAttribute(); return $this; }
[ "public", "function", "removeAllProperties", "(", "array", "$", "exclusions", "=", "[", "]", ")", "{", "$", "this", "->", "parseStyleAttribute", "(", ")", ";", "$", "preservedProperties", "=", "[", "]", ";", "foreach", "(", "$", "exclusions", "as", "$", "propertyName", ")", "{", "if", "(", "!", "is_string", "(", "$", "propertyName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Property name must be a string, %s given'", ",", "(", "is_object", "(", "$", "propertyName", ")", "?", "get_class", "(", "$", "propertyName", ")", ":", "gettype", "(", "$", "propertyName", ")", ")", ")", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "propertyName", ",", "$", "this", "->", "properties", ")", ")", "{", "continue", ";", "}", "$", "preservedProperties", "[", "$", "propertyName", "]", "=", "$", "this", "->", "properties", "[", "$", "propertyName", "]", ";", "}", "$", "this", "->", "properties", "=", "$", "preservedProperties", ";", "$", "this", "->", "updateStyleAttribute", "(", ")", ";", "return", "$", "this", ";", "}" ]
@param string[] $exclusions @return \DiDom\StyleAttribute
[ "@param", "string", "[]", "$exclusions" ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L292-L315
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.createBySelector
public static function createBySelector($selector, $value = null, array $attributes = []) { return Document::create()->createElementBySelector($selector, $value, $attributes); }
php
public static function createBySelector($selector, $value = null, array $attributes = []) { return Document::create()->createElementBySelector($selector, $value, $attributes); }
[ "public", "static", "function", "createBySelector", "(", "$", "selector", ",", "$", "value", "=", "null", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "return", "Document", "::", "create", "(", ")", "->", "createElementBySelector", "(", "$", "selector", ",", "$", "value", ",", "$", "attributes", ")", ";", "}" ]
Creates a new element node by CSS selector. @param string $selector @param string|null $value @param array $attributes @return \DiDom\Element
[ "Creates", "a", "new", "element", "node", "by", "CSS", "selector", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L88-L91
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.prependChild
public function prependChild($nodes) { if ($this->node->ownerDocument === null) { throw new LogicException('Can not prepend child to element without owner document'); } $returnArray = true; if (!is_array($nodes)) { $nodes = [$nodes]; $returnArray = false; } $nodes = array_reverse($nodes); $result = []; $referenceNode = $this->node->firstChild; foreach ($nodes as $node) { $result[] = $this->insertBefore($node, $referenceNode); $referenceNode = $this->node->firstChild; } return $returnArray ? $result : $result[0]; }
php
public function prependChild($nodes) { if ($this->node->ownerDocument === null) { throw new LogicException('Can not prepend child to element without owner document'); } $returnArray = true; if (!is_array($nodes)) { $nodes = [$nodes]; $returnArray = false; } $nodes = array_reverse($nodes); $result = []; $referenceNode = $this->node->firstChild; foreach ($nodes as $node) { $result[] = $this->insertBefore($node, $referenceNode); $referenceNode = $this->node->firstChild; } return $returnArray ? $result : $result[0]; }
[ "public", "function", "prependChild", "(", "$", "nodes", ")", "{", "if", "(", "$", "this", "->", "node", "->", "ownerDocument", "===", "null", ")", "{", "throw", "new", "LogicException", "(", "'Can not prepend child to element without owner document'", ")", ";", "}", "$", "returnArray", "=", "true", ";", "if", "(", "!", "is_array", "(", "$", "nodes", ")", ")", "{", "$", "nodes", "=", "[", "$", "nodes", "]", ";", "$", "returnArray", "=", "false", ";", "}", "$", "nodes", "=", "array_reverse", "(", "$", "nodes", ")", ";", "$", "result", "=", "[", "]", ";", "$", "referenceNode", "=", "$", "this", "->", "node", "->", "firstChild", ";", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "$", "result", "[", "]", "=", "$", "this", "->", "insertBefore", "(", "$", "node", ",", "$", "referenceNode", ")", ";", "$", "referenceNode", "=", "$", "this", "->", "node", "->", "firstChild", ";", "}", "return", "$", "returnArray", "?", "$", "result", ":", "$", "result", "[", "0", "]", ";", "}" ]
Adds a new child at the start of the children. @param \DiDom\Element|\DOMNode|array $nodes The prepended child @return \DiDom\Element|\DiDom\Element[] @throws \LogicException if current node has no owner document @throws \InvalidArgumentException if the provided argument is not an instance of \DOMNode or \DiDom\Element
[ "Adds", "a", "new", "child", "at", "the", "start", "of", "the", "children", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L103-L130
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.insertBefore
public function insertBefore($node, $referenceNode = null) { if ($this->node->ownerDocument === null) { throw new LogicException('Can not insert child to element without owner document'); } if ($node instanceof Element) { $node = $node->getNode(); } if (!$node instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node)))); } if ($referenceNode !== null) { if ($referenceNode instanceof Element) { $referenceNode = $referenceNode->getNode(); } if (!$referenceNode instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode)))); } } Errors::disable(); $clonedNode = $node->cloneNode(true); $newNode = $this->node->ownerDocument->importNode($clonedNode, true); $insertedNode = $this->node->insertBefore($newNode, $referenceNode); Errors::restore(); return new Element($insertedNode); }
php
public function insertBefore($node, $referenceNode = null) { if ($this->node->ownerDocument === null) { throw new LogicException('Can not insert child to element without owner document'); } if ($node instanceof Element) { $node = $node->getNode(); } if (!$node instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node)))); } if ($referenceNode !== null) { if ($referenceNode instanceof Element) { $referenceNode = $referenceNode->getNode(); } if (!$referenceNode instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode)))); } } Errors::disable(); $clonedNode = $node->cloneNode(true); $newNode = $this->node->ownerDocument->importNode($clonedNode, true); $insertedNode = $this->node->insertBefore($newNode, $referenceNode); Errors::restore(); return new Element($insertedNode); }
[ "public", "function", "insertBefore", "(", "$", "node", ",", "$", "referenceNode", "=", "null", ")", "{", "if", "(", "$", "this", "->", "node", "->", "ownerDocument", "===", "null", ")", "{", "throw", "new", "LogicException", "(", "'Can not insert child to element without owner document'", ")", ";", "}", "if", "(", "$", "node", "instanceof", "Element", ")", "{", "$", "node", "=", "$", "node", "->", "getNode", "(", ")", ";", "}", "if", "(", "!", "$", "node", "instanceof", "DOMNode", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Argument 1 passed to %s must be an instance of %s\\Element or DOMNode, %s given'", ",", "__METHOD__", ",", "__NAMESPACE__", ",", "(", "is_object", "(", "$", "node", ")", "?", "get_class", "(", "$", "node", ")", ":", "gettype", "(", "$", "node", ")", ")", ")", ")", ";", "}", "if", "(", "$", "referenceNode", "!==", "null", ")", "{", "if", "(", "$", "referenceNode", "instanceof", "Element", ")", "{", "$", "referenceNode", "=", "$", "referenceNode", "->", "getNode", "(", ")", ";", "}", "if", "(", "!", "$", "referenceNode", "instanceof", "DOMNode", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Argument 2 passed to %s must be an instance of %s\\Element or DOMNode, %s given'", ",", "__METHOD__", ",", "__NAMESPACE__", ",", "(", "is_object", "(", "$", "referenceNode", ")", "?", "get_class", "(", "$", "referenceNode", ")", ":", "gettype", "(", "$", "referenceNode", ")", ")", ")", ")", ";", "}", "}", "Errors", "::", "disable", "(", ")", ";", "$", "clonedNode", "=", "$", "node", "->", "cloneNode", "(", "true", ")", ";", "$", "newNode", "=", "$", "this", "->", "node", "->", "ownerDocument", "->", "importNode", "(", "$", "clonedNode", ",", "true", ")", ";", "$", "insertedNode", "=", "$", "this", "->", "node", "->", "insertBefore", "(", "$", "newNode", ",", "$", "referenceNode", ")", ";", "Errors", "::", "restore", "(", ")", ";", "return", "new", "Element", "(", "$", "insertedNode", ")", ";", "}" ]
Adds a new child before a reference node. @param \DiDom\Element|\DOMNode $node The new node @param \DiDom\Element|\DOMNode|null $referenceNode The reference node @return \DiDom\Element @throws \LogicException if current node has no owner document @throws \InvalidArgumentException if $node is not an instance of \DOMNode or \DiDom\Element @throws \InvalidArgumentException if $referenceNode is not an instance of \DOMNode or \DiDom\Element
[ "Adds", "a", "new", "child", "before", "a", "reference", "node", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L196-L230
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.insertAfter
public function insertAfter($node, $referenceNode = null) { if ($referenceNode === null) { return $this->insertBefore($node); } if ($referenceNode instanceof Element) { $referenceNode = $referenceNode->getNode(); } if (!$referenceNode instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode)))); } return $this->insertBefore($node, $referenceNode->nextSibling); }
php
public function insertAfter($node, $referenceNode = null) { if ($referenceNode === null) { return $this->insertBefore($node); } if ($referenceNode instanceof Element) { $referenceNode = $referenceNode->getNode(); } if (!$referenceNode instanceof DOMNode) { throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode)))); } return $this->insertBefore($node, $referenceNode->nextSibling); }
[ "public", "function", "insertAfter", "(", "$", "node", ",", "$", "referenceNode", "=", "null", ")", "{", "if", "(", "$", "referenceNode", "===", "null", ")", "{", "return", "$", "this", "->", "insertBefore", "(", "$", "node", ")", ";", "}", "if", "(", "$", "referenceNode", "instanceof", "Element", ")", "{", "$", "referenceNode", "=", "$", "referenceNode", "->", "getNode", "(", ")", ";", "}", "if", "(", "!", "$", "referenceNode", "instanceof", "DOMNode", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Argument 2 passed to %s must be an instance of %s\\Element or DOMNode, %s given'", ",", "__METHOD__", ",", "__NAMESPACE__", ",", "(", "is_object", "(", "$", "referenceNode", ")", "?", "get_class", "(", "$", "referenceNode", ")", ":", "gettype", "(", "$", "referenceNode", ")", ")", ")", ")", ";", "}", "return", "$", "this", "->", "insertBefore", "(", "$", "node", ",", "$", "referenceNode", "->", "nextSibling", ")", ";", "}" ]
Adds a new child after a reference node. @param \DiDom\Element|\DOMNode $node The new node @param \DiDom\Element|\DOMNode|null $referenceNode The reference node @return \DiDom\Element @throws \LogicException if current node has no owner document @throws \InvalidArgumentException if $node is not an instance of \DOMNode or \DiDom\Element @throws \InvalidArgumentException if $referenceNode is not an instance of \DOMNode or \DiDom\Element
[ "Adds", "a", "new", "child", "after", "a", "reference", "node", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L244-L259
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.has
public function has($expression, $type = Query::TYPE_CSS) { return $this->toDocument()->has($expression, $type); }
php
public function has($expression, $type = Query::TYPE_CSS) { return $this->toDocument()->has($expression, $type); }
[ "public", "function", "has", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ")", "{", "return", "$", "this", "->", "toDocument", "(", ")", "->", "has", "(", "$", "expression", ",", "$", "type", ")", ";", "}" ]
Checks the existence of the node. @param string $expression XPath expression or CSS selector @param string $type The type of the expression @return bool
[ "Checks", "the", "existence", "of", "the", "node", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L269-L272
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.find
public function find($expression, $type = Query::TYPE_CSS, $wrapElement = true) { return $this->toDocument()->find($expression, $type, $wrapElement); }
php
public function find($expression, $type = Query::TYPE_CSS, $wrapElement = true) { return $this->toDocument()->find($expression, $type, $wrapElement); }
[ "public", "function", "find", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ",", "$", "wrapElement", "=", "true", ")", "{", "return", "$", "this", "->", "toDocument", "(", ")", "->", "find", "(", "$", "expression", ",", "$", "type", ",", "$", "wrapElement", ")", ";", "}" ]
Searches for an node in the DOM tree for a given XPath expression or a CSS selector. @param string $expression XPath expression or a CSS selector @param string $type The type of the expression @param bool $wrapElement Returns array of \DiDom\Element if true, otherwise array of \DOMElement @return \DiDom\Element[]|\DOMElement[]
[ "Searches", "for", "an", "node", "in", "the", "DOM", "tree", "for", "a", "given", "XPath", "expression", "or", "a", "CSS", "selector", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L283-L286
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.findInDocument
public function findInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true) { $ownerDocument = $this->getDocument(); if ($ownerDocument === null) { throw new LogicException('Can not search in context without owner document'); } return $ownerDocument->find($expression, $type, $wrapNode, $this->node); }
php
public function findInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true) { $ownerDocument = $this->getDocument(); if ($ownerDocument === null) { throw new LogicException('Can not search in context without owner document'); } return $ownerDocument->find($expression, $type, $wrapNode, $this->node); }
[ "public", "function", "findInDocument", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ",", "$", "wrapNode", "=", "true", ")", "{", "$", "ownerDocument", "=", "$", "this", "->", "getDocument", "(", ")", ";", "if", "(", "$", "ownerDocument", "===", "null", ")", "{", "throw", "new", "LogicException", "(", "'Can not search in context without owner document'", ")", ";", "}", "return", "$", "ownerDocument", "->", "find", "(", "$", "expression", ",", "$", "type", ",", "$", "wrapNode", ",", "$", "this", "->", "node", ")", ";", "}" ]
Searches for an node in the owner document using current node as context. @param string $expression XPath expression or a CSS selector @param string $type The type of the expression @param bool $wrapNode Returns array of \DiDom\Element if true, otherwise array of \DOMElement @return \DiDom\Element[]|\DOMElement[] @throws \LogicException if current node has no owner document
[ "Searches", "for", "an", "node", "in", "the", "owner", "document", "using", "current", "node", "as", "context", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L299-L308
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.first
public function first($expression, $type = Query::TYPE_CSS, $wrapNode = true) { return $this->toDocument()->first($expression, $type, $wrapNode); }
php
public function first($expression, $type = Query::TYPE_CSS, $wrapNode = true) { return $this->toDocument()->first($expression, $type, $wrapNode); }
[ "public", "function", "first", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ",", "$", "wrapNode", "=", "true", ")", "{", "return", "$", "this", "->", "toDocument", "(", ")", "->", "first", "(", "$", "expression", ",", "$", "type", ",", "$", "wrapNode", ")", ";", "}" ]
Searches for an node in the DOM tree and returns first element or null. @param string $expression XPath expression or a CSS selector @param string $type The type of the expression @param bool $wrapNode Returns \DiDom\Element if true, otherwise \DOMElement @return \DiDom\Element|\DOMElement|null
[ "Searches", "for", "an", "node", "in", "the", "DOM", "tree", "and", "returns", "first", "element", "or", "null", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L319-L322
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.firstInDocument
public function firstInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true) { $ownerDocument = $this->getDocument(); if ($ownerDocument === null) { throw new LogicException('Can not search in context without owner document'); } return $ownerDocument->first($expression, $type, $wrapNode, $this->node); }
php
public function firstInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true) { $ownerDocument = $this->getDocument(); if ($ownerDocument === null) { throw new LogicException('Can not search in context without owner document'); } return $ownerDocument->first($expression, $type, $wrapNode, $this->node); }
[ "public", "function", "firstInDocument", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ",", "$", "wrapNode", "=", "true", ")", "{", "$", "ownerDocument", "=", "$", "this", "->", "getDocument", "(", ")", ";", "if", "(", "$", "ownerDocument", "===", "null", ")", "{", "throw", "new", "LogicException", "(", "'Can not search in context without owner document'", ")", ";", "}", "return", "$", "ownerDocument", "->", "first", "(", "$", "expression", ",", "$", "type", ",", "$", "wrapNode", ",", "$", "this", "->", "node", ")", ";", "}" ]
Searches for an node in the owner document using current node as context and returns first element or null. @param string $expression XPath expression or a CSS selector @param string $type The type of the expression @param bool $wrapNode Returns \DiDom\Element if true, otherwise \DOMElement @return \DiDom\Element|\DOMElement|null
[ "Searches", "for", "an", "node", "in", "the", "owner", "document", "using", "current", "node", "as", "context", "and", "returns", "first", "element", "or", "null", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L333-L342
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.xpath
public function xpath($expression, $wrapNode = true) { return $this->find($expression, Query::TYPE_XPATH, $wrapNode); }
php
public function xpath($expression, $wrapNode = true) { return $this->find($expression, Query::TYPE_XPATH, $wrapNode); }
[ "public", "function", "xpath", "(", "$", "expression", ",", "$", "wrapNode", "=", "true", ")", "{", "return", "$", "this", "->", "find", "(", "$", "expression", ",", "Query", "::", "TYPE_XPATH", ",", "$", "wrapNode", ")", ";", "}" ]
Searches for an node in the DOM tree for a given XPath expression. @param string $expression XPath expression @param bool $wrapNode Returns array of \DiDom\Element if true, otherwise array of \DOMElement @return \DiDom\Element[]|\DOMElement[]
[ "Searches", "for", "an", "node", "in", "the", "DOM", "tree", "for", "a", "given", "XPath", "expression", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L352-L355
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.count
public function count($expression, $type = Query::TYPE_CSS) { return $this->toDocument()->count($expression, $type); }
php
public function count($expression, $type = Query::TYPE_CSS) { return $this->toDocument()->count($expression, $type); }
[ "public", "function", "count", "(", "$", "expression", ",", "$", "type", "=", "Query", "::", "TYPE_CSS", ")", "{", "return", "$", "this", "->", "toDocument", "(", ")", "->", "count", "(", "$", "expression", ",", "$", "type", ")", ";", "}" ]
Counts nodes for a given XPath expression or a CSS selector. @param string $expression XPath expression or CSS selector @param string $type The type of the expression @return int
[ "Counts", "nodes", "for", "a", "given", "XPath", "expression", "or", "a", "CSS", "selector", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L365-L368
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.matches
public function matches($selector, $strict = false) { if (!is_string($selector)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($selector))); } if (!$this->node instanceof DOMElement) { return false; } if ($selector === '*') { return true; } if (!$strict) { $innerHtml = $this->html(); $html = "<root>$innerHtml</root>"; $selector = 'root > ' . trim($selector); $document = new Document(); $document->loadHtml($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED); return $document->has($selector); } $segments = Query::getSegments($selector); if (!array_key_exists('tag', $segments)) { throw new RuntimeException(sprintf('Tag name must be specified in %s', $selector)); } if ($segments['tag'] !== $this->tag && $segments['tag'] !== '*') { return false; } $segments['id'] = array_key_exists('id', $segments) ? $segments['id'] : null; if ($segments['id'] !== $this->getAttribute('id')) { return false; } $classes = $this->hasAttribute('class') ? explode(' ', trim($this->getAttribute('class'))) : []; $segments['classes'] = array_key_exists('classes', $segments) ? $segments['classes'] : []; $diff1 = array_diff($segments['classes'], $classes); $diff2 = array_diff($classes, $segments['classes']); if (count($diff1) > 0 || count($diff2) > 0) { return false; } $attributes = $this->attributes(); unset($attributes['id'], $attributes['class']); $segments['attributes'] = array_key_exists('attributes', $segments) ? $segments['attributes'] : []; $diff1 = array_diff_assoc($segments['attributes'], $attributes); $diff2 = array_diff_assoc($attributes, $segments['attributes']); // if the attributes are not equal if (count($diff1) > 0 || count($diff2) > 0) { return false; } return true; }
php
public function matches($selector, $strict = false) { if (!is_string($selector)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($selector))); } if (!$this->node instanceof DOMElement) { return false; } if ($selector === '*') { return true; } if (!$strict) { $innerHtml = $this->html(); $html = "<root>$innerHtml</root>"; $selector = 'root > ' . trim($selector); $document = new Document(); $document->loadHtml($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED); return $document->has($selector); } $segments = Query::getSegments($selector); if (!array_key_exists('tag', $segments)) { throw new RuntimeException(sprintf('Tag name must be specified in %s', $selector)); } if ($segments['tag'] !== $this->tag && $segments['tag'] !== '*') { return false; } $segments['id'] = array_key_exists('id', $segments) ? $segments['id'] : null; if ($segments['id'] !== $this->getAttribute('id')) { return false; } $classes = $this->hasAttribute('class') ? explode(' ', trim($this->getAttribute('class'))) : []; $segments['classes'] = array_key_exists('classes', $segments) ? $segments['classes'] : []; $diff1 = array_diff($segments['classes'], $classes); $diff2 = array_diff($classes, $segments['classes']); if (count($diff1) > 0 || count($diff2) > 0) { return false; } $attributes = $this->attributes(); unset($attributes['id'], $attributes['class']); $segments['attributes'] = array_key_exists('attributes', $segments) ? $segments['attributes'] : []; $diff1 = array_diff_assoc($segments['attributes'], $attributes); $diff2 = array_diff_assoc($attributes, $segments['attributes']); if (count($diff1) > 0 || count($diff2) > 0) { return false; } return true; }
[ "public", "function", "matches", "(", "$", "selector", ",", "$", "strict", "=", "false", ")", "{", "if", "(", "!", "is_string", "(", "$", "selector", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 1 to be string, %s given'", ",", "__METHOD__", ",", "gettype", "(", "$", "selector", ")", ")", ")", ";", "}", "if", "(", "!", "$", "this", "->", "node", "instanceof", "DOMElement", ")", "{", "return", "false", ";", "}", "if", "(", "$", "selector", "===", "'*'", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "strict", ")", "{", "$", "innerHtml", "=", "$", "this", "->", "html", "(", ")", ";", "$", "html", "=", "\"<root>$innerHtml</root>\"", ";", "$", "selector", "=", "'root > '", ".", "trim", "(", "$", "selector", ")", ";", "$", "document", "=", "new", "Document", "(", ")", ";", "$", "document", "->", "loadHtml", "(", "$", "html", ",", "LIBXML_HTML_NODEFDTD", "|", "LIBXML_HTML_NOIMPLIED", ")", ";", "return", "$", "document", "->", "has", "(", "$", "selector", ")", ";", "}", "$", "segments", "=", "Query", "::", "getSegments", "(", "$", "selector", ")", ";", "if", "(", "!", "array_key_exists", "(", "'tag'", ",", "$", "segments", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Tag name must be specified in %s'", ",", "$", "selector", ")", ")", ";", "}", "if", "(", "$", "segments", "[", "'tag'", "]", "!==", "$", "this", "->", "tag", "&&", "$", "segments", "[", "'tag'", "]", "!==", "'*'", ")", "{", "return", "false", ";", "}", "$", "segments", "[", "'id'", "]", "=", "array_key_exists", "(", "'id'", ",", "$", "segments", ")", "?", "$", "segments", "[", "'id'", "]", ":", "null", ";", "if", "(", "$", "segments", "[", "'id'", "]", "!==", "$", "this", "->", "getAttribute", "(", "'id'", ")", ")", "{", "return", "false", ";", "}", "$", "classes", "=", "$", "this", "->", "hasAttribute", "(", "'class'", ")", "?", "explode", "(", "' '", ",", "trim", "(", "$", "this", "->", "getAttribute", "(", "'class'", ")", ")", ")", ":", "[", "]", ";", "$", "segments", "[", "'classes'", "]", "=", "array_key_exists", "(", "'classes'", ",", "$", "segments", ")", "?", "$", "segments", "[", "'classes'", "]", ":", "[", "]", ";", "$", "diff1", "=", "array_diff", "(", "$", "segments", "[", "'classes'", "]", ",", "$", "classes", ")", ";", "$", "diff2", "=", "array_diff", "(", "$", "classes", ",", "$", "segments", "[", "'classes'", "]", ")", ";", "if", "(", "count", "(", "$", "diff1", ")", ">", "0", "||", "count", "(", "$", "diff2", ")", ">", "0", ")", "{", "return", "false", ";", "}", "$", "attributes", "=", "$", "this", "->", "attributes", "(", ")", ";", "unset", "(", "$", "attributes", "[", "'id'", "]", ",", "$", "attributes", "[", "'class'", "]", ")", ";", "$", "segments", "[", "'attributes'", "]", "=", "array_key_exists", "(", "'attributes'", ",", "$", "segments", ")", "?", "$", "segments", "[", "'attributes'", "]", ":", "[", "]", ";", "$", "diff1", "=", "array_diff_assoc", "(", "$", "segments", "[", "'attributes'", "]", ",", "$", "attributes", ")", ";", "$", "diff2", "=", "array_diff_assoc", "(", "$", "attributes", ",", "$", "segments", "[", "'attributes'", "]", ")", ";", "// if the attributes are not equal", "if", "(", "count", "(", "$", "diff1", ")", ">", "0", "||", "count", "(", "$", "diff2", ")", ">", "0", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks that the node matches selector. @param string $selector CSS selector @param bool $strict @return bool @throws \InvalidArgumentException if the tag name is not a string @throws \RuntimeException if the tag name is not specified in strict mode
[ "Checks", "that", "the", "node", "matches", "selector", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L381-L450
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.setAttribute
public function setAttribute($name, $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_string($value) && $value !== null) { throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string or null, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value)))); } $this->node->setAttribute($name, $value); return $this; }
php
public function setAttribute($name, $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_string($value) && $value !== null) { throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string or null, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value)))); } $this->node->setAttribute($name, $value); return $this; }
[ "public", "function", "setAttribute", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "value", "=", "(", "string", ")", "$", "value", ";", "}", "if", "(", "!", "is_string", "(", "$", "value", ")", "&&", "$", "value", "!==", "null", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'%s expects parameter 2 to be string or null, %s given'", ",", "__METHOD__", ",", "(", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ")", ")", ")", ";", "}", "$", "this", "->", "node", "->", "setAttribute", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Set an attribute on the element. @param string $name The attribute name @param string $value The attribute value @return \DiDom\Element
[ "Set", "an", "attribute", "on", "the", "element", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L472-L485
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.getAttribute
public function getAttribute($name, $default = null) { if ($this->hasAttribute($name)) { return $this->node->getAttribute($name); } return $default; }
php
public function getAttribute($name, $default = null) { if ($this->hasAttribute($name)) { return $this->node->getAttribute($name); } return $default; }
[ "public", "function", "getAttribute", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "this", "->", "hasAttribute", "(", "$", "name", ")", ")", "{", "return", "$", "this", "->", "node", "->", "getAttribute", "(", "$", "name", ")", ";", "}", "return", "$", "default", ";", "}" ]
Access to the element's attributes. @param string $name The attribute name @param string|null $default The value returned if the attribute does not exist @return string|null The value of the attribute or null if attribute does not exist
[ "Access", "to", "the", "element", "s", "attributes", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L495-L502
Imangazaliev/DiDOM
src/DiDom/Element.php
Element.removeAllAttributes
public function removeAllAttributes(array $exclusions = []) { if (!$this->node instanceof DOMElement) { return $this; } foreach ($this->attributes() as $name => $value) { if (in_array($name, $exclusions, true)) { continue; } $this->node->removeAttribute($name); } return $this; }
php
public function removeAllAttributes(array $exclusions = []) { if (!$this->node instanceof DOMElement) { return $this; } foreach ($this->attributes() as $name => $value) { if (in_array($name, $exclusions, true)) { continue; } $this->node->removeAttribute($name); } return $this; }
[ "public", "function", "removeAllAttributes", "(", "array", "$", "exclusions", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "node", "instanceof", "DOMElement", ")", "{", "return", "$", "this", ";", "}", "foreach", "(", "$", "this", "->", "attributes", "(", ")", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "name", ",", "$", "exclusions", ",", "true", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "node", "->", "removeAttribute", "(", "$", "name", ")", ";", "}", "return", "$", "this", ";", "}" ]
Unset all attributes of the element. @param string[] $exclusions @return \DiDom\Element
[ "Unset", "all", "attributes", "of", "the", "element", "." ]
train
https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L525-L540