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\CodeCleaner\NoReturnValue;
15 use Psy\Exception\BreakException;
16 use Psy\Exception\ErrorException;
17 use Psy\Exception\Exception as PsyException;
18 use Psy\Exception\ThrowUpException;
19 use Psy\Input\ShellInput;
20 use Psy\Input\SilentInput;
21 use Psy\Output\ShellOutput;
22 use Psy\TabCompletion\Matcher;
23 use Psy\VarDumper\PresenterAware;
24 use Symfony\Component\Console\Application;
25 use Symfony\Component\Console\Command\Command as BaseCommand;
26 use Symfony\Component\Console\Formatter\OutputFormatter;
27 use Symfony\Component\Console\Input\ArgvInput;
28 use Symfony\Component\Console\Input\InputArgument;
29 use Symfony\Component\Console\Input\InputDefinition;
30 use Symfony\Component\Console\Input\InputInterface;
31 use Symfony\Component\Console\Input\InputOption;
32 use Symfony\Component\Console\Input\StringInput;
33 use Symfony\Component\Console\Output\OutputInterface;
36 * The Psy Shell application.
43 * @author Justin Hileman <justin@justinhileman.info>
45 class Shell extends Application
47 const VERSION = 'v0.8.7';
49 const PROMPT = '>>> ';
50 const BUFF_PROMPT = '... ';
51 const REPLAY = '--> ';
61 private $codeBufferOpen;
65 private $outputWantsNewline = false;
67 private $tabCompletionMatchers = array();
70 * Create a new Psy Shell.
72 * @param Configuration $config (default: null)
74 public function __construct(Configuration $config = null)
76 $this->config = $config ?: new Configuration();
77 $this->cleaner = $this->config->getCodeCleaner();
78 $this->loop = $this->config->getLoop();
79 $this->context = new Context();
80 $this->includes = array();
81 $this->readline = $this->config->getReadline();
82 $this->inputBuffer = array();
84 parent::__construct('Psy Shell', self::VERSION);
86 $this->config->setShell($this);
88 // Register the current shell session's config with \Psy\info
89 \Psy\info($this->config);
93 * Check whether the first thing in a backtrace is an include call.
95 * This is used by the psysh bin to decide whether to start a shell on boot,
96 * or to simply autoload the library.
98 public static function isIncluded(array $trace)
100 return isset($trace[0]['function']) &&
101 in_array($trace[0]['function'], array('require', 'include', 'require_once', 'include_once'));
105 * Invoke a Psy Shell from the current context.
108 * @deprecated will be removed in 1.0. Use \Psy\debug instead
110 * @param array $vars Scope variables from the calling context (default: array())
111 * @param object $boundObject Bound object ($this) value for the shell
113 * @return array Scope variables from the debugger session
115 public static function debug(array $vars = array(), $boundObject = null)
117 return \Psy\debug($vars, $boundObject);
121 * Adds a command object.
125 * @param BaseCommand $command A Symfony Console Command object
127 * @return BaseCommand The registered command
129 public function add(BaseCommand $command)
131 if ($ret = parent::add($command)) {
132 if ($ret instanceof ContextAware) {
133 $ret->setContext($this->context);
136 if ($ret instanceof PresenterAware) {
137 $ret->setPresenter($this->config->getPresenter());
145 * Gets the default input definition.
147 * @return InputDefinition An InputDefinition instance
149 protected function getDefaultInputDefinition()
151 return new InputDefinition(array(
152 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
153 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
158 * Gets the default commands that should always be available.
160 * @return array An array of default Command instances
162 protected function getDefaultCommands()
164 $sudo = new Command\SudoCommand();
165 $sudo->setReadline($this->readline);
167 $hist = new Command\HistoryCommand();
168 $hist->setReadline($this->readline);
171 new Command\HelpCommand(),
172 new Command\ListCommand(),
173 new Command\DumpCommand(),
174 new Command\DocCommand(),
175 new Command\ShowCommand($this->config->colorMode()),
176 new Command\WtfCommand($this->config->colorMode()),
177 new Command\WhereamiCommand($this->config->colorMode()),
178 new Command\ThrowUpCommand(),
179 new Command\TraceCommand(),
180 new Command\BufferCommand(),
181 new Command\ClearCommand(),
182 // new Command\PsyVersionCommand(),
185 new Command\ExitCommand(),
192 protected function getTabCompletionMatchers()
194 if (empty($this->tabCompletionMatchers)) {
195 $this->tabCompletionMatchers = array(
196 new Matcher\CommandsMatcher($this->all()),
197 new Matcher\KeywordsMatcher(),
198 new Matcher\VariablesMatcher(),
199 new Matcher\ConstantsMatcher(),
200 new Matcher\FunctionsMatcher(),
201 new Matcher\ClassNamesMatcher(),
202 new Matcher\ClassMethodsMatcher(),
203 new Matcher\ClassAttributesMatcher(),
204 new Matcher\ObjectMethodsMatcher(),
205 new Matcher\ObjectAttributesMatcher(),
209 return $this->tabCompletionMatchers;
213 * @param array $matchers
215 public function addTabCompletionMatchers(array $matchers)
217 $this->tabCompletionMatchers = array_merge($matchers, $this->getTabCompletionMatchers());
221 * Set the Shell output.
223 * @param OutputInterface $output
225 public function setOutput(OutputInterface $output)
227 $this->output = $output;
231 * Runs the current application.
233 * @param InputInterface $input An Input instance
234 * @param OutputInterface $output An Output instance
236 * @return int 0 if everything went fine, or an error code
238 public function run(InputInterface $input = null, OutputInterface $output = null)
240 $this->initializeTabCompletion();
242 if ($input === null && !isset($_SERVER['argv'])) {
243 $input = new ArgvInput(array());
246 if ($output === null) {
247 $output = $this->config->getOutput();
251 return parent::run($input, $output);
252 } catch (\Exception $e) {
253 $this->writeException($e);
258 * Runs the current application.
260 * @throws Exception if thrown via the `throw-up` command
262 * @param InputInterface $input An Input instance
263 * @param OutputInterface $output An Output instance
265 * @return int 0 if everything went fine, or an error code
267 public function doRun(InputInterface $input, OutputInterface $output)
269 $this->setOutput($output);
271 $this->resetCodeBuffer();
273 $this->setAutoExit(false);
274 $this->setCatchExceptions(false);
276 $this->readline->readHistory();
278 // if ($this->config->useReadline()) {
279 // readline_completion_function(array($this, 'autocomplete'));
282 $this->output->writeln($this->getHeader());
283 $this->writeVersionInfo();
284 $this->writeStartupMessage();
287 $this->loop->run($this);
288 } catch (ThrowUpException $e) {
289 throw $e->getPrevious();
296 * This will continue fetching user input until the code buffer contains
299 * @throws BreakException if user hits Ctrl+D
301 public function getInput()
303 $this->codeBufferOpen = false;
306 // reset output verbosity (in case it was altered by a subcommand)
307 $this->output->setVerbosity(ShellOutput::VERBOSITY_VERBOSE);
309 $input = $this->readline();
312 * Handle Ctrl+D. It behaves differently in different cases:
314 * 1) In an expression, like a function or "if" block, clear the input buffer
315 * 2) At top-level session, behave like the exit command
317 if ($input === false) {
318 $this->output->writeln('');
320 if ($this->hasCode()) {
321 $this->resetCodeBuffer();
323 throw new BreakException('Ctrl+D');
327 // handle empty input
328 if (trim($input) === '') {
332 if ($this->hasCommand($input)) {
333 $this->readline->addHistory($input);
334 $this->runCommand($input);
338 $this->addCode($input);
339 } while (!$this->hasValidCode());
343 * Pass the beforeLoop callback through to the Loop instance.
345 * @see Loop::beforeLoop
347 public function beforeLoop()
349 $this->loop->beforeLoop();
353 * Pass the afterLoop callback through to the Loop instance.
355 * @see Loop::afterLoop
357 public function afterLoop()
359 $this->loop->afterLoop();
363 * Set the variables currently in scope.
367 public function setScopeVariables(array $vars)
369 $this->context->setAll($vars);
373 * Return the set of variables currently in scope.
375 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
376 * passing the scope variables to `extract`
377 * in PHP 7.1+, you _must_ exclude 'this'
379 * @return array Associative array of scope variables
381 public function getScopeVariables($includeBoundObject = true)
383 $vars = $this->context->getAll();
385 if (!$includeBoundObject) {
386 unset($vars['this']);
393 * Return the set of magic variables currently in scope.
395 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
396 * passing the scope variables to `extract`
397 * in PHP 7.1+, you _must_ exclude 'this'
399 * @return array Associative array of magic scope variables
401 public function getSpecialScopeVariables($includeBoundObject = true)
403 $vars = $this->context->getSpecialVariables();
405 if (!$includeBoundObject) {
406 unset($vars['this']);
413 * Get the set of unused command-scope variable names.
415 * @return array Array of unused variable names
417 public function getUnusedCommandScopeVariableNames()
419 return $this->context->getUnusedCommandScopeVariableNames();
423 * Get the set of variable names currently in scope.
425 * @return array Array of variable names
427 public function getScopeVariableNames()
429 return array_keys($this->context->getAll());
433 * Get a scope variable value by name.
435 * @param string $name
439 public function getScopeVariable($name)
441 return $this->context->get($name);
445 * Set the bound object ($this variable) for the interactive shell.
447 * @param object|null $boundObject
449 public function setBoundObject($boundObject)
451 $this->context->setBoundObject($boundObject);
455 * Get the bound object ($this variable) for the interactive shell.
457 * @return object|null
459 public function getBoundObject()
461 return $this->context->getBoundObject();
465 * Add includes, to be parsed and executed before running the interactive shell.
467 * @param array $includes
469 public function setIncludes(array $includes = array())
471 $this->includes = $includes;
475 * Get PHP files to be parsed and executed before running the interactive shell.
479 public function getIncludes()
481 return array_merge($this->config->getDefaultIncludes(), $this->includes);
485 * Check whether this shell's code buffer contains code.
487 * @return bool True if the code buffer contains code
489 public function hasCode()
491 return !empty($this->codeBuffer);
495 * Check whether the code in this shell's code buffer is valid.
497 * If the code is valid, the code buffer should be flushed and evaluated.
499 * @return bool True if the code buffer content is valid
501 protected function hasValidCode()
503 return !$this->codeBufferOpen && $this->code !== false;
507 * Add code to the code buffer.
509 * @param string $code
511 public function addCode($code)
514 // Code lines ending in \ keep the buffer open
515 if (substr(rtrim($code), -1) === '\\') {
516 $this->codeBufferOpen = true;
517 $code = substr(rtrim($code), 0, -1);
519 $this->codeBufferOpen = false;
522 $this->codeBuffer[] = $code;
523 $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons());
524 } catch (\Exception $e) {
525 // Add failed code blocks to the readline history.
526 $this->addCodeBufferToHistory();
532 * Get the current code buffer.
534 * This is useful for commands which manipulate the buffer.
538 public function getCodeBuffer()
540 return $this->codeBuffer;
544 * Run a Psy Shell command given the user input.
546 * @throws InvalidArgumentException if the input is not a valid command
548 * @param string $input User input string
550 * @return mixed Who knows?
552 protected function runCommand($input)
554 $command = $this->getCommand($input);
556 if (empty($command)) {
557 throw new \InvalidArgumentException('Command not found: ' . $input);
560 $input = new ShellInput(str_replace('\\', '\\\\', rtrim($input, " \t\n\r\0\x0B;")));
562 if ($input->hasParameterOption(array('--help', '-h'))) {
563 $helpCommand = $this->get('help');
564 $helpCommand->setCommand($command);
566 return $helpCommand->run($input, $this->output);
569 return $command->run($input, $this->output);
573 * Reset the current code buffer.
575 * This should be run after evaluating user input, catching exceptions, or
576 * on demand by commands such as BufferCommand.
578 public function resetCodeBuffer()
580 $this->codeBuffer = array();
585 * Inject input into the input buffer.
587 * This is useful for commands which want to replay history.
589 * @param string|array $input
590 * @param bool $silent
592 public function addInput($input, $silent = false)
594 foreach ((array) $input as $line) {
595 $this->inputBuffer[] = $silent ? new SilentInput($line) : $line;
600 * Flush the current (valid) code buffer.
602 * If the code buffer is valid, resets the code buffer and returns the
605 * @return string PHP code buffer contents
607 public function flushCode()
609 if ($this->hasValidCode()) {
610 $this->addCodeBufferToHistory();
612 $this->resetCodeBuffer();
619 * Filter silent input from code buffer, write the rest to readline history.
621 private function addCodeBufferToHistory()
623 $codeBuffer = array_filter($this->codeBuffer, function ($line) {
624 return !$line instanceof SilentInput;
627 $code = implode("\n", $codeBuffer);
629 if (trim($code) !== '') {
630 $this->readline->addHistory($code);
635 * Get the current evaluation scope namespace.
637 * @see CodeCleaner::getNamespace
639 * @return string Current code namespace
641 public function getNamespace()
643 if ($namespace = $this->cleaner->getNamespace()) {
644 return implode('\\', $namespace);
649 * Write a string to stdout.
651 * This is used by the shell loop for rendering output from evaluated code.
654 * @param int $phase Output buffering phase
656 public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END)
659 if (version_compare(PHP_VERSION, '5.4', '>=')) {
660 $isCleaning = $phase & PHP_OUTPUT_HANDLER_CLEAN;
664 if ($out !== '' && !$isCleaning) {
665 $this->output->write($out, false, ShellOutput::OUTPUT_RAW);
666 $this->outputWantsNewline = (substr($out, -1) !== "\n");
669 // Output buffering is done!
670 if ($this->outputWantsNewline && $phase & PHP_OUTPUT_HANDLER_END) {
671 $this->output->writeln(sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
672 $this->outputWantsNewline = false;
677 * Write a return value to stdout.
679 * The return value is formatted or pretty-printed, and rendered in a
680 * visibly distinct manner (in this case, as cyan).
682 * @see self::presentValue
686 public function writeReturnValue($ret)
688 if ($ret instanceof NoReturnValue) {
692 $this->context->setReturnValue($ret);
693 $ret = $this->presentValue($ret);
694 $indent = str_repeat(' ', strlen(static::RETVAL));
696 $this->output->writeln(static::RETVAL . str_replace(PHP_EOL, PHP_EOL . $indent, $ret));
700 * Renders a caught Exception.
702 * Exceptions are formatted according to severity. ErrorExceptions which were
703 * warnings or Strict errors aren't rendered as harshly as real errors.
705 * Stores $e as the last Exception in the Shell Context.
707 * @param \Exception $e An exception instance
708 * @param OutputInterface $output An OutputInterface instance
710 public function writeException(\Exception $e)
712 $this->context->setLastException($e);
713 $this->output->writeln($this->formatException($e));
714 $this->resetCodeBuffer();
718 * Helper for formatting an exception for writeException().
720 * @todo extract this to somewhere it makes more sense
722 * @param \Exception $e
726 public function formatException(\Exception $e)
728 $message = $e->getMessage();
729 if (!$e instanceof PsyException) {
730 $message = sprintf('%s with message \'%s\'', get_class($e), $message);
733 $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
735 return sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity);
739 * Helper for getting an output style for the given ErrorException's level.
741 * @param \ErrorException $e
745 protected function getSeverity(\ErrorException $e)
747 $severity = $e->getSeverity();
748 if ($severity & error_reporting()) {
753 case E_COMPILE_WARNING:
763 // Since this is below the user's reporting threshold, it's always going to be a warning.
769 * Helper for throwing an ErrorException.
773 * set_error_handler(array($psysh, 'handleError'));
775 * Unlike ErrorException::throwException, this error handler respects the
776 * current error_reporting level; i.e. it logs warnings and notices, but
777 * doesn't throw an exception unless it's above the current error_reporting
778 * threshold. This should probably only be used in the inner execution loop
779 * of the shell, as most of the time a thrown exception is much more useful.
781 * If the error type matches the `errorLoggingLevel` config, it will be
782 * logged as well, regardless of the `error_reporting` level.
784 * @see \Psy\Exception\ErrorException::throwException
785 * @see \Psy\Shell::writeException
787 * @throws \Psy\Exception\ErrorException depending on the current error_reporting level
789 * @param int $errno Error type
790 * @param string $errstr Message
791 * @param string $errfile Filename
792 * @param int $errline Line number
794 public function handleError($errno, $errstr, $errfile, $errline)
796 if ($errno & error_reporting()) {
797 ErrorException::throwException($errno, $errstr, $errfile, $errline);
798 } elseif ($errno & $this->config->errorLoggingLevel()) {
799 // log it and continue...
800 $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline));
805 * Format a value for display.
807 * @see Presenter::present
811 * @return string Formatted value
813 protected function presentValue($val)
815 return $this->config->getPresenter()->present($val);
819 * Get a command (if one exists) for the current input string.
821 * @param string $input
823 * @return null|BaseCommand
825 protected function getCommand($input)
827 $input = new StringInput($input);
828 if ($name = $input->getFirstArgument()) {
829 return $this->get($name);
834 * Check whether a command is set for the current input string.
836 * @param string $input
838 * @return bool True if the shell has a command for the given input
840 protected function hasCommand($input)
842 $input = new StringInput($input);
843 if ($name = $input->getFirstArgument()) {
844 return $this->has($name);
851 * Get the current input prompt.
855 protected function getPrompt()
857 return $this->hasCode() ? static::BUFF_PROMPT : static::PROMPT;
861 * Read a line of user input.
863 * This will return a line from the input buffer (if any exist). Otherwise,
864 * it will ask the user for input.
866 * If readline is enabled, this delegates to readline. Otherwise, it's an
869 * @return string One line of user input
871 protected function readline()
873 if (!empty($this->inputBuffer)) {
874 $line = array_shift($this->inputBuffer);
875 if (!$line instanceof SilentInput) {
876 $this->output->writeln(sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
882 return $this->readline->readline($this->getPrompt());
886 * Get the shell output header.
890 protected function getHeader()
892 return sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
896 * Get the current version of Psy Shell.
900 public function getVersion()
902 $separator = $this->config->useUnicode() ? '—' : '-';
904 return sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, phpversion(), $separator, php_sapi_name());
908 * Get a PHP manual database instance.
912 public function getManualDb()
914 return $this->config->getManualDb();
918 * Autocomplete variable names.
920 * This is used by `readline` for tab completion.
922 * @param string $text
924 * @return mixed Array possible completions for the given input, if any
926 protected function autocomplete($text)
928 $info = readline_info();
929 // $line = substr($info['line_buffer'], 0, $info['end']);
931 // Check whether there's a command for this
932 // $words = explode(' ', $line);
933 // $firstWord = reset($words);
935 // check whether this is a variable...
936 $firstChar = substr($info['line_buffer'], max(0, $info['end'] - strlen($text) - 1), 1);
937 if ($firstChar === '$') {
938 return $this->getScopeVariableNames();
943 * Initialize tab completion matchers.
945 * If tab completion is enabled this adds tab completion matchers to the
946 * auto completer and sets context if needed.
948 protected function initializeTabCompletion()
950 // auto completer needs shell to be linked to configuration because of the context aware matchers
951 if ($this->config->getTabCompletion()) {
952 $this->completion = $this->config->getAutoCompleter();
953 $this->addTabCompletionMatchers($this->config->getTabCompletionMatchers());
954 foreach ($this->getTabCompletionMatchers() as $matcher) {
955 if ($matcher instanceof ContextAware) {
956 $matcher->setContext($this->context);
958 $this->completion->addMatcher($matcher);
960 $this->completion->activate();
965 * @todo Implement self-update
966 * @todo Implement prompt to start update
968 * @return void|string
970 protected function writeVersionInfo()
972 if (PHP_SAPI !== 'cli') {
977 $client = $this->config->getChecker();
978 if (!$client->isLatest()) {
979 $this->output->writeln(sprintf('New version is available (current: %s, latest: %s)',self::VERSION, $client->getLatest()));
981 } catch (\InvalidArgumentException $e) {
982 $this->output->writeln($e->getMessage());
987 * Write a startup message if set.
989 protected function writeStartupMessage()
991 $message = $this->config->getStartupMessage();
992 if ($message !== null && $message !== '') {
993 $this->output->writeln($message);