Shell.php 47 KB

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