Chris@0: run(); Chris@0: * Chris@0: * @author Justin Hileman Chris@0: */ Chris@0: class Shell extends Application Chris@0: { Chris@12: const VERSION = 'v0.8.17'; Chris@0: Chris@0: const PROMPT = '>>> '; Chris@0: const BUFF_PROMPT = '... '; Chris@0: const REPLAY = '--> '; Chris@0: const RETVAL = '=> '; Chris@0: Chris@0: private $config; Chris@0: private $cleaner; Chris@0: private $output; Chris@0: private $readline; Chris@0: private $inputBuffer; Chris@0: private $code; Chris@0: private $codeBuffer; Chris@0: private $codeBufferOpen; Chris@0: private $context; Chris@0: private $includes; Chris@0: private $loop; Chris@0: private $outputWantsNewline = false; Chris@0: private $completion; Chris@0: private $tabCompletionMatchers = array(); Chris@0: private $stdoutBuffer; Chris@0: private $prompt; Chris@0: Chris@0: /** Chris@0: * Create a new Psy Shell. Chris@0: * Chris@0: * @param Configuration $config (default: null) Chris@0: */ Chris@0: public function __construct(Configuration $config = null) Chris@0: { Chris@12: $this->config = $config ?: new Configuration(); Chris@12: $this->cleaner = $this->config->getCodeCleaner(); Chris@12: $this->loop = $this->config->getLoop(); Chris@12: $this->context = new Context(); Chris@12: $this->includes = array(); Chris@12: $this->readline = $this->config->getReadline(); Chris@12: $this->inputBuffer = array(); Chris@0: $this->stdoutBuffer = ''; Chris@0: Chris@0: parent::__construct('Psy Shell', self::VERSION); Chris@0: Chris@0: $this->config->setShell($this); Chris@0: Chris@0: // Register the current shell session's config with \Psy\info Chris@0: \Psy\info($this->config); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check whether the first thing in a backtrace is an include call. Chris@0: * Chris@0: * This is used by the psysh bin to decide whether to start a shell on boot, Chris@0: * or to simply autoload the library. Chris@0: */ Chris@0: public static function isIncluded(array $trace) Chris@0: { Chris@0: return isset($trace[0]['function']) && Chris@0: in_array($trace[0]['function'], array('require', 'include', 'require_once', 'include_once')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Invoke a Psy Shell from the current context. Chris@0: * Chris@0: * @see Psy\debug Chris@0: * @deprecated will be removed in 1.0. Use \Psy\debug instead Chris@0: * Chris@0: * @param array $vars Scope variables from the calling context (default: array()) Chris@0: * @param object $boundObject Bound object ($this) value for the shell Chris@0: * Chris@0: * @return array Scope variables from the debugger session Chris@0: */ Chris@0: public static function debug(array $vars = array(), $boundObject = null) Chris@0: { Chris@0: return \Psy\debug($vars, $boundObject); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds a command object. Chris@0: * Chris@0: * {@inheritdoc} Chris@0: * Chris@0: * @param BaseCommand $command A Symfony Console Command object Chris@0: * Chris@0: * @return BaseCommand The registered command Chris@0: */ Chris@0: public function add(BaseCommand $command) Chris@0: { Chris@0: if ($ret = parent::add($command)) { Chris@0: if ($ret instanceof ContextAware) { Chris@0: $ret->setContext($this->context); Chris@0: } Chris@0: Chris@0: if ($ret instanceof PresenterAware) { Chris@0: $ret->setPresenter($this->config->getPresenter()); Chris@0: } Chris@0: } Chris@0: Chris@0: return $ret; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the default input definition. Chris@0: * Chris@0: * @return InputDefinition An InputDefinition instance Chris@0: */ Chris@0: protected function getDefaultInputDefinition() Chris@0: { Chris@0: return new InputDefinition(array( Chris@0: new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), Chris@0: new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'), Chris@0: )); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the default commands that should always be available. Chris@0: * Chris@0: * @return array An array of default Command instances Chris@0: */ Chris@0: protected function getDefaultCommands() Chris@0: { Chris@0: $sudo = new Command\SudoCommand(); Chris@0: $sudo->setReadline($this->readline); Chris@0: Chris@0: $hist = new Command\HistoryCommand(); Chris@0: $hist->setReadline($this->readline); Chris@0: Chris@0: return array( Chris@0: new Command\HelpCommand(), Chris@0: new Command\ListCommand(), Chris@0: new Command\DumpCommand(), Chris@0: new Command\DocCommand(), Chris@0: new Command\ShowCommand($this->config->colorMode()), Chris@0: new Command\WtfCommand($this->config->colorMode()), Chris@0: new Command\WhereamiCommand($this->config->colorMode()), Chris@0: new Command\ThrowUpCommand(), Chris@0: new Command\TraceCommand(), Chris@0: new Command\BufferCommand(), Chris@0: new Command\ClearCommand(), Chris@0: new Command\EditCommand($this->config->getRuntimeDir()), Chris@0: // new Command\PsyVersionCommand(), Chris@0: $sudo, Chris@0: $hist, Chris@0: new Command\ExitCommand(), Chris@0: ); Chris@0: } Chris@0: Chris@0: /** Chris@0: * @return array Chris@0: */ Chris@0: protected function getTabCompletionMatchers() Chris@0: { Chris@0: if (empty($this->tabCompletionMatchers)) { Chris@0: $this->tabCompletionMatchers = array( Chris@0: new Matcher\CommandsMatcher($this->all()), Chris@0: new Matcher\KeywordsMatcher(), Chris@0: new Matcher\VariablesMatcher(), Chris@0: new Matcher\ConstantsMatcher(), Chris@0: new Matcher\FunctionsMatcher(), Chris@0: new Matcher\ClassNamesMatcher(), Chris@0: new Matcher\ClassMethodsMatcher(), Chris@0: new Matcher\ClassAttributesMatcher(), Chris@0: new Matcher\ObjectMethodsMatcher(), Chris@0: new Matcher\ObjectAttributesMatcher(), Chris@0: new Matcher\ClassMethodDefaultParametersMatcher(), Chris@0: new Matcher\ObjectMethodDefaultParametersMatcher(), Chris@0: new Matcher\FunctionDefaultParametersMatcher(), Chris@0: ); Chris@0: } Chris@0: Chris@0: return $this->tabCompletionMatchers; Chris@0: } Chris@0: Chris@0: /** Chris@0: * @param array $matchers Chris@0: */ Chris@0: public function addTabCompletionMatchers(array $matchers) Chris@0: { Chris@0: $this->tabCompletionMatchers = array_merge($matchers, $this->getTabCompletionMatchers()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set the Shell output. Chris@0: * Chris@0: * @param OutputInterface $output Chris@0: */ Chris@0: public function setOutput(OutputInterface $output) Chris@0: { Chris@0: $this->output = $output; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the current application. Chris@0: * Chris@0: * @param InputInterface $input An Input instance Chris@0: * @param OutputInterface $output An Output instance Chris@0: * Chris@0: * @return int 0 if everything went fine, or an error code Chris@0: */ Chris@0: public function run(InputInterface $input = null, OutputInterface $output = null) Chris@0: { Chris@0: $this->initializeTabCompletion(); Chris@0: Chris@0: if ($input === null && !isset($_SERVER['argv'])) { Chris@0: $input = new ArgvInput(array()); Chris@0: } Chris@0: Chris@0: if ($output === null) { Chris@0: $output = $this->config->getOutput(); Chris@0: } Chris@0: Chris@0: try { Chris@0: return parent::run($input, $output); Chris@0: } catch (\Exception $e) { Chris@0: $this->writeException($e); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the current application. Chris@0: * Chris@0: * @throws Exception if thrown via the `throw-up` command Chris@0: * Chris@0: * @param InputInterface $input An Input instance Chris@0: * @param OutputInterface $output An Output instance Chris@0: * Chris@0: * @return int 0 if everything went fine, or an error code Chris@0: */ Chris@0: public function doRun(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: $this->setOutput($output); Chris@0: Chris@0: $this->resetCodeBuffer(); Chris@0: Chris@0: $this->setAutoExit(false); Chris@0: $this->setCatchExceptions(false); Chris@0: Chris@0: $this->readline->readHistory(); Chris@0: Chris@0: // if ($this->config->useReadline()) { Chris@0: // readline_completion_function(array($this, 'autocomplete')); Chris@0: // } Chris@0: Chris@0: $this->output->writeln($this->getHeader()); Chris@0: $this->writeVersionInfo(); Chris@0: $this->writeStartupMessage(); Chris@0: Chris@0: try { Chris@0: $this->loop->run($this); Chris@0: } catch (ThrowUpException $e) { Chris@0: throw $e->getPrevious(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Read user input. Chris@0: * Chris@0: * This will continue fetching user input until the code buffer contains Chris@0: * valid code. Chris@0: * Chris@0: * @throws BreakException if user hits Ctrl+D Chris@0: */ Chris@0: public function getInput() Chris@0: { Chris@0: $this->codeBufferOpen = false; Chris@0: Chris@0: do { Chris@0: // reset output verbosity (in case it was altered by a subcommand) Chris@0: $this->output->setVerbosity(ShellOutput::VERBOSITY_VERBOSE); Chris@0: Chris@0: $input = $this->readline(); Chris@0: Chris@0: /* Chris@0: * Handle Ctrl+D. It behaves differently in different cases: Chris@0: * Chris@0: * 1) In an expression, like a function or "if" block, clear the input buffer Chris@0: * 2) At top-level session, behave like the exit command Chris@0: */ Chris@0: if ($input === false) { Chris@0: $this->output->writeln(''); Chris@0: Chris@0: if ($this->hasCode()) { Chris@0: $this->resetCodeBuffer(); Chris@0: } else { Chris@0: throw new BreakException('Ctrl+D'); Chris@0: } Chris@0: } Chris@0: Chris@0: // handle empty input Chris@0: if (trim($input) === '') { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($this->hasCommand($input)) { Chris@0: $this->readline->addHistory($input); Chris@0: $this->runCommand($input); Chris@0: Chris@0: continue; Chris@0: } Chris@0: Chris@0: $this->addCode($input); Chris@0: } while (!$this->hasValidCode()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pass the beforeLoop callback through to the Loop instance. Chris@0: * Chris@0: * @see Loop::beforeLoop Chris@0: */ Chris@0: public function beforeLoop() Chris@0: { Chris@0: $this->loop->beforeLoop(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pass the afterLoop callback through to the Loop instance. Chris@0: * Chris@0: * @see Loop::afterLoop Chris@0: */ Chris@0: public function afterLoop() Chris@0: { Chris@0: $this->loop->afterLoop(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set the variables currently in scope. Chris@0: * Chris@0: * @param array $vars Chris@0: */ Chris@0: public function setScopeVariables(array $vars) Chris@0: { Chris@0: $this->context->setAll($vars); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Return the set of variables currently in scope. Chris@0: * Chris@0: * @param bool $includeBoundObject Pass false to exclude 'this'. If you're Chris@0: * passing the scope variables to `extract` Chris@0: * in PHP 7.1+, you _must_ exclude 'this' Chris@0: * Chris@0: * @return array Associative array of scope variables Chris@0: */ Chris@0: public function getScopeVariables($includeBoundObject = true) Chris@0: { Chris@0: $vars = $this->context->getAll(); Chris@0: Chris@0: if (!$includeBoundObject) { Chris@0: unset($vars['this']); Chris@0: } Chris@0: Chris@0: return $vars; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Return the set of magic variables currently in scope. Chris@0: * Chris@0: * @param bool $includeBoundObject Pass false to exclude 'this'. If you're Chris@0: * passing the scope variables to `extract` Chris@0: * in PHP 7.1+, you _must_ exclude 'this' Chris@0: * Chris@0: * @return array Associative array of magic scope variables Chris@0: */ Chris@0: public function getSpecialScopeVariables($includeBoundObject = true) Chris@0: { Chris@0: $vars = $this->context->getSpecialVariables(); Chris@0: Chris@0: if (!$includeBoundObject) { Chris@0: unset($vars['this']); Chris@0: } Chris@0: Chris@0: return $vars; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the set of unused command-scope variable names. Chris@0: * Chris@0: * @return array Array of unused variable names Chris@0: */ Chris@0: public function getUnusedCommandScopeVariableNames() Chris@0: { Chris@0: return $this->context->getUnusedCommandScopeVariableNames(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the set of variable names currently in scope. Chris@0: * Chris@0: * @return array Array of variable names Chris@0: */ Chris@0: public function getScopeVariableNames() Chris@0: { Chris@0: return array_keys($this->context->getAll()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get a scope variable value by name. Chris@0: * Chris@0: * @param string $name Chris@0: * Chris@0: * @return mixed Chris@0: */ Chris@0: public function getScopeVariable($name) Chris@0: { Chris@0: return $this->context->get($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set the bound object ($this variable) for the interactive shell. Chris@0: * Chris@0: * @param object|null $boundObject Chris@0: */ Chris@0: public function setBoundObject($boundObject) Chris@0: { Chris@0: $this->context->setBoundObject($boundObject); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the bound object ($this variable) for the interactive shell. Chris@0: * Chris@0: * @return object|null Chris@0: */ Chris@0: public function getBoundObject() Chris@0: { Chris@0: return $this->context->getBoundObject(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Add includes, to be parsed and executed before running the interactive shell. Chris@0: * Chris@0: * @param array $includes Chris@0: */ Chris@0: public function setIncludes(array $includes = array()) Chris@0: { Chris@0: $this->includes = $includes; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get PHP files to be parsed and executed before running the interactive shell. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function getIncludes() Chris@0: { Chris@0: return array_merge($this->config->getDefaultIncludes(), $this->includes); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check whether this shell's code buffer contains code. Chris@0: * Chris@0: * @return bool True if the code buffer contains code Chris@0: */ Chris@0: public function hasCode() Chris@0: { Chris@0: return !empty($this->codeBuffer); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check whether the code in this shell's code buffer is valid. Chris@0: * Chris@0: * If the code is valid, the code buffer should be flushed and evaluated. Chris@0: * Chris@0: * @return bool True if the code buffer content is valid Chris@0: */ Chris@0: protected function hasValidCode() Chris@0: { Chris@0: return !$this->codeBufferOpen && $this->code !== false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Add code to the code buffer. Chris@0: * Chris@0: * @param string $code Chris@0: */ Chris@0: public function addCode($code) Chris@0: { Chris@0: try { Chris@0: // Code lines ending in \ keep the buffer open Chris@0: if (substr(rtrim($code), -1) === '\\') { Chris@0: $this->codeBufferOpen = true; Chris@0: $code = substr(rtrim($code), 0, -1); Chris@0: } else { Chris@0: $this->codeBufferOpen = false; Chris@0: } Chris@0: Chris@0: $this->codeBuffer[] = $code; Chris@0: $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons()); Chris@0: } catch (\Exception $e) { Chris@0: // Add failed code blocks to the readline history. Chris@0: $this->addCodeBufferToHistory(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the current code buffer. Chris@0: * Chris@0: * This is useful for commands which manipulate the buffer. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function getCodeBuffer() Chris@0: { Chris@0: return $this->codeBuffer; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Run a Psy Shell command given the user input. Chris@0: * Chris@0: * @throws InvalidArgumentException if the input is not a valid command Chris@0: * Chris@0: * @param string $input User input string Chris@0: * Chris@0: * @return mixed Who knows? Chris@0: */ Chris@0: protected function runCommand($input) Chris@0: { Chris@0: $command = $this->getCommand($input); Chris@0: Chris@0: if (empty($command)) { Chris@0: throw new \InvalidArgumentException('Command not found: ' . $input); Chris@0: } Chris@0: Chris@0: $input = new ShellInput(str_replace('\\', '\\\\', rtrim($input, " \t\n\r\0\x0B;"))); Chris@0: Chris@0: if ($input->hasParameterOption(array('--help', '-h'))) { Chris@0: $helpCommand = $this->get('help'); Chris@0: $helpCommand->setCommand($command); Chris@0: Chris@0: return $helpCommand->run($input, $this->output); Chris@0: } Chris@0: Chris@0: return $command->run($input, $this->output); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Reset the current code buffer. Chris@0: * Chris@0: * This should be run after evaluating user input, catching exceptions, or Chris@0: * on demand by commands such as BufferCommand. Chris@0: */ Chris@0: public function resetCodeBuffer() Chris@0: { Chris@0: $this->codeBuffer = array(); Chris@0: $this->code = false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Inject input into the input buffer. Chris@0: * Chris@0: * This is useful for commands which want to replay history. Chris@0: * Chris@0: * @param string|array $input Chris@0: * @param bool $silent Chris@0: */ Chris@0: public function addInput($input, $silent = false) Chris@0: { Chris@0: foreach ((array) $input as $line) { Chris@0: $this->inputBuffer[] = $silent ? new SilentInput($line) : $line; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Flush the current (valid) code buffer. Chris@0: * Chris@0: * If the code buffer is valid, resets the code buffer and returns the Chris@0: * current code. Chris@0: * Chris@0: * @return string PHP code buffer contents Chris@0: */ Chris@0: public function flushCode() Chris@0: { Chris@0: if ($this->hasValidCode()) { Chris@0: $this->addCodeBufferToHistory(); Chris@0: $code = $this->code; Chris@0: $this->resetCodeBuffer(); Chris@0: Chris@0: return $code; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Filter silent input from code buffer, write the rest to readline history. Chris@0: */ Chris@0: private function addCodeBufferToHistory() Chris@0: { Chris@0: $codeBuffer = array_filter($this->codeBuffer, function ($line) { Chris@0: return !$line instanceof SilentInput; Chris@0: }); Chris@0: Chris@0: $code = implode("\n", $codeBuffer); Chris@0: Chris@0: if (trim($code) !== '') { Chris@0: $this->readline->addHistory($code); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the current evaluation scope namespace. Chris@0: * Chris@0: * @see CodeCleaner::getNamespace Chris@0: * Chris@0: * @return string Current code namespace Chris@0: */ Chris@0: public function getNamespace() Chris@0: { Chris@0: if ($namespace = $this->cleaner->getNamespace()) { Chris@0: return implode('\\', $namespace); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Write a string to stdout. Chris@0: * Chris@0: * This is used by the shell loop for rendering output from evaluated code. Chris@0: * Chris@0: * @param string $out Chris@0: * @param int $phase Output buffering phase Chris@0: */ Chris@0: public function writeStdout($out, $phase = PHP_OUTPUT_HANDLER_END) Chris@0: { Chris@0: $isCleaning = false; Chris@0: if (version_compare(PHP_VERSION, '5.4', '>=')) { Chris@0: $isCleaning = $phase & PHP_OUTPUT_HANDLER_CLEAN; Chris@0: } Chris@0: Chris@0: // Incremental flush Chris@0: if ($out !== '' && !$isCleaning) { Chris@0: $this->output->write($out, false, ShellOutput::OUTPUT_RAW); Chris@0: $this->outputWantsNewline = (substr($out, -1) !== "\n"); Chris@0: $this->stdoutBuffer .= $out; Chris@0: } Chris@0: Chris@0: // Output buffering is done! Chris@0: if ($phase & PHP_OUTPUT_HANDLER_END) { Chris@0: // Write an extra newline if stdout didn't end with one Chris@0: if ($this->outputWantsNewline) { Chris@0: $this->output->writeln(sprintf('', $this->config->useUnicode() ? '⏎' : '\\n')); Chris@0: $this->outputWantsNewline = false; Chris@0: } Chris@0: Chris@0: // Save the stdout buffer as $__out Chris@0: if ($this->stdoutBuffer !== '') { Chris@0: $this->context->setLastStdout($this->stdoutBuffer); Chris@0: $this->stdoutBuffer = ''; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Write a return value to stdout. Chris@0: * Chris@0: * The return value is formatted or pretty-printed, and rendered in a Chris@0: * visibly distinct manner (in this case, as cyan). Chris@0: * Chris@0: * @see self::presentValue Chris@0: * Chris@0: * @param mixed $ret Chris@0: */ Chris@0: public function writeReturnValue($ret) Chris@0: { Chris@0: if ($ret instanceof NoReturnValue) { Chris@0: return; Chris@0: } Chris@0: Chris@0: $this->context->setReturnValue($ret); Chris@0: $ret = $this->presentValue($ret); Chris@0: $indent = str_repeat(' ', strlen(static::RETVAL)); Chris@0: Chris@0: $this->output->writeln(static::RETVAL . str_replace(PHP_EOL, PHP_EOL . $indent, $ret)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Renders a caught Exception. Chris@0: * Chris@0: * Exceptions are formatted according to severity. ErrorExceptions which were Chris@0: * warnings or Strict errors aren't rendered as harshly as real errors. Chris@0: * Chris@0: * Stores $e as the last Exception in the Shell Context. Chris@0: * Chris@0: * @param \Exception $e An exception instance Chris@0: * @param OutputInterface $output An OutputInterface instance Chris@0: */ Chris@0: public function writeException(\Exception $e) Chris@0: { Chris@0: $this->context->setLastException($e); Chris@0: $this->output->writeln($this->formatException($e)); Chris@0: $this->resetCodeBuffer(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper for formatting an exception for writeException(). Chris@0: * Chris@0: * @todo extract this to somewhere it makes more sense Chris@0: * Chris@0: * @param \Exception $e Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function formatException(\Exception $e) Chris@0: { Chris@0: $message = $e->getMessage(); Chris@0: if (!$e instanceof PsyException) { Chris@0: if ($message === '') { Chris@0: $message = get_class($e); Chris@0: } else { Chris@0: $message = sprintf('%s with message \'%s\'', get_class($e), $message); Chris@0: } Chris@0: } Chris@0: Chris@0: $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error'; Chris@0: Chris@0: return sprintf('<%s>%s', $severity, OutputFormatter::escape($message), $severity); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper for getting an output style for the given ErrorException's level. Chris@0: * Chris@0: * @param \ErrorException $e Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function getSeverity(\ErrorException $e) Chris@0: { Chris@0: $severity = $e->getSeverity(); Chris@0: if ($severity & error_reporting()) { Chris@0: switch ($severity) { Chris@0: case E_WARNING: Chris@0: case E_NOTICE: Chris@0: case E_CORE_WARNING: Chris@0: case E_COMPILE_WARNING: Chris@0: case E_USER_WARNING: Chris@0: case E_USER_NOTICE: Chris@0: case E_STRICT: Chris@0: return 'warning'; Chris@0: Chris@0: default: Chris@0: return 'error'; Chris@0: } Chris@0: } else { Chris@0: // Since this is below the user's reporting threshold, it's always going to be a warning. Chris@0: return 'warning'; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper for throwing an ErrorException. Chris@0: * Chris@0: * This allows us to: Chris@0: * Chris@0: * set_error_handler(array($psysh, 'handleError')); Chris@0: * Chris@0: * Unlike ErrorException::throwException, this error handler respects the Chris@0: * current error_reporting level; i.e. it logs warnings and notices, but Chris@0: * doesn't throw an exception unless it's above the current error_reporting Chris@0: * threshold. This should probably only be used in the inner execution loop Chris@0: * of the shell, as most of the time a thrown exception is much more useful. Chris@0: * Chris@0: * If the error type matches the `errorLoggingLevel` config, it will be Chris@0: * logged as well, regardless of the `error_reporting` level. Chris@0: * Chris@0: * @see \Psy\Exception\ErrorException::throwException Chris@0: * @see \Psy\Shell::writeException Chris@0: * Chris@0: * @throws \Psy\Exception\ErrorException depending on the current error_reporting level Chris@0: * Chris@0: * @param int $errno Error type Chris@0: * @param string $errstr Message Chris@0: * @param string $errfile Filename Chris@0: * @param int $errline Line number Chris@0: */ Chris@0: public function handleError($errno, $errstr, $errfile, $errline) Chris@0: { Chris@0: if ($errno & error_reporting()) { Chris@0: ErrorException::throwException($errno, $errstr, $errfile, $errline); Chris@0: } elseif ($errno & $this->config->errorLoggingLevel()) { Chris@0: // log it and continue... Chris@0: $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline)); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Format a value for display. Chris@0: * Chris@0: * @see Presenter::present Chris@0: * Chris@0: * @param mixed $val Chris@0: * Chris@0: * @return string Formatted value Chris@0: */ Chris@0: protected function presentValue($val) Chris@0: { Chris@0: return $this->config->getPresenter()->present($val); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get a command (if one exists) for the current input string. Chris@0: * Chris@0: * @param string $input Chris@0: * Chris@0: * @return null|BaseCommand Chris@0: */ Chris@0: protected function getCommand($input) Chris@0: { Chris@0: $input = new StringInput($input); Chris@0: if ($name = $input->getFirstArgument()) { Chris@0: return $this->get($name); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Check whether a command is set for the current input string. Chris@0: * Chris@0: * @param string $input Chris@0: * Chris@0: * @return bool True if the shell has a command for the given input Chris@0: */ Chris@0: protected function hasCommand($input) Chris@0: { Chris@0: $input = new StringInput($input); Chris@0: if ($name = $input->getFirstArgument()) { Chris@0: return $this->has($name); Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the current input prompt. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function getPrompt() Chris@0: { Chris@0: if ($this->hasCode()) { Chris@0: return static::BUFF_PROMPT; Chris@0: } Chris@0: Chris@0: return $this->config->getPrompt() ?: static::PROMPT; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Read a line of user input. Chris@0: * Chris@0: * This will return a line from the input buffer (if any exist). Otherwise, Chris@0: * it will ask the user for input. Chris@0: * Chris@0: * If readline is enabled, this delegates to readline. Otherwise, it's an Chris@0: * ugly `fgets` call. Chris@0: * Chris@0: * @return string One line of user input Chris@0: */ Chris@0: protected function readline() Chris@0: { Chris@0: if (!empty($this->inputBuffer)) { Chris@0: $line = array_shift($this->inputBuffer); Chris@0: if (!$line instanceof SilentInput) { Chris@0: $this->output->writeln(sprintf('', static::REPLAY, OutputFormatter::escape($line))); Chris@0: } Chris@0: Chris@0: return $line; Chris@0: } Chris@0: Chris@0: if ($bracketedPaste = $this->config->useBracketedPaste()) { Chris@0: printf("\e[?2004h"); // Enable bracketed paste Chris@0: } Chris@0: Chris@0: $line = $this->readline->readline($this->getPrompt()); Chris@0: Chris@0: if ($bracketedPaste) { Chris@0: printf("\e[?2004l"); // ... and disable it again Chris@0: } Chris@0: Chris@0: return $line; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the shell output header. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function getHeader() Chris@0: { Chris@0: return sprintf('', $this->getVersion()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the current version of Psy Shell. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getVersion() Chris@0: { Chris@0: $separator = $this->config->useUnicode() ? '—' : '-'; Chris@0: Chris@0: return sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, phpversion(), $separator, php_sapi_name()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get a PHP manual database instance. Chris@0: * Chris@0: * @return \PDO|null Chris@0: */ Chris@0: public function getManualDb() Chris@0: { Chris@0: return $this->config->getManualDb(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Autocomplete variable names. Chris@0: * Chris@0: * This is used by `readline` for tab completion. Chris@0: * Chris@0: * @param string $text Chris@0: * Chris@0: * @return mixed Array possible completions for the given input, if any Chris@0: */ Chris@0: protected function autocomplete($text) Chris@0: { Chris@0: $info = readline_info(); Chris@0: // $line = substr($info['line_buffer'], 0, $info['end']); Chris@0: Chris@0: // Check whether there's a command for this Chris@0: // $words = explode(' ', $line); Chris@0: // $firstWord = reset($words); Chris@0: Chris@0: // check whether this is a variable... Chris@0: $firstChar = substr($info['line_buffer'], max(0, $info['end'] - strlen($text) - 1), 1); Chris@0: if ($firstChar === '$') { Chris@0: return $this->getScopeVariableNames(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initialize tab completion matchers. Chris@0: * Chris@0: * If tab completion is enabled this adds tab completion matchers to the Chris@0: * auto completer and sets context if needed. Chris@0: */ Chris@0: protected function initializeTabCompletion() Chris@0: { Chris@0: // auto completer needs shell to be linked to configuration because of the context aware matchers Chris@0: if ($this->config->getTabCompletion()) { Chris@0: $this->completion = $this->config->getAutoCompleter(); Chris@0: $this->addTabCompletionMatchers($this->config->getTabCompletionMatchers()); Chris@0: foreach ($this->getTabCompletionMatchers() as $matcher) { Chris@0: if ($matcher instanceof ContextAware) { Chris@0: $matcher->setContext($this->context); Chris@0: } Chris@0: $this->completion->addMatcher($matcher); Chris@0: } Chris@0: $this->completion->activate(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * @todo Implement self-update Chris@0: * @todo Implement prompt to start update Chris@0: * Chris@0: * @return void|string Chris@0: */ Chris@0: protected function writeVersionInfo() Chris@0: { Chris@0: if (PHP_SAPI !== 'cli') { Chris@0: return; Chris@0: } Chris@0: Chris@0: try { Chris@0: $client = $this->config->getChecker(); Chris@0: if (!$client->isLatest()) { Chris@12: $this->output->writeln(sprintf('New version is available (current: %s, latest: %s)', self::VERSION, $client->getLatest())); Chris@0: } Chris@0: } catch (\InvalidArgumentException $e) { Chris@0: $this->output->writeln($e->getMessage()); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Write a startup message if set. Chris@0: */ Chris@0: protected function writeStartupMessage() Chris@0: { Chris@0: $message = $this->config->getStartupMessage(); Chris@0: if ($message !== null && $message !== '') { Chris@0: $this->output->writeln($message); Chris@0: } Chris@0: } Chris@0: }