Shell.php 37 KB

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