repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
bobthecow/psysh
src/Configuration.php
Configuration.getConfigFile
public function getConfigFile() { if (isset($this->configFile)) { return $this->configFile; } $files = ConfigPaths::getConfigFiles(['config.php', 'rc.php'], $this->configDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple configuration files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } return $files[0]; } }
php
public function getConfigFile() { if (isset($this->configFile)) { return $this->configFile; } $files = ConfigPaths::getConfigFiles(['config.php', 'rc.php'], $this->configDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple configuration files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } return $files[0]; } }
[ "public", "function", "getConfigFile", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "configFile", ")", ")", "{", "return", "$", "this", "->", "configFile", ";", "}", "$", "files", "=", "ConfigPaths", "::", "getConfigFiles", "(", "[", "'config.php'", ",", "'rc.php'", "]", ",", "$", "this", "->", "configDir", ")", ";", "if", "(", "!", "empty", "(", "$", "files", ")", ")", "{", "if", "(", "$", "this", "->", "warnOnMultipleConfigs", "&&", "\\", "count", "(", "$", "files", ")", ">", "1", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Multiple configuration files found: %s. Using %s'", ",", "\\", "implode", "(", "$", "files", ",", "', '", ")", ",", "$", "files", "[", "0", "]", ")", ";", "\\", "trigger_error", "(", "$", "msg", ",", "E_USER_NOTICE", ")", ";", "}", "return", "$", "files", "[", "0", "]", ";", "}", "}" ]
Get the current PsySH config file. If a `configFile` option was passed to the Configuration constructor, this file will be returned. If not, all possible config directories will be searched, and the first `config.php` or `rc.php` file which exists will be returned. If you're trying to decide where to put your config file, pick ~/.config/psysh/config.php @return string
[ "Get", "the", "current", "PsySH", "config", "file", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L174-L190
train
bobthecow/psysh
src/Configuration.php
Configuration.loadConfig
public function loadConfig(array $options) { foreach (self::$AVAILABLE_OPTIONS as $option) { if (isset($options[$option])) { $method = 'set' . \ucfirst($option); $this->$method($options[$option]); } } // legacy `tabCompletion` option if (isset($options['tabCompletion'])) { $msg = '`tabCompletion` is deprecated; use `useTabCompletion` instead.'; @\trigger_error($msg, E_USER_DEPRECATED); $this->setUseTabCompletion($options['tabCompletion']); } foreach (['commands', 'matchers', 'casters'] as $option) { if (isset($options[$option])) { $method = 'add' . \ucfirst($option); $this->$method($options[$option]); } } // legacy `tabCompletionMatchers` option if (isset($options['tabCompletionMatchers'])) { $msg = '`tabCompletionMatchers` is deprecated; use `matchers` instead.'; @\trigger_error($msg, E_USER_DEPRECATED); $this->addMatchers($options['tabCompletionMatchers']); } }
php
public function loadConfig(array $options) { foreach (self::$AVAILABLE_OPTIONS as $option) { if (isset($options[$option])) { $method = 'set' . \ucfirst($option); $this->$method($options[$option]); } } // legacy `tabCompletion` option if (isset($options['tabCompletion'])) { $msg = '`tabCompletion` is deprecated; use `useTabCompletion` instead.'; @\trigger_error($msg, E_USER_DEPRECATED); $this->setUseTabCompletion($options['tabCompletion']); } foreach (['commands', 'matchers', 'casters'] as $option) { if (isset($options[$option])) { $method = 'add' . \ucfirst($option); $this->$method($options[$option]); } } // legacy `tabCompletionMatchers` option if (isset($options['tabCompletionMatchers'])) { $msg = '`tabCompletionMatchers` is deprecated; use `matchers` instead.'; @\trigger_error($msg, E_USER_DEPRECATED); $this->addMatchers($options['tabCompletionMatchers']); } }
[ "public", "function", "loadConfig", "(", "array", "$", "options", ")", "{", "foreach", "(", "self", "::", "$", "AVAILABLE_OPTIONS", "as", "$", "option", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "$", "option", "]", ")", ")", "{", "$", "method", "=", "'set'", ".", "\\", "ucfirst", "(", "$", "option", ")", ";", "$", "this", "->", "$", "method", "(", "$", "options", "[", "$", "option", "]", ")", ";", "}", "}", "// legacy `tabCompletion` option", "if", "(", "isset", "(", "$", "options", "[", "'tabCompletion'", "]", ")", ")", "{", "$", "msg", "=", "'`tabCompletion` is deprecated; use `useTabCompletion` instead.'", ";", "@", "\\", "trigger_error", "(", "$", "msg", ",", "E_USER_DEPRECATED", ")", ";", "$", "this", "->", "setUseTabCompletion", "(", "$", "options", "[", "'tabCompletion'", "]", ")", ";", "}", "foreach", "(", "[", "'commands'", ",", "'matchers'", ",", "'casters'", "]", "as", "$", "option", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "$", "option", "]", ")", ")", "{", "$", "method", "=", "'add'", ".", "\\", "ucfirst", "(", "$", "option", ")", ";", "$", "this", "->", "$", "method", "(", "$", "options", "[", "$", "option", "]", ")", ";", "}", "}", "// legacy `tabCompletionMatchers` option", "if", "(", "isset", "(", "$", "options", "[", "'tabCompletionMatchers'", "]", ")", ")", "{", "$", "msg", "=", "'`tabCompletionMatchers` is deprecated; use `matchers` instead.'", ";", "@", "\\", "trigger_error", "(", "$", "msg", ",", "E_USER_DEPRECATED", ")", ";", "$", "this", "->", "addMatchers", "(", "$", "options", "[", "'tabCompletionMatchers'", "]", ")", ";", "}", "}" ]
Load configuration values from an array of options. @param array $options
[ "Load", "configuration", "values", "from", "an", "array", "of", "options", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L214-L245
train
bobthecow/psysh
src/Configuration.php
Configuration.getRuntimeDir
public function getRuntimeDir() { if (!isset($this->runtimeDir)) { $this->runtimeDir = ConfigPaths::getRuntimeDir(); } if (!\is_dir($this->runtimeDir)) { \mkdir($this->runtimeDir, 0700, true); } return $this->runtimeDir; }
php
public function getRuntimeDir() { if (!isset($this->runtimeDir)) { $this->runtimeDir = ConfigPaths::getRuntimeDir(); } if (!\is_dir($this->runtimeDir)) { \mkdir($this->runtimeDir, 0700, true); } return $this->runtimeDir; }
[ "public", "function", "getRuntimeDir", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "runtimeDir", ")", ")", "{", "$", "this", "->", "runtimeDir", "=", "ConfigPaths", "::", "getRuntimeDir", "(", ")", ";", "}", "if", "(", "!", "\\", "is_dir", "(", "$", "this", "->", "runtimeDir", ")", ")", "{", "\\", "mkdir", "(", "$", "this", "->", "runtimeDir", ",", "0700", ",", "true", ")", ";", "}", "return", "$", "this", "->", "runtimeDir", ";", "}" ]
Get the shell's temporary directory location. Defaults to `/psysh` inside the system's temp dir unless explicitly overridden. @return string
[ "Get", "the", "shell", "s", "temporary", "directory", "location", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L356-L367
train
bobthecow/psysh
src/Configuration.php
Configuration.getHistoryFile
public function getHistoryFile() { if (isset($this->historyFile)) { return $this->historyFile; } $files = ConfigPaths::getConfigFiles(['psysh_history', 'history'], $this->configDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple history files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } $this->setHistoryFile($files[0]); } else { // fallback: create our own history file $dir = $this->configDir ?: ConfigPaths::getCurrentConfigDir(); $this->setHistoryFile($dir . '/psysh_history'); } return $this->historyFile; }
php
public function getHistoryFile() { if (isset($this->historyFile)) { return $this->historyFile; } $files = ConfigPaths::getConfigFiles(['psysh_history', 'history'], $this->configDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple history files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } $this->setHistoryFile($files[0]); } else { // fallback: create our own history file $dir = $this->configDir ?: ConfigPaths::getCurrentConfigDir(); $this->setHistoryFile($dir . '/psysh_history'); } return $this->historyFile; }
[ "public", "function", "getHistoryFile", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "historyFile", ")", ")", "{", "return", "$", "this", "->", "historyFile", ";", "}", "$", "files", "=", "ConfigPaths", "::", "getConfigFiles", "(", "[", "'psysh_history'", ",", "'history'", "]", ",", "$", "this", "->", "configDir", ")", ";", "if", "(", "!", "empty", "(", "$", "files", ")", ")", "{", "if", "(", "$", "this", "->", "warnOnMultipleConfigs", "&&", "\\", "count", "(", "$", "files", ")", ">", "1", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Multiple history files found: %s. Using %s'", ",", "\\", "implode", "(", "$", "files", ",", "', '", ")", ",", "$", "files", "[", "0", "]", ")", ";", "\\", "trigger_error", "(", "$", "msg", ",", "E_USER_NOTICE", ")", ";", "}", "$", "this", "->", "setHistoryFile", "(", "$", "files", "[", "0", "]", ")", ";", "}", "else", "{", "// fallback: create our own history file", "$", "dir", "=", "$", "this", "->", "configDir", "?", ":", "ConfigPaths", "::", "getCurrentConfigDir", "(", ")", ";", "$", "this", "->", "setHistoryFile", "(", "$", "dir", ".", "'/psysh_history'", ")", ";", "}", "return", "$", "this", "->", "historyFile", ";", "}" ]
Get the readline history file path. Defaults to `/history` inside the shell's base config dir unless explicitly overridden. @return string
[ "Get", "the", "readline", "history", "file", "path", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L387-L409
train
bobthecow/psysh
src/Configuration.php
Configuration.useReadline
public function useReadline() { return isset($this->useReadline) ? ($this->hasReadline && $this->useReadline) : $this->hasReadline; }
php
public function useReadline() { return isset($this->useReadline) ? ($this->hasReadline && $this->useReadline) : $this->hasReadline; }
[ "public", "function", "useReadline", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "useReadline", ")", "?", "(", "$", "this", "->", "hasReadline", "&&", "$", "this", "->", "useReadline", ")", ":", "$", "this", "->", "hasReadline", ";", "}" ]
Check whether to use Readline. If `setUseReadline` as been set to true, but Readline is not actually available, this will return false. @return bool True if the current Shell should use Readline
[ "Check", "whether", "to", "use", "Readline", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L511-L514
train
bobthecow/psysh
src/Configuration.php
Configuration.getReadline
public function getReadline() { if (!isset($this->readline)) { $className = $this->getReadlineClass(); $this->readline = new $className( $this->getHistoryFile(), $this->getHistorySize(), $this->getEraseDuplicates() ); } return $this->readline; }
php
public function getReadline() { if (!isset($this->readline)) { $className = $this->getReadlineClass(); $this->readline = new $className( $this->getHistoryFile(), $this->getHistorySize(), $this->getEraseDuplicates() ); } return $this->readline; }
[ "public", "function", "getReadline", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "readline", ")", ")", "{", "$", "className", "=", "$", "this", "->", "getReadlineClass", "(", ")", ";", "$", "this", "->", "readline", "=", "new", "$", "className", "(", "$", "this", "->", "getHistoryFile", "(", ")", ",", "$", "this", "->", "getHistorySize", "(", ")", ",", "$", "this", "->", "getEraseDuplicates", "(", ")", ")", ";", "}", "return", "$", "this", "->", "readline", ";", "}" ]
Get the Psy Shell readline service. By default, this service uses (in order of preference): * GNU Readline * Libedit * A transient array-based readline emulation. @return Readline
[ "Get", "the", "Psy", "Shell", "readline", "service", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L537-L549
train
bobthecow/psysh
src/Configuration.php
Configuration.usePcntl
public function usePcntl() { return isset($this->usePcntl) ? ($this->hasPcntl && $this->usePcntl) : $this->hasPcntl; }
php
public function usePcntl() { return isset($this->usePcntl) ? ($this->hasPcntl && $this->usePcntl) : $this->hasPcntl; }
[ "public", "function", "usePcntl", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "usePcntl", ")", "?", "(", "$", "this", "->", "hasPcntl", "&&", "$", "this", "->", "usePcntl", ")", ":", "$", "this", "->", "hasPcntl", ";", "}" ]
Check whether to use Pcntl. If `setUsePcntl` has been set to true, but Pcntl is not actually available, this will return false. @return bool True if the current Shell should use Pcntl
[ "Check", "whether", "to", "use", "Pcntl", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L639-L642
train
bobthecow/psysh
src/Configuration.php
Configuration.useTabCompletion
public function useTabCompletion() { return isset($this->useTabCompletion) ? ($this->hasReadline && $this->useTabCompletion) : $this->hasReadline; }
php
public function useTabCompletion() { return isset($this->useTabCompletion) ? ($this->hasReadline && $this->useTabCompletion) : $this->hasReadline; }
[ "public", "function", "useTabCompletion", "(", ")", "{", "return", "isset", "(", "$", "this", "->", "useTabCompletion", ")", "?", "(", "$", "this", "->", "hasReadline", "&&", "$", "this", "->", "useTabCompletion", ")", ":", "$", "this", "->", "hasReadline", ";", "}" ]
Check whether to use tab completion. If `setUseTabCompletion` has been set to true, but readline is not actually available, this will return false. @return bool True if the current Shell should use tab completion
[ "Check", "whether", "to", "use", "tab", "completion", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L787-L790
train
bobthecow/psysh
src/Configuration.php
Configuration.getOutput
public function getOutput() { if (!isset($this->output)) { $this->output = new ShellOutput( ShellOutput::VERBOSITY_NORMAL, $this->getOutputDecorated(), null, $this->getPager() ); } return $this->output; }
php
public function getOutput() { if (!isset($this->output)) { $this->output = new ShellOutput( ShellOutput::VERBOSITY_NORMAL, $this->getOutputDecorated(), null, $this->getPager() ); } return $this->output; }
[ "public", "function", "getOutput", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "output", ")", ")", "{", "$", "this", "->", "output", "=", "new", "ShellOutput", "(", "ShellOutput", "::", "VERBOSITY_NORMAL", ",", "$", "this", "->", "getOutputDecorated", "(", ")", ",", "null", ",", "$", "this", "->", "getPager", "(", ")", ")", ";", "}", "return", "$", "this", "->", "output", ";", "}" ]
Get a Shell Output service instance. If none has been explicitly provided, this will create a new instance with VERBOSITY_NORMAL and the output page supplied by self::getPager @see self::getPager @return ShellOutput
[ "Get", "a", "Shell", "Output", "service", "instance", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L822-L834
train
bobthecow/psysh
src/Configuration.php
Configuration.setPager
public function setPager($pager) { if ($pager && !\is_string($pager) && !$pager instanceof OutputPager) { throw new \InvalidArgumentException('Unexpected pager instance'); } $this->pager = $pager; }
php
public function setPager($pager) { if ($pager && !\is_string($pager) && !$pager instanceof OutputPager) { throw new \InvalidArgumentException('Unexpected pager instance'); } $this->pager = $pager; }
[ "public", "function", "setPager", "(", "$", "pager", ")", "{", "if", "(", "$", "pager", "&&", "!", "\\", "is_string", "(", "$", "pager", ")", "&&", "!", "$", "pager", "instanceof", "OutputPager", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unexpected pager instance'", ")", ";", "}", "$", "this", "->", "pager", "=", "$", "pager", ";", "}" ]
Set the OutputPager service. If a string is supplied, a ProcOutputPager will be used which shells out to the specified command. @throws \InvalidArgumentException if $pager is not a string or OutputPager instance @param string|OutputPager $pager
[ "Set", "the", "OutputPager", "service", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L862-L869
train
bobthecow/psysh
src/Configuration.php
Configuration.getPager
public function getPager() { if (!isset($this->pager) && $this->usePcntl()) { if ($pager = \ini_get('cli.pager')) { // use the default pager $this->pager = $pager; } elseif ($less = \exec('which less 2>/dev/null')) { // check for the presence of less... $this->pager = $less . ' -R -S -F -X'; } } return $this->pager; }
php
public function getPager() { if (!isset($this->pager) && $this->usePcntl()) { if ($pager = \ini_get('cli.pager')) { // use the default pager $this->pager = $pager; } elseif ($less = \exec('which less 2>/dev/null')) { // check for the presence of less... $this->pager = $less . ' -R -S -F -X'; } } return $this->pager; }
[ "public", "function", "getPager", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "pager", ")", "&&", "$", "this", "->", "usePcntl", "(", ")", ")", "{", "if", "(", "$", "pager", "=", "\\", "ini_get", "(", "'cli.pager'", ")", ")", "{", "// use the default pager", "$", "this", "->", "pager", "=", "$", "pager", ";", "}", "elseif", "(", "$", "less", "=", "\\", "exec", "(", "'which less 2>/dev/null'", ")", ")", "{", "// check for the presence of less...", "$", "this", "->", "pager", "=", "$", "less", ".", "' -R -S -F -X'", ";", "}", "}", "return", "$", "this", "->", "pager", ";", "}" ]
Get an OutputPager instance or a command for an external Proc pager. If no Pager has been explicitly provided, and Pcntl is available, this will default to `cli.pager` ini value, falling back to `which less`. @return string|OutputPager
[ "Get", "an", "OutputPager", "instance", "or", "a", "command", "for", "an", "external", "Proc", "pager", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L879-L892
train
bobthecow/psysh
src/Configuration.php
Configuration.addMatchers
public function addMatchers(array $matchers) { $this->newMatchers = \array_merge($this->newMatchers, $matchers); if (isset($this->shell)) { $this->doAddMatchers(); } }
php
public function addMatchers(array $matchers) { $this->newMatchers = \array_merge($this->newMatchers, $matchers); if (isset($this->shell)) { $this->doAddMatchers(); } }
[ "public", "function", "addMatchers", "(", "array", "$", "matchers", ")", "{", "$", "this", "->", "newMatchers", "=", "\\", "array_merge", "(", "$", "this", "->", "newMatchers", ",", "$", "matchers", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "shell", ")", ")", "{", "$", "this", "->", "doAddMatchers", "(", ")", ";", "}", "}" ]
Add tab completion matchers to the AutoCompleter. This will buffer new matchers in the event that the Shell has not yet been instantiated. This allows the user to specify matchers in their config rc file, despite the fact that their file is needed in the Shell constructor. @param array $matchers
[ "Add", "tab", "completion", "matchers", "to", "the", "AutoCompleter", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L938-L944
train
bobthecow/psysh
src/Configuration.php
Configuration.doAddMatchers
private function doAddMatchers() { if (!empty($this->newMatchers)) { $this->shell->addMatchers($this->newMatchers); $this->newMatchers = []; } }
php
private function doAddMatchers() { if (!empty($this->newMatchers)) { $this->shell->addMatchers($this->newMatchers); $this->newMatchers = []; } }
[ "private", "function", "doAddMatchers", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "newMatchers", ")", ")", "{", "$", "this", "->", "shell", "->", "addMatchers", "(", "$", "this", "->", "newMatchers", ")", ";", "$", "this", "->", "newMatchers", "=", "[", "]", ";", "}", "}" ]
Internal method for adding tab completion matchers. This will set any new matchers once a Shell is available.
[ "Internal", "method", "for", "adding", "tab", "completion", "matchers", ".", "This", "will", "set", "any", "new", "matchers", "once", "a", "Shell", "is", "available", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L950-L956
train
bobthecow/psysh
src/Configuration.php
Configuration.addCommands
public function addCommands(array $commands) { $this->newCommands = \array_merge($this->newCommands, $commands); if (isset($this->shell)) { $this->doAddCommands(); } }
php
public function addCommands(array $commands) { $this->newCommands = \array_merge($this->newCommands, $commands); if (isset($this->shell)) { $this->doAddCommands(); } }
[ "public", "function", "addCommands", "(", "array", "$", "commands", ")", "{", "$", "this", "->", "newCommands", "=", "\\", "array_merge", "(", "$", "this", "->", "newCommands", ",", "$", "commands", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "shell", ")", ")", "{", "$", "this", "->", "doAddCommands", "(", ")", ";", "}", "}" ]
Add commands to the Shell. This will buffer new commands in the event that the Shell has not yet been instantiated. This allows the user to specify commands in their config rc file, despite the fact that their file is needed in the Shell constructor. @param array $commands
[ "Add", "commands", "to", "the", "Shell", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L978-L984
train
bobthecow/psysh
src/Configuration.php
Configuration.doAddCommands
private function doAddCommands() { if (!empty($this->newCommands)) { $this->shell->addCommands($this->newCommands); $this->newCommands = []; } }
php
private function doAddCommands() { if (!empty($this->newCommands)) { $this->shell->addCommands($this->newCommands); $this->newCommands = []; } }
[ "private", "function", "doAddCommands", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "newCommands", ")", ")", "{", "$", "this", "->", "shell", "->", "addCommands", "(", "$", "this", "->", "newCommands", ")", ";", "$", "this", "->", "newCommands", "=", "[", "]", ";", "}", "}" ]
Internal method for adding commands. This will set any new commands once a Shell is available.
[ "Internal", "method", "for", "adding", "commands", ".", "This", "will", "set", "any", "new", "commands", "once", "a", "Shell", "is", "available", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L990-L996
train
bobthecow/psysh
src/Configuration.php
Configuration.setShell
public function setShell(Shell $shell) { $this->shell = $shell; $this->doAddCommands(); $this->doAddMatchers(); }
php
public function setShell(Shell $shell) { $this->shell = $shell; $this->doAddCommands(); $this->doAddMatchers(); }
[ "public", "function", "setShell", "(", "Shell", "$", "shell", ")", "{", "$", "this", "->", "shell", "=", "$", "shell", ";", "$", "this", "->", "doAddCommands", "(", ")", ";", "$", "this", "->", "doAddMatchers", "(", ")", ";", "}" ]
Set the Shell backreference and add any new commands to the Shell. @param Shell $shell
[ "Set", "the", "Shell", "backreference", "and", "add", "any", "new", "commands", "to", "the", "Shell", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1003-L1008
train
bobthecow/psysh
src/Configuration.php
Configuration.getManualDbFile
public function getManualDbFile() { if (isset($this->manualDbFile)) { return $this->manualDbFile; } $files = ConfigPaths::getDataFiles(['php_manual.sqlite'], $this->dataDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple manual database files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } return $this->manualDbFile = $files[0]; } }
php
public function getManualDbFile() { if (isset($this->manualDbFile)) { return $this->manualDbFile; } $files = ConfigPaths::getDataFiles(['php_manual.sqlite'], $this->dataDir); if (!empty($files)) { if ($this->warnOnMultipleConfigs && \count($files) > 1) { $msg = \sprintf('Multiple manual database files found: %s. Using %s', \implode($files, ', '), $files[0]); \trigger_error($msg, E_USER_NOTICE); } return $this->manualDbFile = $files[0]; } }
[ "public", "function", "getManualDbFile", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "manualDbFile", ")", ")", "{", "return", "$", "this", "->", "manualDbFile", ";", "}", "$", "files", "=", "ConfigPaths", "::", "getDataFiles", "(", "[", "'php_manual.sqlite'", "]", ",", "$", "this", "->", "dataDir", ")", ";", "if", "(", "!", "empty", "(", "$", "files", ")", ")", "{", "if", "(", "$", "this", "->", "warnOnMultipleConfigs", "&&", "\\", "count", "(", "$", "files", ")", ">", "1", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'Multiple manual database files found: %s. Using %s'", ",", "\\", "implode", "(", "$", "files", ",", "', '", ")", ",", "$", "files", "[", "0", "]", ")", ";", "\\", "trigger_error", "(", "$", "msg", ",", "E_USER_NOTICE", ")", ";", "}", "return", "$", "this", "->", "manualDbFile", "=", "$", "files", "[", "0", "]", ";", "}", "}" ]
Get the current PHP manual database file. @return string Default: '~/.local/share/psysh/php_manual.sqlite'
[ "Get", "the", "current", "PHP", "manual", "database", "file", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1028-L1043
train
bobthecow/psysh
src/Configuration.php
Configuration.getManualDb
public function getManualDb() { if (!isset($this->manualDb)) { $dbFile = $this->getManualDbFile(); if (\is_file($dbFile)) { try { $this->manualDb = new \PDO('sqlite:' . $dbFile); } catch (\PDOException $e) { if ($e->getMessage() === 'could not find driver') { throw new RuntimeException('SQLite PDO driver not found', 0, $e); } else { throw $e; } } } } return $this->manualDb; }
php
public function getManualDb() { if (!isset($this->manualDb)) { $dbFile = $this->getManualDbFile(); if (\is_file($dbFile)) { try { $this->manualDb = new \PDO('sqlite:' . $dbFile); } catch (\PDOException $e) { if ($e->getMessage() === 'could not find driver') { throw new RuntimeException('SQLite PDO driver not found', 0, $e); } else { throw $e; } } } } return $this->manualDb; }
[ "public", "function", "getManualDb", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "manualDb", ")", ")", "{", "$", "dbFile", "=", "$", "this", "->", "getManualDbFile", "(", ")", ";", "if", "(", "\\", "is_file", "(", "$", "dbFile", ")", ")", "{", "try", "{", "$", "this", "->", "manualDb", "=", "new", "\\", "PDO", "(", "'sqlite:'", ".", "$", "dbFile", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "if", "(", "$", "e", "->", "getMessage", "(", ")", "===", "'could not find driver'", ")", "{", "throw", "new", "RuntimeException", "(", "'SQLite PDO driver not found'", ",", "0", ",", "$", "e", ")", ";", "}", "else", "{", "throw", "$", "e", ";", "}", "}", "}", "}", "return", "$", "this", "->", "manualDb", ";", "}" ]
Get a PHP manual database connection. @return \PDO
[ "Get", "a", "PHP", "manual", "database", "connection", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1050-L1068
train
bobthecow/psysh
src/Configuration.php
Configuration.getPresenter
public function getPresenter() { if (!isset($this->presenter)) { $this->presenter = new Presenter($this->getOutput()->getFormatter(), $this->forceArrayIndexes()); } return $this->presenter; }
php
public function getPresenter() { if (!isset($this->presenter)) { $this->presenter = new Presenter($this->getOutput()->getFormatter(), $this->forceArrayIndexes()); } return $this->presenter; }
[ "public", "function", "getPresenter", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "presenter", ")", ")", "{", "$", "this", "->", "presenter", "=", "new", "Presenter", "(", "$", "this", "->", "getOutput", "(", ")", "->", "getFormatter", "(", ")", ",", "$", "this", "->", "forceArrayIndexes", "(", ")", ")", ";", "}", "return", "$", "this", "->", "presenter", ";", "}" ]
Get the Presenter service. @return Presenter
[ "Get", "the", "Presenter", "service", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1085-L1092
train
bobthecow/psysh
src/Configuration.php
Configuration.setColorMode
public function setColorMode($colorMode) { $validColorModes = [ self::COLOR_MODE_AUTO, self::COLOR_MODE_FORCED, self::COLOR_MODE_DISABLED, ]; if (\in_array($colorMode, $validColorModes)) { $this->colorMode = $colorMode; } else { throw new \InvalidArgumentException('invalid color mode: ' . $colorMode); } }
php
public function setColorMode($colorMode) { $validColorModes = [ self::COLOR_MODE_AUTO, self::COLOR_MODE_FORCED, self::COLOR_MODE_DISABLED, ]; if (\in_array($colorMode, $validColorModes)) { $this->colorMode = $colorMode; } else { throw new \InvalidArgumentException('invalid color mode: ' . $colorMode); } }
[ "public", "function", "setColorMode", "(", "$", "colorMode", ")", "{", "$", "validColorModes", "=", "[", "self", "::", "COLOR_MODE_AUTO", ",", "self", "::", "COLOR_MODE_FORCED", ",", "self", "::", "COLOR_MODE_DISABLED", ",", "]", ";", "if", "(", "\\", "in_array", "(", "$", "colorMode", ",", "$", "validColorModes", ")", ")", "{", "$", "this", "->", "colorMode", "=", "$", "colorMode", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'invalid color mode: '", ".", "$", "colorMode", ")", ";", "}", "}" ]
Set the current color mode. @param string $colorMode
[ "Set", "the", "current", "color", "mode", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1128-L1141
train
bobthecow/psysh
src/Configuration.php
Configuration.getChecker
public function getChecker() { if (!isset($this->checker)) { $interval = $this->getUpdateCheck(); switch ($interval) { case Checker::ALWAYS: $this->checker = new GitHubChecker(); break; case Checker::DAILY: case Checker::WEEKLY: case Checker::MONTHLY: $checkFile = $this->getUpdateCheckCacheFile(); if ($checkFile === false) { $this->checker = new NoopChecker(); } else { $this->checker = new IntervalChecker($checkFile, $interval); } break; case Checker::NEVER: $this->checker = new NoopChecker(); break; } } return $this->checker; }
php
public function getChecker() { if (!isset($this->checker)) { $interval = $this->getUpdateCheck(); switch ($interval) { case Checker::ALWAYS: $this->checker = new GitHubChecker(); break; case Checker::DAILY: case Checker::WEEKLY: case Checker::MONTHLY: $checkFile = $this->getUpdateCheckCacheFile(); if ($checkFile === false) { $this->checker = new NoopChecker(); } else { $this->checker = new IntervalChecker($checkFile, $interval); } break; case Checker::NEVER: $this->checker = new NoopChecker(); break; } } return $this->checker; }
[ "public", "function", "getChecker", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "checker", ")", ")", "{", "$", "interval", "=", "$", "this", "->", "getUpdateCheck", "(", ")", ";", "switch", "(", "$", "interval", ")", "{", "case", "Checker", "::", "ALWAYS", ":", "$", "this", "->", "checker", "=", "new", "GitHubChecker", "(", ")", ";", "break", ";", "case", "Checker", "::", "DAILY", ":", "case", "Checker", "::", "WEEKLY", ":", "case", "Checker", "::", "MONTHLY", ":", "$", "checkFile", "=", "$", "this", "->", "getUpdateCheckCacheFile", "(", ")", ";", "if", "(", "$", "checkFile", "===", "false", ")", "{", "$", "this", "->", "checker", "=", "new", "NoopChecker", "(", ")", ";", "}", "else", "{", "$", "this", "->", "checker", "=", "new", "IntervalChecker", "(", "$", "checkFile", ",", "$", "interval", ")", ";", "}", "break", ";", "case", "Checker", "::", "NEVER", ":", "$", "this", "->", "checker", "=", "new", "NoopChecker", "(", ")", ";", "break", ";", "}", "}", "return", "$", "this", "->", "checker", ";", "}" ]
Get an update checker service instance. If none has been explicitly defined, this will create a new instance. @return Checker
[ "Get", "an", "update", "checker", "service", "instance", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1170-L1197
train
bobthecow/psysh
src/Configuration.php
Configuration.setUpdateCheck
public function setUpdateCheck($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; }
php
public function setUpdateCheck($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; }
[ "public", "function", "setUpdateCheck", "(", "$", "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 \InvalidArgumentDescription if the update check interval is unknown @param string $interval
[ "Set", "the", "update", "check", "interval", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Configuration.php#L1219-L1234
train
bobthecow/psysh
src/Command/SudoCommand.php
SudoCommand.parse
private function parse($code) { try { return $this->parser->parse($code); } catch (\PhpParser\Error $e) { if (\strpos($e->getMessage(), 'unexpected EOF') === false) { throw $e; } // If we got an unexpected EOF, let's try it again with a semicolon. return $this->parser->parse($code . ';'); } }
php
private function parse($code) { try { return $this->parser->parse($code); } catch (\PhpParser\Error $e) { if (\strpos($e->getMessage(), 'unexpected EOF') === false) { throw $e; } // If we got an unexpected EOF, let's try it again with a semicolon. return $this->parser->parse($code . ';'); } }
[ "private", "function", "parse", "(", "$", "code", ")", "{", "try", "{", "return", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ")", ";", "}", "catch", "(", "\\", "PhpParser", "\\", "Error", "$", "e", ")", "{", "if", "(", "\\", "strpos", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'unexpected EOF'", ")", "===", "false", ")", "{", "throw", "$", "e", ";", "}", "// If we got an unexpected EOF, let's try it again with a semicolon.", "return", "$", "this", "->", "parser", "->", "parse", "(", "$", "code", ".", "';'", ")", ";", "}", "}" ]
Lex and parse a string of code into statements. @param string $code @return array Statements
[ "Lex", "and", "parse", "a", "string", "of", "code", "into", "statements", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/SudoCommand.php#L130-L142
train
bobthecow/psysh
src/ExecutionLoop.php
ExecutionLoop.run
public function run(Shell $shell) { $this->loadIncludes($shell); $closure = new ExecutionLoopClosure($shell); $closure->execute(); }
php
public function run(Shell $shell) { $this->loadIncludes($shell); $closure = new ExecutionLoopClosure($shell); $closure->execute(); }
[ "public", "function", "run", "(", "Shell", "$", "shell", ")", "{", "$", "this", "->", "loadIncludes", "(", "$", "shell", ")", ";", "$", "closure", "=", "new", "ExecutionLoopClosure", "(", "$", "shell", ")", ";", "$", "closure", "->", "execute", "(", ")", ";", "}" ]
Run the execution loop. @throws ThrowUpException if thrown by the `throw-up` command @param Shell $shell
[ "Run", "the", "execution", "loop", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop.php#L28-L34
train
bobthecow/psysh
src/ExecutionLoop.php
ExecutionLoop.loadIncludes
protected function loadIncludes(Shell $shell) { // Load user-defined includes $load = function (Shell $__psysh__) { \set_error_handler([$__psysh__, 'handleError']); foreach ($__psysh__->getIncludes() as $__psysh_include__) { try { include $__psysh_include__; } catch (\Error $_e) { $__psysh__->writeException(ErrorException::fromError($_e)); } catch (\Exception $_e) { $__psysh__->writeException($_e); } } \restore_error_handler(); unset($__psysh_include__); // Override any new local variables with pre-defined scope variables \extract($__psysh__->getScopeVariables(false)); // ... then add the whole mess of variables back. $__psysh__->setScopeVariables(\get_defined_vars()); }; $load($shell); }
php
protected function loadIncludes(Shell $shell) { // Load user-defined includes $load = function (Shell $__psysh__) { \set_error_handler([$__psysh__, 'handleError']); foreach ($__psysh__->getIncludes() as $__psysh_include__) { try { include $__psysh_include__; } catch (\Error $_e) { $__psysh__->writeException(ErrorException::fromError($_e)); } catch (\Exception $_e) { $__psysh__->writeException($_e); } } \restore_error_handler(); unset($__psysh_include__); // Override any new local variables with pre-defined scope variables \extract($__psysh__->getScopeVariables(false)); // ... then add the whole mess of variables back. $__psysh__->setScopeVariables(\get_defined_vars()); }; $load($shell); }
[ "protected", "function", "loadIncludes", "(", "Shell", "$", "shell", ")", "{", "// Load user-defined includes", "$", "load", "=", "function", "(", "Shell", "$", "__psysh__", ")", "{", "\\", "set_error_handler", "(", "[", "$", "__psysh__", ",", "'handleError'", "]", ")", ";", "foreach", "(", "$", "__psysh__", "->", "getIncludes", "(", ")", "as", "$", "__psysh_include__", ")", "{", "try", "{", "include", "$", "__psysh_include__", ";", "}", "catch", "(", "\\", "Error", "$", "_e", ")", "{", "$", "__psysh__", "->", "writeException", "(", "ErrorException", "::", "fromError", "(", "$", "_e", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "_e", ")", "{", "$", "__psysh__", "->", "writeException", "(", "$", "_e", ")", ";", "}", "}", "\\", "restore_error_handler", "(", ")", ";", "unset", "(", "$", "__psysh_include__", ")", ";", "// Override any new local variables with pre-defined scope variables", "\\", "extract", "(", "$", "__psysh__", "->", "getScopeVariables", "(", "false", ")", ")", ";", "// ... then add the whole mess of variables back.", "$", "__psysh__", "->", "setScopeVariables", "(", "\\", "get_defined_vars", "(", ")", ")", ";", "}", ";", "$", "load", "(", "$", "shell", ")", ";", "}" ]
Load user-defined includes. @param Shell $shell
[ "Load", "user", "-", "defined", "includes", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop.php#L41-L66
train
bobthecow/psysh
src/CodeCleaner/StrictTypesPass.php
StrictTypesPass.beforeTraverse
public function beforeTraverse(array $nodes) { if (!$this->atLeastPhp7) { return; // @codeCoverageIgnore } $prependStrictTypes = $this->strictTypes; foreach ($nodes as $key => $node) { if ($node instanceof Declare_) { foreach ($node->declares as $declare) { // For PHP Parser 4.x $declareKey = $declare->key instanceof Identifier ? $declare->key->toString() : $declare->key; if ($declareKey === 'strict_types') { $value = $declare->value; if (!$value instanceof LNumber || ($value->value !== 0 && $value->value !== 1)) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } $this->strictTypes = $value->value === 1; } } } } if ($prependStrictTypes) { $first = \reset($nodes); if (!$first instanceof Declare_) { $declare = new Declare_([new DeclareDeclare('strict_types', new LNumber(1))]); \array_unshift($nodes, $declare); } } return $nodes; }
php
public function beforeTraverse(array $nodes) { if (!$this->atLeastPhp7) { return; // @codeCoverageIgnore } $prependStrictTypes = $this->strictTypes; foreach ($nodes as $key => $node) { if ($node instanceof Declare_) { foreach ($node->declares as $declare) { // For PHP Parser 4.x $declareKey = $declare->key instanceof Identifier ? $declare->key->toString() : $declare->key; if ($declareKey === 'strict_types') { $value = $declare->value; if (!$value instanceof LNumber || ($value->value !== 0 && $value->value !== 1)) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } $this->strictTypes = $value->value === 1; } } } } if ($prependStrictTypes) { $first = \reset($nodes); if (!$first instanceof Declare_) { $declare = new Declare_([new DeclareDeclare('strict_types', new LNumber(1))]); \array_unshift($nodes, $declare); } } return $nodes; }
[ "public", "function", "beforeTraverse", "(", "array", "$", "nodes", ")", "{", "if", "(", "!", "$", "this", "->", "atLeastPhp7", ")", "{", "return", ";", "// @codeCoverageIgnore", "}", "$", "prependStrictTypes", "=", "$", "this", "->", "strictTypes", ";", "foreach", "(", "$", "nodes", "as", "$", "key", "=>", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "Declare_", ")", "{", "foreach", "(", "$", "node", "->", "declares", "as", "$", "declare", ")", "{", "// For PHP Parser 4.x", "$", "declareKey", "=", "$", "declare", "->", "key", "instanceof", "Identifier", "?", "$", "declare", "->", "key", "->", "toString", "(", ")", ":", "$", "declare", "->", "key", ";", "if", "(", "$", "declareKey", "===", "'strict_types'", ")", "{", "$", "value", "=", "$", "declare", "->", "value", ";", "if", "(", "!", "$", "value", "instanceof", "LNumber", "||", "(", "$", "value", "->", "value", "!==", "0", "&&", "$", "value", "->", "value", "!==", "1", ")", ")", "{", "throw", "new", "FatalErrorException", "(", "self", "::", "EXCEPTION_MESSAGE", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "$", "this", "->", "strictTypes", "=", "$", "value", "->", "value", "===", "1", ";", "}", "}", "}", "}", "if", "(", "$", "prependStrictTypes", ")", "{", "$", "first", "=", "\\", "reset", "(", "$", "nodes", ")", ";", "if", "(", "!", "$", "first", "instanceof", "Declare_", ")", "{", "$", "declare", "=", "new", "Declare_", "(", "[", "new", "DeclareDeclare", "(", "'strict_types'", ",", "new", "LNumber", "(", "1", ")", ")", "]", ")", ";", "\\", "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
[ "If", "this", "is", "a", "standalone", "strict", "types", "declaration", "remember", "it", "for", "later", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/StrictTypesPass.php#L52-L86
train
bobthecow/psysh
src/Util/Mirror.php
Mirror.get
public static function get($value, $member = null, $filter = 15) { if ($member === null && \is_string($value)) { if (\function_exists($value)) { return new \ReflectionFunction($value); } elseif (\defined($value) || ReflectionConstant_::isMagicConstant($value)) { return new ReflectionConstant_($value); } } $class = self::getClass($value); if ($member === null) { return $class; } elseif ($filter & self::CONSTANT && $class->hasConstant($member)) { return ReflectionClassConstant::create($value, $member); } elseif ($filter & self::METHOD && $class->hasMethod($member)) { return $class->getMethod($member); } elseif ($filter & self::PROPERTY && $class->hasProperty($member)) { return $class->getProperty($member); } elseif ($filter & self::STATIC_PROPERTY && $class->hasProperty($member) && $class->getProperty($member)->isStatic()) { return $class->getProperty($member); } else { throw new RuntimeException(\sprintf( 'Unknown member %s on class %s', $member, \is_object($value) ? \get_class($value) : $value )); } }
php
public static function get($value, $member = null, $filter = 15) { if ($member === null && \is_string($value)) { if (\function_exists($value)) { return new \ReflectionFunction($value); } elseif (\defined($value) || ReflectionConstant_::isMagicConstant($value)) { return new ReflectionConstant_($value); } } $class = self::getClass($value); if ($member === null) { return $class; } elseif ($filter & self::CONSTANT && $class->hasConstant($member)) { return ReflectionClassConstant::create($value, $member); } elseif ($filter & self::METHOD && $class->hasMethod($member)) { return $class->getMethod($member); } elseif ($filter & self::PROPERTY && $class->hasProperty($member)) { return $class->getProperty($member); } elseif ($filter & self::STATIC_PROPERTY && $class->hasProperty($member) && $class->getProperty($member)->isStatic()) { return $class->getProperty($member); } else { throw new RuntimeException(\sprintf( 'Unknown member %s on class %s', $member, \is_object($value) ? \get_class($value) : $value )); } }
[ "public", "static", "function", "get", "(", "$", "value", ",", "$", "member", "=", "null", ",", "$", "filter", "=", "15", ")", "{", "if", "(", "$", "member", "===", "null", "&&", "\\", "is_string", "(", "$", "value", ")", ")", "{", "if", "(", "\\", "function_exists", "(", "$", "value", ")", ")", "{", "return", "new", "\\", "ReflectionFunction", "(", "$", "value", ")", ";", "}", "elseif", "(", "\\", "defined", "(", "$", "value", ")", "||", "ReflectionConstant_", "::", "isMagicConstant", "(", "$", "value", ")", ")", "{", "return", "new", "ReflectionConstant_", "(", "$", "value", ")", ";", "}", "}", "$", "class", "=", "self", "::", "getClass", "(", "$", "value", ")", ";", "if", "(", "$", "member", "===", "null", ")", "{", "return", "$", "class", ";", "}", "elseif", "(", "$", "filter", "&", "self", "::", "CONSTANT", "&&", "$", "class", "->", "hasConstant", "(", "$", "member", ")", ")", "{", "return", "ReflectionClassConstant", "::", "create", "(", "$", "value", ",", "$", "member", ")", ";", "}", "elseif", "(", "$", "filter", "&", "self", "::", "METHOD", "&&", "$", "class", "->", "hasMethod", "(", "$", "member", ")", ")", "{", "return", "$", "class", "->", "getMethod", "(", "$", "member", ")", ";", "}", "elseif", "(", "$", "filter", "&", "self", "::", "PROPERTY", "&&", "$", "class", "->", "hasProperty", "(", "$", "member", ")", ")", "{", "return", "$", "class", "->", "getProperty", "(", "$", "member", ")", ";", "}", "elseif", "(", "$", "filter", "&", "self", "::", "STATIC_PROPERTY", "&&", "$", "class", "->", "hasProperty", "(", "$", "member", ")", "&&", "$", "class", "->", "getProperty", "(", "$", "member", ")", "->", "isStatic", "(", ")", ")", "{", "return", "$", "class", "->", "getProperty", "(", "$", "member", ")", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\\", "sprintf", "(", "'Unknown member %s on class %s'", ",", "$", "member", ",", "\\", "is_object", "(", "$", "value", ")", "?", "\\", "get_class", "(", "$", "value", ")", ":", "$", "value", ")", ")", ";", "}", "}" ]
Get a Reflector for a function, class or instance, constant, method or property. Optionally, pass a $filter param to restrict the types of members checked. For example, to only Reflectors for static properties and constants, pass: $filter = Mirror::CONSTANT | Mirror::STATIC_PROPERTY @throws \Psy\Exception\RuntimeException when a $member specified but not present on $value @throws \InvalidArgumentException if $value is something other than an object or class/function name @param mixed $value Class or function name, or variable instance @param string $member Optional: property, constant or method name (default: null) @param int $filter (default: CONSTANT | METHOD | PROPERTY | STATIC_PROPERTY) @return \Reflector
[ "Get", "a", "Reflector", "for", "a", "function", "class", "or", "instance", "constant", "method", "or", "property", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Util/Mirror.php#L45-L74
train
bobthecow/psysh
src/Command/ListCommand/InterfaceEnumerator.php
InterfaceEnumerator.prepareInterfaces
protected function prepareInterfaces(array $interfaces) { \natcasesort($interfaces); // My kingdom for a generator. $ret = []; foreach ($interfaces as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
php
protected function prepareInterfaces(array $interfaces) { \natcasesort($interfaces); // My kingdom for a generator. $ret = []; foreach ($interfaces as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_CLASS, 'value' => $this->presentSignature($name), ]; } } return $ret; }
[ "protected", "function", "prepareInterfaces", "(", "array", "$", "interfaces", ")", "{", "\\", "natcasesort", "(", "$", "interfaces", ")", ";", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "interfaces", "as", "$", "name", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "ret", "[", "$", "name", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'style'", "=>", "self", "::", "IS_CLASS", ",", "'value'", "=>", "$", "this", "->", "presentSignature", "(", "$", "name", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted interface array. @param array $interfaces @return array
[ "Prepare", "formatted", "interface", "array", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/InterfaceEnumerator.php#L70-L88
train
bobthecow/psysh
src/CodeCleaner/LegacyEmptyPass.php
LegacyEmptyPass.enterNode
public function enterNode(Node $node) { if ($this->atLeastPhp55) { return; } if (!$node instanceof Empty_) { return; } if (!$node->expr instanceof Variable) { $msg = \sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr)); throw new ParseErrorException($msg, $node->expr->getLine()); } }
php
public function enterNode(Node $node) { if ($this->atLeastPhp55) { return; } if (!$node instanceof Empty_) { return; } if (!$node->expr instanceof Variable) { $msg = \sprintf('syntax error, unexpected %s', $this->getUnexpectedThing($node->expr)); throw new ParseErrorException($msg, $node->expr->getLine()); } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "if", "(", "$", "this", "->", "atLeastPhp55", ")", "{", "return", ";", "}", "if", "(", "!", "$", "node", "instanceof", "Empty_", ")", "{", "return", ";", "}", "if", "(", "!", "$", "node", "->", "expr", "instanceof", "Variable", ")", "{", "$", "msg", "=", "\\", "sprintf", "(", "'syntax error, unexpected %s'", ",", "$", "this", "->", "getUnexpectedThing", "(", "$", "node", "->", "expr", ")", ")", ";", "throw", "new", "ParseErrorException", "(", "$", "msg", ",", "$", "node", "->", "expr", "->", "getLine", "(", ")", ")", ";", "}", "}" ]
Validate use of empty in PHP < 5.5. @throws ParseErrorException if the user used empty with anything but a variable @param Node $node
[ "Validate", "use", "of", "empty", "in", "PHP", "<", "5", ".", "5", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/LegacyEmptyPass.php#L41-L56
train
bobthecow/psysh
src/Command/ThrowUpCommand.php
ThrowUpCommand.prepareArgs
private function prepareArgs($code = null) { if (!$code) { // Default to last exception if nothing else was supplied return [new Arg(new Variable('_e'))]; } if (\strpos('<?', $code) === false) { $code = '<?php ' . $code; } $nodes = $this->parse($code); if (\count($nodes) !== 1) { throw new \InvalidArgumentException('No idea how to throw this'); } $node = $nodes[0]; // Make this work for PHP Parser v3.x $expr = isset($node->expr) ? $node->expr : $node; $args = [new Arg($expr, false, false, $node->getAttributes())]; // Allow throwing via a string, e.g. `throw-up "SUP"` if ($expr instanceof String_) { return [new New_(new FullyQualifiedName('Exception'), $args)]; } return $args; }
php
private function prepareArgs($code = null) { if (!$code) { // Default to last exception if nothing else was supplied return [new Arg(new Variable('_e'))]; } if (\strpos('<?', $code) === false) { $code = '<?php ' . $code; } $nodes = $this->parse($code); if (\count($nodes) !== 1) { throw new \InvalidArgumentException('No idea how to throw this'); } $node = $nodes[0]; // Make this work for PHP Parser v3.x $expr = isset($node->expr) ? $node->expr : $node; $args = [new Arg($expr, false, false, $node->getAttributes())]; // Allow throwing via a string, e.g. `throw-up "SUP"` if ($expr instanceof String_) { return [new New_(new FullyQualifiedName('Exception'), $args)]; } return $args; }
[ "private", "function", "prepareArgs", "(", "$", "code", "=", "null", ")", "{", "if", "(", "!", "$", "code", ")", "{", "// Default to last exception if nothing else was supplied", "return", "[", "new", "Arg", "(", "new", "Variable", "(", "'_e'", ")", ")", "]", ";", "}", "if", "(", "\\", "strpos", "(", "'<?'", ",", "$", "code", ")", "===", "false", ")", "{", "$", "code", "=", "'<?php '", ".", "$", "code", ";", "}", "$", "nodes", "=", "$", "this", "->", "parse", "(", "$", "code", ")", ";", "if", "(", "\\", "count", "(", "$", "nodes", ")", "!==", "1", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'No idea how to throw this'", ")", ";", "}", "$", "node", "=", "$", "nodes", "[", "0", "]", ";", "// Make this work for PHP Parser v3.x", "$", "expr", "=", "isset", "(", "$", "node", "->", "expr", ")", "?", "$", "node", "->", "expr", ":", "$", "node", ";", "$", "args", "=", "[", "new", "Arg", "(", "$", "expr", ",", "false", ",", "false", ",", "$", "node", "->", "getAttributes", "(", ")", ")", "]", ";", "// Allow throwing via a string, e.g. `throw-up \"SUP\"`", "if", "(", "$", "expr", "instanceof", "String_", ")", "{", "return", "[", "new", "New_", "(", "new", "FullyQualifiedName", "(", "'Exception'", ")", ",", "$", "args", ")", "]", ";", "}", "return", "$", "args", ";", "}" ]
Parse the supplied command argument. If no argument was given, this falls back to `$_e` @throws InvalidArgumentException if there is no exception to throw @param string $code @return Arg[]
[ "Parse", "the", "supplied", "command", "argument", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ThrowUpCommand.php#L121-L150
train
bobthecow/psysh
src/Command/ListCommand.php
ListCommand.initEnumerators
protected function initEnumerators() { if (!isset($this->enumerators)) { $mgr = $this->presenter; $this->enumerators = [ new ClassConstantEnumerator($mgr), new ClassEnumerator($mgr), new ConstantEnumerator($mgr), new FunctionEnumerator($mgr), new GlobalVariableEnumerator($mgr), new PropertyEnumerator($mgr), new MethodEnumerator($mgr), new VariableEnumerator($mgr, $this->context), ]; } }
php
protected function initEnumerators() { if (!isset($this->enumerators)) { $mgr = $this->presenter; $this->enumerators = [ new ClassConstantEnumerator($mgr), new ClassEnumerator($mgr), new ConstantEnumerator($mgr), new FunctionEnumerator($mgr), new GlobalVariableEnumerator($mgr), new PropertyEnumerator($mgr), new MethodEnumerator($mgr), new VariableEnumerator($mgr, $this->context), ]; } }
[ "protected", "function", "initEnumerators", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "enumerators", ")", ")", "{", "$", "mgr", "=", "$", "this", "->", "presenter", ";", "$", "this", "->", "enumerators", "=", "[", "new", "ClassConstantEnumerator", "(", "$", "mgr", ")", ",", "new", "ClassEnumerator", "(", "$", "mgr", ")", ",", "new", "ConstantEnumerator", "(", "$", "mgr", ")", ",", "new", "FunctionEnumerator", "(", "$", "mgr", ")", ",", "new", "GlobalVariableEnumerator", "(", "$", "mgr", ")", ",", "new", "PropertyEnumerator", "(", "$", "mgr", ")", ",", "new", "MethodEnumerator", "(", "$", "mgr", ")", ",", "new", "VariableEnumerator", "(", "$", "mgr", ",", "$", "this", "->", "context", ")", ",", "]", ";", "}", "}" ]
Initialize Enumerators.
[ "Initialize", "Enumerators", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand.php#L150-L166
train
bobthecow/psysh
src/Command/ListCommand.php
ListCommand.validateInput
private function validateInput(InputInterface $input) { if (!$input->getArgument('target')) { // if no target is passed, there can be no properties or methods foreach (['properties', 'methods', 'no-inherit'] as $option) { if ($input->getOption($option)) { throw new RuntimeException('--' . $option . ' does not make sense without a specified target'); } } foreach (['globals', 'vars', 'constants', 'functions', 'classes', 'interfaces', 'traits'] as $option) { if ($input->getOption($option)) { return; } } // default to --vars if no other options are passed $input->setOption('vars', true); } else { // if a target is passed, classes, functions, etc don't make sense foreach (['vars', 'globals', 'functions', 'classes', 'interfaces', 'traits'] as $option) { if ($input->getOption($option)) { throw new RuntimeException('--' . $option . ' does not make sense with a specified target'); } } foreach (['constants', 'properties', 'methods'] as $option) { if ($input->getOption($option)) { return; } } // default to --constants --properties --methods if no other options are passed $input->setOption('constants', true); $input->setOption('properties', true); $input->setOption('methods', true); } }
php
private function validateInput(InputInterface $input) { if (!$input->getArgument('target')) { // if no target is passed, there can be no properties or methods foreach (['properties', 'methods', 'no-inherit'] as $option) { if ($input->getOption($option)) { throw new RuntimeException('--' . $option . ' does not make sense without a specified target'); } } foreach (['globals', 'vars', 'constants', 'functions', 'classes', 'interfaces', 'traits'] as $option) { if ($input->getOption($option)) { return; } } // default to --vars if no other options are passed $input->setOption('vars', true); } else { // if a target is passed, classes, functions, etc don't make sense foreach (['vars', 'globals', 'functions', 'classes', 'interfaces', 'traits'] as $option) { if ($input->getOption($option)) { throw new RuntimeException('--' . $option . ' does not make sense with a specified target'); } } foreach (['constants', 'properties', 'methods'] as $option) { if ($input->getOption($option)) { return; } } // default to --constants --properties --methods if no other options are passed $input->setOption('constants', true); $input->setOption('properties', true); $input->setOption('methods', true); } }
[ "private", "function", "validateInput", "(", "InputInterface", "$", "input", ")", "{", "if", "(", "!", "$", "input", "->", "getArgument", "(", "'target'", ")", ")", "{", "// if no target is passed, there can be no properties or methods", "foreach", "(", "[", "'properties'", ",", "'methods'", ",", "'no-inherit'", "]", "as", "$", "option", ")", "{", "if", "(", "$", "input", "->", "getOption", "(", "$", "option", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'--'", ".", "$", "option", ".", "' does not make sense without a specified target'", ")", ";", "}", "}", "foreach", "(", "[", "'globals'", ",", "'vars'", ",", "'constants'", ",", "'functions'", ",", "'classes'", ",", "'interfaces'", ",", "'traits'", "]", "as", "$", "option", ")", "{", "if", "(", "$", "input", "->", "getOption", "(", "$", "option", ")", ")", "{", "return", ";", "}", "}", "// default to --vars if no other options are passed", "$", "input", "->", "setOption", "(", "'vars'", ",", "true", ")", ";", "}", "else", "{", "// if a target is passed, classes, functions, etc don't make sense", "foreach", "(", "[", "'vars'", ",", "'globals'", ",", "'functions'", ",", "'classes'", ",", "'interfaces'", ",", "'traits'", "]", "as", "$", "option", ")", "{", "if", "(", "$", "input", "->", "getOption", "(", "$", "option", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'--'", ".", "$", "option", ".", "' does not make sense with a specified target'", ")", ";", "}", "}", "foreach", "(", "[", "'constants'", ",", "'properties'", ",", "'methods'", "]", "as", "$", "option", ")", "{", "if", "(", "$", "input", "->", "getOption", "(", "$", "option", ")", ")", "{", "return", ";", "}", "}", "// default to --constants --properties --methods if no other options are passed", "$", "input", "->", "setOption", "(", "'constants'", ",", "true", ")", ";", "$", "input", "->", "setOption", "(", "'properties'", ",", "true", ")", ";", "$", "input", "->", "setOption", "(", "'methods'", ",", "true", ")", ";", "}", "}" ]
Validate that input options make sense, provide defaults when called without options. @throws RuntimeException if options are inconsistent @param InputInterface $input
[ "Validate", "that", "input", "options", "make", "sense", "provide", "defaults", "when", "called", "without", "options", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand.php#L238-L275
train
bobthecow/psysh
src/Command/TimeitCommand/TimeitVisitor.php
TimeitVisitor.getEndCall
private function getEndCall(Expr $arg = null) { if ($arg === null) { $arg = NoReturnValue::create(); } return new StaticCall(new FullyQualifiedName('Psy\Command\TimeitCommand'), 'markEnd', [new Arg($arg)]); }
php
private function getEndCall(Expr $arg = null) { if ($arg === null) { $arg = NoReturnValue::create(); } return new StaticCall(new FullyQualifiedName('Psy\Command\TimeitCommand'), 'markEnd', [new Arg($arg)]); }
[ "private", "function", "getEndCall", "(", "Expr", "$", "arg", "=", "null", ")", "{", "if", "(", "$", "arg", "===", "null", ")", "{", "$", "arg", "=", "NoReturnValue", "::", "create", "(", ")", ";", "}", "return", "new", "StaticCall", "(", "new", "FullyQualifiedName", "(", "'Psy\\Command\\TimeitCommand'", ")", ",", "'markEnd'", ",", "[", "new", "Arg", "(", "$", "arg", ")", "]", ")", ";", "}" ]
Get PhpParser AST nodes for a `markEnd` call. Optionally pass in a return value. @param Expr|null $arg @return PhpParser\Node\Expr\StaticCall
[ "Get", "PhpParser", "AST", "nodes", "for", "a", "markEnd", "call", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand/TimeitVisitor.php#L116-L123
train
bobthecow/psysh
src/Command/ParseCommand.php
ParseCommand.setPresenter
public function setPresenter(Presenter $presenter) { $this->presenter = clone $presenter; $this->presenter->addCasters([ 'PhpParser\Node' => function (Node $node, array $a) { $a = [ Caster::PREFIX_VIRTUAL . 'type' => $node->getType(), Caster::PREFIX_VIRTUAL . 'attributes' => $node->getAttributes(), ]; foreach ($node->getSubNodeNames() as $name) { $a[Caster::PREFIX_VIRTUAL . $name] = $node->$name; } return $a; }, ]); }
php
public function setPresenter(Presenter $presenter) { $this->presenter = clone $presenter; $this->presenter->addCasters([ 'PhpParser\Node' => function (Node $node, array $a) { $a = [ Caster::PREFIX_VIRTUAL . 'type' => $node->getType(), Caster::PREFIX_VIRTUAL . 'attributes' => $node->getAttributes(), ]; foreach ($node->getSubNodeNames() as $name) { $a[Caster::PREFIX_VIRTUAL . $name] = $node->$name; } return $a; }, ]); }
[ "public", "function", "setPresenter", "(", "Presenter", "$", "presenter", ")", "{", "$", "this", "->", "presenter", "=", "clone", "$", "presenter", ";", "$", "this", "->", "presenter", "->", "addCasters", "(", "[", "'PhpParser\\Node'", "=>", "function", "(", "Node", "$", "node", ",", "array", "$", "a", ")", "{", "$", "a", "=", "[", "Caster", "::", "PREFIX_VIRTUAL", ".", "'type'", "=>", "$", "node", "->", "getType", "(", ")", ",", "Caster", "::", "PREFIX_VIRTUAL", ".", "'attributes'", "=>", "$", "node", "->", "getAttributes", "(", ")", ",", "]", ";", "foreach", "(", "$", "node", "->", "getSubNodeNames", "(", ")", "as", "$", "name", ")", "{", "$", "a", "[", "Caster", "::", "PREFIX_VIRTUAL", ".", "$", "name", "]", "=", "$", "node", "->", "$", "name", ";", "}", "return", "$", "a", ";", "}", ",", "]", ")", ";", "}" ]
PresenterAware interface. @param Presenter $presenter
[ "PresenterAware", "interface", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ParseCommand.php#L69-L86
train
bobthecow/psysh
src/CodeCleaner/NamespacePass.php
NamespacePass.beforeTraverse
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; }
php
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; }
[ "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
[ "If", "this", "is", "a", "standalone", "namespace", "line", "remember", "it", "for", "later", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/NamespacePass.php#L50-L75
train
bobthecow/psysh
src/CodeCleaner/ListPass.php
ListPass.enterNode
public function enterNode(Node $node) { if (!$node instanceof Assign) { return; } if (!$node->var instanceof Array_ && !$node->var instanceof List_) { return; } if (!$this->atLeastPhp71 && $node->var instanceof Array_) { $msg = "syntax error, unexpected '='"; throw new ParseErrorException($msg, $node->expr->getLine()); } // Polyfill for PHP-Parser 2.x $items = isset($node->var->items) ? $node->var->items : $node->var->vars; if ($items === [] || $items === [null]) { throw new ParseErrorException('Cannot use empty list', $node->var->getLine()); } $itemFound = false; foreach ($items as $item) { if ($item === null) { continue; } $itemFound = true; // List_->$vars in PHP-Parser 2.x is Variable instead of ArrayItem. if (!$this->atLeastPhp71 && $item instanceof ArrayItem && $item->key !== null) { $msg = 'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \',\' or \')\''; throw new ParseErrorException($msg, $item->key->getLine()); } if (!self::isValidArrayItem($item)) { $msg = 'Assignments can only happen to writable values'; throw new ParseErrorException($msg, $item->getLine()); } } if (!$itemFound) { throw new ParseErrorException('Cannot use empty list'); } }
php
public function enterNode(Node $node) { if (!$node instanceof Assign) { return; } if (!$node->var instanceof Array_ && !$node->var instanceof List_) { return; } if (!$this->atLeastPhp71 && $node->var instanceof Array_) { $msg = "syntax error, unexpected '='"; throw new ParseErrorException($msg, $node->expr->getLine()); } // Polyfill for PHP-Parser 2.x $items = isset($node->var->items) ? $node->var->items : $node->var->vars; if ($items === [] || $items === [null]) { throw new ParseErrorException('Cannot use empty list', $node->var->getLine()); } $itemFound = false; foreach ($items as $item) { if ($item === null) { continue; } $itemFound = true; // List_->$vars in PHP-Parser 2.x is Variable instead of ArrayItem. if (!$this->atLeastPhp71 && $item instanceof ArrayItem && $item->key !== null) { $msg = 'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \',\' or \')\''; throw new ParseErrorException($msg, $item->key->getLine()); } if (!self::isValidArrayItem($item)) { $msg = 'Assignments can only happen to writable values'; throw new ParseErrorException($msg, $item->getLine()); } } if (!$itemFound) { throw new ParseErrorException('Cannot use empty list'); } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "if", "(", "!", "$", "node", "instanceof", "Assign", ")", "{", "return", ";", "}", "if", "(", "!", "$", "node", "->", "var", "instanceof", "Array_", "&&", "!", "$", "node", "->", "var", "instanceof", "List_", ")", "{", "return", ";", "}", "if", "(", "!", "$", "this", "->", "atLeastPhp71", "&&", "$", "node", "->", "var", "instanceof", "Array_", ")", "{", "$", "msg", "=", "\"syntax error, unexpected '='\"", ";", "throw", "new", "ParseErrorException", "(", "$", "msg", ",", "$", "node", "->", "expr", "->", "getLine", "(", ")", ")", ";", "}", "// Polyfill for PHP-Parser 2.x", "$", "items", "=", "isset", "(", "$", "node", "->", "var", "->", "items", ")", "?", "$", "node", "->", "var", "->", "items", ":", "$", "node", "->", "var", "->", "vars", ";", "if", "(", "$", "items", "===", "[", "]", "||", "$", "items", "===", "[", "null", "]", ")", "{", "throw", "new", "ParseErrorException", "(", "'Cannot use empty list'", ",", "$", "node", "->", "var", "->", "getLine", "(", ")", ")", ";", "}", "$", "itemFound", "=", "false", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", "$", "item", "===", "null", ")", "{", "continue", ";", "}", "$", "itemFound", "=", "true", ";", "// List_->$vars in PHP-Parser 2.x is Variable instead of ArrayItem.", "if", "(", "!", "$", "this", "->", "atLeastPhp71", "&&", "$", "item", "instanceof", "ArrayItem", "&&", "$", "item", "->", "key", "!==", "null", ")", "{", "$", "msg", "=", "'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \\',\\' or \\')\\''", ";", "throw", "new", "ParseErrorException", "(", "$", "msg", ",", "$", "item", "->", "key", "->", "getLine", "(", ")", ")", ";", "}", "if", "(", "!", "self", "::", "isValidArrayItem", "(", "$", "item", ")", ")", "{", "$", "msg", "=", "'Assignments can only happen to writable values'", ";", "throw", "new", "ParseErrorException", "(", "$", "msg", ",", "$", "item", "->", "getLine", "(", ")", ")", ";", "}", "}", "if", "(", "!", "$", "itemFound", ")", "{", "throw", "new", "ParseErrorException", "(", "'Cannot use empty list'", ")", ";", "}", "}" ]
Validate use of list assignment. @throws ParseErrorException if the user used empty with anything but a variable @param Node $node
[ "Validate", "use", "of", "list", "assignment", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ListPass.php#L46-L91
train
bobthecow/psysh
src/CodeCleaner/ListPass.php
ListPass.isValidArrayItem
private static function isValidArrayItem(Expr $item) { $value = ($item instanceof ArrayItem) ? $item->value : $item; while ($value instanceof ArrayDimFetch || $value instanceof PropertyFetch) { $value = $value->var; } // We just kind of give up if it's a method call. We can't tell if it's // valid via static analysis. return $value instanceof Variable || $value instanceof MethodCall || $value instanceof FuncCall; }
php
private static function isValidArrayItem(Expr $item) { $value = ($item instanceof ArrayItem) ? $item->value : $item; while ($value instanceof ArrayDimFetch || $value instanceof PropertyFetch) { $value = $value->var; } // We just kind of give up if it's a method call. We can't tell if it's // valid via static analysis. return $value instanceof Variable || $value instanceof MethodCall || $value instanceof FuncCall; }
[ "private", "static", "function", "isValidArrayItem", "(", "Expr", "$", "item", ")", "{", "$", "value", "=", "(", "$", "item", "instanceof", "ArrayItem", ")", "?", "$", "item", "->", "value", ":", "$", "item", ";", "while", "(", "$", "value", "instanceof", "ArrayDimFetch", "||", "$", "value", "instanceof", "PropertyFetch", ")", "{", "$", "value", "=", "$", "value", "->", "var", ";", "}", "// We just kind of give up if it's a method call. We can't tell if it's", "// valid via static analysis.", "return", "$", "value", "instanceof", "Variable", "||", "$", "value", "instanceof", "MethodCall", "||", "$", "value", "instanceof", "FuncCall", ";", "}" ]
Validate whether a given item in an array is valid for short assignment. @param Expr $item @return bool
[ "Validate", "whether", "a", "given", "item", "in", "an", "array", "is", "valid", "for", "short", "assignment", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ListPass.php#L100-L111
train
bobthecow/psysh
src/Command/ListCommand/VariableEnumerator.php
VariableEnumerator.getVariables
protected function getVariables($showAll) { $scopeVars = $this->context->getAll(); \uksort($scopeVars, function ($a, $b) { $aIndex = \array_search($a, self::$specialNames); $bIndex = \array_search($b, self::$specialNames); if ($aIndex !== false) { if ($bIndex !== false) { return $aIndex - $bIndex; } return 1; } if ($bIndex !== false) { return -1; } return \strnatcasecmp($a, $b); }); $ret = []; foreach ($scopeVars as $name => $val) { if (!$showAll && \in_array($name, self::$specialNames)) { continue; } $ret[$name] = $val; } return $ret; }
php
protected function getVariables($showAll) { $scopeVars = $this->context->getAll(); \uksort($scopeVars, function ($a, $b) { $aIndex = \array_search($a, self::$specialNames); $bIndex = \array_search($b, self::$specialNames); if ($aIndex !== false) { if ($bIndex !== false) { return $aIndex - $bIndex; } return 1; } if ($bIndex !== false) { return -1; } return \strnatcasecmp($a, $b); }); $ret = []; foreach ($scopeVars as $name => $val) { if (!$showAll && \in_array($name, self::$specialNames)) { continue; } $ret[$name] = $val; } return $ret; }
[ "protected", "function", "getVariables", "(", "$", "showAll", ")", "{", "$", "scopeVars", "=", "$", "this", "->", "context", "->", "getAll", "(", ")", ";", "\\", "uksort", "(", "$", "scopeVars", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "aIndex", "=", "\\", "array_search", "(", "$", "a", ",", "self", "::", "$", "specialNames", ")", ";", "$", "bIndex", "=", "\\", "array_search", "(", "$", "b", ",", "self", "::", "$", "specialNames", ")", ";", "if", "(", "$", "aIndex", "!==", "false", ")", "{", "if", "(", "$", "bIndex", "!==", "false", ")", "{", "return", "$", "aIndex", "-", "$", "bIndex", ";", "}", "return", "1", ";", "}", "if", "(", "$", "bIndex", "!==", "false", ")", "{", "return", "-", "1", ";", "}", "return", "\\", "strnatcasecmp", "(", "$", "a", ",", "$", "b", ")", ";", "}", ")", ";", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "scopeVars", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "!", "$", "showAll", "&&", "\\", "in_array", "(", "$", "name", ",", "self", "::", "$", "specialNames", ")", ")", "{", "continue", ";", "}", "$", "ret", "[", "$", "name", "]", "=", "$", "val", ";", "}", "return", "$", "ret", ";", "}" ]
Get scope variables. @param bool $showAll Include special variables (e.g. $_) @return array
[ "Get", "scope", "variables", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/VariableEnumerator.php#L79-L111
train
bobthecow/psysh
src/Command/ListCommand/VariableEnumerator.php
VariableEnumerator.prepareVariables
protected function prepareVariables(array $variables) { // My kingdom for a generator. $ret = []; foreach ($variables as $name => $val) { if ($this->showItem($name)) { $fname = '$' . $name; $ret[$fname] = [ 'name' => $fname, 'style' => \in_array($name, self::$specialNames) ? self::IS_PRIVATE : self::IS_PUBLIC, 'value' => $this->presentRef($val), ]; } } return $ret; }
php
protected function prepareVariables(array $variables) { // My kingdom for a generator. $ret = []; foreach ($variables as $name => $val) { if ($this->showItem($name)) { $fname = '$' . $name; $ret[$fname] = [ 'name' => $fname, 'style' => \in_array($name, self::$specialNames) ? self::IS_PRIVATE : self::IS_PUBLIC, 'value' => $this->presentRef($val), ]; } } return $ret; }
[ "protected", "function", "prepareVariables", "(", "array", "$", "variables", ")", "{", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "variables", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "fname", "=", "'$'", ".", "$", "name", ";", "$", "ret", "[", "$", "fname", "]", "=", "[", "'name'", "=>", "$", "fname", ",", "'style'", "=>", "\\", "in_array", "(", "$", "name", ",", "self", "::", "$", "specialNames", ")", "?", "self", "::", "IS_PRIVATE", ":", "self", "::", "IS_PUBLIC", ",", "'value'", "=>", "$", "this", "->", "presentRef", "(", "$", "val", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted variable array. @param array $variables @return array
[ "Prepare", "formatted", "variable", "array", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/VariableEnumerator.php#L120-L136
train
bobthecow/psysh
src/Exception/ErrorException.php
ErrorException.fromError
public static function fromError(\Error $e) { return new self($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e); }
php
public static function fromError(\Error $e) { return new self($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e); }
[ "public", "static", "function", "fromError", "(", "\\", "Error", "$", "e", ")", "{", "return", "new", "self", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "1", ",", "$", "e", "->", "getFile", "(", ")", ",", "$", "e", "->", "getLine", "(", ")", ",", "$", "e", ")", ";", "}" ]
Create an ErrorException from an Error. @param \Error $e @return ErrorException
[ "Create", "an", "ErrorException", "from", "an", "Error", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Exception/ErrorException.php#L110-L113
train
bobthecow/psysh
src/Command/HistoryCommand.php
HistoryCommand.extractRange
private function extractRange($range) { if (\preg_match('/^\d+$/', $range)) { return [$range, $range + 1]; } $matches = []; if ($range !== '..' && \preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) { $start = $matches[1] ? \intval($matches[1]) : 0; $end = $matches[2] ? \intval($matches[2]) + 1 : PHP_INT_MAX; return [$start, $end]; } throw new \InvalidArgumentException('Unexpected range: ' . $range); }
php
private function extractRange($range) { if (\preg_match('/^\d+$/', $range)) { return [$range, $range + 1]; } $matches = []; if ($range !== '..' && \preg_match('/^(\d*)\.\.(\d*)$/', $range, $matches)) { $start = $matches[1] ? \intval($matches[1]) : 0; $end = $matches[2] ? \intval($matches[2]) + 1 : PHP_INT_MAX; return [$start, $end]; } throw new \InvalidArgumentException('Unexpected range: ' . $range); }
[ "private", "function", "extractRange", "(", "$", "range", ")", "{", "if", "(", "\\", "preg_match", "(", "'/^\\d+$/'", ",", "$", "range", ")", ")", "{", "return", "[", "$", "range", ",", "$", "range", "+", "1", "]", ";", "}", "$", "matches", "=", "[", "]", ";", "if", "(", "$", "range", "!==", "'..'", "&&", "\\", "preg_match", "(", "'/^(\\d*)\\.\\.(\\d*)$/'", ",", "$", "range", ",", "$", "matches", ")", ")", "{", "$", "start", "=", "$", "matches", "[", "1", "]", "?", "\\", "intval", "(", "$", "matches", "[", "1", "]", ")", ":", "0", ";", "$", "end", "=", "$", "matches", "[", "2", "]", "?", "\\", "intval", "(", "$", "matches", "[", "2", "]", ")", "+", "1", ":", "PHP_INT_MAX", ";", "return", "[", "$", "start", ",", "$", "end", "]", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unexpected range: '", ".", "$", "range", ")", ";", "}" ]
Extract a range from a string. @param string $range @return array [ start, end ]
[ "Extract", "a", "range", "from", "a", "string", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/HistoryCommand.php#L157-L172
train
bobthecow/psysh
src/Command/HistoryCommand.php
HistoryCommand.getHistorySlice
private function getHistorySlice($show, $head, $tail) { $history = $this->readline->listHistory(); // don't show the current `history` invocation \array_pop($history); if ($show) { list($start, $end) = $this->extractRange($show); $length = $end - $start; } elseif ($head) { if (!\preg_match('/^\d+$/', $head)) { throw new \InvalidArgumentException('Please specify an integer argument for --head'); } $start = 0; $length = \intval($head); } elseif ($tail) { if (!\preg_match('/^\d+$/', $tail)) { throw new \InvalidArgumentException('Please specify an integer argument for --tail'); } $start = \count($history) - $tail; $length = \intval($tail) + 1; } else { return $history; } return \array_slice($history, $start, $length, true); }
php
private function getHistorySlice($show, $head, $tail) { $history = $this->readline->listHistory(); // don't show the current `history` invocation \array_pop($history); if ($show) { list($start, $end) = $this->extractRange($show); $length = $end - $start; } elseif ($head) { if (!\preg_match('/^\d+$/', $head)) { throw new \InvalidArgumentException('Please specify an integer argument for --head'); } $start = 0; $length = \intval($head); } elseif ($tail) { if (!\preg_match('/^\d+$/', $tail)) { throw new \InvalidArgumentException('Please specify an integer argument for --tail'); } $start = \count($history) - $tail; $length = \intval($tail) + 1; } else { return $history; } return \array_slice($history, $start, $length, true); }
[ "private", "function", "getHistorySlice", "(", "$", "show", ",", "$", "head", ",", "$", "tail", ")", "{", "$", "history", "=", "$", "this", "->", "readline", "->", "listHistory", "(", ")", ";", "// don't show the current `history` invocation", "\\", "array_pop", "(", "$", "history", ")", ";", "if", "(", "$", "show", ")", "{", "list", "(", "$", "start", ",", "$", "end", ")", "=", "$", "this", "->", "extractRange", "(", "$", "show", ")", ";", "$", "length", "=", "$", "end", "-", "$", "start", ";", "}", "elseif", "(", "$", "head", ")", "{", "if", "(", "!", "\\", "preg_match", "(", "'/^\\d+$/'", ",", "$", "head", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Please specify an integer argument for --head'", ")", ";", "}", "$", "start", "=", "0", ";", "$", "length", "=", "\\", "intval", "(", "$", "head", ")", ";", "}", "elseif", "(", "$", "tail", ")", "{", "if", "(", "!", "\\", "preg_match", "(", "'/^\\d+$/'", ",", "$", "tail", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Please specify an integer argument for --tail'", ")", ";", "}", "$", "start", "=", "\\", "count", "(", "$", "history", ")", "-", "$", "tail", ";", "$", "length", "=", "\\", "intval", "(", "$", "tail", ")", "+", "1", ";", "}", "else", "{", "return", "$", "history", ";", "}", "return", "\\", "array_slice", "(", "$", "history", ",", "$", "start", ",", "$", "length", ",", "true", ")", ";", "}" ]
Retrieve a slice of the readline history. @param string $show @param string $head @param string $tail @return array A slilce of history
[ "Retrieve", "a", "slice", "of", "the", "readline", "history", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/HistoryCommand.php#L183-L212
train
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
ProcessForker.beforeRun
public function beforeRun(Shell $shell) { list($up, $down) = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); if (!$up) { throw new \RuntimeException('Unable to create socket pair'); } $pid = \pcntl_fork(); if ($pid < 0) { throw new \RuntimeException('Unable to start execution loop'); } elseif ($pid > 0) { // This is the main thread. We'll just wait for a while. // We won't be needing this one. \fclose($up); // Wait for a return value from the loop process. $read = [$down]; $write = null; $except = null; do { $n = @\stream_select($read, $write, $except, null); if ($n === 0) { throw new \RuntimeException('Process timed out waiting for execution loop'); } if ($n === false) { $err = \error_get_last(); if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) { $msg = $err['message'] ? \sprintf('Error waiting for execution loop: %s', $err['message']) : 'Error waiting for execution loop'; throw new \RuntimeException($msg); } } } while ($n < 1); $content = \stream_get_contents($down); \fclose($down); if ($content) { $shell->setScopeVariables(@\unserialize($content)); } throw new BreakException('Exiting main thread'); } // This is the child process. It's going to do all the work. if (\function_exists('setproctitle')) { setproctitle('psysh (loop)'); } // We won't be needing this one. \fclose($down); // Save this; we'll need to close it in `afterRun` $this->up = $up; }
php
public function beforeRun(Shell $shell) { list($up, $down) = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); if (!$up) { throw new \RuntimeException('Unable to create socket pair'); } $pid = \pcntl_fork(); if ($pid < 0) { throw new \RuntimeException('Unable to start execution loop'); } elseif ($pid > 0) { // This is the main thread. We'll just wait for a while. // We won't be needing this one. \fclose($up); // Wait for a return value from the loop process. $read = [$down]; $write = null; $except = null; do { $n = @\stream_select($read, $write, $except, null); if ($n === 0) { throw new \RuntimeException('Process timed out waiting for execution loop'); } if ($n === false) { $err = \error_get_last(); if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) { $msg = $err['message'] ? \sprintf('Error waiting for execution loop: %s', $err['message']) : 'Error waiting for execution loop'; throw new \RuntimeException($msg); } } } while ($n < 1); $content = \stream_get_contents($down); \fclose($down); if ($content) { $shell->setScopeVariables(@\unserialize($content)); } throw new BreakException('Exiting main thread'); } // This is the child process. It's going to do all the work. if (\function_exists('setproctitle')) { setproctitle('psysh (loop)'); } // We won't be needing this one. \fclose($down); // Save this; we'll need to close it in `afterRun` $this->up = $up; }
[ "public", "function", "beforeRun", "(", "Shell", "$", "shell", ")", "{", "list", "(", "$", "up", ",", "$", "down", ")", "=", "\\", "stream_socket_pair", "(", "STREAM_PF_UNIX", ",", "STREAM_SOCK_STREAM", ",", "STREAM_IPPROTO_IP", ")", ";", "if", "(", "!", "$", "up", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to create socket pair'", ")", ";", "}", "$", "pid", "=", "\\", "pcntl_fork", "(", ")", ";", "if", "(", "$", "pid", "<", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to start execution loop'", ")", ";", "}", "elseif", "(", "$", "pid", ">", "0", ")", "{", "// This is the main thread. We'll just wait for a while.", "// We won't be needing this one.", "\\", "fclose", "(", "$", "up", ")", ";", "// Wait for a return value from the loop process.", "$", "read", "=", "[", "$", "down", "]", ";", "$", "write", "=", "null", ";", "$", "except", "=", "null", ";", "do", "{", "$", "n", "=", "@", "\\", "stream_select", "(", "$", "read", ",", "$", "write", ",", "$", "except", ",", "null", ")", ";", "if", "(", "$", "n", "===", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Process timed out waiting for execution loop'", ")", ";", "}", "if", "(", "$", "n", "===", "false", ")", "{", "$", "err", "=", "\\", "error_get_last", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "err", "[", "'message'", "]", ")", "||", "\\", "stripos", "(", "$", "err", "[", "'message'", "]", ",", "'interrupted system call'", ")", "===", "false", ")", "{", "$", "msg", "=", "$", "err", "[", "'message'", "]", "?", "\\", "sprintf", "(", "'Error waiting for execution loop: %s'", ",", "$", "err", "[", "'message'", "]", ")", ":", "'Error waiting for execution loop'", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "msg", ")", ";", "}", "}", "}", "while", "(", "$", "n", "<", "1", ")", ";", "$", "content", "=", "\\", "stream_get_contents", "(", "$", "down", ")", ";", "\\", "fclose", "(", "$", "down", ")", ";", "if", "(", "$", "content", ")", "{", "$", "shell", "->", "setScopeVariables", "(", "@", "\\", "unserialize", "(", "$", "content", ")", ")", ";", "}", "throw", "new", "BreakException", "(", "'Exiting main thread'", ")", ";", "}", "// This is the child process. It's going to do all the work.", "if", "(", "\\", "function_exists", "(", "'setproctitle'", ")", ")", "{", "setproctitle", "(", "'psysh (loop)'", ")", ";", "}", "// We won't be needing this one.", "\\", "fclose", "(", "$", "down", ")", ";", "// Save this; we'll need to close it in `afterRun`", "$", "this", "->", "up", "=", "$", "up", ";", "}" ]
Forks into a master and a loop process. The loop process will handle the evaluation of all instructions, then return its state via a socket upon completion. @param Shell $shell
[ "Forks", "into", "a", "master", "and", "a", "loop", "process", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop/ProcessForker.php#L47-L107
train
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
ProcessForker.afterLoop
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(); } }
php
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(); } }
[ "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
[ "Clean", "up", "old", "savegames", "at", "the", "end", "of", "each", "loop", "iteration", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop/ProcessForker.php#L124-L131
train
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
ProcessForker.createSavegame
private function createSavegame() { // the current process will become the savegame $this->savegame = \posix_getpid(); $pid = \pcntl_fork(); if ($pid < 0) { throw new \RuntimeException('Unable to create savegame fork'); } elseif ($pid > 0) { // we're the savegame now... let's wait and see what happens \pcntl_waitpid($pid, $status); // worker exited cleanly, let's bail if (!\pcntl_wexitstatus($status)) { \posix_kill(\posix_getpid(), SIGKILL); } // worker didn't exit cleanly, we'll need to have another go $this->createSavegame(); } }
php
private function createSavegame() { // the current process will become the savegame $this->savegame = \posix_getpid(); $pid = \pcntl_fork(); if ($pid < 0) { throw new \RuntimeException('Unable to create savegame fork'); } elseif ($pid > 0) { // we're the savegame now... let's wait and see what happens \pcntl_waitpid($pid, $status); // worker exited cleanly, let's bail if (!\pcntl_wexitstatus($status)) { \posix_kill(\posix_getpid(), SIGKILL); } // worker didn't exit cleanly, we'll need to have another go $this->createSavegame(); } }
[ "private", "function", "createSavegame", "(", ")", "{", "// the current process will become the savegame", "$", "this", "->", "savegame", "=", "\\", "posix_getpid", "(", ")", ";", "$", "pid", "=", "\\", "pcntl_fork", "(", ")", ";", "if", "(", "$", "pid", "<", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to create savegame fork'", ")", ";", "}", "elseif", "(", "$", "pid", ">", "0", ")", "{", "// we're the savegame now... let's wait and see what happens", "\\", "pcntl_waitpid", "(", "$", "pid", ",", "$", "status", ")", ";", "// worker exited cleanly, let's bail", "if", "(", "!", "\\", "pcntl_wexitstatus", "(", "$", "status", ")", ")", "{", "\\", "posix_kill", "(", "\\", "posix_getpid", "(", ")", ",", "SIGKILL", ")", ";", "}", "// worker didn't exit cleanly, we'll need to have another go", "$", "this", "->", "createSavegame", "(", ")", ";", "}", "}" ]
Create a savegame fork. The savegame contains the current execution state, and can be resumed in the event that the worker dies unexpectedly (for example, by encountering a PHP fatal error).
[ "Create", "a", "savegame", "fork", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop/ProcessForker.php#L157-L177
train
bobthecow/psysh
src/ExecutionLoop/ProcessForker.php
ProcessForker.serializeReturn
private function serializeReturn(array $return) { $serializable = []; foreach ($return as $key => $value) { // No need to return magic variables if (Context::isSpecialVariableName($key)) { continue; } // Resources and Closures don't error, but they don't serialize well either. if (\is_resource($value) || $value instanceof \Closure) { continue; } try { @\serialize($value); $serializable[$key] = $value; } catch (\Throwable $e) { // we'll just ignore this one... } catch (\Exception $e) { // and this one too... // @todo remove this once we don't support PHP 5.x anymore :) } } return @\serialize($serializable); }
php
private function serializeReturn(array $return) { $serializable = []; foreach ($return as $key => $value) { // No need to return magic variables if (Context::isSpecialVariableName($key)) { continue; } // Resources and Closures don't error, but they don't serialize well either. if (\is_resource($value) || $value instanceof \Closure) { continue; } try { @\serialize($value); $serializable[$key] = $value; } catch (\Throwable $e) { // we'll just ignore this one... } catch (\Exception $e) { // and this one too... // @todo remove this once we don't support PHP 5.x anymore :) } } return @\serialize($serializable); }
[ "private", "function", "serializeReturn", "(", "array", "$", "return", ")", "{", "$", "serializable", "=", "[", "]", ";", "foreach", "(", "$", "return", "as", "$", "key", "=>", "$", "value", ")", "{", "// No need to return magic variables", "if", "(", "Context", "::", "isSpecialVariableName", "(", "$", "key", ")", ")", "{", "continue", ";", "}", "// Resources and Closures don't error, but they don't serialize well either.", "if", "(", "\\", "is_resource", "(", "$", "value", ")", "||", "$", "value", "instanceof", "\\", "Closure", ")", "{", "continue", ";", "}", "try", "{", "@", "\\", "serialize", "(", "$", "value", ")", ";", "$", "serializable", "[", "$", "key", "]", "=", "$", "value", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "// we'll just ignore this one...", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// and this one too...", "// @todo remove this once we don't support PHP 5.x anymore :)", "}", "}", "return", "@", "\\", "serialize", "(", "$", "serializable", ")", ";", "}" ]
Serialize all serializable return values. A naïve serialization will run into issues if there is a Closure or SimpleXMLElement (among other things) in scope when exiting the execution loop. We'll just ignore these unserializable classes, and serialize what we can. @param array $return @return string
[ "Serialize", "all", "serializable", "return", "values", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionLoop/ProcessForker.php#L191-L218
train
bobthecow/psysh
src/Command/Command.php
Command.argumentsAsText
private function argumentsAsText() { $max = $this->getMaxWidth(); $messages = []; $arguments = $this->getArguments(); if (!empty($arguments)) { $messages[] = '<comment>Arguments:</comment>'; foreach ($arguments as $argument) { if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) { $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault())); } else { $default = ''; } $description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $argument->getDescription()); $messages[] = \sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default); } $messages[] = ''; } return \implode(PHP_EOL, $messages); }
php
private function argumentsAsText() { $max = $this->getMaxWidth(); $messages = []; $arguments = $this->getArguments(); if (!empty($arguments)) { $messages[] = '<comment>Arguments:</comment>'; foreach ($arguments as $argument) { if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) { $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault())); } else { $default = ''; } $description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $argument->getDescription()); $messages[] = \sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default); } $messages[] = ''; } return \implode(PHP_EOL, $messages); }
[ "private", "function", "argumentsAsText", "(", ")", "{", "$", "max", "=", "$", "this", "->", "getMaxWidth", "(", ")", ";", "$", "messages", "=", "[", "]", ";", "$", "arguments", "=", "$", "this", "->", "getArguments", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "arguments", ")", ")", "{", "$", "messages", "[", "]", "=", "'<comment>Arguments:</comment>'", ";", "foreach", "(", "$", "arguments", "as", "$", "argument", ")", "{", "if", "(", "null", "!==", "$", "argument", "->", "getDefault", "(", ")", "&&", "(", "!", "\\", "is_array", "(", "$", "argument", "->", "getDefault", "(", ")", ")", "||", "\\", "count", "(", "$", "argument", "->", "getDefault", "(", ")", ")", ")", ")", "{", "$", "default", "=", "\\", "sprintf", "(", "'<comment> (default: %s)</comment>'", ",", "$", "this", "->", "formatDefaultValue", "(", "$", "argument", "->", "getDefault", "(", ")", ")", ")", ";", "}", "else", "{", "$", "default", "=", "''", ";", "}", "$", "description", "=", "\\", "str_replace", "(", "\"\\n\"", ",", "\"\\n\"", ".", "\\", "str_pad", "(", "''", ",", "$", "max", "+", "2", ",", "' '", ")", ",", "$", "argument", "->", "getDescription", "(", ")", ")", ";", "$", "messages", "[", "]", "=", "\\", "sprintf", "(", "\" <info>%-${max}s</info> %s%s\"", ",", "$", "argument", "->", "getName", "(", ")", ",", "$", "description", ",", "$", "default", ")", ";", "}", "$", "messages", "[", "]", "=", "''", ";", "}", "return", "\\", "implode", "(", "PHP_EOL", ",", "$", "messages", ")", ";", "}" ]
Format command arguments as text. @return string
[ "Format", "command", "arguments", "as", "text", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/Command.php#L133-L157
train
bobthecow/psysh
src/Command/Command.php
Command.optionsAsText
private function optionsAsText() { $max = $this->getMaxWidth(); $messages = []; $options = $this->getOptions(); if ($options) { $messages[] = '<comment>Options:</comment>'; foreach ($options as $option) { if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) { $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault())); } else { $default = ''; } $multiple = $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''; $description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $option->getDescription()); $optionMax = $max - \strlen($option->getName()) - 2; $messages[] = \sprintf( " <info>%s</info> %-${optionMax}s%s%s%s", '--' . $option->getName(), $option->getShortcut() ? \sprintf('(-%s) ', $option->getShortcut()) : '', $description, $default, $multiple ); } $messages[] = ''; } return \implode(PHP_EOL, $messages); }
php
private function optionsAsText() { $max = $this->getMaxWidth(); $messages = []; $options = $this->getOptions(); if ($options) { $messages[] = '<comment>Options:</comment>'; foreach ($options as $option) { if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) { $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault())); } else { $default = ''; } $multiple = $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''; $description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $option->getDescription()); $optionMax = $max - \strlen($option->getName()) - 2; $messages[] = \sprintf( " <info>%s</info> %-${optionMax}s%s%s%s", '--' . $option->getName(), $option->getShortcut() ? \sprintf('(-%s) ', $option->getShortcut()) : '', $description, $default, $multiple ); } $messages[] = ''; } return \implode(PHP_EOL, $messages); }
[ "private", "function", "optionsAsText", "(", ")", "{", "$", "max", "=", "$", "this", "->", "getMaxWidth", "(", ")", ";", "$", "messages", "=", "[", "]", ";", "$", "options", "=", "$", "this", "->", "getOptions", "(", ")", ";", "if", "(", "$", "options", ")", "{", "$", "messages", "[", "]", "=", "'<comment>Options:</comment>'", ";", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "if", "(", "$", "option", "->", "acceptValue", "(", ")", "&&", "null", "!==", "$", "option", "->", "getDefault", "(", ")", "&&", "(", "!", "\\", "is_array", "(", "$", "option", "->", "getDefault", "(", ")", ")", "||", "\\", "count", "(", "$", "option", "->", "getDefault", "(", ")", ")", ")", ")", "{", "$", "default", "=", "\\", "sprintf", "(", "'<comment> (default: %s)</comment>'", ",", "$", "this", "->", "formatDefaultValue", "(", "$", "option", "->", "getDefault", "(", ")", ")", ")", ";", "}", "else", "{", "$", "default", "=", "''", ";", "}", "$", "multiple", "=", "$", "option", "->", "isArray", "(", ")", "?", "'<comment> (multiple values allowed)</comment>'", ":", "''", ";", "$", "description", "=", "\\", "str_replace", "(", "\"\\n\"", ",", "\"\\n\"", ".", "\\", "str_pad", "(", "''", ",", "$", "max", "+", "2", ",", "' '", ")", ",", "$", "option", "->", "getDescription", "(", ")", ")", ";", "$", "optionMax", "=", "$", "max", "-", "\\", "strlen", "(", "$", "option", "->", "getName", "(", ")", ")", "-", "2", ";", "$", "messages", "[", "]", "=", "\\", "sprintf", "(", "\" <info>%s</info> %-${optionMax}s%s%s%s\"", ",", "'--'", ".", "$", "option", "->", "getName", "(", ")", ",", "$", "option", "->", "getShortcut", "(", ")", "?", "\\", "sprintf", "(", "'(-%s) '", ",", "$", "option", "->", "getShortcut", "(", ")", ")", ":", "''", ",", "$", "description", ",", "$", "default", ",", "$", "multiple", ")", ";", "}", "$", "messages", "[", "]", "=", "''", ";", "}", "return", "\\", "implode", "(", "PHP_EOL", ",", "$", "messages", ")", ";", "}" ]
Format options as text. @return string
[ "Format", "options", "as", "text", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/Command.php#L164-L198
train
bobthecow/psysh
src/Command/Command.php
Command.getMaxWidth
private function getMaxWidth() { $max = 0; foreach ($this->getOptions() as $option) { $nameLength = \strlen($option->getName()) + 2; if ($option->getShortcut()) { $nameLength += \strlen($option->getShortcut()) + 3; } $max = \max($max, $nameLength); } foreach ($this->getArguments() as $argument) { $max = \max($max, \strlen($argument->getName())); } return ++$max; }
php
private function getMaxWidth() { $max = 0; foreach ($this->getOptions() as $option) { $nameLength = \strlen($option->getName()) + 2; if ($option->getShortcut()) { $nameLength += \strlen($option->getShortcut()) + 3; } $max = \max($max, $nameLength); } foreach ($this->getArguments() as $argument) { $max = \max($max, \strlen($argument->getName())); } return ++$max; }
[ "private", "function", "getMaxWidth", "(", ")", "{", "$", "max", "=", "0", ";", "foreach", "(", "$", "this", "->", "getOptions", "(", ")", "as", "$", "option", ")", "{", "$", "nameLength", "=", "\\", "strlen", "(", "$", "option", "->", "getName", "(", ")", ")", "+", "2", ";", "if", "(", "$", "option", "->", "getShortcut", "(", ")", ")", "{", "$", "nameLength", "+=", "\\", "strlen", "(", "$", "option", "->", "getShortcut", "(", ")", ")", "+", "3", ";", "}", "$", "max", "=", "\\", "max", "(", "$", "max", ",", "$", "nameLength", ")", ";", "}", "foreach", "(", "$", "this", "->", "getArguments", "(", ")", "as", "$", "argument", ")", "{", "$", "max", "=", "\\", "max", "(", "$", "max", ",", "\\", "strlen", "(", "$", "argument", "->", "getName", "(", ")", ")", ")", ";", "}", "return", "++", "$", "max", ";", "}" ]
Calculate the maximum padding width for a set of lines. @return int
[ "Calculate", "the", "maximum", "padding", "width", "for", "a", "set", "of", "lines", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/Command.php#L205-L223
train
bobthecow/psysh
src/Command/Command.php
Command.getTable
protected function getTable(OutputInterface $output) { if (!\class_exists('Symfony\Component\Console\Helper\Table')) { return $this->getTableHelper(); } $style = new TableStyle(); $style ->setVerticalBorderChar(' ') ->setHorizontalBorderChar('') ->setCrossingChar(''); $table = new Table($output); return $table ->setRows([]) ->setStyle($style); }
php
protected function getTable(OutputInterface $output) { if (!\class_exists('Symfony\Component\Console\Helper\Table')) { return $this->getTableHelper(); } $style = new TableStyle(); $style ->setVerticalBorderChar(' ') ->setHorizontalBorderChar('') ->setCrossingChar(''); $table = new Table($output); return $table ->setRows([]) ->setStyle($style); }
[ "protected", "function", "getTable", "(", "OutputInterface", "$", "output", ")", "{", "if", "(", "!", "\\", "class_exists", "(", "'Symfony\\Component\\Console\\Helper\\Table'", ")", ")", "{", "return", "$", "this", "->", "getTableHelper", "(", ")", ";", "}", "$", "style", "=", "new", "TableStyle", "(", ")", ";", "$", "style", "->", "setVerticalBorderChar", "(", "' '", ")", "->", "setHorizontalBorderChar", "(", "''", ")", "->", "setCrossingChar", "(", "''", ")", ";", "$", "table", "=", "new", "Table", "(", "$", "output", ")", ";", "return", "$", "table", "->", "setRows", "(", "[", "]", ")", "->", "setStyle", "(", "$", "style", ")", ";", "}" ]
Get a Table instance. Falls back to legacy TableHelper. @return Table|TableHelper
[ "Get", "a", "Table", "instance", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/Command.php#L248-L265
train
bobthecow/psysh
src/Command/Command.php
Command.getTableHelper
protected function getTableHelper() { $table = $this->getApplication()->getHelperSet()->get('table'); return $table ->setRows([]) ->setLayout(TableHelper::LAYOUT_BORDERLESS) ->setHorizontalBorderChar('') ->setCrossingChar(''); }
php
protected function getTableHelper() { $table = $this->getApplication()->getHelperSet()->get('table'); return $table ->setRows([]) ->setLayout(TableHelper::LAYOUT_BORDERLESS) ->setHorizontalBorderChar('') ->setCrossingChar(''); }
[ "protected", "function", "getTableHelper", "(", ")", "{", "$", "table", "=", "$", "this", "->", "getApplication", "(", ")", "->", "getHelperSet", "(", ")", "->", "get", "(", "'table'", ")", ";", "return", "$", "table", "->", "setRows", "(", "[", "]", ")", "->", "setLayout", "(", "TableHelper", "::", "LAYOUT_BORDERLESS", ")", "->", "setHorizontalBorderChar", "(", "''", ")", "->", "setCrossingChar", "(", "''", ")", ";", "}" ]
Legacy fallback for getTable. @return TableHelper
[ "Legacy", "fallback", "for", "getTable", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/Command.php#L272-L281
train
bobthecow/psysh
src/Input/FilterOptions.php
FilterOptions.getOptions
public static function getOptions() { return [ new InputOption('grep', 'G', InputOption::VALUE_REQUIRED, 'Limit to items matching the given pattern (string or regex).'), new InputOption('insensitive', 'i', InputOption::VALUE_NONE, 'Case-insensitive search (requires --grep).'), new InputOption('invert', 'v', InputOption::VALUE_NONE, 'Inverted search (requires --grep).'), ]; }
php
public static function getOptions() { return [ new InputOption('grep', 'G', InputOption::VALUE_REQUIRED, 'Limit to items matching the given pattern (string or regex).'), new InputOption('insensitive', 'i', InputOption::VALUE_NONE, 'Case-insensitive search (requires --grep).'), new InputOption('invert', 'v', InputOption::VALUE_NONE, 'Inverted search (requires --grep).'), ]; }
[ "public", "static", "function", "getOptions", "(", ")", "{", "return", "[", "new", "InputOption", "(", "'grep'", ",", "'G'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Limit to items matching the given pattern (string or regex).'", ")", ",", "new", "InputOption", "(", "'insensitive'", ",", "'i'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Case-insensitive search (requires --grep).'", ")", ",", "new", "InputOption", "(", "'invert'", ",", "'v'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Inverted search (requires --grep).'", ")", ",", "]", ";", "}" ]
Get input option definitions for filtering. @return InputOption[]
[ "Get", "input", "option", "definitions", "for", "filtering", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/FilterOptions.php#L34-L41
train
bobthecow/psysh
src/Input/FilterOptions.php
FilterOptions.bind
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'); }
php
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'); }
[ "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", "input", "and", "prepare", "filter", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/FilterOptions.php#L48-L72
train
bobthecow/psysh
src/Input/FilterOptions.php
FilterOptions.match
public function match($string, array &$matches = null) { return $this->filter === false || (\preg_match($this->pattern, $string, $matches) xor $this->invert); }
php
public function match($string, array &$matches = null) { return $this->filter === false || (\preg_match($this->pattern, $string, $matches) xor $this->invert); }
[ "public", "function", "match", "(", "$", "string", ",", "array", "&", "$", "matches", "=", "null", ")", "{", "return", "$", "this", "->", "filter", "===", "false", "||", "(", "\\", "preg_match", "(", "$", "this", "->", "pattern", ",", "$", "string", ",", "$", "matches", ")", "xor", "$", "this", "->", "invert", ")", ";", "}" ]
Check whether a string matches the current filter options. @param string $string @param array $matches @return bool
[ "Check", "whether", "a", "string", "matches", "the", "current", "filter", "options", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/FilterOptions.php#L92-L95
train
bobthecow/psysh
src/Input/FilterOptions.php
FilterOptions.validateInput
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'); } } } }
php
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'); } } } }
[ "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. @param InputInterface $input @return bool
[ "Validate", "that", "grep", "invert", "and", "insensitive", "input", "options", "are", "consistent", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/FilterOptions.php#L104-L113
train
bobthecow/psysh
src/Output/ProcOutputPager.php
ProcOutputPager.close
public function close() { if (isset($this->pipe)) { \fclose($this->pipe); } if (isset($this->proc)) { $exit = \proc_close($this->proc); if ($exit !== 0) { throw new \RuntimeException('Error closing output stream'); } } unset($this->pipe, $this->proc); }
php
public function close() { if (isset($this->pipe)) { \fclose($this->pipe); } if (isset($this->proc)) { $exit = \proc_close($this->proc); if ($exit !== 0) { throw new \RuntimeException('Error closing output stream'); } } unset($this->pipe, $this->proc); }
[ "public", "function", "close", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "pipe", ")", ")", "{", "\\", "fclose", "(", "$", "this", "->", "pipe", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "proc", ")", ")", "{", "$", "exit", "=", "\\", "proc_close", "(", "$", "this", "->", "proc", ")", ";", "if", "(", "$", "exit", "!==", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Error closing output stream'", ")", ";", "}", "}", "unset", "(", "$", "this", "->", "pipe", ",", "$", "this", "->", "proc", ")", ";", "}" ]
Close the current pager process.
[ "Close", "the", "current", "pager", "process", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ProcOutputPager.php#L67-L81
train
bobthecow/psysh
src/Output/ProcOutputPager.php
ProcOutputPager.getPipe
private function getPipe() { if (!isset($this->pipe) || !isset($this->proc)) { $desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')]; $this->proc = \proc_open($this->cmd, $desc, $pipes); if (!\is_resource($this->proc)) { throw new \RuntimeException('Error opening output stream'); } $this->pipe = $pipes[0]; } return $this->pipe; }
php
private function getPipe() { if (!isset($this->pipe) || !isset($this->proc)) { $desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')]; $this->proc = \proc_open($this->cmd, $desc, $pipes); if (!\is_resource($this->proc)) { throw new \RuntimeException('Error opening output stream'); } $this->pipe = $pipes[0]; } return $this->pipe; }
[ "private", "function", "getPipe", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "pipe", ")", "||", "!", "isset", "(", "$", "this", "->", "proc", ")", ")", "{", "$", "desc", "=", "[", "[", "'pipe'", ",", "'r'", "]", ",", "$", "this", "->", "stream", ",", "\\", "fopen", "(", "'php://stderr'", ",", "'w'", ")", "]", ";", "$", "this", "->", "proc", "=", "\\", "proc_open", "(", "$", "this", "->", "cmd", ",", "$", "desc", ",", "$", "pipes", ")", ";", "if", "(", "!", "\\", "is_resource", "(", "$", "this", "->", "proc", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Error opening output stream'", ")", ";", "}", "$", "this", "->", "pipe", "=", "$", "pipes", "[", "0", "]", ";", "}", "return", "$", "this", "->", "pipe", ";", "}" ]
Get a pipe for paging output. If no active pager process exists, fork one and return its input pipe.
[ "Get", "a", "pipe", "for", "paging", "output", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ProcOutputPager.php#L88-L102
train
bobthecow/psysh
src/CodeCleaner/ImplicitReturnPass.php
ImplicitReturnPass.isNonExpressionStmt
private static function isNonExpressionStmt(Node $node) { return $node instanceof Stmt && !$node instanceof Expression && !$node instanceof Return_ && !$node instanceof Namespace_; }
php
private static function isNonExpressionStmt(Node $node) { return $node instanceof Stmt && !$node instanceof Expression && !$node instanceof Return_ && !$node instanceof Namespace_; }
[ "private", "static", "function", "isNonExpressionStmt", "(", "Node", "$", "node", ")", "{", "return", "$", "node", "instanceof", "Stmt", "&&", "!", "$", "node", "instanceof", "Expression", "&&", "!", "$", "node", "instanceof", "Return_", "&&", "!", "$", "node", "instanceof", "Namespace_", ";", "}" ]
Check whether a given node is a non-expression statement. As of PHP Parser 4.x, Expressions are now instances of Stmt as well, so we'll exclude them here. @param Node $node @return bool
[ "Check", "whether", "a", "given", "node", "is", "a", "non", "-", "expression", "statement", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ImplicitReturnPass.php#L121-L127
train
bobthecow/psysh
src/Command/ListCommand/MethodEnumerator.php
MethodEnumerator.getMethods
protected function getMethods($showAll, \Reflector $reflector, $noInherit = false) { $className = $reflector->getName(); $methods = []; foreach ($reflector->getMethods() as $name => $method) { if ($noInherit && $method->getDeclaringClass()->getName() !== $className) { continue; } if ($showAll || $method->isPublic()) { $methods[$method->getName()] = $method; } } \ksort($methods, SORT_NATURAL | SORT_FLAG_CASE); return $methods; }
php
protected function getMethods($showAll, \Reflector $reflector, $noInherit = false) { $className = $reflector->getName(); $methods = []; foreach ($reflector->getMethods() as $name => $method) { if ($noInherit && $method->getDeclaringClass()->getName() !== $className) { continue; } if ($showAll || $method->isPublic()) { $methods[$method->getName()] = $method; } } \ksort($methods, SORT_NATURAL | SORT_FLAG_CASE); return $methods; }
[ "protected", "function", "getMethods", "(", "$", "showAll", ",", "\\", "Reflector", "$", "reflector", ",", "$", "noInherit", "=", "false", ")", "{", "$", "className", "=", "$", "reflector", "->", "getName", "(", ")", ";", "$", "methods", "=", "[", "]", ";", "foreach", "(", "$", "reflector", "->", "getMethods", "(", ")", "as", "$", "name", "=>", "$", "method", ")", "{", "if", "(", "$", "noInherit", "&&", "$", "method", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", "!==", "$", "className", ")", "{", "continue", ";", "}", "if", "(", "$", "showAll", "||", "$", "method", "->", "isPublic", "(", ")", ")", "{", "$", "methods", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "method", ";", "}", "}", "\\", "ksort", "(", "$", "methods", ",", "SORT_NATURAL", "|", "SORT_FLAG_CASE", ")", ";", "return", "$", "methods", ";", "}" ]
Get defined methods for the given class or object Reflector. @param bool $showAll Include private and protected methods @param \Reflector $reflector @param bool $noInherit Exclude inherited methods @return array
[ "Get", "defined", "methods", "for", "the", "given", "class", "or", "object", "Reflector", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/MethodEnumerator.php#L65-L83
train
bobthecow/psysh
src/Command/ListCommand/MethodEnumerator.php
MethodEnumerator.prepareMethods
protected function prepareMethods(array $methods) { // My kingdom for a generator. $ret = []; foreach ($methods as $name => $method) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => $this->getVisibilityStyle($method), 'value' => $this->presentSignature($method), ]; } } return $ret; }
php
protected function prepareMethods(array $methods) { // My kingdom for a generator. $ret = []; foreach ($methods as $name => $method) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => $this->getVisibilityStyle($method), 'value' => $this->presentSignature($method), ]; } } return $ret; }
[ "protected", "function", "prepareMethods", "(", "array", "$", "methods", ")", "{", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "methods", "as", "$", "name", "=>", "$", "method", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "ret", "[", "$", "name", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'style'", "=>", "$", "this", "->", "getVisibilityStyle", "(", "$", "method", ")", ",", "'value'", "=>", "$", "this", "->", "presentSignature", "(", "$", "method", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted method array. @param array $methods @return array
[ "Prepare", "formatted", "method", "array", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/MethodEnumerator.php#L92-L108
train
bobthecow/psysh
src/Command/ListCommand/MethodEnumerator.php
MethodEnumerator.getVisibilityStyle
private function getVisibilityStyle(\ReflectionMethod $method) { if ($method->isPublic()) { return self::IS_PUBLIC; } elseif ($method->isProtected()) { return self::IS_PROTECTED; } else { return self::IS_PRIVATE; } }
php
private function getVisibilityStyle(\ReflectionMethod $method) { if ($method->isPublic()) { return self::IS_PUBLIC; } elseif ($method->isProtected()) { return self::IS_PROTECTED; } else { return self::IS_PRIVATE; } }
[ "private", "function", "getVisibilityStyle", "(", "\\", "ReflectionMethod", "$", "method", ")", "{", "if", "(", "$", "method", "->", "isPublic", "(", ")", ")", "{", "return", "self", "::", "IS_PUBLIC", ";", "}", "elseif", "(", "$", "method", "->", "isProtected", "(", ")", ")", "{", "return", "self", "::", "IS_PROTECTED", ";", "}", "else", "{", "return", "self", "::", "IS_PRIVATE", ";", "}", "}" ]
Get output style for the given method's visibility. @param \ReflectionMethod $method @return string
[ "Get", "output", "style", "for", "the", "given", "method", "s", "visibility", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/MethodEnumerator.php#L135-L144
train
bobthecow/psysh
src/ExecutionClosure.php
ExecutionClosure.setClosure
protected function setClosure(Shell $shell, \Closure $closure) { if (self::shouldBindClosure()) { $that = $shell->getBoundObject(); if (\is_object($that)) { $closure = $closure->bindTo($that, \get_class($that)); } else { $closure = $closure->bindTo(null, $shell->getBoundClass()); } } $this->closure = $closure; }
php
protected function setClosure(Shell $shell, \Closure $closure) { if (self::shouldBindClosure()) { $that = $shell->getBoundObject(); if (\is_object($that)) { $closure = $closure->bindTo($that, \get_class($that)); } else { $closure = $closure->bindTo(null, $shell->getBoundClass()); } } $this->closure = $closure; }
[ "protected", "function", "setClosure", "(", "Shell", "$", "shell", ",", "\\", "Closure", "$", "closure", ")", "{", "if", "(", "self", "::", "shouldBindClosure", "(", ")", ")", "{", "$", "that", "=", "$", "shell", "->", "getBoundObject", "(", ")", ";", "if", "(", "\\", "is_object", "(", "$", "that", ")", ")", "{", "$", "closure", "=", "$", "closure", "->", "bindTo", "(", "$", "that", ",", "\\", "get_class", "(", "$", "that", ")", ")", ";", "}", "else", "{", "$", "closure", "=", "$", "closure", "->", "bindTo", "(", "null", ",", "$", "shell", "->", "getBoundClass", "(", ")", ")", ";", "}", "}", "$", "this", "->", "closure", "=", "$", "closure", ";", "}" ]
Set the closure instance. @param Shell $psysh @param \Closure $closure
[ "Set", "the", "closure", "instance", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ExecutionClosure.php#L78-L90
train
bobthecow/psysh
src/CodeCleaner/CallTimePassByReferencePass.php
CallTimePassByReferencePass.enterNode
public function enterNode(Node $node) { if (!$node instanceof FuncCall && !$node instanceof MethodCall && !$node instanceof StaticCall) { return; } foreach ($node->args as $arg) { if ($arg->byRef) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } }
php
public function enterNode(Node $node) { if (!$node instanceof FuncCall && !$node instanceof MethodCall && !$node instanceof StaticCall) { return; } foreach ($node->args as $arg) { if ($arg->byRef) { throw new FatalErrorException(self::EXCEPTION_MESSAGE, 0, E_ERROR, null, $node->getLine()); } } }
[ "public", "function", "enterNode", "(", "Node", "$", "node", ")", "{", "if", "(", "!", "$", "node", "instanceof", "FuncCall", "&&", "!", "$", "node", "instanceof", "MethodCall", "&&", "!", "$", "node", "instanceof", "StaticCall", ")", "{", "return", ";", "}", "foreach", "(", "$", "node", "->", "args", "as", "$", "arg", ")", "{", "if", "(", "$", "arg", "->", "byRef", ")", "{", "throw", "new", "FatalErrorException", "(", "self", "::", "EXCEPTION_MESSAGE", ",", "0", ",", "E_ERROR", ",", "null", ",", "$", "node", "->", "getLine", "(", ")", ")", ";", "}", "}", "}" ]
Validate of use call-time pass-by-reference. @throws RuntimeException if the user used call-time pass-by-reference @param Node $node
[ "Validate", "of", "use", "call", "-", "time", "pass", "-", "by", "-", "reference", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/CallTimePassByReferencePass.php#L38-L49
train
bobthecow/psysh
src/Command/WhereamiCommand.php
WhereamiCommand.trace
protected function trace() { foreach (\array_reverse($this->backtrace) as $stackFrame) { if ($this->isDebugCall($stackFrame)) { return $stackFrame; } } return \end($this->backtrace); }
php
protected function trace() { foreach (\array_reverse($this->backtrace) as $stackFrame) { if ($this->isDebugCall($stackFrame)) { return $stackFrame; } } return \end($this->backtrace); }
[ "protected", "function", "trace", "(", ")", "{", "foreach", "(", "\\", "array_reverse", "(", "$", "this", "->", "backtrace", ")", "as", "$", "stackFrame", ")", "{", "if", "(", "$", "this", "->", "isDebugCall", "(", "$", "stackFrame", ")", ")", "{", "return", "$", "stackFrame", ";", "}", "}", "return", "\\", "end", "(", "$", "this", "->", "backtrace", ")", ";", "}" ]
Obtains the correct stack frame in the full backtrace. @return array
[ "Obtains", "the", "correct", "stack", "frame", "in", "the", "full", "backtrace", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/WhereamiCommand.php#L70-L79
train
bobthecow/psysh
src/Command/WhereamiCommand.php
WhereamiCommand.fileInfo
protected function fileInfo() { $stackFrame = $this->trace(); if (\preg_match('/eval\(/', $stackFrame['file'])) { \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); $file = $matches[1][0]; $line = (int) $matches[2][0]; } else { $file = $stackFrame['file']; $line = $stackFrame['line']; } return \compact('file', 'line'); }
php
protected function fileInfo() { $stackFrame = $this->trace(); if (\preg_match('/eval\(/', $stackFrame['file'])) { \preg_match_all('/([^\(]+)\((\d+)/', $stackFrame['file'], $matches); $file = $matches[1][0]; $line = (int) $matches[2][0]; } else { $file = $stackFrame['file']; $line = $stackFrame['line']; } return \compact('file', 'line'); }
[ "protected", "function", "fileInfo", "(", ")", "{", "$", "stackFrame", "=", "$", "this", "->", "trace", "(", ")", ";", "if", "(", "\\", "preg_match", "(", "'/eval\\(/'", ",", "$", "stackFrame", "[", "'file'", "]", ")", ")", "{", "\\", "preg_match_all", "(", "'/([^\\(]+)\\((\\d+)/'", ",", "$", "stackFrame", "[", "'file'", "]", ",", "$", "matches", ")", ";", "$", "file", "=", "$", "matches", "[", "1", "]", "[", "0", "]", ";", "$", "line", "=", "(", "int", ")", "$", "matches", "[", "2", "]", "[", "0", "]", ";", "}", "else", "{", "$", "file", "=", "$", "stackFrame", "[", "'file'", "]", ";", "$", "line", "=", "$", "stackFrame", "[", "'line'", "]", ";", "}", "return", "\\", "compact", "(", "'file'", ",", "'line'", ")", ";", "}" ]
Determine the file and line based on the specific backtrace. @return array
[ "Determine", "the", "file", "and", "line", "based", "on", "the", "specific", "backtrace", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/WhereamiCommand.php#L95-L108
train
bobthecow/psysh
src/Command/ListCommand/PropertyEnumerator.php
PropertyEnumerator.getProperties
protected function getProperties($showAll, \Reflector $reflector, $noInherit = false) { $className = $reflector->getName(); $properties = []; foreach ($reflector->getProperties() as $property) { if ($noInherit && $property->getDeclaringClass()->getName() !== $className) { continue; } if ($showAll || $property->isPublic()) { $properties[$property->getName()] = $property; } } \ksort($properties, SORT_NATURAL | SORT_FLAG_CASE); return $properties; }
php
protected function getProperties($showAll, \Reflector $reflector, $noInherit = false) { $className = $reflector->getName(); $properties = []; foreach ($reflector->getProperties() as $property) { if ($noInherit && $property->getDeclaringClass()->getName() !== $className) { continue; } if ($showAll || $property->isPublic()) { $properties[$property->getName()] = $property; } } \ksort($properties, SORT_NATURAL | SORT_FLAG_CASE); return $properties; }
[ "protected", "function", "getProperties", "(", "$", "showAll", ",", "\\", "Reflector", "$", "reflector", ",", "$", "noInherit", "=", "false", ")", "{", "$", "className", "=", "$", "reflector", "->", "getName", "(", ")", ";", "$", "properties", "=", "[", "]", ";", "foreach", "(", "$", "reflector", "->", "getProperties", "(", ")", "as", "$", "property", ")", "{", "if", "(", "$", "noInherit", "&&", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", "!==", "$", "className", ")", "{", "continue", ";", "}", "if", "(", "$", "showAll", "||", "$", "property", "->", "isPublic", "(", ")", ")", "{", "$", "properties", "[", "$", "property", "->", "getName", "(", ")", "]", "=", "$", "property", ";", "}", "}", "\\", "ksort", "(", "$", "properties", ",", "SORT_NATURAL", "|", "SORT_FLAG_CASE", ")", ";", "return", "$", "properties", ";", "}" ]
Get defined properties for the given class or object Reflector. @param bool $showAll Include private and protected properties @param \Reflector $reflector @param bool $noInherit Exclude inherited properties @return array
[ "Get", "defined", "properties", "for", "the", "given", "class", "or", "object", "Reflector", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/PropertyEnumerator.php#L65-L83
train
bobthecow/psysh
src/Command/ListCommand/PropertyEnumerator.php
PropertyEnumerator.prepareProperties
protected function prepareProperties(array $properties, $target = null) { // My kingdom for a generator. $ret = []; foreach ($properties as $name => $property) { if ($this->showItem($name)) { $fname = '$' . $name; $ret[$fname] = [ 'name' => $fname, 'style' => $this->getVisibilityStyle($property), 'value' => $this->presentValue($property, $target), ]; } } return $ret; }
php
protected function prepareProperties(array $properties, $target = null) { // My kingdom for a generator. $ret = []; foreach ($properties as $name => $property) { if ($this->showItem($name)) { $fname = '$' . $name; $ret[$fname] = [ 'name' => $fname, 'style' => $this->getVisibilityStyle($property), 'value' => $this->presentValue($property, $target), ]; } } return $ret; }
[ "protected", "function", "prepareProperties", "(", "array", "$", "properties", ",", "$", "target", "=", "null", ")", "{", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "properties", "as", "$", "name", "=>", "$", "property", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "fname", "=", "'$'", ".", "$", "name", ";", "$", "ret", "[", "$", "fname", "]", "=", "[", "'name'", "=>", "$", "fname", ",", "'style'", "=>", "$", "this", "->", "getVisibilityStyle", "(", "$", "property", ")", ",", "'value'", "=>", "$", "this", "->", "presentValue", "(", "$", "property", ",", "$", "target", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted property array. @param array $properties @return array
[ "Prepare", "formatted", "property", "array", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/PropertyEnumerator.php#L92-L109
train
bobthecow/psysh
src/Command/ListCommand/PropertyEnumerator.php
PropertyEnumerator.getVisibilityStyle
private function getVisibilityStyle(\ReflectionProperty $property) { if ($property->isPublic()) { return self::IS_PUBLIC; } elseif ($property->isProtected()) { return self::IS_PROTECTED; } else { return self::IS_PRIVATE; } }
php
private function getVisibilityStyle(\ReflectionProperty $property) { if ($property->isPublic()) { return self::IS_PUBLIC; } elseif ($property->isProtected()) { return self::IS_PROTECTED; } else { return self::IS_PRIVATE; } }
[ "private", "function", "getVisibilityStyle", "(", "\\", "ReflectionProperty", "$", "property", ")", "{", "if", "(", "$", "property", "->", "isPublic", "(", ")", ")", "{", "return", "self", "::", "IS_PUBLIC", ";", "}", "elseif", "(", "$", "property", "->", "isProtected", "(", ")", ")", "{", "return", "self", "::", "IS_PROTECTED", ";", "}", "else", "{", "return", "self", "::", "IS_PRIVATE", ";", "}", "}" ]
Get output style for the given property's visibility. @param \ReflectionProperty $property @return string
[ "Get", "output", "style", "for", "the", "given", "property", "s", "visibility", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/PropertyEnumerator.php#L136-L145
train
bobthecow/psysh
src/Command/ListCommand/FunctionEnumerator.php
FunctionEnumerator.getFunctions
protected function getFunctions($type = null) { $funcs = \get_defined_functions(); if ($type) { return $funcs[$type]; } else { return \array_merge($funcs['internal'], $funcs['user']); } }
php
protected function getFunctions($type = null) { $funcs = \get_defined_functions(); if ($type) { return $funcs[$type]; } else { return \array_merge($funcs['internal'], $funcs['user']); } }
[ "protected", "function", "getFunctions", "(", "$", "type", "=", "null", ")", "{", "$", "funcs", "=", "\\", "get_defined_functions", "(", ")", ";", "if", "(", "$", "type", ")", "{", "return", "$", "funcs", "[", "$", "type", "]", ";", "}", "else", "{", "return", "\\", "array_merge", "(", "$", "funcs", "[", "'internal'", "]", ",", "$", "funcs", "[", "'user'", "]", ")", ";", "}", "}" ]
Get defined functions. Optionally limit functions to "user" or "internal" functions. @param null|string $type "user" or "internal" (default: both) @return array
[ "Get", "defined", "functions", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/FunctionEnumerator.php#L75-L84
train
bobthecow/psysh
src/Command/ListCommand/FunctionEnumerator.php
FunctionEnumerator.prepareFunctions
protected function prepareFunctions(array $functions) { \natcasesort($functions); // My kingdom for a generator. $ret = []; foreach ($functions as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_FUNCTION, 'value' => $this->presentSignature($name), ]; } } return $ret; }
php
protected function prepareFunctions(array $functions) { \natcasesort($functions); // My kingdom for a generator. $ret = []; foreach ($functions as $name) { if ($this->showItem($name)) { $ret[$name] = [ 'name' => $name, 'style' => self::IS_FUNCTION, 'value' => $this->presentSignature($name), ]; } } return $ret; }
[ "protected", "function", "prepareFunctions", "(", "array", "$", "functions", ")", "{", "\\", "natcasesort", "(", "$", "functions", ")", ";", "// My kingdom for a generator.", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "functions", "as", "$", "name", ")", "{", "if", "(", "$", "this", "->", "showItem", "(", "$", "name", ")", ")", "{", "$", "ret", "[", "$", "name", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'style'", "=>", "self", "::", "IS_FUNCTION", ",", "'value'", "=>", "$", "this", "->", "presentSignature", "(", "$", "name", ")", ",", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Prepare formatted function array. @param array $functions @return array
[ "Prepare", "formatted", "function", "array", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/FunctionEnumerator.php#L93-L111
train
bobthecow/psysh
src/Input/ShellInput.php
ShellInput.tokenize
private function tokenize($input) { $tokens = []; $length = \strlen($input); $cursor = 0; while ($cursor < $length) { if (\preg_match('/\s+/A', $input, $match, null, $cursor)) { } elseif (\preg_match('/([^="\'\s]+?)(=?)(' . StringInput::REGEX_QUOTED_STRING . '+)/A', $input, $match, null, $cursor)) { $tokens[] = [ $match[1] . $match[2] . \stripcslashes(\str_replace(['"\'', '\'"', '\'\'', '""'], '', \substr($match[3], 1, \strlen($match[3]) - 2))), \stripcslashes(\substr($input, $cursor)), ]; } elseif (\preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) { $tokens[] = [ \stripcslashes(\substr($match[0], 1, \strlen($match[0]) - 2)), \stripcslashes(\substr($input, $cursor)), ]; } elseif (\preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) { $tokens[] = [ \stripcslashes($match[1]), \stripcslashes(\substr($input, $cursor)), ]; } else { // should never happen // @codeCoverageIgnoreStart throw new \InvalidArgumentException(\sprintf('Unable to parse input near "... %s ..."', \substr($input, $cursor, 10))); // @codeCoverageIgnoreEnd } $cursor += \strlen($match[0]); } return $tokens; }
php
private function tokenize($input) { $tokens = []; $length = \strlen($input); $cursor = 0; while ($cursor < $length) { if (\preg_match('/\s+/A', $input, $match, null, $cursor)) { } elseif (\preg_match('/([^="\'\s]+?)(=?)(' . StringInput::REGEX_QUOTED_STRING . '+)/A', $input, $match, null, $cursor)) { $tokens[] = [ $match[1] . $match[2] . \stripcslashes(\str_replace(['"\'', '\'"', '\'\'', '""'], '', \substr($match[3], 1, \strlen($match[3]) - 2))), \stripcslashes(\substr($input, $cursor)), ]; } elseif (\preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) { $tokens[] = [ \stripcslashes(\substr($match[0], 1, \strlen($match[0]) - 2)), \stripcslashes(\substr($input, $cursor)), ]; } elseif (\preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) { $tokens[] = [ \stripcslashes($match[1]), \stripcslashes(\substr($input, $cursor)), ]; } else { // should never happen // @codeCoverageIgnoreStart throw new \InvalidArgumentException(\sprintf('Unable to parse input near "... %s ..."', \substr($input, $cursor, 10))); // @codeCoverageIgnoreEnd } $cursor += \strlen($match[0]); } return $tokens; }
[ "private", "function", "tokenize", "(", "$", "input", ")", "{", "$", "tokens", "=", "[", "]", ";", "$", "length", "=", "\\", "strlen", "(", "$", "input", ")", ";", "$", "cursor", "=", "0", ";", "while", "(", "$", "cursor", "<", "$", "length", ")", "{", "if", "(", "\\", "preg_match", "(", "'/\\s+/A'", ",", "$", "input", ",", "$", "match", ",", "null", ",", "$", "cursor", ")", ")", "{", "}", "elseif", "(", "\\", "preg_match", "(", "'/([^=\"\\'\\s]+?)(=?)('", ".", "StringInput", "::", "REGEX_QUOTED_STRING", ".", "'+)/A'", ",", "$", "input", ",", "$", "match", ",", "null", ",", "$", "cursor", ")", ")", "{", "$", "tokens", "[", "]", "=", "[", "$", "match", "[", "1", "]", ".", "$", "match", "[", "2", "]", ".", "\\", "stripcslashes", "(", "\\", "str_replace", "(", "[", "'\"\\''", ",", "'\\'\"'", ",", "'\\'\\''", ",", "'\"\"'", "]", ",", "''", ",", "\\", "substr", "(", "$", "match", "[", "3", "]", ",", "1", ",", "\\", "strlen", "(", "$", "match", "[", "3", "]", ")", "-", "2", ")", ")", ")", ",", "\\", "stripcslashes", "(", "\\", "substr", "(", "$", "input", ",", "$", "cursor", ")", ")", ",", "]", ";", "}", "elseif", "(", "\\", "preg_match", "(", "'/'", ".", "StringInput", "::", "REGEX_QUOTED_STRING", ".", "'/A'", ",", "$", "input", ",", "$", "match", ",", "null", ",", "$", "cursor", ")", ")", "{", "$", "tokens", "[", "]", "=", "[", "\\", "stripcslashes", "(", "\\", "substr", "(", "$", "match", "[", "0", "]", ",", "1", ",", "\\", "strlen", "(", "$", "match", "[", "0", "]", ")", "-", "2", ")", ")", ",", "\\", "stripcslashes", "(", "\\", "substr", "(", "$", "input", ",", "$", "cursor", ")", ")", ",", "]", ";", "}", "elseif", "(", "\\", "preg_match", "(", "'/'", ".", "StringInput", "::", "REGEX_STRING", ".", "'/A'", ",", "$", "input", ",", "$", "match", ",", "null", ",", "$", "cursor", ")", ")", "{", "$", "tokens", "[", "]", "=", "[", "\\", "stripcslashes", "(", "$", "match", "[", "1", "]", ")", ",", "\\", "stripcslashes", "(", "\\", "substr", "(", "$", "input", ",", "$", "cursor", ")", ")", ",", "]", ";", "}", "else", "{", "// should never happen", "// @codeCoverageIgnoreStart", "throw", "new", "\\", "InvalidArgumentException", "(", "\\", "sprintf", "(", "'Unable to parse input near \"... %s ...\"'", ",", "\\", "substr", "(", "$", "input", ",", "$", "cursor", ",", "10", ")", ")", ")", ";", "// @codeCoverageIgnoreEnd", "}", "$", "cursor", "+=", "\\", "strlen", "(", "$", "match", "[", "0", "]", ")", ";", "}", "return", "$", "tokens", ";", "}" ]
Tokenizes a string. The version of this on StringInput is good, but doesn't handle code arguments if they're at all complicated. This does :) @param string $input The input to tokenize @return array An array of token/rest pairs @throws \InvalidArgumentException When unable to parse input (should never happen)
[ "Tokenizes", "a", "string", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/ShellInput.php#L84-L117
train
bobthecow/psysh
src/Input/ShellInput.php
ShellInput.parse
protected function parse() { $parseOptions = true; $this->parsed = $this->tokenPairs; while (null !== $tokenPair = \array_shift($this->parsed)) { // token is what you'd expect. rest is the remainder of the input // string, including token, and will be used if this is a code arg. list($token, $rest) = $tokenPair; if ($parseOptions && '' === $token) { $this->parseShellArgument($token, $rest); } elseif ($parseOptions && '--' === $token) { $parseOptions = false; } elseif ($parseOptions && 0 === \strpos($token, '--')) { $this->parseLongOption($token); } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) { $this->parseShortOption($token); } else { $this->parseShellArgument($token, $rest); } } }
php
protected function parse() { $parseOptions = true; $this->parsed = $this->tokenPairs; while (null !== $tokenPair = \array_shift($this->parsed)) { // token is what you'd expect. rest is the remainder of the input // string, including token, and will be used if this is a code arg. list($token, $rest) = $tokenPair; if ($parseOptions && '' === $token) { $this->parseShellArgument($token, $rest); } elseif ($parseOptions && '--' === $token) { $parseOptions = false; } elseif ($parseOptions && 0 === \strpos($token, '--')) { $this->parseLongOption($token); } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) { $this->parseShortOption($token); } else { $this->parseShellArgument($token, $rest); } } }
[ "protected", "function", "parse", "(", ")", "{", "$", "parseOptions", "=", "true", ";", "$", "this", "->", "parsed", "=", "$", "this", "->", "tokenPairs", ";", "while", "(", "null", "!==", "$", "tokenPair", "=", "\\", "array_shift", "(", "$", "this", "->", "parsed", ")", ")", "{", "// token is what you'd expect. rest is the remainder of the input", "// string, including token, and will be used if this is a code arg.", "list", "(", "$", "token", ",", "$", "rest", ")", "=", "$", "tokenPair", ";", "if", "(", "$", "parseOptions", "&&", "''", "===", "$", "token", ")", "{", "$", "this", "->", "parseShellArgument", "(", "$", "token", ",", "$", "rest", ")", ";", "}", "elseif", "(", "$", "parseOptions", "&&", "'--'", "===", "$", "token", ")", "{", "$", "parseOptions", "=", "false", ";", "}", "elseif", "(", "$", "parseOptions", "&&", "0", "===", "\\", "strpos", "(", "$", "token", ",", "'--'", ")", ")", "{", "$", "this", "->", "parseLongOption", "(", "$", "token", ")", ";", "}", "elseif", "(", "$", "parseOptions", "&&", "'-'", "===", "$", "token", "[", "0", "]", "&&", "'-'", "!==", "$", "token", ")", "{", "$", "this", "->", "parseShortOption", "(", "$", "token", ")", ";", "}", "else", "{", "$", "this", "->", "parseShellArgument", "(", "$", "token", ",", "$", "rest", ")", ";", "}", "}", "}" ]
Same as parent, but with some bonus handling for code arguments.
[ "Same", "as", "parent", "but", "with", "some", "bonus", "handling", "for", "code", "arguments", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/ShellInput.php#L122-L143
train
bobthecow/psysh
src/Input/ShellInput.php
ShellInput.parseShellArgument
private function parseShellArgument($token, $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 }
php
private function parseShellArgument($token, $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 }
[ "private", "function", "parseShellArgument", "(", "$", "token", ",", "$", "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
[ "Parses", "an", "argument", "with", "bonus", "handling", "for", "code", "arguments", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Input/ShellInput.php#L153-L193
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/InstanceOfPass.php#L37-L46
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand.php#L137-L143
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/TimeitCommand.php#L168-L171
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/Matcher/AbstractMatcher.php#L64-L73
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Reflection/ReflectionLanguageConstruct.php#L121-L129
train
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); } // 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); }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/VarDumper/Presenter.php#L110-L136
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/ClassEnumerator.php#L73-L98
train
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); // 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; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/ClassEnumerator.php#L107-L125
train
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 = []) { // 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 : ['']; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/TabCompletion/AutoCompleter.php#L53-L82
train
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; // 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()); } } }
[ "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", "..." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/PassableByReferencePass.php#L96-L108
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L66-L85
train
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')); // 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')); }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Output/ShellOutput.php#L173-L203
train
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); // 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(), ]; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L82-L122
train
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; } // 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. } }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L133-L163
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L170-L187
train
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; } // 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; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L215-L235
train
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 { // Unexpected EOF, try again with an implicit semicolon 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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L272-L304
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner.php#L325-L338
train
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); // @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; } }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidFunctionNamePass.php#L40-L61
train
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) { // 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()); } } } }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidFunctionNamePass.php#L71-L88
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidConstantPass.php#L44-L55
train
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) { // 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()); } } } }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/CodeCleaner/ValidConstantPass.php#L64-L89
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L67-L77
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L87-L92
train
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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L121-L126
train
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 { // 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'; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ConfigPaths.php#L135-L155
train
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); // 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; }
[ "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", "." ]
9aaf29575bb8293206bb0420c1e1c87ff2ffa94e
https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/Command/ListCommand/TraitEnumerator.php#L70-L88
train