4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
14 use Psy\Exception\BreakException;
15 use Psy\Exception\ErrorException;
16 use Psy\Exception\Exception as PsyException;
17 use Psy\Exception\ThrowUpException;
18 use Psy\Output\ShellOutput;
19 use Psy\TabCompletion\Matcher;
20 use Psy\VarDumper\PresenterAware;
21 use Symfony\Component\Console\Application;
22 use Symfony\Component\Console\Command\Command as BaseCommand;
23 use Symfony\Component\Console\Formatter\OutputFormatter;
24 use Symfony\Component\Console\Input\ArgvInput;
25 use Symfony\Component\Console\Input\InputArgument;
26 use Symfony\Component\Console\Input\InputDefinition;
27 use Symfony\Component\Console\Input\InputInterface;
28 use Symfony\Component\Console\Input\InputOption;
29 use Symfony\Component\Console\Input\StringInput;
30 use Symfony\Component\Console\Output\OutputInterface;
33 * The Psy Shell application.
40 * @author Justin Hileman <justin@justinhileman.info>
42 class Shell extends Application
44 const VERSION = 'v0.8.3';
46 const PROMPT = '>>> ';
47 const BUFF_PROMPT = '... ';
48 const REPLAY = '--> ';
58 private $codeBufferOpen;
62 private $outputWantsNewline = false;
64 private $tabCompletionMatchers = array();
67 * Create a new Psy Shell.
69 * @param Configuration $config (default: null)
71 public function __construct(Configuration $config = null)
73 $this->config = $config ?: new Configuration();
74 $this->cleaner = $this->config->getCodeCleaner();
75 $this->loop = $this->config->getLoop();
76 $this->context = new Context();
77 $this->includes = array();
78 $this->readline = $this->config->getReadline();
80 parent::__construct('Psy Shell', self::VERSION);
82 $this->config->setShell($this);
84 // Register the current shell session's config with \Psy\info
85 \Psy\info($this->config);
89 * Check whether the first thing in a backtrace is an include call.
91 * This is used by the psysh bin to decide whether to start a shell on boot,
92 * or to simply autoload the library.
94 public static function isIncluded(array $trace)
96 return isset($trace[0]['function']) &&
97 in_array($trace[0]['function'], array('require', 'include', 'require_once', 'include_once'));
101 * Invoke a Psy Shell from the current context.
105 * foreach ($items as $item) {
106 * \Psy\Shell::debug(get_defined_vars());
109 * If you would like your shell interaction to affect the state of the
110 * current context, you can extract() the values returned from this call:
112 * foreach ($items as $item) {
113 * extract(\Psy\Shell::debug(get_defined_vars()));
114 * var_dump($item); // will be whatever you set $item to in Psy Shell
117 * Optionally, supply an object as the `$boundObject` parameter. This
118 * determines the value `$this` will have in the shell, and sets up class
119 * scope so that private and protected members are accessible:
123 * \Psy\Shell::debug(get_defined_vars(), $this);
127 * This only really works in PHP 5.4+ and HHVM 3.5+, so upgrade already.
129 * @param array $vars Scope variables from the calling context (default: array())
130 * @param object $boundObject Bound object ($this) value for the shell
132 * @return array Scope variables from the debugger session
134 public static function debug(array $vars = array(), $boundObject = null)
138 $sh = new \Psy\Shell();
139 $sh->setScopeVariables($vars);
141 if ($boundObject !== null) {
142 $sh->setBoundObject($boundObject);
147 return $sh->getScopeVariables(false);
151 * Adds a command object.
155 * @param BaseCommand $command A Symfony Console Command object
157 * @return BaseCommand The registered command
159 public function add(BaseCommand $command)
161 if ($ret = parent::add($command)) {
162 if ($ret instanceof ContextAware) {
163 $ret->setContext($this->context);
166 if ($ret instanceof PresenterAware) {
167 $ret->setPresenter($this->config->getPresenter());
175 * Gets the default input definition.
177 * @return InputDefinition An InputDefinition instance
179 protected function getDefaultInputDefinition()
181 return new InputDefinition(array(
182 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
183 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
188 * Gets the default commands that should always be available.
190 * @return array An array of default Command instances
192 protected function getDefaultCommands()
194 $hist = new Command\HistoryCommand();
195 $hist->setReadline($this->readline);
198 new Command\HelpCommand(),
199 new Command\ListCommand(),
200 new Command\DumpCommand(),
201 new Command\DocCommand(),
202 new Command\ShowCommand($this->config->colorMode()),
203 new Command\WtfCommand(),
204 new Command\WhereamiCommand($this->config->colorMode()),
205 new Command\ThrowUpCommand(),
206 new Command\TraceCommand(),
207 new Command\BufferCommand(),
208 new Command\ClearCommand(),
209 // new Command\PsyVersionCommand(),
211 new Command\ExitCommand(),
218 protected function getTabCompletionMatchers()
220 if (empty($this->tabCompletionMatchers)) {
221 $this->tabCompletionMatchers = array(
222 new Matcher\CommandsMatcher($this->all()),
223 new Matcher\KeywordsMatcher(),
224 new Matcher\VariablesMatcher(),
225 new Matcher\ConstantsMatcher(),
226 new Matcher\FunctionsMatcher(),
227 new Matcher\ClassNamesMatcher(),
228 new Matcher\ClassMethodsMatcher(),
229 new Matcher\ClassAttributesMatcher(),
230 new Matcher\ObjectMethodsMatcher(),
231 new Matcher\ObjectAttributesMatcher(),
235 return $this->tabCompletionMatchers;
239 * @param array $matchers
241 public function addTabCompletionMatchers(array $matchers)
243 $this->tabCompletionMatchers = array_merge($matchers, $this->getTabCompletionMatchers());
247 * Set the Shell output.
249 * @param OutputInterface $output
251 public function setOutput(OutputInterface $output)
253 $this->output = $output;
257 * Runs the current application.
259 * @param InputInterface $input An Input instance
260 * @param OutputInterface $output An Output instance
262 * @return int 0 if everything went fine, or an error code
264 public function run(InputInterface $input = null, OutputInterface $output = null)
266 $this->initializeTabCompletion();
268 if ($input === null && !isset($_SERVER['argv'])) {
269 $input = new ArgvInput(array());
272 if ($output === null) {
273 $output = $this->config->getOutput();
277 return parent::run($input, $output);
278 } catch (\Exception $e) {
279 $this->writeException($e);
284 * Runs the current application.
286 * @throws Exception if thrown via the `throw-up` command
288 * @param InputInterface $input An Input instance
289 * @param OutputInterface $output An Output instance
291 * @return int 0 if everything went fine, or an error code
293 public function doRun(InputInterface $input, OutputInterface $output)
295 $this->setOutput($output);
297 $this->resetCodeBuffer();
299 $this->setAutoExit(false);
300 $this->setCatchExceptions(false);
302 $this->readline->readHistory();
304 // if ($this->config->useReadline()) {
305 // readline_completion_function(array($this, 'autocomplete'));
308 $this->output->writeln($this->getHeader());
309 $this->writeVersionInfo();
310 $this->writeStartupMessage();
313 $this->loop->run($this);
314 } catch (ThrowUpException $e) {
315 throw $e->getPrevious();
322 * This will continue fetching user input until the code buffer contains
325 * @throws BreakException if user hits Ctrl+D
327 public function getInput()
329 $this->codeBufferOpen = false;
332 // reset output verbosity (in case it was altered by a subcommand)
333 $this->output->setVerbosity(ShellOutput::VERBOSITY_VERBOSE);
335 $input = $this->readline();
338 * Handle Ctrl+D. It behaves differently in different cases:
340 * 1) In an expression, like a function or "if" block, clear the input buffer
341 * 2) At top-level session, behave like the exit command
343 if ($input === false) {
344 $this->output->writeln('');
346 if ($this->hasCode()) {
347 $this->resetCodeBuffer();
349 throw new BreakException('Ctrl+D');
353 // handle empty input
354 if (trim($input) === '') {
358 if ($this->hasCommand($input)) {
359 $this->readline->addHistory($input);
360 $this->runCommand($input);
364 $this->addCode($input);
365 } while (!$this->hasValidCode());
369 * Pass the beforeLoop callback through to the Loop instance.
371 * @see Loop::beforeLoop
373 public function beforeLoop()
375 $this->loop->beforeLoop();
379 * Pass the afterLoop callback through to the Loop instance.
381 * @see Loop::afterLoop
383 public function afterLoop()
385 $this->loop->afterLoop();
389 * Set the variables currently in scope.
393 public function setScopeVariables(array $vars)
395 $this->context->setAll($vars);
399 * Return the set of variables currently in scope.
401 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
402 * passing the scope variables to `extract`
403 * in PHP 7.1+, you _must_ exclude 'this'
405 * @return array Associative array of scope variables
407 public function getScopeVariables($includeBoundObject = true)
409 $vars = $this->context->getAll();
411 if (!$includeBoundObject) {
412 unset($vars['this']);
419 * Return the set of magic variables currently in scope.
421 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
422 * passing the scope variables to `extract`
423 * in PHP 7.1+, you _must_ exclude 'this'
425 * @return array Associative array of magic scope variables
427 public function getSpecialScopeVariables($includeBoundObject = true)
429 $vars = $this->context->getSpecialVariables();
431 if (!$includeBoundObject) {
432 unset($vars['this']);
439 * Get the set of unused command-scope variable names.
441 * @return array Array of unused variable names
443 public function getUnusedCommandScopeVariableNames()
445 return $this->context->getUnusedCommandScopeVariableNames();
449 * Get the set of variable names currently in scope.
451 * @return array Array of variable names
453 public function getScopeVariableNames()
455 return array_keys($this->context->getAll());
459 * Get a scope variable value by name.
461 * @param string $name
465 public function getScopeVariable($name)
467 return $this->context->get($name);
471 * Set the bound object ($this variable) for the interactive shell.
473 * @param object|null $boundObject
475 public function setBoundObject($boundObject)
477 $this->context->setBoundObject($boundObject);
481 * Get the bound object ($this variable) for the interactive shell.
483 * @return object|null
485 public function getBoundObject()
487 return $this->context->getBoundObject();
491 * Add includes, to be parsed and executed before running the interactive shell.
493 * @param array $includes
495 public function setIncludes(array $includes = array())
497 $this->includes = $includes;
501 * Get PHP files to be parsed and executed before running the interactive shell.
505 public function getIncludes()
507 return array_merge($this->config->getDefaultIncludes(), $this->includes);
511 * Check whether this shell's code buffer contains code.
513 * @return bool True if the code buffer contains code
515 public function hasCode()
517 return !empty($this->codeBuffer);
521 * Check whether the code in this shell's code buffer is valid.
523 * If the code is valid, the code buffer should be flushed and evaluated.
525 * @return bool True if the code buffer content is valid
527 protected function hasValidCode()
529 return !$this->codeBufferOpen && $this->code !== false;
533 * Add code to the code buffer.
535 * @param string $code
537 public function addCode($code)
540 // Code lines ending in \ keep the buffer open
541 if (substr(rtrim($code), -1) === '\\') {
542 $this->codeBufferOpen = true;
543 $code = substr(rtrim($code), 0, -1);
545 $this->codeBufferOpen = false;
548 $this->codeBuffer[] = $code;
549 $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons());
550 } catch (\Exception $e) {
551 // Add failed code blocks to the readline history.
552 $this->readline->addHistory(implode("\n", $this->codeBuffer));
558 * Get the current code buffer.
560 * This is useful for commands which manipulate the buffer.
564 public function getCodeBuffer()
566 return $this->codeBuffer;
570 * Run a Psy Shell command given the user input.
572 * @throws InvalidArgumentException if the input is not a valid command
574 * @param string $input User input string
576 * @return mixed Who knows?
578 protected function runCommand($input)
580 $command = $this->getCommand($input);
582 if (empty($command)) {
583 throw new \InvalidArgumentException('Command not found: ' . $input);
586 $input = new StringInput(str_replace('\\', '\\\\', rtrim($input, " \t\n\r\0\x0B;")));
588 if ($input->hasParameterOption(array('--help', '-h'))) {
589 $helpCommand = $this->get('help');
590 $helpCommand->setCommand($command);
592 return $helpCommand->run($input, $this->output);
595 return $command->run($input, $this->output);
599 * Reset the current code buffer.
601 * This should be run after evaluating user input, catching exceptions, or
602 * on demand by commands such as BufferCommand.
604 public function resetCodeBuffer()
606 $this->codeBuffer = array();
611 * Inject input into the input buffer.
613 * This is useful for commands which want to replay history.
615 * @param string|array $input
617 public function addInput($input)
619 foreach ((array) $input as $line) {
620 $this->inputBuffer[] = $line;
625 * Flush the current (valid) code buffer.
627 * If the code buffer is valid, resets the code buffer and returns the
630 * @return string PHP code buffer contents
632 public function flushCode()
634 if ($this->hasValidCode()) {
635 $this->readline->addHistory(implode("\n", $this->codeBuffer));
637 $this->resetCodeBuffer();
644 * Get the current evaluation scope namespace.
646 * @see CodeCleaner::getNamespace
648 * @return string Current code namespace
650 public function getNamespace()
652 if ($namespace = $this->cleaner->getNamespace()) {
653 return implode('\\', $namespace);
658 * Write a string to stdout.
660 * This is used by the shell loop for rendering output from evaluated code.
663 * @param int $phase Output buffering phase
665 public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END)
668 if (version_compare(PHP_VERSION, '5.4', '>=')) {
669 $isCleaning = $phase & PHP_OUTPUT_HANDLER_CLEAN;
673 if ($out !== '' && !$isCleaning) {
674 $this->output->write($out, false, ShellOutput::OUTPUT_RAW);
675 $this->outputWantsNewline = (substr($out, -1) !== "\n");
678 // Output buffering is done!
679 if ($this->outputWantsNewline && $phase & PHP_OUTPUT_HANDLER_END) {
680 $this->output->writeln(sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
681 $this->outputWantsNewline = false;
686 * Write a return value to stdout.
688 * The return value is formatted or pretty-printed, and rendered in a
689 * visibly distinct manner (in this case, as cyan).
691 * @see self::presentValue
695 public function writeReturnValue($ret)
697 $this->context->setReturnValue($ret);
698 $ret = $this->presentValue($ret);
699 $indent = str_repeat(' ', strlen(static::RETVAL));
701 $this->output->writeln(static::RETVAL . str_replace(PHP_EOL, PHP_EOL . $indent, $ret));
705 * Renders a caught Exception.
707 * Exceptions are formatted according to severity. ErrorExceptions which were
708 * warnings or Strict errors aren't rendered as harshly as real errors.
710 * Stores $e as the last Exception in the Shell Context.
712 * @param \Exception $e An exception instance
713 * @param OutputInterface $output An OutputInterface instance
715 public function writeException(\Exception $e)
717 $this->context->setLastException($e);
719 $message = $e->getMessage();
720 if (!$e instanceof PsyException) {
721 $message = sprintf('%s with message \'%s\'', get_class($e), $message);
724 $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
725 $this->output->writeln(sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity));
727 $this->resetCodeBuffer();
731 * Helper for getting an output style for the given ErrorException's level.
733 * @param \ErrorException $e
737 protected function getSeverity(\ErrorException $e)
739 $severity = $e->getSeverity();
740 if ($severity & error_reporting()) {
745 case E_COMPILE_WARNING:
755 // Since this is below the user's reporting threshold, it's always going to be a warning.
761 * Helper for throwing an ErrorException.
765 * set_error_handler(array($psysh, 'handleError'));
767 * Unlike ErrorException::throwException, this error handler respects the
768 * current error_reporting level; i.e. it logs warnings and notices, but
769 * doesn't throw an exception unless it's above the current error_reporting
770 * threshold. This should probably only be used in the inner execution loop
771 * of the shell, as most of the time a thrown exception is much more useful.
773 * If the error type matches the `errorLoggingLevel` config, it will be
774 * logged as well, regardless of the `error_reporting` level.
776 * @see \Psy\Exception\ErrorException::throwException
777 * @see \Psy\Shell::writeException
779 * @throws \Psy\Exception\ErrorException depending on the current error_reporting level
781 * @param int $errno Error type
782 * @param string $errstr Message
783 * @param string $errfile Filename
784 * @param int $errline Line number
786 public function handleError($errno, $errstr, $errfile, $errline)
788 if ($errno & error_reporting()) {
789 ErrorException::throwException($errno, $errstr, $errfile, $errline);
790 } elseif ($errno & $this->config->errorLoggingLevel()) {
791 // log it and continue...
792 $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline));
797 * Format a value for display.
799 * @see Presenter::present
803 * @return string Formatted value
805 protected function presentValue($val)
807 return $this->config->getPresenter()->present($val);
811 * Get a command (if one exists) for the current input string.
813 * @param string $input
815 * @return null|BaseCommand
817 protected function getCommand($input)
819 $input = new StringInput($input);
820 if ($name = $input->getFirstArgument()) {
821 return $this->get($name);
826 * Check whether a command is set for the current input string.
828 * @param string $input
830 * @return bool True if the shell has a command for the given input
832 protected function hasCommand($input)
834 $input = new StringInput($input);
835 if ($name = $input->getFirstArgument()) {
836 return $this->has($name);
843 * Get the current input prompt.
847 protected function getPrompt()
849 return $this->hasCode() ? static::BUFF_PROMPT : static::PROMPT;
853 * Read a line of user input.
855 * This will return a line from the input buffer (if any exist). Otherwise,
856 * it will ask the user for input.
858 * If readline is enabled, this delegates to readline. Otherwise, it's an
861 * @return string One line of user input
863 protected function readline()
865 if (!empty($this->inputBuffer)) {
866 $line = array_shift($this->inputBuffer);
867 $this->output->writeln(sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
872 return $this->readline->readline($this->getPrompt());
876 * Get the shell output header.
880 protected function getHeader()
882 return sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
886 * Get the current version of Psy Shell.
890 public function getVersion()
892 $separator = $this->config->useUnicode() ? '—' : '-';
894 return sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, phpversion(), $separator, php_sapi_name());
898 * Get a PHP manual database instance.
902 public function getManualDb()
904 return $this->config->getManualDb();
908 * Autocomplete variable names.
910 * This is used by `readline` for tab completion.
912 * @param string $text
914 * @return mixed Array possible completions for the given input, if any
916 protected function autocomplete($text)
918 $info = readline_info();
919 // $line = substr($info['line_buffer'], 0, $info['end']);
921 // Check whether there's a command for this
922 // $words = explode(' ', $line);
923 // $firstWord = reset($words);
925 // check whether this is a variable...
926 $firstChar = substr($info['line_buffer'], max(0, $info['end'] - strlen($text) - 1), 1);
927 if ($firstChar === '$') {
928 return $this->getScopeVariableNames();
933 * Initialize tab completion matchers.
935 * If tab completion is enabled this adds tab completion matchers to the
936 * auto completer and sets context if needed.
938 protected function initializeTabCompletion()
940 // auto completer needs shell to be linked to configuration because of the context aware matchers
941 if ($this->config->getTabCompletion()) {
942 $this->completion = $this->config->getAutoCompleter();
943 $this->addTabCompletionMatchers($this->config->getTabCompletionMatchers());
944 foreach ($this->getTabCompletionMatchers() as $matcher) {
945 if ($matcher instanceof ContextAware) {
946 $matcher->setContext($this->context);
948 $this->completion->addMatcher($matcher);
950 $this->completion->activate();
955 * @todo Implement self-update
956 * @todo Implement prompt to start update
958 * @return void|string
960 protected function writeVersionInfo()
962 if (PHP_SAPI !== 'cli') {
967 $client = $this->config->getChecker();
968 if (!$client->isLatest()) {
969 $this->output->writeln(sprintf('New version is available (current: %s, latest: %s)',self::VERSION, $client->getLatest()));
971 } catch (\InvalidArgumentException $e) {
972 $this->output->writeln($e->getMessage());
977 * Write a startup message if set.
979 protected function writeStartupMessage()
981 $message = $this->config->getStartupMessage();
982 if ($message !== null && $message !== '') {
983 $this->output->writeln($message);