Shell.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2020 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Psy;
  11. use Psy\CodeCleaner\NoReturnValue;
  12. use Psy\Exception\BreakException;
  13. use Psy\Exception\ErrorException;
  14. use Psy\Exception\Exception as PsyException;
  15. use Psy\Exception\ThrowUpException;
  16. use Psy\Exception\TypeErrorException;
  17. use Psy\ExecutionLoop\ProcessForker;
  18. use Psy\ExecutionLoop\RunkitReloader;
  19. use Psy\Formatter\TraceFormatter;
  20. use Psy\Input\ShellInput;
  21. use Psy\Input\SilentInput;
  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\ArrayInput;
  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\ConsoleOutput;
  34. use Symfony\Component\Console\Output\OutputInterface;
  35. /**
  36. * The Psy Shell application.
  37. *
  38. * Usage:
  39. *
  40. * $shell = new Shell;
  41. * $shell->run();
  42. *
  43. * @author Justin Hileman <justin@justinhileman.info>
  44. */
  45. class Shell extends Application
  46. {
  47. const VERSION = 'v0.10.5';
  48. const PROMPT = '>>> ';
  49. const BUFF_PROMPT = '... ';
  50. const REPLAY = '--> ';
  51. const RETVAL = '=> ';
  52. private $config;
  53. private $cleaner;
  54. private $output;
  55. private $originalVerbosity;
  56. private $readline;
  57. private $inputBuffer;
  58. private $code;
  59. private $codeBuffer;
  60. private $codeBufferOpen;
  61. private $codeStack;
  62. private $stdoutBuffer;
  63. private $context;
  64. private $includes;
  65. private $outputWantsNewline = false;
  66. private $loopListeners;
  67. private $autoCompleter;
  68. private $matchers = [];
  69. private $commandsMatcher;
  70. private $lastExecSuccess = true;
  71. /**
  72. * Create a new Psy Shell.
  73. *
  74. * @param Configuration|null $config (default: null)
  75. */
  76. public function __construct(Configuration $config = null)
  77. {
  78. $this->config = $config ?: new Configuration();
  79. $this->cleaner = $this->config->getCodeCleaner();
  80. $this->context = new Context();
  81. $this->includes = [];
  82. $this->readline = $this->config->getReadline();
  83. $this->inputBuffer = [];
  84. $this->codeStack = [];
  85. $this->stdoutBuffer = '';
  86. $this->loopListeners = $this->getDefaultLoopListeners();
  87. parent::__construct('Psy Shell', self::VERSION);
  88. $this->config->setShell($this);
  89. // Register the current shell session's config with \Psy\info
  90. \Psy\info($this->config);
  91. }
  92. /**
  93. * Check whether the first thing in a backtrace is an include call.
  94. *
  95. * This is used by the psysh bin to decide whether to start a shell on boot,
  96. * or to simply autoload the library.
  97. */
  98. public static function isIncluded(array $trace)
  99. {
  100. return isset($trace[0]['function']) &&
  101. \in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']);
  102. }
  103. /**
  104. * Invoke a Psy Shell from the current context.
  105. *
  106. * @see Psy\debug
  107. * @deprecated will be removed in 1.0. Use \Psy\debug instead
  108. *
  109. * @param array $vars Scope variables from the calling context (default: [])
  110. * @param object|string $bindTo Bound object ($this) or class (self) value for the shell
  111. *
  112. * @return array Scope variables from the debugger session
  113. */
  114. public static function debug(array $vars = [], $bindTo = null)
  115. {
  116. return \Psy\debug($vars, $bindTo);
  117. }
  118. /**
  119. * Adds a command object.
  120. *
  121. * {@inheritdoc}
  122. *
  123. * @param BaseCommand $command A Symfony Console Command object
  124. *
  125. * @return BaseCommand The registered command
  126. */
  127. public function add(BaseCommand $command)
  128. {
  129. if ($ret = parent::add($command)) {
  130. if ($ret instanceof ContextAware) {
  131. $ret->setContext($this->context);
  132. }
  133. if ($ret instanceof PresenterAware) {
  134. $ret->setPresenter($this->config->getPresenter());
  135. }
  136. if (isset($this->commandsMatcher)) {
  137. $this->commandsMatcher->setCommands($this->all());
  138. }
  139. }
  140. return $ret;
  141. }
  142. /**
  143. * Gets the default input definition.
  144. *
  145. * @return InputDefinition An InputDefinition instance
  146. */
  147. protected function getDefaultInputDefinition()
  148. {
  149. return new InputDefinition([
  150. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  151. new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
  152. ]);
  153. }
  154. /**
  155. * Gets the default commands that should always be available.
  156. *
  157. * @return array An array of default Command instances
  158. */
  159. protected function getDefaultCommands()
  160. {
  161. $sudo = new Command\SudoCommand();
  162. $sudo->setReadline($this->readline);
  163. $hist = new Command\HistoryCommand();
  164. $hist->setReadline($this->readline);
  165. return [
  166. new Command\HelpCommand(),
  167. new Command\ListCommand(),
  168. new Command\DumpCommand(),
  169. new Command\DocCommand(),
  170. new Command\ShowCommand(),
  171. new Command\WtfCommand(),
  172. new Command\WhereamiCommand(),
  173. new Command\ThrowUpCommand(),
  174. new Command\TimeitCommand(),
  175. new Command\TraceCommand(),
  176. new Command\BufferCommand(),
  177. new Command\ClearCommand(),
  178. new Command\EditCommand($this->config->getRuntimeDir()),
  179. // new Command\PsyVersionCommand(),
  180. $sudo,
  181. $hist,
  182. new Command\ExitCommand(),
  183. ];
  184. }
  185. /**
  186. * @return array
  187. */
  188. protected function getDefaultMatchers()
  189. {
  190. // Store the Commands Matcher for later. If more commands are added,
  191. // we'll update the Commands Matcher too.
  192. $this->commandsMatcher = new Matcher\CommandsMatcher($this->all());
  193. return [
  194. $this->commandsMatcher,
  195. new Matcher\KeywordsMatcher(),
  196. new Matcher\VariablesMatcher(),
  197. new Matcher\ConstantsMatcher(),
  198. new Matcher\FunctionsMatcher(),
  199. new Matcher\ClassNamesMatcher(),
  200. new Matcher\ClassMethodsMatcher(),
  201. new Matcher\ClassAttributesMatcher(),
  202. new Matcher\ObjectMethodsMatcher(),
  203. new Matcher\ObjectAttributesMatcher(),
  204. new Matcher\ClassMethodDefaultParametersMatcher(),
  205. new Matcher\ObjectMethodDefaultParametersMatcher(),
  206. new Matcher\FunctionDefaultParametersMatcher(),
  207. ];
  208. }
  209. /**
  210. * @deprecated Nothing should use this anymore
  211. */
  212. protected function getTabCompletionMatchers()
  213. {
  214. @\trigger_error('getTabCompletionMatchers is no longer used', \E_USER_DEPRECATED);
  215. }
  216. /**
  217. * Gets the default command loop listeners.
  218. *
  219. * @return array An array of Execution Loop Listener instances
  220. */
  221. protected function getDefaultLoopListeners()
  222. {
  223. $listeners = [];
  224. if (ProcessForker::isSupported() && $this->config->usePcntl()) {
  225. $listeners[] = new ProcessForker();
  226. }
  227. if (RunkitReloader::isSupported()) {
  228. $listeners[] = new RunkitReloader();
  229. }
  230. return $listeners;
  231. }
  232. /**
  233. * Add tab completion matchers.
  234. *
  235. * @param array $matchers
  236. */
  237. public function addMatchers(array $matchers)
  238. {
  239. $this->matchers = \array_merge($this->matchers, $matchers);
  240. if (isset($this->autoCompleter)) {
  241. $this->addMatchersToAutoCompleter($matchers);
  242. }
  243. }
  244. /**
  245. * @deprecated Call `addMatchers` instead
  246. *
  247. * @param array $matchers
  248. */
  249. public function addTabCompletionMatchers(array $matchers)
  250. {
  251. $this->addMatchers($matchers);
  252. }
  253. /**
  254. * Set the Shell output.
  255. *
  256. * @param OutputInterface $output
  257. */
  258. public function setOutput(OutputInterface $output)
  259. {
  260. $this->output = $output;
  261. $this->originalVerbosity = $output->getVerbosity();
  262. }
  263. /**
  264. * Runs PsySH.
  265. *
  266. * @param InputInterface|null $input An Input instance
  267. * @param OutputInterface|null $output An Output instance
  268. *
  269. * @return int 0 if everything went fine, or an error code
  270. */
  271. public function run(InputInterface $input = null, OutputInterface $output = null)
  272. {
  273. // We'll just ignore the input passed in, and set up our own!
  274. $input = new ArrayInput([]);
  275. if ($output === null) {
  276. $output = $this->config->getOutput();
  277. }
  278. $this->setAutoExit(false);
  279. $this->setCatchExceptions(false);
  280. try {
  281. return parent::run($input, $output);
  282. } catch (\Exception $e) {
  283. $this->writeException($e);
  284. }
  285. return 1;
  286. }
  287. /**
  288. * Runs PsySH.
  289. *
  290. * @throws \Exception if thrown via the `throw-up` command
  291. *
  292. * @param InputInterface $input An Input instance
  293. * @param OutputInterface $output An Output instance
  294. *
  295. * @return int 0 if everything went fine, or an error code
  296. */
  297. public function doRun(InputInterface $input, OutputInterface $output)
  298. {
  299. $this->setOutput($output);
  300. $this->resetCodeBuffer();
  301. if ($input->isInteractive()) {
  302. // @todo should it be possible to have raw output in an interactive run?
  303. return $this->doInteractiveRun();
  304. } else {
  305. return $this->doNonInteractiveRun($this->config->rawOutput());
  306. }
  307. }
  308. /**
  309. * Run PsySH in interactive mode.
  310. *
  311. * Initializes tab completion and readline history, then spins up the
  312. * execution loop.
  313. *
  314. * @throws \Exception if thrown via the `throw-up` command
  315. *
  316. * @return int 0 if everything went fine, or an error code
  317. */
  318. private function doInteractiveRun()
  319. {
  320. $this->initializeTabCompletion();
  321. $this->readline->readHistory();
  322. $this->output->writeln($this->getHeader());
  323. $this->writeVersionInfo();
  324. $this->writeStartupMessage();
  325. try {
  326. $this->beforeRun();
  327. $this->loadIncludes();
  328. $loop = new ExecutionLoopClosure($this);
  329. $loop->execute();
  330. $this->afterRun();
  331. } catch (ThrowUpException $e) {
  332. throw $e->getPrevious();
  333. } catch (BreakException $e) {
  334. // The ProcessForker throws a BreakException to finish the main thread.
  335. }
  336. return 0;
  337. }
  338. /**
  339. * Run PsySH in non-interactive mode.
  340. *
  341. * Note that this isn't very useful unless you supply "include" arguments at
  342. * the command line, or code via stdin.
  343. *
  344. * @param bool $rawOutput
  345. *
  346. * @return int 0 if everything went fine, or an error code
  347. */
  348. private function doNonInteractiveRun($rawOutput)
  349. {
  350. // If raw output is enabled (or output is piped) we don't want startup messages.
  351. if (!$rawOutput && !$this->config->outputIsPiped()) {
  352. $this->output->writeln($this->getHeader());
  353. $this->writeVersionInfo();
  354. $this->writeStartupMessage();
  355. }
  356. $this->beforeRun();
  357. $this->loadIncludes();
  358. // For non-interactive execution, read only from the input buffer or from piped input.
  359. // Otherwise it'll try to readline and hang, waiting for user input with no indication of
  360. // what's holding things up.
  361. if (!empty($this->inputBuffer) || $this->config->inputIsPiped()) {
  362. $this->getInput(false);
  363. }
  364. if ($this->hasCode()) {
  365. $ret = $this->execute($this->flushCode());
  366. $this->writeReturnValue($ret, $rawOutput);
  367. }
  368. $this->afterRun();
  369. return 0;
  370. }
  371. /**
  372. * Configures the input and output instances based on the user arguments and options.
  373. */
  374. protected function configureIO(InputInterface $input, OutputInterface $output)
  375. {
  376. // @todo overrides via environment variables (or should these happen in config? ... probably config)
  377. $input->setInteractive($this->config->getInputInteractive());
  378. if ($this->config->getOutputDecorated() !== null) {
  379. $output->setDecorated($this->config->getOutputDecorated());
  380. }
  381. $output->setVerbosity($this->config->getOutputVerbosity());
  382. }
  383. /**
  384. * Load user-defined includes.
  385. */
  386. private function loadIncludes()
  387. {
  388. // Load user-defined includes
  389. $load = function (self $__psysh__) {
  390. \set_error_handler([$__psysh__, 'handleError']);
  391. foreach ($__psysh__->getIncludes() as $__psysh_include__) {
  392. try {
  393. include_once $__psysh_include__;
  394. } catch (\Error $_e) {
  395. $__psysh__->writeException(ErrorException::fromError($_e));
  396. } catch (\Exception $_e) {
  397. $__psysh__->writeException($_e);
  398. }
  399. }
  400. \restore_error_handler();
  401. unset($__psysh_include__);
  402. // Override any new local variables with pre-defined scope variables
  403. \extract($__psysh__->getScopeVariables(false));
  404. // ... then add the whole mess of variables back.
  405. $__psysh__->setScopeVariables(\get_defined_vars());
  406. };
  407. $load($this);
  408. }
  409. /**
  410. * Read user input.
  411. *
  412. * This will continue fetching user input until the code buffer contains
  413. * valid code.
  414. *
  415. * @throws BreakException if user hits Ctrl+D
  416. *
  417. * @param bool $interactive
  418. */
  419. public function getInput($interactive = true)
  420. {
  421. $this->codeBufferOpen = false;
  422. do {
  423. // reset output verbosity (in case it was altered by a subcommand)
  424. $this->output->setVerbosity($this->originalVerbosity);
  425. $input = $this->readline();
  426. /*
  427. * Handle Ctrl+D. It behaves differently in different cases:
  428. *
  429. * 1) In an expression, like a function or "if" block, clear the input buffer
  430. * 2) At top-level session, behave like the exit command
  431. * 3) When non-interactive, return, because that's the end of stdin
  432. */
  433. if ($input === false) {
  434. if (!$interactive) {
  435. return;
  436. }
  437. $this->output->writeln('');
  438. if ($this->hasCode()) {
  439. $this->resetCodeBuffer();
  440. } else {
  441. throw new BreakException('Ctrl+D');
  442. }
  443. }
  444. // handle empty input
  445. if (\trim($input) === '' && !$this->codeBufferOpen) {
  446. continue;
  447. }
  448. $input = $this->onInput($input);
  449. // If the input isn't in an open string or comment, check for commands to run.
  450. if ($this->hasCommand($input) && !$this->inputInOpenStringOrComment($input)) {
  451. $this->addHistory($input);
  452. $this->runCommand($input);
  453. continue;
  454. }
  455. $this->addCode($input);
  456. } while (!$interactive || !$this->hasValidCode());
  457. }
  458. /**
  459. * Check whether the code buffer (plus current input) is in an open string or comment.
  460. *
  461. * @param string $input current line of input
  462. *
  463. * @return bool true if the input is in an open string or comment
  464. */
  465. private function inputInOpenStringOrComment($input)
  466. {
  467. if (!$this->hasCode()) {
  468. return false;
  469. }
  470. $code = $this->codeBuffer;
  471. $code[] = $input;
  472. $tokens = @\token_get_all('<?php '.\implode("\n", $code));
  473. $last = \array_pop($tokens);
  474. return $last === '"' || $last === '`' ||
  475. (\is_array($last) && \in_array($last[0], [\T_ENCAPSED_AND_WHITESPACE, \T_START_HEREDOC, \T_COMMENT]));
  476. }
  477. /**
  478. * Run execution loop listeners before the shell session.
  479. */
  480. protected function beforeRun()
  481. {
  482. foreach ($this->loopListeners as $listener) {
  483. $listener->beforeRun($this);
  484. }
  485. }
  486. /**
  487. * Run execution loop listeners at the start of each loop.
  488. */
  489. public function beforeLoop()
  490. {
  491. foreach ($this->loopListeners as $listener) {
  492. $listener->beforeLoop($this);
  493. }
  494. }
  495. /**
  496. * Run execution loop listeners on user input.
  497. *
  498. * @param string $input
  499. *
  500. * @return string
  501. */
  502. public function onInput($input)
  503. {
  504. foreach ($this->loopListeners as $listeners) {
  505. if (($return = $listeners->onInput($this, $input)) !== null) {
  506. $input = $return;
  507. }
  508. }
  509. return $input;
  510. }
  511. /**
  512. * Run execution loop listeners on code to be executed.
  513. *
  514. * @param string $code
  515. *
  516. * @return string
  517. */
  518. public function onExecute($code)
  519. {
  520. foreach ($this->loopListeners as $listener) {
  521. if (($return = $listener->onExecute($this, $code)) !== null) {
  522. $code = $return;
  523. }
  524. }
  525. $output = $this->output;
  526. if ($output instanceof ConsoleOutput) {
  527. $output = $output->getErrorOutput();
  528. }
  529. $output->writeln(\sprintf('<aside>%s</aside>', OutputFormatter::escape($code)), ConsoleOutput::VERBOSITY_DEBUG);
  530. return $code;
  531. }
  532. /**
  533. * Run execution loop listeners after each loop.
  534. */
  535. public function afterLoop()
  536. {
  537. foreach ($this->loopListeners as $listener) {
  538. $listener->afterLoop($this);
  539. }
  540. }
  541. /**
  542. * Run execution loop listers after the shell session.
  543. */
  544. protected function afterRun()
  545. {
  546. foreach ($this->loopListeners as $listener) {
  547. $listener->afterRun($this);
  548. }
  549. }
  550. /**
  551. * Set the variables currently in scope.
  552. *
  553. * @param array $vars
  554. */
  555. public function setScopeVariables(array $vars)
  556. {
  557. $this->context->setAll($vars);
  558. }
  559. /**
  560. * Return the set of variables currently in scope.
  561. *
  562. * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
  563. * passing the scope variables to `extract`
  564. * in PHP 7.1+, you _must_ exclude 'this'
  565. *
  566. * @return array Associative array of scope variables
  567. */
  568. public function getScopeVariables($includeBoundObject = true)
  569. {
  570. $vars = $this->context->getAll();
  571. if (!$includeBoundObject) {
  572. unset($vars['this']);
  573. }
  574. return $vars;
  575. }
  576. /**
  577. * Return the set of magic variables currently in scope.
  578. *
  579. * @param bool $includeBoundObject Pass false to exclude 'this'. If you're
  580. * passing the scope variables to `extract`
  581. * in PHP 7.1+, you _must_ exclude 'this'
  582. *
  583. * @return array Associative array of magic scope variables
  584. */
  585. public function getSpecialScopeVariables($includeBoundObject = true)
  586. {
  587. $vars = $this->context->getSpecialVariables();
  588. if (!$includeBoundObject) {
  589. unset($vars['this']);
  590. }
  591. return $vars;
  592. }
  593. /**
  594. * Return the set of variables currently in scope which differ from the
  595. * values passed as $currentVars.
  596. *
  597. * This is used inside the Execution Loop Closure to pick up scope variable
  598. * changes made by commands while the loop is running.
  599. *
  600. * @param array $currentVars
  601. *
  602. * @return array Associative array of scope variables which differ from $currentVars
  603. */
  604. public function getScopeVariablesDiff(array $currentVars)
  605. {
  606. $newVars = [];
  607. foreach ($this->getScopeVariables(false) as $key => $value) {
  608. if (!\array_key_exists($key, $currentVars) || $currentVars[$key] !== $value) {
  609. $newVars[$key] = $value;
  610. }
  611. }
  612. return $newVars;
  613. }
  614. /**
  615. * Get the set of unused command-scope variable names.
  616. *
  617. * @return array Array of unused variable names
  618. */
  619. public function getUnusedCommandScopeVariableNames()
  620. {
  621. return $this->context->getUnusedCommandScopeVariableNames();
  622. }
  623. /**
  624. * Get the set of variable names currently in scope.
  625. *
  626. * @return array Array of variable names
  627. */
  628. public function getScopeVariableNames()
  629. {
  630. return \array_keys($this->context->getAll());
  631. }
  632. /**
  633. * Get a scope variable value by name.
  634. *
  635. * @param string $name
  636. *
  637. * @return mixed
  638. */
  639. public function getScopeVariable($name)
  640. {
  641. return $this->context->get($name);
  642. }
  643. /**
  644. * Set the bound object ($this variable) for the interactive shell.
  645. *
  646. * @param object|null $boundObject
  647. */
  648. public function setBoundObject($boundObject)
  649. {
  650. $this->context->setBoundObject($boundObject);
  651. }
  652. /**
  653. * Get the bound object ($this variable) for the interactive shell.
  654. *
  655. * @return object|null
  656. */
  657. public function getBoundObject()
  658. {
  659. return $this->context->getBoundObject();
  660. }
  661. /**
  662. * Set the bound class (self) for the interactive shell.
  663. *
  664. * @param string|null $boundClass
  665. */
  666. public function setBoundClass($boundClass)
  667. {
  668. $this->context->setBoundClass($boundClass);
  669. }
  670. /**
  671. * Get the bound class (self) for the interactive shell.
  672. *
  673. * @return string|null
  674. */
  675. public function getBoundClass()
  676. {
  677. return $this->context->getBoundClass();
  678. }
  679. /**
  680. * Add includes, to be parsed and executed before running the interactive shell.
  681. *
  682. * @param array $includes
  683. */
  684. public function setIncludes(array $includes = [])
  685. {
  686. $this->includes = $includes;
  687. }
  688. /**
  689. * Get PHP files to be parsed and executed before running the interactive shell.
  690. *
  691. * @return array
  692. */
  693. public function getIncludes()
  694. {
  695. return \array_merge($this->config->getDefaultIncludes(), $this->includes);
  696. }
  697. /**
  698. * Check whether this shell's code buffer contains code.
  699. *
  700. * @return bool True if the code buffer contains code
  701. */
  702. public function hasCode()
  703. {
  704. return !empty($this->codeBuffer);
  705. }
  706. /**
  707. * Check whether the code in this shell's code buffer is valid.
  708. *
  709. * If the code is valid, the code buffer should be flushed and evaluated.
  710. *
  711. * @return bool True if the code buffer content is valid
  712. */
  713. protected function hasValidCode()
  714. {
  715. return !$this->codeBufferOpen && $this->code !== false;
  716. }
  717. /**
  718. * Add code to the code buffer.
  719. *
  720. * @param string $code
  721. * @param bool $silent
  722. */
  723. public function addCode($code, $silent = false)
  724. {
  725. try {
  726. // Code lines ending in \ keep the buffer open
  727. if (\substr(\rtrim($code), -1) === '\\') {
  728. $this->codeBufferOpen = true;
  729. $code = \substr(\rtrim($code), 0, -1);
  730. } else {
  731. $this->codeBufferOpen = false;
  732. }
  733. $this->codeBuffer[] = $silent ? new SilentInput($code) : $code;
  734. $this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons());
  735. } catch (\Exception $e) {
  736. // Add failed code blocks to the readline history.
  737. $this->addCodeBufferToHistory();
  738. throw $e;
  739. }
  740. }
  741. /**
  742. * Set the code buffer.
  743. *
  744. * This is mostly used by `Shell::execute`. Any existing code in the input
  745. * buffer is pushed onto a stack and will come back after this new code is
  746. * executed.
  747. *
  748. * @throws \InvalidArgumentException if $code isn't a complete statement
  749. *
  750. * @param string $code
  751. * @param bool $silent
  752. */
  753. private function setCode($code, $silent = false)
  754. {
  755. if ($this->hasCode()) {
  756. $this->codeStack[] = [$this->codeBuffer, $this->codeBufferOpen, $this->code];
  757. }
  758. $this->resetCodeBuffer();
  759. try {
  760. $this->addCode($code, $silent);
  761. } catch (\Throwable $e) {
  762. $this->popCodeStack();
  763. throw $e;
  764. } catch (\Exception $e) {
  765. $this->popCodeStack();
  766. throw $e;
  767. }
  768. if (!$this->hasValidCode()) {
  769. $this->popCodeStack();
  770. throw new \InvalidArgumentException('Unexpected end of input');
  771. }
  772. }
  773. /**
  774. * Get the current code buffer.
  775. *
  776. * This is useful for commands which manipulate the buffer.
  777. *
  778. * @return array
  779. */
  780. public function getCodeBuffer()
  781. {
  782. return $this->codeBuffer;
  783. }
  784. /**
  785. * Run a Psy Shell command given the user input.
  786. *
  787. * @throws \InvalidArgumentException if the input is not a valid command
  788. *
  789. * @param string $input User input string
  790. *
  791. * @return mixed Who knows?
  792. */
  793. protected function runCommand($input)
  794. {
  795. $command = $this->getCommand($input);
  796. if (empty($command)) {
  797. throw new \InvalidArgumentException('Command not found: '.$input);
  798. }
  799. $input = new ShellInput(\str_replace('\\', '\\\\', \rtrim($input, " \t\n\r\0\x0B;")));
  800. if ($input->hasParameterOption(['--help', '-h'])) {
  801. $helpCommand = $this->get('help');
  802. $helpCommand->setCommand($command);
  803. return $helpCommand->run(new StringInput(''), $this->output);
  804. }
  805. return $command->run($input, $this->output);
  806. }
  807. /**
  808. * Reset the current code buffer.
  809. *
  810. * This should be run after evaluating user input, catching exceptions, or
  811. * on demand by commands such as BufferCommand.
  812. */
  813. public function resetCodeBuffer()
  814. {
  815. $this->codeBuffer = [];
  816. $this->code = false;
  817. }
  818. /**
  819. * Inject input into the input buffer.
  820. *
  821. * This is useful for commands which want to replay history.
  822. *
  823. * @param string|array $input
  824. * @param bool $silent
  825. */
  826. public function addInput($input, $silent = false)
  827. {
  828. foreach ((array) $input as $line) {
  829. $this->inputBuffer[] = $silent ? new SilentInput($line) : $line;
  830. }
  831. }
  832. /**
  833. * Flush the current (valid) code buffer.
  834. *
  835. * If the code buffer is valid, resets the code buffer and returns the
  836. * current code.
  837. *
  838. * @return string PHP code buffer contents
  839. */
  840. public function flushCode()
  841. {
  842. if ($this->hasValidCode()) {
  843. $this->addCodeBufferToHistory();
  844. $code = $this->code;
  845. $this->popCodeStack();
  846. return $code;
  847. }
  848. }
  849. /**
  850. * Reset the code buffer and restore any code pushed during `execute` calls.
  851. */
  852. private function popCodeStack()
  853. {
  854. $this->resetCodeBuffer();
  855. if (empty($this->codeStack)) {
  856. return;
  857. }
  858. list($codeBuffer, $codeBufferOpen, $code) = \array_pop($this->codeStack);
  859. $this->codeBuffer = $codeBuffer;
  860. $this->codeBufferOpen = $codeBufferOpen;
  861. $this->code = $code;
  862. }
  863. /**
  864. * (Possibly) add a line to the readline history.
  865. *
  866. * Like Bash, if the line starts with a space character, it will be omitted
  867. * from history. Note that an entire block multi-line code input will be
  868. * omitted iff the first line begins with a space.
  869. *
  870. * Additionally, if a line is "silent", i.e. it was initially added with the
  871. * silent flag, it will also be omitted.
  872. *
  873. * @param string|SilentInput $line
  874. */
  875. private function addHistory($line)
  876. {
  877. if ($line instanceof SilentInput) {
  878. return;
  879. }
  880. // Skip empty lines and lines starting with a space
  881. if (\trim($line) !== '' && \substr($line, 0, 1) !== ' ') {
  882. $this->readline->addHistory($line);
  883. }
  884. }
  885. /**
  886. * Filter silent input from code buffer, write the rest to readline history.
  887. */
  888. private function addCodeBufferToHistory()
  889. {
  890. $codeBuffer = \array_filter($this->codeBuffer, function ($line) {
  891. return !$line instanceof SilentInput;
  892. });
  893. $this->addHistory(\implode("\n", $codeBuffer));
  894. }
  895. /**
  896. * Get the current evaluation scope namespace.
  897. *
  898. * @see CodeCleaner::getNamespace
  899. *
  900. * @return string Current code namespace
  901. */
  902. public function getNamespace()
  903. {
  904. if ($namespace = $this->cleaner->getNamespace()) {
  905. return \implode('\\', $namespace);
  906. }
  907. }
  908. /**
  909. * Write a string to stdout.
  910. *
  911. * This is used by the shell loop for rendering output from evaluated code.
  912. *
  913. * @param string $out
  914. * @param int $phase Output buffering phase
  915. */
  916. public function writeStdout($out, $phase = \PHP_OUTPUT_HANDLER_END)
  917. {
  918. $isCleaning = $phase & \PHP_OUTPUT_HANDLER_CLEAN;
  919. // Incremental flush
  920. if ($out !== '' && !$isCleaning) {
  921. $this->output->write($out, false, OutputInterface::OUTPUT_RAW);
  922. $this->outputWantsNewline = (\substr($out, -1) !== "\n");
  923. $this->stdoutBuffer .= $out;
  924. }
  925. // Output buffering is done!
  926. if ($phase & \PHP_OUTPUT_HANDLER_END) {
  927. // Write an extra newline if stdout didn't end with one
  928. if ($this->outputWantsNewline) {
  929. if (!$this->config->rawOutput() && !$this->config->outputIsPiped()) {
  930. $this->output->writeln(\sprintf('<aside>%s</aside>', $this->config->useUnicode() ? '⏎' : '\\n'));
  931. } else {
  932. $this->output->writeln('');
  933. }
  934. $this->outputWantsNewline = false;
  935. }
  936. // Save the stdout buffer as $__out
  937. if ($this->stdoutBuffer !== '') {
  938. $this->context->setLastStdout($this->stdoutBuffer);
  939. $this->stdoutBuffer = '';
  940. }
  941. }
  942. }
  943. /**
  944. * Write a return value to stdout.
  945. *
  946. * The return value is formatted or pretty-printed, and rendered in a
  947. * visibly distinct manner (in this case, as cyan).
  948. *
  949. * @see self::presentValue
  950. *
  951. * @param mixed $ret
  952. * @param bool $rawOutput Write raw var_export-style values
  953. */
  954. public function writeReturnValue($ret, $rawOutput = false)
  955. {
  956. $this->lastExecSuccess = true;
  957. if ($ret instanceof NoReturnValue) {
  958. return;
  959. }
  960. $this->context->setReturnValue($ret);
  961. if ($rawOutput) {
  962. $formatted = \var_export($ret, true);
  963. } else {
  964. $indent = \str_repeat(' ', \strlen(static::RETVAL));
  965. $formatted = $this->presentValue($ret);
  966. $formatted = static::RETVAL.\str_replace(\PHP_EOL, \PHP_EOL.$indent, $formatted);
  967. }
  968. $this->output->writeln($formatted);
  969. }
  970. /**
  971. * Renders a caught Exception.
  972. *
  973. * Exceptions are formatted according to severity. ErrorExceptions which were
  974. * warnings or Strict errors aren't rendered as harshly as real errors.
  975. *
  976. * Stores $e as the last Exception in the Shell Context.
  977. *
  978. * @param \Exception $e An exception instance
  979. */
  980. public function writeException(\Exception $e)
  981. {
  982. $this->lastExecSuccess = false;
  983. $this->context->setLastException($e);
  984. $output = $this->output;
  985. if ($output instanceof ConsoleOutput) {
  986. $output = $output->getErrorOutput();
  987. }
  988. $output->writeln($this->formatException($e));
  989. // Include an exception trace (as long as this isn't a BreakException).
  990. if (!$e instanceof BreakException && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
  991. $trace = TraceFormatter::formatTrace($e);
  992. if (\count($trace) !== 0) {
  993. $output->writeln('--');
  994. $output->write($trace, true);
  995. $output->writeln('');
  996. }
  997. }
  998. $this->resetCodeBuffer();
  999. }
  1000. /**
  1001. * Check whether the last exec was successful.
  1002. *
  1003. * Returns true if a return value was logged rather than an exception.
  1004. *
  1005. * @return bool
  1006. */
  1007. public function getLastExecSuccess()
  1008. {
  1009. return $this->lastExecSuccess;
  1010. }
  1011. /**
  1012. * Helper for formatting an exception for writeException().
  1013. *
  1014. * @todo extract this to somewhere it makes more sense
  1015. *
  1016. * @param \Exception $e
  1017. *
  1018. * @return string
  1019. */
  1020. public function formatException(\Exception $e)
  1021. {
  1022. $message = $e->getMessage();
  1023. if (!$e instanceof PsyException) {
  1024. if ($message === '') {
  1025. $message = \get_class($e);
  1026. } else {
  1027. $message = \sprintf('%s with message \'%s\'', \get_class($e), $message);
  1028. }
  1029. }
  1030. $message = \preg_replace(
  1031. "#(\\w:)?([\\\\/]\\w+)*[\\\\/]src[\\\\/]Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code#",
  1032. "eval()'d code",
  1033. $message
  1034. );
  1035. $message = \str_replace(" in eval()'d code", ' in Psy Shell code', $message);
  1036. $severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
  1037. return \sprintf('<%s>%s</%s>', $severity, OutputFormatter::escape($message), $severity);
  1038. }
  1039. /**
  1040. * Helper for getting an output style for the given ErrorException's level.
  1041. *
  1042. * @param \ErrorException $e
  1043. *
  1044. * @return string
  1045. */
  1046. protected function getSeverity(\ErrorException $e)
  1047. {
  1048. $severity = $e->getSeverity();
  1049. if ($severity & \error_reporting()) {
  1050. switch ($severity) {
  1051. case \E_WARNING:
  1052. case \E_NOTICE:
  1053. case \E_CORE_WARNING:
  1054. case \E_COMPILE_WARNING:
  1055. case \E_USER_WARNING:
  1056. case \E_USER_NOTICE:
  1057. case \E_STRICT:
  1058. return 'warning';
  1059. default:
  1060. return 'error';
  1061. }
  1062. } else {
  1063. // Since this is below the user's reporting threshold, it's always going to be a warning.
  1064. return 'warning';
  1065. }
  1066. }
  1067. /**
  1068. * Execute code in the shell execution context.
  1069. *
  1070. * @param string $code
  1071. * @param bool $throwExceptions
  1072. *
  1073. * @return mixed
  1074. */
  1075. public function execute($code, $throwExceptions = false)
  1076. {
  1077. $this->setCode($code, true);
  1078. $closure = new ExecutionClosure($this);
  1079. if ($throwExceptions) {
  1080. return $closure->execute();
  1081. }
  1082. try {
  1083. return $closure->execute();
  1084. } catch (\TypeError $_e) {
  1085. $this->writeException(TypeErrorException::fromTypeError($_e));
  1086. } catch (\Error $_e) {
  1087. $this->writeException(ErrorException::fromError($_e));
  1088. } catch (\Exception $_e) {
  1089. $this->writeException($_e);
  1090. }
  1091. }
  1092. /**
  1093. * Helper for throwing an ErrorException.
  1094. *
  1095. * This allows us to:
  1096. *
  1097. * set_error_handler([$psysh, 'handleError']);
  1098. *
  1099. * Unlike ErrorException::throwException, this error handler respects error
  1100. * levels; i.e. it logs warnings and notices, but doesn't throw exceptions.
  1101. * This should probably only be used in the inner execution loop of the
  1102. * shell, as most of the time a thrown exception is much more useful.
  1103. *
  1104. * If the error type matches the `errorLoggingLevel` config, it will be
  1105. * logged as well, regardless of the `error_reporting` level.
  1106. *
  1107. * @see \Psy\Exception\ErrorException::throwException
  1108. * @see \Psy\Shell::writeException
  1109. *
  1110. * @throws \Psy\Exception\ErrorException depending on the error level
  1111. *
  1112. * @param int $errno Error type
  1113. * @param string $errstr Message
  1114. * @param string $errfile Filename
  1115. * @param int $errline Line number
  1116. */
  1117. public function handleError($errno, $errstr, $errfile, $errline)
  1118. {
  1119. // This is an error worth throwing.
  1120. //
  1121. // n.b. Technically we can't handle all of these in userland code, but
  1122. // we'll list 'em all for good measure
  1123. if ($errno & (\E_ERROR | \E_PARSE | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR | \E_RECOVERABLE_ERROR)) {
  1124. ErrorException::throwException($errno, $errstr, $errfile, $errline);
  1125. }
  1126. // Otherwise log it and continue.
  1127. if ($errno & \error_reporting() || $errno & $this->config->errorLoggingLevel()) {
  1128. $this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline));
  1129. }
  1130. }
  1131. /**
  1132. * Format a value for display.
  1133. *
  1134. * @see Presenter::present
  1135. *
  1136. * @param mixed $val
  1137. *
  1138. * @return string Formatted value
  1139. */
  1140. protected function presentValue($val)
  1141. {
  1142. return $this->config->getPresenter()->present($val);
  1143. }
  1144. /**
  1145. * Get a command (if one exists) for the current input string.
  1146. *
  1147. * @param string $input
  1148. *
  1149. * @return BaseCommand|null
  1150. */
  1151. protected function getCommand($input)
  1152. {
  1153. $input = new StringInput($input);
  1154. if ($name = $input->getFirstArgument()) {
  1155. return $this->get($name);
  1156. }
  1157. }
  1158. /**
  1159. * Check whether a command is set for the current input string.
  1160. *
  1161. * @param string $input
  1162. *
  1163. * @return bool True if the shell has a command for the given input
  1164. */
  1165. protected function hasCommand($input)
  1166. {
  1167. if (\preg_match('/([^\s]+?)(?:\s|$)/A', \ltrim($input), $match)) {
  1168. return $this->has($match[1]);
  1169. }
  1170. return false;
  1171. }
  1172. /**
  1173. * Get the current input prompt.
  1174. *
  1175. * @return string | null
  1176. */
  1177. protected function getPrompt()
  1178. {
  1179. if ($this->output->isQuiet()) {
  1180. return null;
  1181. }
  1182. if ($this->hasCode()) {
  1183. return static::BUFF_PROMPT;
  1184. }
  1185. return $this->config->getPrompt() ?: static::PROMPT;
  1186. }
  1187. /**
  1188. * Read a line of user input.
  1189. *
  1190. * This will return a line from the input buffer (if any exist). Otherwise,
  1191. * it will ask the user for input.
  1192. *
  1193. * If readline is enabled, this delegates to readline. Otherwise, it's an
  1194. * ugly `fgets` call.
  1195. *
  1196. * @param bool $interactive
  1197. *
  1198. * @return string One line of user input
  1199. */
  1200. protected function readline($interactive = true)
  1201. {
  1202. if (!empty($this->inputBuffer)) {
  1203. $line = \array_shift($this->inputBuffer);
  1204. if (!$line instanceof SilentInput) {
  1205. $this->output->writeln(\sprintf('<aside>%s %s</aside>', static::REPLAY, OutputFormatter::escape($line)));
  1206. }
  1207. return $line;
  1208. }
  1209. $bracketedPaste = $interactive && $this->config->useBracketedPaste();
  1210. if ($bracketedPaste) {
  1211. \printf("\e[?2004h"); // Enable bracketed paste
  1212. }
  1213. $line = $this->readline->readline($this->getPrompt());
  1214. if ($bracketedPaste) {
  1215. \printf("\e[?2004l"); // ... and disable it again
  1216. }
  1217. return $line;
  1218. }
  1219. /**
  1220. * Get the shell output header.
  1221. *
  1222. * @return string
  1223. */
  1224. protected function getHeader()
  1225. {
  1226. return \sprintf('<aside>%s by Justin Hileman</aside>', $this->getVersion());
  1227. }
  1228. /**
  1229. * Get the current version of Psy Shell.
  1230. *
  1231. * @deprecated call self::getVersionHeader instead
  1232. *
  1233. * @return string
  1234. */
  1235. public function getVersion()
  1236. {
  1237. return self::getVersionHeader($this->config->useUnicode());
  1238. }
  1239. /**
  1240. * Get a pretty header including the current version of Psy Shell.
  1241. *
  1242. * @param bool $useUnicode
  1243. *
  1244. * @return string
  1245. */
  1246. public static function getVersionHeader($useUnicode = false)
  1247. {
  1248. $separator = $useUnicode ? '—' : '-';
  1249. return \sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, \PHP_VERSION, $separator, \PHP_SAPI);
  1250. }
  1251. /**
  1252. * Get a PHP manual database instance.
  1253. *
  1254. * @return \PDO|null
  1255. */
  1256. public function getManualDb()
  1257. {
  1258. return $this->config->getManualDb();
  1259. }
  1260. /**
  1261. * @deprecated Tab completion is provided by the AutoCompleter service
  1262. */
  1263. protected function autocomplete($text)
  1264. {
  1265. @\trigger_error('Tab completion is provided by the AutoCompleter service', \E_USER_DEPRECATED);
  1266. }
  1267. /**
  1268. * Initialize tab completion matchers.
  1269. *
  1270. * If tab completion is enabled this adds tab completion matchers to the
  1271. * auto completer and sets context if needed.
  1272. */
  1273. protected function initializeTabCompletion()
  1274. {
  1275. if (!$this->config->useTabCompletion()) {
  1276. return;
  1277. }
  1278. $this->autoCompleter = $this->config->getAutoCompleter();
  1279. // auto completer needs shell to be linked to configuration because of
  1280. // the context aware matchers
  1281. $this->addMatchersToAutoCompleter($this->getDefaultMatchers());
  1282. $this->addMatchersToAutoCompleter($this->matchers);
  1283. $this->autoCompleter->activate();
  1284. }
  1285. /**
  1286. * Add matchers to the auto completer, setting context if needed.
  1287. *
  1288. * @param array $matchers
  1289. */
  1290. private function addMatchersToAutoCompleter(array $matchers)
  1291. {
  1292. foreach ($matchers as $matcher) {
  1293. if ($matcher instanceof ContextAware) {
  1294. $matcher->setContext($this->context);
  1295. }
  1296. $this->autoCompleter->addMatcher($matcher);
  1297. }
  1298. }
  1299. /**
  1300. * @todo Implement self-update
  1301. * @todo Implement prompt to start update
  1302. *
  1303. * @return void|string
  1304. */
  1305. protected function writeVersionInfo()
  1306. {
  1307. if (\PHP_SAPI !== 'cli') {
  1308. return;
  1309. }
  1310. try {
  1311. $client = $this->config->getChecker();
  1312. if (!$client->isLatest()) {
  1313. $this->output->writeln(\sprintf('New version is available (current: %s, latest: %s)', self::VERSION, $client->getLatest()));
  1314. }
  1315. } catch (\InvalidArgumentException $e) {
  1316. $this->output->writeln($e->getMessage());
  1317. }
  1318. }
  1319. /**
  1320. * Write a startup message if set.
  1321. */
  1322. protected function writeStartupMessage()
  1323. {
  1324. $message = $this->config->getStartupMessage();
  1325. if ($message !== null && $message !== '') {
  1326. $this->output->writeln($message);
  1327. }
  1328. }
  1329. }