code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function setChecker(Checker $checker) { $this->checker = $checker; }
Set an update checker service instance. @param Checker $checker
setChecker
php
bobthecow/psysh
src/Configuration.php
https://github.com/bobthecow/psysh/blob/master/src/Configuration.php
MIT
public function setUpdateCheck(string $interval) { $validIntervals = [ Checker::ALWAYS, Checker::DAILY, Checker::WEEKLY, Checker::MONTHLY, Checker::NEVER, ]; if (!\in_array($interval, $validIntervals)) { throw new \InvalidArgumentException('Invalid update check interval: '.$interval); } $this->updateCheck = $interval; }
Set the update check interval. @throws \InvalidArgumentException if the update check interval is unknown @param string $interval
setUpdateCheck
php
bobthecow/psysh
src/Configuration.php
https://github.com/bobthecow/psysh/blob/master/src/Configuration.php
MIT
public function getUpdateCheckCacheFile() { $configDir = $this->configPaths->currentConfigDir(); if ($configDir === null) { return false; } return ConfigPaths::touchFileWithMkdir($configDir.'/update_check.json'); }
Get a cache file path for the update checker. @return string|false Return false if config file/directory is not writable
getUpdateCheckCacheFile
php
bobthecow/psysh
src/Configuration.php
https://github.com/bobthecow/psysh/blob/master/src/Configuration.php
MIT
public function setPrompt(string $prompt) { $this->prompt = $prompt; if (isset($this->theme)) { $this->theme->setPrompt($prompt); } }
Set the prompt. @deprecated The `prompt` configuration has been replaced by Themes and support will eventually be removed. In the meantime, prompt is applied first by the Theme, then overridden by any explicitly defined prompt. Note that providing a prompt but not a theme config will implicitly use the `classic` theme.
setPrompt
php
bobthecow/psysh
src/Configuration.php
https://github.com/bobthecow/psysh/blob/master/src/Configuration.php
MIT
public function setVerbosity(string $verbosity) { $validVerbosityLevels = [ self::VERBOSITY_QUIET, self::VERBOSITY_NORMAL, self::VERBOSITY_VERBOSE, self::VERBOSITY_VERY_VERBOSE, self::VERBOSITY_DEBUG, ]; if (!\in_array($verbosity, $validVerbosityLevels)) { throw new \InvalidArgumentException('Invalid verbosity level: '.$verbosity); } $this->verbosity = $verbosity; if (isset($this->output)) { $this->output->setVerbosity($this->getOutputVerbosity()); } }
Set the shell output verbosity. Accepts OutputInterface verbosity constants. @throws \InvalidArgumentException if verbosity level is invalid @param string $verbosity
setVerbosity
php
bobthecow/psysh
src/Configuration.php
https://github.com/bobthecow/psysh/blob/master/src/Configuration.php
MIT
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
getDebugFile
php
bobthecow/psysh
src/CodeCleaner.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner.php
MIT
public function clean(array $codeLines, bool $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
php
bobthecow/psysh
src/CodeCleaner.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner.php
MIT
public function setNamespace(?array $namespace = null) { $this->namespace = $namespace; }
Set the current local namespace.
setNamespace
php
bobthecow/psysh
src/CodeCleaner.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner.php
MIT
public function getNamespace() { return $this->namespace; }
Get the current local namespace. @return array|null
getNamespace
php
bobthecow/psysh
src/CodeCleaner.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner.php
MIT
protected function parse(string $code, bool $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 @return array|false A set of statements, or false if incomplete
parse
php
bobthecow/psysh
src/CodeCleaner.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner.php
MIT
private function parseShellArgument(string $token, string $rest) { $c = \count($this->arguments); // if input is expecting another argument, add it if ($this->definition->hasArgument($c)) { $arg = $this->definition->getArgument($c); if ($arg instanceof CodeArgument) { // When we find a code argument, we're done parsing. Add the // remaining input to the current argument and call it a day. $this->parsed = []; $this->arguments[$arg->getName()] = $rest; } else { $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token; } return; } // (copypasta) // // @codeCoverageIgnoreStart // if last argument isArray(), append token to last argument if ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) { $arg = $this->definition->getArgument($c - 1); $this->arguments[$arg->getName()][] = $token; return; } // unexpected argument $all = $this->definition->getArguments(); if (\count($all)) { throw new \RuntimeException(\sprintf('Too many arguments, expected arguments "%s".', \implode('" "', \array_keys($all)))); } throw new \RuntimeException(\sprintf('No arguments expected, got "%s".', $token)); // @codeCoverageIgnoreEnd }
Parses an argument, with bonus handling for code arguments. @param string $token The current token @param string $rest The remaining unparsed input, including the current token @throws \RuntimeException When too many arguments are given
parseShellArgument
php
bobthecow/psysh
src/Input/ShellInput.php
https://github.com/bobthecow/psysh/blob/master/src/Input/ShellInput.php
MIT
public function bind(InputInterface $input) { $this->validateInput($input); if (!$pattern = $input->getOption('grep')) { $this->filter = false; return; } if (!$this->stringIsRegex($pattern)) { $pattern = '/'.\preg_quote($pattern, '/').'/'; } if ($insensitive = $input->getOption('insensitive')) { $pattern .= 'i'; } $this->validateRegex($pattern); $this->filter = true; $this->pattern = $pattern; $this->insensitive = $insensitive; $this->invert = $input->getOption('invert'); }
Bind input and prepare filter. @param InputInterface $input
bind
php
bobthecow/psysh
src/Input/FilterOptions.php
https://github.com/bobthecow/psysh/blob/master/src/Input/FilterOptions.php
MIT
private function validateInput(InputInterface $input) { if (!$input->getOption('grep')) { foreach (['invert', 'insensitive'] as $option) { if ($input->getOption($option)) { throw new RuntimeException('--'.$option.' does not make sense without --grep'); } } } }
Validate that grep, invert and insensitive input options are consistent. @throws RuntimeException if input is invalid @param InputInterface $input
validateInput
php
bobthecow/psysh
src/Input/FilterOptions.php
https://github.com/bobthecow/psysh/blob/master/src/Input/FilterOptions.php
MIT
private static function nextHighlightType($token, $currentType) { if ($token === '"') { return self::HIGHLIGHT_STRING; } if (\is_array($token)) { if ($token[0] === \T_WHITESPACE) { return $currentType; } if (\array_key_exists($token[0], self::TOKEN_MAP)) { return self::TOKEN_MAP[$token[0]]; } } return self::HIGHLIGHT_KEYWORD; }
Given a token and the current highlight span type, compute the next type. @param array|string $token \token_get_all token @param string|null $currentType @return string|null
nextHighlightType
php
bobthecow/psysh
src/Formatter/CodeFormatter.php
https://github.com/bobthecow/psysh/blob/master/src/Formatter/CodeFormatter.php
MIT
public static function disabledPcntlFunctions() { return self::checkDisabledFunctions(self::PCNTL_FUNCTIONS); }
Check whether required pcntl functions are disabled.
disabledPcntlFunctions
php
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
https://github.com/bobthecow/psysh/blob/master/src/ExecutionLoop/ProcessForker.php
MIT
public static function disabledPosixFunctions() { return self::checkDisabledFunctions(self::POSIX_FUNCTIONS); }
Check whether required posix functions are disabled.
disabledPosixFunctions
php
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
https://github.com/bobthecow/psysh/blob/master/src/ExecutionLoop/ProcessForker.php
MIT
public function beforeLoop(Shell $shell) { $this->createSavegame(); }
Create a savegame at the start of each loop iteration. @param Shell $shell
beforeLoop
php
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
https://github.com/bobthecow/psysh/blob/master/src/ExecutionLoop/ProcessForker.php
MIT
public function afterLoop(Shell $shell) { // if there's an old savegame hanging around, let's kill it. if (isset($this->savegame)) { \posix_kill($this->savegame, \SIGKILL); \pcntl_signal_dispatch(); } }
Clean up old savegames at the end of each loop iteration. @param Shell $shell
afterLoop
php
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
https://github.com/bobthecow/psysh/blob/master/src/ExecutionLoop/ProcessForker.php
MIT
public function afterRun(Shell $shell) { // We're a child thread. Send the scope variables back up to the main thread. if (isset($this->up)) { \fwrite($this->up, $this->serializeReturn($shell->getScopeVariables(false))); \fclose($this->up); \posix_kill(\posix_getpid(), \SIGKILL); } }
After the REPL session ends, send the scope variables back up to the main thread (if this is a child thread). @param Shell $shell
afterRun
php
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
https://github.com/bobthecow/psysh/blob/master/src/ExecutionLoop/ProcessForker.php
MIT
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->getStartLine()); } } }
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
validateArrayMultisort
php
bobthecow/psysh
src/CodeCleaner/PassableByReferencePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/PassableByReferencePass.php
MIT
public function beforeTraverse(array $nodes) { if (empty($nodes)) { return $nodes; } $last = \end($nodes); if ($last instanceof Namespace_) { $kind = $last->getAttribute('kind'); // Treat all namespace statements pre-PHP-Parser v3.1.2 as "open", // even though we really have no way of knowing. if ($kind === null || $kind === Namespace_::KIND_SEMICOLON) { // Save the current namespace for open namespaces $this->setNamespace($last->name); } else { // Clear the current namespace after a braced namespace $this->setNamespace(null); } return $nodes; } return $this->namespace ? [new Namespace_($this->namespace, $nodes)] : $nodes; }
If this is a standalone namespace line, remember it for later. Otherwise, apply remembered namespaces to the code until a new namespace is encountered. @param array $nodes @return Node[]|null Array of nodes
beforeTraverse
php
bobthecow/psysh
src/CodeCleaner/NamespacePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/NamespacePass.php
MIT
private function setNamespace(?Name $namespace) { $this->namespace = $namespace; $this->cleaner->setNamespace($namespace === null ? null : $this->getParts($namespace)); }
Remember the namespace and (re)set the namespace on the CodeCleaner as well. @param Name|null $namespace
setNamespace
php
bobthecow/psysh
src/CodeCleaner/NamespacePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/NamespacePass.php
MIT
public function enterNode(Node $node) { if ($node instanceof Assign && $node->var instanceof Variable && $node->var->name === 'this') { throw new FatalErrorException('Cannot re-assign $this', 0, \E_ERROR, null, $node->getStartLine()); } }
Validate that the user input does not assign the `$this` variable. @throws FatalErrorException if the user assign the `$this` variable @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/AssignThisVariablePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/AssignThisVariablePass.php
MIT
public function enterNode(Node $node) { if (!$node instanceof FuncCall && !$node instanceof MethodCall && !$node instanceof StaticCall) { return; } foreach ($node->args as $arg) { if ($arg instanceof VariadicPlaceholder) { continue; } if ($arg->byRef) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); } } }
Validate of use call-time pass-by-reference. @throws FatalErrorException if the user used call-time pass-by-reference @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/CallTimePassByReferencePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/CallTimePassByReferencePass.php
MIT
public function leaveNode(Node $node) { if ($node instanceof Exit_) { return new StaticCall(new FullyQualifiedName(BreakException::class), 'exitShell'); } }
Converts exit calls to BreakExceptions. @param \PhpParser\Node $node @return int|Node|Node[]|null Replacement node (or special return value)
leaveNode
php
bobthecow/psysh
src/CodeCleaner/ExitPass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ExitPass.php
MIT
public function enterNode(Node $node) { if ($node instanceof Variable && $node->name === '__psysh__') { throw new RuntimeException('Don\'t mess with $__psysh__; bad things will happen'); } }
Validate that the user input does not reference the `$__psysh__` variable. @throws RuntimeException if the user is messing with $__psysh__ @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/LeavePsyshAlonePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/LeavePsyshAlonePass.php
MIT
protected function validateClassStatement(Class_ $stmt) { $this->ensureCanDefine($stmt, self::CLASS_TYPE); if (isset($stmt->extends)) { $this->ensureClassExists($this->getFullyQualifiedName($stmt->extends), $stmt); } $this->ensureInterfacesExist($stmt->implements, $stmt); }
Validate a class definition statement. @param Class_ $stmt
validateClassStatement
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function validateInterfaceStatement(Interface_ $stmt) { $this->ensureCanDefine($stmt, self::INTERFACE_TYPE); $this->ensureInterfacesExist($stmt->extends, $stmt); }
Validate an interface definition statement. @param Interface_ $stmt
validateInterfaceStatement
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function validateTraitStatement(Trait_ $stmt) { $this->ensureCanDefine($stmt, self::TRAIT_TYPE); }
Validate a trait definition statement. @param Trait_ $stmt
validateTraitStatement
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function ensureCanDefine(Stmt $stmt, string $scopeType = self::CLASS_TYPE) { // Anonymous classes don't have a name, and uniqueness shouldn't be enforced. if ($stmt->name === null) { return; } $name = $this->getFullyQualifiedName($stmt->name); // check for name collisions $errorType = null; if ($this->classExists($name)) { $errorType = self::CLASS_TYPE; } elseif ($this->interfaceExists($name)) { $errorType = self::INTERFACE_TYPE; } elseif ($this->traitExists($name)) { $errorType = self::TRAIT_TYPE; } if ($errorType !== null) { throw $this->createError(\sprintf('%s named %s already exists', \ucfirst($errorType), $name), $stmt); } // Store creation for the rest of this code snippet so we can find local // issue too $this->currentScope[\strtolower($name)] = $scopeType; }
Ensure that no class, interface or trait name collides with a new definition. @throws FatalErrorException @param Stmt $stmt @param string $scopeType
ensureCanDefine
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function ensureClassExists(string $name, Stmt $stmt) { if (!$this->classExists($name)) { throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); } }
Ensure that a referenced class exists. @throws FatalErrorException @param string $name @param Stmt $stmt
ensureClassExists
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function ensureClassOrInterfaceExists(string $name, Stmt $stmt) { if (!$this->classExists($name) && !$this->interfaceExists($name)) { throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); } }
Ensure that a referenced class _or interface_ exists. @throws FatalErrorException @param string $name @param Stmt $stmt
ensureClassOrInterfaceExists
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function ensureClassOrTraitExists(string $name, Stmt $stmt) { if (!$this->classExists($name) && !$this->traitExists($name)) { throw $this->createError(\sprintf('Class \'%s\' not found', $name), $stmt); } }
Ensure that a referenced class _or trait_ exists. @throws FatalErrorException @param string $name @param Stmt $stmt
ensureClassOrTraitExists
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function ensureMethodExists(string $class, string $name, Stmt $stmt) { $this->ensureClassOrTraitExists($class, $stmt); // let's pretend all calls to self, parent and static are valid if (\in_array(\strtolower($class), ['self', 'parent', 'static'])) { return; } // ... and all calls to classes defined right now if ($this->findInScope($class) === self::CLASS_TYPE) { return; } // if method name is an expression, give it a pass for now if ($name instanceof Expr) { return; } if (!\method_exists($class, $name) && !\method_exists($class, '__callStatic')) { throw $this->createError(\sprintf('Call to undefined method %s::%s()', $class, $name), $stmt); } }
Ensure that a statically called method exists. @throws FatalErrorException @param string $class @param string $name @param Stmt $stmt
ensureMethodExists
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
protected function findInScope(string $name) { $name = \strtolower($name); if (isset($this->currentScope[$name])) { return $this->currentScope[$name]; } }
Find a symbol in the current code snippet scope. @param string $name @return string|null
findInScope
php
bobthecow/psysh
src/CodeCleaner/ValidClassNamePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidClassNamePass.php
MIT
public function enterNode(Node $node) { if ($node instanceof Namespace_) { // If this is the same namespace as last namespace, let's do ourselves // a favor and reload all the aliases... if (\strtolower($node->name ?: '') === \strtolower($this->lastNamespace ?: '')) { $this->aliases = $this->lastAliases; } } }
Re-load the last set of use statements on re-entering a namespace. This isn't how namespaces normally work, but because PsySH has to spin up a new namespace for every line of code, we do this to make things work like you'd expect. @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/UseStatementPass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/UseStatementPass.php
MIT
public function beforeTraverse(array $nodes) { $this->namespace = []; $this->currentScope = []; }
@todo should this be final? Extending classes should be sure to either use afterTraverse or call parent::beforeTraverse() when overloading. Reset the namespace and the current scope before beginning analysis @return Node[]|null Array of nodes
beforeTraverse
php
bobthecow/psysh
src/CodeCleaner/NamespaceAwarePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/NamespaceAwarePass.php
MIT
public function enterNode(Node $node) { if ($node instanceof Namespace_) { $this->namespace = isset($node->name) ? $this->getParts($node->name) : []; } }
@todo should this be final? Extending classes should be sure to either use leaveNode or call parent::enterNode() when overloading @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/NamespaceAwarePass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/NamespaceAwarePass.php
MIT
public function enterNode(Node $node) { if ($node instanceof Namespace_) { $this->namespace = isset($node->name) ? $this->getParts($node->name) : []; } elseif ($node instanceof Class_) { $constructor = null; foreach ($node->stmts as $stmt) { if ($stmt instanceof ClassMethod) { // If we find a new-style constructor, no need to look for the old-style if ('__construct' === \strtolower($stmt->name)) { $this->validateConstructor($stmt, $node); return; } // We found a possible old-style constructor (unless there is also a __construct method) if (empty($this->namespace) && \strtolower($node->name) === \strtolower($stmt->name)) { $constructor = $stmt; } } } if ($constructor) { $this->validateConstructor($constructor, $node); } } }
Validate that the constructor is not static and does not have a return type. @throws FatalErrorException the constructor function is static @throws FatalErrorException the constructor function has a return type @param Node $node @return int|Node|null Replacement node (or special return value)
enterNode
php
bobthecow/psysh
src/CodeCleaner/ValidConstructorPass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/ValidConstructorPass.php
MIT
public function beforeTraverse(array $nodes) { $prependStrictTypes = $this->strictTypes; foreach ($nodes as $node) { if ($node instanceof Declare_) { foreach ($node->declares as $declare) { if ($declare->key->toString() === 'strict_types') { $value = $declare->value; // @todo Remove LNumber once we drop support for PHP-Parser 4.x if ((!$value instanceof LNumber && !$value instanceof Int_) || ($value->value !== 0 && $value->value !== 1)) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, \E_ERROR, null, $node->getStartLine()); } $this->strictTypes = $value->value === 1; } } } } if ($prependStrictTypes) { $first = \reset($nodes); if (!$first instanceof Declare_) { // @todo Switch to PhpParser\Node\DeclareItem once we drop support for PHP-Parser 4.x // @todo Remove LNumber once we drop support for PHP-Parser 4.x $arg = \class_exists('PhpParser\Node\Scalar\Int_') ? new Int_(1) : new LNumber(1); $declareItem = \class_exists('PhpParser\Node\DeclareItem') ? new DeclareItem('strict_types', $arg) : new DeclareDeclare('strict_types', $arg); $declare = new Declare_([$declareItem]); \array_unshift($nodes, $declare); } } return $nodes; }
If this is a standalone strict types declaration, remember it for later. Otherwise, apply remembered strict types declaration to to the code until a new declaration is encountered. @throws FatalErrorException if an invalid `strict_types` declaration is found @param array $nodes @return Node[]|null Array of nodes
beforeTraverse
php
bobthecow/psysh
src/CodeCleaner/StrictTypesPass.php
https://github.com/bobthecow/psysh/blob/master/src/CodeCleaner/StrictTypesPass.php
MIT
public function __construct($historyFile = null, $historySize = 0, $eraseDups = false) { // don't do anything with the history file... $this->history = []; $this->historySize = $historySize; $this->eraseDups = $eraseDups ?? false; }
Transient Readline constructor.
__construct
php
bobthecow/psysh
src/Readline/Transient.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Transient.php
MIT
public function __construct($historyFile = null, $historySize = 0, $eraseDups = false) { static::bootstrapHoa(true); $this->hoaReadline = new HoaReadline(); $this->hoaReadline->addMapping('\C-l', function () { $this->redisplay(); return HoaReadline::STATE_NO_ECHO; }); $this->tput = new HoaConsoleTput(); HoaConsole::setTput($this->tput); $this->input = new HoaConsoleInput(); HoaConsole::setInput($this->input); $this->output = new HoaConsoleOutput(); HoaConsole::setOutput($this->output); }
Doesn't (currently) support history file, size or erase dupes configs.
__construct
php
bobthecow/psysh
src/Readline/Userland.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Userland.php
MIT
public static function bootstrapHoa(bool $withTerminalResize = false) { // A side effect registers hoa:// stream wrapper \class_exists('Psy\Readline\Hoa\ProtocolWrapper'); // A side effect registers hoa://Library/Stream \class_exists('Psy\Readline\Hoa\Stream'); // A side effect binds terminal resize $withTerminalResize && \class_exists('Psy\Readline\Hoa\ConsoleWindow'); }
Bootstrap some things that Hoa used to do itself.
bootstrapHoa
php
bobthecow/psysh
src/Readline/Userland.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Userland.php
MIT
protected function &_open(string $streamName, ?StreamContext $context = null) { static $createModes = [ parent::MODE_READ_WRITE, parent::MODE_TRUNCATE_READ_WRITE, parent::MODE_APPEND_READ_WRITE, parent::MODE_CREATE_READ_WRITE, ]; if (!\in_array($this->getMode(), $createModes)) { throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); } \preg_match('#^(\w+)://#', $streamName, $match); if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && !\file_exists($streamName) && parent::MODE_READ_WRITE === $this->getMode()) { throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); } $out = parent::_open($streamName, $context); return $out; }
Open the stream and return the associated resource.
_open
php
bobthecow/psysh
src/Readline/Hoa/FileLinkReadWrite.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkReadWrite.php
MIT
public function readArray(?string $format = null) { return $this->scanf($format); }
Read an array. Alias of the $this->scanf() method.
readArray
php
bobthecow/psysh
src/Readline/Hoa/FileLinkReadWrite.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkReadWrite.php
MIT
public function readAll(int $offset = 0) { return \stream_get_contents($this->getStream(), -1, $offset); }
Read all, i.e. read as much as possible.
readAll
php
bobthecow/psysh
src/Readline/Hoa/FileLinkReadWrite.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkReadWrite.php
MIT
public function writeAll(string $string) { return $this->write($string, \strlen($string)); }
Write all, i.e. as much as possible.
writeAll
php
bobthecow/psysh
src/Readline/Hoa/FileLinkReadWrite.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkReadWrite.php
MIT
public function setIteratorFactory(\Closure $iteratorFactory) { $old = $this->_iteratorFactory; $this->_iteratorFactory = $iteratorFactory; return $old; }
Set iterator factory (a finder).
setIteratorFactory
php
bobthecow/psysh
src/Readline/Hoa/AutocompleterPath.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/AutocompleterPath.php
MIT
public static function getDefaultIteratorFactory() { return function ($path) { return new \DirectoryIterator($path); }; }
Get default iterator factory (based on \DirectoryIterator).
getDefaultIteratorFactory
php
bobthecow/psysh
src/Readline/Hoa/AutocompleterPath.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/AutocompleterPath.php
MIT
public static function restoreInteraction() { if (null === self::$_old) { return; } ConsoleProcessus::execute('stty '.self::$_old.' < /dev/tty', false); return; }
Restore previous interaction options.
restoreInteraction
php
bobthecow/psysh
src/Readline/Hoa/Console.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Console.php
MIT
public static function moveTo(?int $x = null, ?int $y = null) { if (null === $x || null === $y) { $position = static::getPosition(); if (null === $x) { $x = $position['x']; } if (null === $y) { $y = $position['y']; } } Console::getOutput()->writeAll( \str_replace( ['%i%p1%d', '%p2%d'], [$y, $x], Console::getTput()->get('cursor_address') ) ); }
Move to the line X and the column Y. If null, use the current coordinate.
moveTo
php
bobthecow/psysh
src/Readline/Hoa/ConsoleCursor.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleCursor.php
MIT
public static function restore() { Console::getOutput()->writeAll( Console::getTput()->get('restore_cursor') ); }
Restore cursor to the last saved position.
restore
php
bobthecow/psysh
src/Readline/Hoa/ConsoleCursor.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleCursor.php
MIT
public static function changeColor(int $fromCode, int $toColor) { $tput = Console::getTput(); if (true !== $tput->has('can_change')) { return; } $r = ($toColor >> 16) & 255; $g = ($toColor >> 8) & 255; $b = $toColor & 255; Console::getOutput()->writeAll( \str_replace( [ '%p1%d', 'rgb:', '%p2%{255}%*%{1000}%/%2.2X/', '%p3%{255}%*%{1000}%/%2.2X/', '%p4%{255}%*%{1000}%/%2.2X', ], [ $fromCode, '', \sprintf('%02x', $r), \sprintf('%02x', $g), \sprintf('%02x', $b), ], $tput->get('initialize_color') ) ); return; }
Change color number to a specific RGB color.
changeColor
php
bobthecow/psysh
src/Readline/Hoa/ConsoleCursor.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleCursor.php
MIT
public function __construct($data = null) { $this->setData($data); return; }
Allocates a new bucket with various data attached to it.
__construct
php
bobthecow/psysh
src/Readline/Hoa/EventBucket.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/EventBucket.php
MIT
public function send(string $eventId, EventSource $source) { return Event::notify($eventId, $source, $this); }
Sends this object on the event channel.
send
php
bobthecow/psysh
src/Readline/Hoa/EventBucket.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/EventBucket.php
MIT
public function __construct() { if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { return; } $this->_mapping["\033[A"] = [$this, '_bindArrowUp']; $this->_mapping["\033[B"] = [$this, '_bindArrowDown']; $this->_mapping["\033[C"] = [$this, '_bindArrowRight']; $this->_mapping["\033[D"] = [$this, '_bindArrowLeft']; $this->_mapping["\001"] = [$this, '_bindControlA']; $this->_mapping["\002"] = [$this, '_bindControlB']; $this->_mapping["\005"] = [$this, '_bindControlE']; $this->_mapping["\006"] = [$this, '_bindControlF']; $this->_mapping["\010"] = $this->_mapping["\177"] = [$this, '_bindBackspace']; $this->_mapping["\027"] = [$this, '_bindControlW']; $this->_mapping["\n"] = [$this, '_bindNewline']; $this->_mapping["\t"] = [$this, '_bindTab']; return; }
Initialize the readline editor.
__construct
php
bobthecow/psysh
src/Readline/Hoa/Readline.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Readline.php
MIT
public function insertLine(string $insert) { if ($this->_lineLength === $this->_lineCurrent) { return $this->appendLine($insert); } $this->_line = \mb_substr($this->_line, 0, $this->_lineCurrent). $insert. \mb_substr($this->_line, $this->_lineCurrent); $this->_lineLength = \mb_strlen($this->_line); $this->_lineCurrent += \mb_strlen($insert); return; }
Insert into current line at the current seek.
insertLine
php
bobthecow/psysh
src/Readline/Hoa/Readline.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Readline.php
MIT
public function setLine(string $line) { $this->_line = $line; $this->_lineLength = \mb_strlen($this->_line ?: ''); $this->_lineCurrent = $this->_lineLength; }
Set current line. Not for user.
setLine
php
bobthecow/psysh
src/Readline/Hoa/Readline.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Readline.php
MIT
public function setLineCurrent(int $current) { $this->_lineCurrent = $current; }
Set current line seek. Not for user.
setLineCurrent
php
bobthecow/psysh
src/Readline/Hoa/Readline.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Readline.php
MIT
public function setLineLength(int $length) { $this->_lineLength = $length; }
Set line length. Not for user.
setLineLength
php
bobthecow/psysh
src/Readline/Hoa/Readline.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Readline.php
MIT
public static function realPath(string $path, bool $exists = true) { return ProtocolNode::getRoot()->resolve($path, $exists); }
Get the real path of the given URL. Could return false if the path cannot be reached.
realPath
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function stream_cast(int $castAs) { return null; }
Retrieve the underlying resource. `$castAs` can be `STREAM_CAST_FOR_SELECT` when `stream_select` is calling `stream_cast` or `STREAM_CAST_AS_STREAM` when `stream_cast` is called for other uses.
stream_cast
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function stream_close() { if (true === @\fclose($this->getStream())) { $this->_stream = null; $this->_streamName = null; } }
Closes a resource. This method is called in response to `fclose`. All resources that were locked, or allocated, by the wrapper should be released.
stream_close
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function dir_closedir() { \closedir($this->getStream()); $this->_stream = null; $this->_streamName = null; }
Close directory handle. This method is called in to closedir(). Any resources which were locked, or allocated, during opening and use of the directory stream should be released.
dir_closedir
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function dir_readdir() { return \readdir($this->getStream()); }
Read entry from directory handle. This method is called in response to readdir(). @return mixed
dir_readdir
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function dir_rewinddir() { \rewinddir($this->getStream()); }
Rewind directory handle. This method is called in response to rewinddir(). Should reset the output generated by self::dir_readdir, i.e. the next call to self::dir_readdir should return the first entry in the location returned by self::dir_opendir.
dir_rewinddir
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public function url_stat(string $path, int $flags) { $path = static::realPath($path); if (Protocol::NO_RESOLUTION === $path) { if ($flags & \STREAM_URL_STAT_QUIET) { return 0; } else { return \trigger_error( 'Path '.$path.' cannot be resolved.', \E_WARNING ); } } if ($flags & \STREAM_URL_STAT_LINK) { return @\lstat($path); } return @\stat($path); }
Retrieve information about a file. This method is called in response to all stat() related functions. The `$flags` input holds additional flags set by the streams API. It can hold one or more of the following values OR'd together. STREAM_URL_STAT_LINK: for resource with the ability to link to other resource (such as an HTTP location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype(). STREAM_URL_STAT_QUIET: if this flag is set, our wrapper should not raise any errors. If this flag is not set, we are responsible for reporting errors using the trigger_error() function during stating of the path.
url_stat
php
bobthecow/psysh
src/Readline/Hoa/ProtocolWrapper.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolWrapper.php
MIT
public static function register(string $eventId, /* Source|string */ $source) { if (true === self::eventExists($eventId)) { throw new EventException('Cannot redeclare an event with the same ID, i.e. the event '.'ID %s already exists.', 0, $eventId); } if (\is_object($source) && !($source instanceof EventSource)) { throw new EventException('The source must implement \Hoa\Event\Source '.'interface; given %s.', 1, \get_class($source)); } else { $reflection = new \ReflectionClass($source); if (false === $reflection->implementsInterface('\Psy\Readline\Hoa\EventSource')) { throw new EventException('The source must implement \Hoa\Event\Source '.'interface; given %s.', 2, $source); } } if (!isset(self::$_register[$eventId][self::KEY_EVENT])) { self::$_register[$eventId][self::KEY_EVENT] = new self(); } self::$_register[$eventId][self::KEY_SOURCE] = $source; }
Declares a new object in the observable collection. Note: Hoa's libraries use `hoa://Event/anID` for their observable objects.
register
php
bobthecow/psysh
src/Readline/Hoa/Event.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Event.php
MIT
public static function unregister(string $eventId, bool $hard = false) { if (false !== $hard) { unset(self::$_register[$eventId]); } else { self::$_register[$eventId][self::KEY_SOURCE] = null; } }
Undeclares an object in the observable collection. If `$hard` is set to `true, then the source and its attached callables will be deleted.
unregister
php
bobthecow/psysh
src/Readline/Hoa/Event.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Event.php
MIT
private function __construct() { Event::register( 'hoa://Event/Console/Window:resize', $this ); return; }
Set the event channel. We need to declare(ticks = 1) in the main script to ensure that the event is fired. Also, we need the pcntl_signal() function enabled.
__construct
php
bobthecow/psysh
src/Readline/Hoa/ConsoleWindow.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleWindow.php
MIT
public static function setSize(int $x, int $y) { if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { return; } Console::getOutput()->writeAll("\033[8;".$y.';'.$x.'t'); return; }
Set size to X lines and Y columns.
setSize
php
bobthecow/psysh
src/Readline/Hoa/ConsoleWindow.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleWindow.php
MIT
public static function restore() { if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { return; } Console::getOutput()->writeAll("\033[1t"); return; }
Restore the window (de-minimize).
restore
php
bobthecow/psysh
src/Readline/Hoa/ConsoleWindow.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleWindow.php
MIT
public static function raise() { if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { return; } Console::getOutput()->writeAll("\033[5t"); return; }
Raise the window to the front of the stacking order.
raise
php
bobthecow/psysh
src/Readline/Hoa/ConsoleWindow.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleWindow.php
MIT
public static function lower() { if (\defined('PHP_WINDOWS_VERSION_PLATFORM')) { return; } Console::getOutput()->writeAll("\033[6t"); return; }
Lower the window to the bottom of the stacking order.
lower
php
bobthecow/psysh
src/Readline/Hoa/ConsoleWindow.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleWindow.php
MIT
public function resolve(string $path, bool $exists = true, bool $unfold = false) { if (\substr($path, 0, 6) !== 'hoa://') { if (true === \is_dir($path)) { $path = \rtrim($path, '/\\'); if ('' === $path) { $path = '/'; } } return $path; } if (isset(self::$_cache[$path])) { $handle = self::$_cache[$path]; } else { $out = $this->_resolve($path, $handle); // Not a path but a resource. if (!\is_array($handle)) { return $out; } $handle = \array_values(\array_unique($handle, \SORT_REGULAR)); foreach ($handle as &$entry) { if (true === \is_dir($entry)) { $entry = \rtrim($entry, '/\\'); if ('' === $entry) { $entry = '/'; } } } self::$_cache[$path] = $handle; } if (true === $unfold) { if (true !== $exists) { return $handle; } $out = []; foreach ($handle as $solution) { if (\file_exists($solution)) { $out[] = $solution; } } return $out; } if (true !== $exists) { return $handle[0]; } foreach ($handle as $solution) { if (\file_exists($solution)) { return $solution; } } return static::NO_RESOLUTION; }
Resolve (unfold) an `hoa://` path to its real resource. If `$exists` is set to `true`, try to find the first that exists, otherwise returns the first solution. If `$unfold` is set to `true`, it returns all the paths.
resolve
php
bobthecow/psysh
src/Readline/Hoa/Protocol.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Protocol.php
MIT
public function __construct( string $streamName, string $mode = parent::MODE_READ, ?string $context = null, bool $wait = false ) { parent::__construct($streamName, $mode, $context, $wait); return; }
Open a file. @param string $streamName stream name @param string $mode open mode, see the parent::MODE_* constants @param string $context context ID (please, see the \Hoa\Stream\Context class) @param bool $wait differ opening or not
__construct
php
bobthecow/psysh
src/Readline/Hoa/FileLinkRead.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkRead.php
MIT
protected function &_open(string $streamName, ?StreamContext $context = null) { static $createModes = [ parent::MODE_READ, ]; if (!\in_array($this->getMode(), $createModes)) { throw new FileException('Open mode are not supported; given %d. Only %s are supported.', 0, [$this->getMode(), \implode(', ', $createModes)]); } \preg_match('#^(\w+)://#', $streamName, $match); if (((isset($match[1]) && $match[1] === 'file') || !isset($match[1])) && !\file_exists($streamName)) { throw new FileDoesNotExistException('File %s does not exist.', 1, $streamName); } $out = parent::_open($streamName, $context); return $out; }
Open the stream and return the associated resource. @param string $streamName Stream name (e.g. path or URL). @param \Hoa\Stream\Context $context context @return resource @throws \Hoa\File\Exception\FileDoesNotExist @throws \Hoa\File\Exception
_open
php
bobthecow/psysh
src/Readline/Hoa/FileLinkRead.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/FileLinkRead.php
MIT
public function complete(&$prefix) { $out = []; $length = \mb_strlen($prefix); foreach ($this->getWords() as $word) { if (\mb_substr($word, 0, $length) === $prefix) { $out[] = $word; } } if (empty($out)) { return null; } if (1 === \count($out)) { return $out[0]; } return $out; }
Complete a word. Returns null for no word, a full-word or an array of full-words. @param string &$prefix Prefix to autocomplete @return mixed
complete
php
bobthecow/psysh
src/Readline/Hoa/AutocompleterWord.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/AutocompleterWord.php
MIT
public function __construct(string $streamName, ?string $context = null, bool $wait = false) { $this->_streamName = $streamName; $this->_context = $context; $this->_hasBeenDeferred = $wait; $this->setListener( new EventListener( $this, [ 'authrequire', 'authresult', 'complete', 'connect', 'failure', 'mimetype', 'progress', 'redirect', 'resolve', 'size', ] ) ); if (true === $wait) { return; } $this->open(); return; }
Set the current stream. If not exists in the register, try to call the `$this->_open()` method. Please, see the `self::_getStream()` method.
__construct
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
public function getStreamContext() { if (empty($this->_bucket)) { return null; } return $this->_bucket[self::CONTEXT]; }
Get the current stream context.
getStreamContext
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
public static function getStreamHandler(string $streamName) { $name = \md5($streamName); if (!isset(self::$_register[$name])) { return null; } return self::$_register[$name][self::HANDLER]; }
Get stream handler according to its name.
getStreamHandler
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
public function _setStream($stream) { if (false === \is_resource($stream) && ('resource' !== \gettype($stream) || 'Unknown' !== \get_resource_type($stream))) { throw new StreamException('Try to change the stream resource with an invalid one; '.'given %s.', 1, \gettype($stream)); } $old = $this->_bucket[self::RESOURCE]; $this->_bucket[self::RESOURCE] = $stream; return $old; }
Set the current stream. Useful to manage a stack of streams (e.g. socket and select). Notice that it could be unsafe to use this method without taking time to think about it two minutes. Resource of type “Unknown” is considered as valid.
_setStream
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
protected function hasBeenDeferred() { return $this->_hasBeenDeferred; }
Whether the opening of the stream has been deferred.
hasBeenDeferred
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
public function __destruct() { if (false === $this->isOpened()) { return; } $this->close(); return; }
Close the stream when destructing.
__destruct
php
bobthecow/psysh
src/Readline/Hoa/Stream.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Stream.php
MIT
protected function setCwd(string $cwd) { $old = $this->_cwd; $this->_cwd = $cwd; return $old; }
Set current working directory of the process.
setCwd
php
bobthecow/psysh
src/Readline/Hoa/ConsoleProcessus.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleProcessus.php
MIT
protected function setEnvironment(array $environment) { $old = $this->_environment; $this->_environment = $environment; return $old; }
Set environment of the process.
setEnvironment
php
bobthecow/psysh
src/Readline/Hoa/ConsoleProcessus.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleProcessus.php
MIT
public function getEnvironment() { return $this->_environment; }
Get environment of the process.
getEnvironment
php
bobthecow/psysh
src/Readline/Hoa/ConsoleProcessus.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleProcessus.php
MIT
public function __construct(string $path, ?int $flags = null, ?string $splFileInfoClass = null) { if (null === $flags) { parent::__construct($path); } else { parent::__construct($path, $flags); } $this->_relativePath = $path; $this->setSplFileInfoClass($splFileInfoClass); return; }
Constructor. Please, see \RecursiveDirectoryIterator::__construct() method. We add the $splFileInfoClass parameter.
__construct
php
bobthecow/psysh
src/Readline/Hoa/IteratorRecursiveDirectory.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/IteratorRecursiveDirectory.php
MIT
public function current() { $out = parent::current(); if (null !== $this->_splFileInfoClass && $out instanceof \SplFileInfo) { $out->setInfoClass($this->_splFileInfoClass); $out = $out->getFileInfo(); if ($out instanceof IteratorSplFileInfo) { $out->setRelativePath($this->getRelativePath()); } } return $out; }
Current. Please, see \RecursiveDirectoryIterator::current() method.
current
php
bobthecow/psysh
src/Readline/Hoa/IteratorRecursiveDirectory.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/IteratorRecursiveDirectory.php
MIT
public function getChildren() { $out = parent::getChildren(); $out->_relativePath = $this->getRelativePath(); $out->setSplFileInfoClass($this->_splFileInfoClass); return $out; }
Get children. Please, see \RecursiveDirectoryIterator::getChildren() method.
getChildren
php
bobthecow/psysh
src/Readline/Hoa/IteratorRecursiveDirectory.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/IteratorRecursiveDirectory.php
MIT
public function addIds(array $ids) { foreach ($ids as $id) { $this->_callables[$id] = []; } }
Adds acceptable ID (or reset).
addIds
php
bobthecow/psysh
src/Readline/Hoa/EventListener.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/EventListener.php
MIT
public function __construct( string $message, int $code = 0, $arguments = [], ?\Throwable $previous = null ) { parent::__construct($message, $code, $arguments, $previous); if (false === Event::eventExists('hoa://Event/Exception')) { Event::register('hoa://Event/Exception', __CLASS__); } $this->send(); return; }
Allocates a new exception. An exception is built with a formatted message, a code (an ID), and an array that contains the list of formatted string for the message. If chaining, a previous exception can be added.
__construct
php
bobthecow/psysh
src/Readline/Hoa/Exception.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Exception.php
MIT
public function send() { Event::notify( 'hoa://Event/Exception', $this, new EventBucket($this) ); }
Sends the exception on `hoa://Event/Exception`.
send
php
bobthecow/psysh
src/Readline/Hoa/Exception.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/Exception.php
MIT
public function __construct(string $path, ?int $flags = null, ?string $splFileInfoClass = null) { $this->_splFileInfoClass = $splFileInfoClass; if (null === $flags) { parent::__construct($path); } else { parent::__construct($path, $flags); } return; }
Constructor. Please, see \FileSystemIterator::__construct() method. We add the $splFileInfoClass parameter.
__construct
php
bobthecow/psysh
src/Readline/Hoa/IteratorFileSystem.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/IteratorFileSystem.php
MIT
public function current() { $out = parent::current(); if (null !== $this->_splFileInfoClass && $out instanceof \SplFileInfo) { $out->setInfoClass($this->_splFileInfoClass); $out = $out->getFileInfo(); } return $out; }
Current. Please, see \FileSystemIterator::current() method.
current
php
bobthecow/psysh
src/Readline/Hoa/IteratorFileSystem.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/IteratorFileSystem.php
MIT
public function __construct(?string $name = null, ?string $reach = null, array $children = []) { if (null !== $name) { $this->_name = $name; } if (null !== $reach) { $this->_reach = $reach; } foreach ($children as $child) { $this[] = $child; } return; }
Construct a protocol's node. If it is not a data object (i.e. if it does not extend this class to overload the `$_name` attribute), we can set the `$_name` attribute dynamically. This is useful to create a node on-the-fly.
__construct
php
bobthecow/psysh
src/Readline/Hoa/ProtocolNode.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolNode.php
MIT
protected function _resolve(string $path, &$accumulator, ?string $id = null) { if (\substr($path, 0, 6) === 'hoa://') { $path = \substr($path, 6); } if (empty($path)) { return null; } if (null === $accumulator) { $accumulator = []; $posId = \strpos($path, '#'); if (false !== $posId) { $id = \substr($path, $posId + 1); $path = \substr($path, 0, $posId); } else { $id = null; } } $path = \trim($path, '/'); $pos = \strpos($path, '/'); if (false !== $pos) { $next = \substr($path, 0, $pos); } else { $next = $path; } if (isset($this[$next])) { if (false === $pos) { if (null === $id) { $this->_resolveChoice($this[$next]->reach(), $accumulator); return true; } $accumulator = null; return $this[$next]->reachId($id); } $tnext = $this[$next]; $this->_resolveChoice($tnext->reach(), $accumulator); return $tnext->_resolve(\substr($path, $pos + 1), $accumulator, $id); } $this->_resolveChoice($this->reach($path), $accumulator); return true; }
Resolve a path, i.e. iterate the nodes tree and reach the queue of the path.
_resolve
php
bobthecow/psysh
src/Readline/Hoa/ProtocolNode.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolNode.php
MIT
protected function _resolveChoice($reach, &$accumulator) { if (null === $reach) { $reach = ''; } if (empty($accumulator)) { $accumulator = \explode(';', $reach); return; } if (false === \strpos($reach, ';')) { if (false !== $pos = \strrpos($reach, "\r")) { $reach = \substr($reach, $pos + 1); foreach ($accumulator as &$entry) { $entry = null; } } foreach ($accumulator as &$entry) { $entry .= $reach; } return; } $choices = \explode(';', $reach); $ref = $accumulator; $accumulator = []; foreach ($choices as $choice) { if (false !== $pos = \strrpos($choice, "\r")) { $choice = \substr($choice, $pos + 1); foreach ($ref as $entry) { $accumulator[] = $choice; } } else { foreach ($ref as $entry) { $accumulator[] = $entry.$choice; } } } unset($ref); return; }
Resolve choices, i.e. a reach value has a “;”.
_resolveChoice
php
bobthecow/psysh
src/Readline/Hoa/ProtocolNode.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolNode.php
MIT
public function reach(?string $queue = null) { return empty($queue) ? $this->_reach : $queue; }
Queue of the node. Generic one. Must be overrided in children classes.
reach
php
bobthecow/psysh
src/Readline/Hoa/ProtocolNode.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolNode.php
MIT
public function reachId(string $id) { throw new ProtocolException('The node %s has no ID support (tried to reach #%s).', 4, [$this->getName(), $id]); }
ID of the component. Generic one. Should be overrided in children classes.
reachId
php
bobthecow/psysh
src/Readline/Hoa/ProtocolNode.php
https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ProtocolNode.php
MIT