4 * This file is part of Psy Shell.
6 * (c) 2012-2018 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\Exception\TypeErrorException;
20 use Psy\ExecutionLoop\ProcessForker;
21 use Psy\ExecutionLoop\RunkitReloader;
22 use Psy\Input\ShellInput;
23 use Psy\Input\SilentInput;
24 use Psy\Output\ShellOutput;
25 use Psy\TabCompletion\Matcher;
26 use Psy\VarDumper\PresenterAware;
27 use Symfony\Component\Console\Application;
28 use Symfony\Component\Console\Command\Command as BaseCommand;
29 use Symfony\Component\Console\Formatter\OutputFormatter;
30 use Symfony\Component\Console\Input\ArgvInput;
31 use Symfony\Component\Console\Input\InputArgument;
32 use Symfony\Component\Console\Input\InputDefinition;
33 use Symfony\Component\Console\Input\InputInterface;
34 use Symfony\Component\Console\Input\InputOption;
35 use Symfony\Component\Console\Input\StringInput;
36 use Symfony\Component\Console\Output\OutputInterface;
39 * The Psy Shell application.
46 * @author Justin Hileman <justin@justinhileman.info>
48 class Shell extends Application
50 const VERSION = 'v0.9.4';
52 const PROMPT = '>>> ';
53 const BUFF_PROMPT = '... ';
54 const REPLAY = '--> ';
64 private $codeBufferOpen;
66 private $stdoutBuffer;
70 private $outputWantsNewline = false;
72 private $loopListeners;
73 private $autoCompleter;
74 private $matchers = [];
75 private $commandsMatcher;
78 * Create a new Psy Shell.
80 * @param Configuration $config (default: null)
82 public function __construct(Configuration $config = null)
84 $this->config = $config ?: new Configuration();
85 $this->cleaner = $this->config->getCodeCleaner();
86 $this->loop = new ExecutionLoop();
87 $this->context = new Context();
89 $this->readline = $this->config->getReadline();
90 $this->inputBuffer = [];
91 $this->codeStack = [];
92 $this->stdoutBuffer = '';
93 $this->loopListeners = $this->getDefaultLoopListeners();
95 parent::__construct('Psy Shell', self::VERSION);
97 $this->config->setShell($this);
99 // Register the current shell session's config with \Psy\info
100 \Psy\info($this->config);
104 * Check whether the first thing in a backtrace is an include call.
106 * This is used by the psysh bin to decide whether to start a shell on boot,
107 * or to simply autoload the library.
109 public static function isIncluded(array $trace)
111 return isset($trace[0]['function']) &&
112 in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']);
116 * Invoke a Psy Shell from the current context.
119 * @deprecated will be removed in 1.0. Use \Psy\debug instead
121 * @param array $vars Scope variables from the calling context (default: array())
122 * @param object|string $bindTo Bound object ($this) or class (self) value for the shell
124 * @return array Scope variables from the debugger session
126 public static function debug(array $vars = [], $bindTo = null)
128 return \Psy\debug($vars, $bindTo);
132 * Adds a command object.
136 * @param BaseCommand $command A Symfony Console Command object
138 * @return BaseCommand The registered command
140 public function add(BaseCommand $command)
142 if ($ret = parent::add($command)) {
143 if ($ret instanceof ContextAware) {
144 $ret->setContext($this->context);
147 if ($ret instanceof PresenterAware) {
148 $ret->setPresenter($this->config->getPresenter());
151 if (isset($this->commandsMatcher)) {
152 $this->commandsMatcher->setCommands($this->all());
160 * Gets the default input definition.
162 * @return InputDefinition An InputDefinition instance
164 protected function getDefaultInputDefinition()
166 return new InputDefinition([
167 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
168 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
173 * Gets the default commands that should always be available.
175 * @return array An array of default Command instances
177 protected function getDefaultCommands()
179 $sudo = new Command\SudoCommand();
180 $sudo->setReadline($this->readline);
182 $hist = new Command\HistoryCommand();
183 $hist->setReadline($this->readline);
186 new Command\HelpCommand(),
187 new Command\ListCommand(),
188 new Command\DumpCommand(),
189 new Command\DocCommand(),
190 new Command\ShowCommand($this->config->colorMode()),
191 new Command\WtfCommand($this->config->colorMode()),
192 new Command\WhereamiCommand($this->config->colorMode()),
193 new Command\ThrowUpCommand(),
194 new Command\TimeitCommand(),
195 new Command\TraceCommand(),
196 new Command\BufferCommand(),
197 new Command\ClearCommand(),
198 new Command\EditCommand($this->config->getRuntimeDir()),
199 // new Command\PsyVersionCommand(),
202 new Command\ExitCommand(),
209 protected function getDefaultMatchers()
211 // Store the Commands Matcher for later. If more commands are added,
212 // we'll update the Commands Matcher too.
213 $this->commandsMatcher = new Matcher\CommandsMatcher($this->all());
216 $this->commandsMatcher,
217 new Matcher\KeywordsMatcher(),
218 new Matcher\VariablesMatcher(),
219 new Matcher\ConstantsMatcher(),
220 new Matcher\FunctionsMatcher(),
221 new Matcher\ClassNamesMatcher(),
222 new Matcher\ClassMethodsMatcher(),
223 new Matcher\ClassAttributesMatcher(),
224 new Matcher\ObjectMethodsMatcher(),
225 new Matcher\ObjectAttributesMatcher(),
226 new Matcher\ClassMethodDefaultParametersMatcher(),
227 new Matcher\ObjectMethodDefaultParametersMatcher(),
228 new Matcher\FunctionDefaultParametersMatcher(),
233 * @deprecated Nothing should use this anymore
235 protected function getTabCompletionMatchers()
237 @trigger_error('getTabCompletionMatchers is no longer used', E_USER_DEPRECATED);
241 * Gets the default command loop listeners.
243 * @return array An array of Execution Loop Listener instances
245 protected function getDefaultLoopListeners()
249 if (ProcessForker::isSupported() && $this->config->usePcntl()) {
250 $listeners[] = new ProcessForker();
253 if (RunkitReloader::isSupported()) {
254 $listeners[] = new RunkitReloader();
261 * Add tab completion matchers.
263 * @param array $matchers
265 public function addMatchers(array $matchers)
267 $this->matchers = array_merge($this->matchers, $matchers);
269 if (isset($this->autoCompleter)) {
270 $this->addMatchersToAutoCompleter($matchers);
275 * @deprecated Call `addMatchers` instead
277 * @param array $matchers
279 public function addTabCompletionMatchers(array $matchers)
281 $this->addMatchers($matchers);
285 * Set the Shell output.
287 * @param OutputInterface $output
289 public function setOutput(OutputInterface $output)
291 $this->output = $output;
295 * Runs the current application.
297 * @param InputInterface $input An Input instance
298 * @param OutputInterface $output An Output instance
300 * @return int 0 if everything went fine, or an error code
302 public function run(InputInterface $input = null, OutputInterface $output = null)
304 $this->initializeTabCompletion();
306 if ($input === null && !isset($_SERVER['argv'])) {
307 $input = new ArgvInput([]);
310 if ($output === null) {
311 $output = $this->config->getOutput();
315 return parent::run($input, $output);
316 } catch (\Exception $e) {
317 $this->writeException($e);
324 * Runs the current application.
326 * @throws Exception if thrown via the `throw-up` command
328 * @param InputInterface $input An Input instance
329 * @param OutputInterface $output An Output instance
331 * @return int 0 if everything went fine, or an error code
333 public function doRun(InputInterface $input, OutputInterface $output)
335 $this->setOutput($output);
337 $this->resetCodeBuffer();
339 $this->setAutoExit(false);
340 $this->setCatchExceptions(false);
342 $this->readline->readHistory();
344 $this->output->writeln($this->getHeader());
345 $this->writeVersionInfo();
346 $this->writeStartupMessage();
350 $this->loop->run($this);
352 } catch (ThrowUpException $e) {
353 throw $e->getPrevious();
354 } catch (BreakException $e) {
355 // The ProcessForker throws a BreakException to finish the main thread.
363 * This will continue fetching user input until the code buffer contains
366 * @throws BreakException if user hits Ctrl+D
368 public function getInput()
370 $this->codeBufferOpen = false;
373 // reset output verbosity (in case it was altered by a subcommand)
374 $this->output->setVerbosity(ShellOutput::VERBOSITY_VERBOSE);
376 $input = $this->readline();
379 * Handle Ctrl+D. It behaves differently in different cases:
381 * 1) In an expression, like a function or "if" block, clear the input buffer
382 * 2) At top-level session, behave like the exit command
384 if ($input === false) {
385 $this->output->writeln('');
387 if ($this->hasCode()) {
388 $this->resetCodeBuffer();
390 throw new BreakException('Ctrl+D');
394 // handle empty input
395 if (trim($input) === '' && !$this->codeBufferOpen) {
399 $input = $this->onInput($input);
401 // If the input isn't in an open string or comment, check for commands to run.
402 if ($this->hasCommand($input) && !$this->inputInOpenStringOrComment($input)) {
403 $this->addHistory($input);
404 $this->runCommand($input);
409 $this->addCode($input);
410 } while (!$this->hasValidCode());
414 * Check whether the code buffer (plus current input) is in an open string or comment.
416 * @param string $input current line of input
418 * @return bool true if the input is in an open string or comment
420 private function inputInOpenStringOrComment($input)
422 if (!$this->hasCode()) {
426 $code = $this->codeBuffer;
427 array_push($code, $input);
428 $tokens = @token_get_all('<?php ' . implode("\n", $code));
429 $last = array_pop($tokens);
431 return $last === '"' || $last === '`' ||
432 (is_array($last) && in_array($last[0], [T_ENCAPSED_AND_WHITESPACE, T_START_HEREDOC, T_COMMENT]));
436 * Run execution loop listeners before the shell session.
438 protected function beforeRun()
440 foreach ($this->loopListeners as $listener) {
441 $listener->beforeRun($this);
446 * Run execution loop listeners at the start of each loop.
448 public function beforeLoop()
450 foreach ($this->loopListeners as $listener) {
451 $listener->beforeLoop($this);
456 * Run execution loop listeners on user input.
458 * @param string $input
462 public function onInput($input)
464 foreach ($this->loopListeners as $listeners) {
465 if (($return = $listeners->onInput($this, $input)) !== null) {
474 * Run execution loop listeners on code to be executed.
476 * @param string $code
480 public function onExecute($code)
482 foreach ($this->loopListeners as $listener) {
483 if (($return = $listener->onExecute($this, $code)) !== null) {
492 * Run execution loop listeners after each loop.
494 public function afterLoop()
496 foreach ($this->loopListeners as $listener) {
497 $listener->afterLoop($this);
502 * Run execution loop listers after the shell session.
504 protected function afterRun()
506 foreach ($this->loopListeners as $listener) {
507 $listener->afterRun($this);
512 * Set the variables currently in scope.
516 public function setScopeVariables(array $vars)
518 $this->context->setAll($vars);
522 * Return the set of variables currently in scope.
524 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
525 * passing the scope variables to `extract`
526 * in PHP 7.1+, you _must_ exclude 'this'
528 * @return array Associative array of scope variables
530 public function getScopeVariables($includeBoundObject = true)
532 $vars = $this->context->getAll();
534 if (!$includeBoundObject) {
535 unset($vars['this']);
542 * Return the set of magic variables currently in scope.
544 * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
545 * passing the scope variables to `extract`
546 * in PHP 7.1+, you _must_ exclude 'this'
548 * @return array Associative array of magic scope variables
550 public function getSpecialScopeVariables($includeBoundObject = true)
552 $vars = $this->context->getSpecialVariables();
554 if (!$includeBoundObject) {
555 unset($vars['this']);
562 * Get the set of unused command-scope variable names.
564 * @return array Array of unused variable names
566 public function getUnusedCommandScopeVariableNames()
568 return $this->context->getUnusedCommandScopeVariableNames();
572 * Get the set of variable names currently in scope.
574 * @return array Array of variable names
576 public function getScopeVariableNames()
578 return array_keys($this->context->getAll());
582 * Get a scope variable value by name.
584 * @param string $name
588 public function getScopeVariable($name)
590 return $this->context->get($name);
594 * Set the bound object ($this variable) for the interactive shell.
596 * @param object|null $boundObject
598 public function setBoundObject($boundObject)
600 $this->context->setBoundObject($boundObject);
604 * Get the bound object ($this variable) for the interactive shell.
606 * @return object|null
608 public function getBoundObject()
610 return $this->context->getBoundObject();
614 * Set the bound class (self) for the interactive shell.
616 * @param string|null $boundClass
618 public function setBoundClass($boundClass)
620 $this->context->setBoundClass($boundClass);
624 * Get the bound class (self) for the interactive shell.
626 * @return string|null
628 public function getBoundClass()
630 return $this->context->getBoundClass();
634 * Add includes, to be parsed and executed before running the interactive shell.
636 * @param array $includes
638 public function setIncludes(array $includes = [])
640 $this->includes = $includes;
644 * Get PHP files to be parsed and executed before running the interactive shell.
648 public function getIncludes()
650 return array_merge($this->config->getDefaultIncludes(), $this->includes);
654 * Check whether this shell's code buffer contains code.
656 * @return bool True if the code buffer contains code
658 public function hasCode()
660 return !empty($this->codeBuffer);
664 * Check whether the code in this shell's code buffer is valid.
666 * If the code is valid, the code buffer should be flushed and evaluated.
668 * @return bool True if the code buffer content is valid
670 protected function hasValidCode()
672 return !$this->codeBufferOpen && $this->code !== false;
676 * Add code to the code buffer.
678 * @param string $code
679 * @param bool $silent
681 public function addCode($code, $silent = false)
684 // Code lines ending in \ keep the buffer open
685 if (substr(rtrim($code), -1) === '\\') {
686 $this->codeBufferOpen = true;
687 $code = substr(rtrim($code), 0, -1);
689 $this->codeBufferOpen = false;
692 $this->codeBuffer[] = $silent ? new SilentInput($code) : $code;
693 $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons());
694 } catch (\Exception $e) {
695 // Add failed code blocks to the readline history.
696 $this->addCodeBufferToHistory();
703 * Set the code buffer.
705 * This is mostly used by `Shell::execute`. Any existing code in the input
706 * buffer is pushed onto a stack and will come back after this new code is
709 * @throws \InvalidArgumentException if $code isn't a complete statement
711 * @param string $code
712 * @param bool $silent
714 private function setCode($code, $silent = false)
716 if ($this->hasCode()) {
717 $this->codeStack[] = [$this->codeBuffer, $this->codeBufferOpen, $this->code];
720 $this->resetCodeBuffer();
722 $this->addCode($code, $silent);
723 } catch (\Throwable $e) {
724 $this->popCodeStack();
727 } catch (\Exception $e) {
728 $this->popCodeStack();
733 if (!$this->hasValidCode()) {
734 $this->popCodeStack();
736 throw new \InvalidArgumentException('Unexpected end of input');
741 * Get the current code buffer.
743 * This is useful for commands which manipulate the buffer.
747 public function getCodeBuffer()
749 return $this->codeBuffer;
753 * Run a Psy Shell command given the user input.
755 * @throws InvalidArgumentException if the input is not a valid command
757 * @param string $input User input string
759 * @return mixed Who knows?
761 protected function runCommand($input)
763 $command = $this->getCommand($input);
765 if (empty($command)) {
766 throw new \InvalidArgumentException('Command not found: ' . $input);
769 $input = new ShellInput(str_replace('\\', '\\\\', rtrim($input, " \t\n\r\0\x0B;")));
771 if ($input->hasParameterOption(['--help', '-h'])) {
772 $helpCommand = $this->get('help');
773 $helpCommand->setCommand($command);
775 return $helpCommand->run($input, $this->output);
778 return $command->run($input, $this->output);
782 * Reset the current code buffer.
784 * This should be run after evaluating user input, catching exceptions, or
785 * on demand by commands such as BufferCommand.
787 public function resetCodeBuffer()
789 $this->codeBuffer = [];
794 * Inject input into the input buffer.
796 * This is useful for commands which want to replay history.
798 * @param string|array $input
799 * @param bool $silent
801 public function addInput($input, $silent = false)
803 foreach ((array) $input as $line) {
804 $this->inputBuffer[] = $silent ? new SilentInput($line) : $line;
809 * Flush the current (valid) code buffer.
811 * If the code buffer is valid, resets the code buffer and returns the
814 * @return string PHP code buffer contents
816 public function flushCode()
818 if ($this->hasValidCode()) {
819 $this->addCodeBufferToHistory();
821 $this->popCodeStack();
828 * Reset the code buffer and restore any code pushed during `execute` calls.
830 private function popCodeStack()
832 $this->resetCodeBuffer();
834 if (empty($this->codeStack)) {
838 list($codeBuffer, $codeBufferOpen, $code) = array_pop($this->codeStack);
840 $this->codeBuffer = $codeBuffer;
841 $this->codeBufferOpen = $codeBufferOpen;
846 * (Possibly) add a line to the readline history.
848 * Like Bash, if the line starts with a space character, it will be omitted
849 * from history. Note that an entire block multi-line code input will be
850 * omitted iff the first line begins with a space.
852 * Additionally, if a line is "silent", i.e. it was initially added with the
853 * silent flag, it will also be omitted.
855 * @param string|SilentInput $line
857 private function addHistory($line)
859 if ($line instanceof SilentInput) {
863 // Skip empty lines and lines starting with a space
864 if (trim($line) !== '' && substr($line, 0, 1) !== ' ') {
865 $this->readline->addHistory($line);
870 * Filter silent input from code buffer, write the rest to readline history.
872 private function addCodeBufferToHistory()
874 $codeBuffer = array_filter($this->codeBuffer, function ($line) {
875 return !$line instanceof SilentInput;
878 $this->addHistory(implode("\n", $codeBuffer));
882 * Get the current evaluation scope namespace.
884 * @see CodeCleaner::getNamespace
886 * @return string Current code namespace
888 public function getNamespace()
890 if ($namespace = $this->cleaner->getNamespace()) {
891 return implode('\\', $namespace);
896 * Write a string to stdout.
898 * This is used by the shell loop for rendering output from evaluated code.
901 * @param int $phase Output buffering phase
903 public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END)
905 $isCleaning = $phase & PHP_OUTPUT_HANDLER_CLEAN;
908 if ($out !== '' && !$isCleaning) {
909 $this->output->write($out, false, ShellOutput::OUTPUT_RAW);
910 $this->outputWantsNewline = (substr($out, -1) !== "\n");
911 $this->stdoutBuffer .= $out;
914 // Output buffering is done!
915 if ($phase & PHP_OUTPUT_HANDLER_END) {
916 // Write an extra newline if stdout didn't end with one
917 if ($this->outputWantsNewline) {
918 $this->output->writeln(sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
919 $this->outputWantsNewline = false;
922 // Save the stdout buffer as $__out
923 if ($this->stdoutBuffer !== '') {
924 $this->context->setLastStdout($this->stdoutBuffer);
925 $this->stdoutBuffer = '';
931 * Write a return value to stdout.
933 * The return value is formatted or pretty-printed, and rendered in a
934 * visibly distinct manner (in this case, as cyan).
936 * @see self::presentValue
940 public function writeReturnValue($ret)
942 if ($ret instanceof NoReturnValue) {
946 $this->context->setReturnValue($ret);
947 $ret = $this->presentValue($ret);
948 $indent = str_repeat(' ', strlen(static::RETVAL));
950 $this->output->writeln(static::RETVAL . str_replace(PHP_EOL, PHP_EOL . $indent, $ret));
954 * Renders a caught Exception.
956 * Exceptions are formatted according to severity. ErrorExceptions which were
957 * warnings or Strict errors aren't rendered as harshly as real errors.
959 * Stores $e as the last Exception in the Shell Context.
961 * @param \Exception $e An exception instance
963 public function writeException(\Exception $e)
965 $this->context->setLastException($e);
966 $this->output->writeln($this->formatException($e));
967 $this->resetCodeBuffer();
971 * Helper for formatting an exception for writeException().
973 * @todo extract this to somewhere it makes more sense
975 * @param \Exception $e
979 public function formatException(\Exception $e)
981 $message = $e->getMessage();
982 if (!$e instanceof PsyException) {
983 if ($message === '') {
984 $message = get_class($e);
986 $message = sprintf('%s with message \'%s\'', get_class($e), $message);
990 $message = preg_replace(
991 "#(\\w:)?(/\\w+)*/src/Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code#",
993 str_replace('\\', '/', $message)
996 $message = str_replace(" in eval()'d code", ' in Psy Shell code', $message);
998 $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
1000 return sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity);
1004 * Helper for getting an output style for the given ErrorException's level.
1006 * @param \ErrorException $e
1010 protected function getSeverity(\ErrorException $e)
1012 $severity = $e->getSeverity();
1013 if ($severity & error_reporting()) {
1014 switch ($severity) {
1017 case E_CORE_WARNING:
1018 case E_COMPILE_WARNING:
1019 case E_USER_WARNING:
1028 // Since this is below the user's reporting threshold, it's always going to be a warning.
1034 * Execute code in the shell execution context.
1036 * @param string $code
1037 * @param bool $throwExceptions
1041 public function execute($code, $throwExceptions = false)
1043 $this->setCode($code, true);
1044 $closure = new ExecutionClosure($this);
1046 if ($throwExceptions) {
1047 return $closure->execute();
1051 return $closure->execute();
1052 } catch (\TypeError $_e) {
1053 $this->writeException(TypeErrorException::fromTypeError($_e));
1054 } catch (\Error $_e) {
1055 $this->writeException(ErrorException::fromError($_e));
1056 } catch (\Exception $_e) {
1057 $this->writeException($_e);
1062 * Helper for throwing an ErrorException.
1064 * This allows us to:
1066 * set_error_handler(array($psysh, 'handleError'));
1068 * Unlike ErrorException::throwException, this error handler respects the
1069 * current error_reporting level; i.e. it logs warnings and notices, but
1070 * doesn't throw an exception unless it's above the current error_reporting
1071 * threshold. This should probably only be used in the inner execution loop
1072 * of the shell, as most of the time a thrown exception is much more useful.
1074 * If the error type matches the `errorLoggingLevel` config, it will be
1075 * logged as well, regardless of the `error_reporting` level.
1077 * @see \Psy\Exception\ErrorException::throwException
1078 * @see \Psy\Shell::writeException
1080 * @throws \Psy\Exception\ErrorException depending on the current error_reporting level
1082 * @param int $errno Error type
1083 * @param string $errstr Message
1084 * @param string $errfile Filename
1085 * @param int $errline Line number
1087 public function handleError($errno, $errstr, $errfile, $errline)
1089 if ($errno & error_reporting()) {
1090 ErrorException::throwException($errno, $errstr, $errfile, $errline);
1091 } elseif ($errno & $this->config->errorLoggingLevel()) {
1092 // log it and continue...
1093 $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline));
1098 * Format a value for display.
1100 * @see Presenter::present
1104 * @return string Formatted value
1106 protected function presentValue($val)
1108 return $this->config->getPresenter()->present($val);
1112 * Get a command (if one exists) for the current input string.
1114 * @param string $input
1116 * @return null|BaseCommand
1118 protected function getCommand($input)
1120 $input = new StringInput($input);
1121 if ($name = $input->getFirstArgument()) {
1122 return $this->get($name);
1127 * Check whether a command is set for the current input string.
1129 * @param string $input
1131 * @return bool True if the shell has a command for the given input
1133 protected function hasCommand($input)
1135 if (preg_match('/([^\s]+?)(?:\s|$)/A', ltrim($input), $match)) {
1136 return $this->has($match[1]);
1143 * Get the current input prompt.
1147 protected function getPrompt()
1149 if ($this->hasCode()) {
1150 return static::BUFF_PROMPT;
1153 return $this->config->getPrompt() ?: static::PROMPT;
1157 * Read a line of user input.
1159 * This will return a line from the input buffer (if any exist). Otherwise,
1160 * it will ask the user for input.
1162 * If readline is enabled, this delegates to readline. Otherwise, it's an
1163 * ugly `fgets` call.
1165 * @return string One line of user input
1167 protected function readline()
1169 if (!empty($this->inputBuffer)) {
1170 $line = array_shift($this->inputBuffer);
1171 if (!$line instanceof SilentInput) {
1172 $this->output->writeln(sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
1178 if ($bracketedPaste = $this->config->useBracketedPaste()) {
1179 printf("\e[?2004h"); // Enable bracketed paste
1182 $line = $this->readline->readline($this->getPrompt());
1184 if ($bracketedPaste) {
1185 printf("\e[?2004l"); // ... and disable it again
1192 * Get the shell output header.
1196 protected function getHeader()
1198 return sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
1202 * Get the current version of Psy Shell.
1206 public function getVersion()
1208 $separator = $this->config->useUnicode() ? '—' : '-';
1210 return sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, phpversion(), $separator, php_sapi_name());
1214 * Get a PHP manual database instance.
1218 public function getManualDb()
1220 return $this->config->getManualDb();
1224 * @deprecated Tab completion is provided by the AutoCompleter service
1226 protected function autocomplete($text)
1228 @trigger_error('Tab completion is provided by the AutoCompleter service', E_USER_DEPRECATED);
1232 * Initialize tab completion matchers.
1234 * If tab completion is enabled this adds tab completion matchers to the
1235 * auto completer and sets context if needed.
1237 protected function initializeTabCompletion()
1239 if (!$this->config->useTabCompletion()) {
1243 $this->autoCompleter = $this->config->getAutoCompleter();
1245 // auto completer needs shell to be linked to configuration because of
1246 // the context aware matchers
1247 $this->addMatchersToAutoCompleter($this->getDefaultMatchers());
1248 $this->addMatchersToAutoCompleter($this->matchers);
1250 $this->autoCompleter->activate();
1254 * Add matchers to the auto completer, setting context if needed.
1256 * @param array $matchers
1258 private function addMatchersToAutoCompleter(array $matchers)
1260 foreach ($matchers as $matcher) {
1261 if ($matcher instanceof ContextAware) {
1262 $matcher->setContext($this->context);
1264 $this->autoCompleter->addMatcher($matcher);
1269 * @todo Implement self-update
1270 * @todo Implement prompt to start update
1272 * @return void|string
1274 protected function writeVersionInfo()
1276 if (PHP_SAPI !== 'cli') {
1281 $client = $this->config->getChecker();
1282 if (!$client->isLatest()) {
1283 $this->output->writeln(sprintf('New version is available (current: %s, latest: %s)', self::VERSION, $client->getLatest()));
1285 } catch (\InvalidArgumentException $e) {
1286 $this->output->writeln($e->getMessage());
1291 * Write a startup message if set.
1293 protected function writeStartupMessage()
1295 $message = $this->config->getStartupMessage();
1296 if ($message !== null && $message !== '') {
1297 $this->output->writeln($message);