Shell.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Console;
  11. use Symfony\Component\Console\Input\StringInput;
  12. use Symfony\Component\Console\Output\ConsoleOutput;
  13. use Symfony\Component\Process\ProcessBuilder;
  14. use Symfony\Component\Process\PhpExecutableFinder;
  15. /**
  16. * A Shell wraps an Application to add shell capabilities to it.
  17. *
  18. * Support for history and completion only works with a PHP compiled
  19. * with readline support (either --with-readline or --with-libedit)
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Martin Hasoň <martin.hason@gmail.com>
  23. */
  24. class Shell
  25. {
  26. private $application;
  27. private $history;
  28. private $output;
  29. private $hasReadline;
  30. private $processIsolation = false;
  31. /**
  32. * Constructor.
  33. *
  34. * If there is no readline support for the current PHP executable
  35. * a \RuntimeException exception is thrown.
  36. *
  37. * @param Application $application An application instance
  38. */
  39. public function __construct(Application $application)
  40. {
  41. $this->hasReadline = function_exists('readline');
  42. $this->application = $application;
  43. $this->history = getenv('HOME').'/.history_'.$application->getName();
  44. $this->output = new ConsoleOutput();
  45. }
  46. /**
  47. * Runs the shell.
  48. */
  49. public function run()
  50. {
  51. $this->application->setAutoExit(false);
  52. $this->application->setCatchExceptions(true);
  53. if ($this->hasReadline) {
  54. readline_read_history($this->history);
  55. readline_completion_function(array($this, 'autocompleter'));
  56. }
  57. $this->output->writeln($this->getHeader());
  58. $php = null;
  59. if ($this->processIsolation) {
  60. $finder = new PhpExecutableFinder();
  61. $php = $finder->find();
  62. $this->output->writeln(<<<EOF
  63. <info>Running with process isolation, you should consider this:</info>
  64. * each command is executed as separate process,
  65. * commands don't support interactivity, all params must be passed explicitly,
  66. * commands output is not colorized.
  67. EOF
  68. );
  69. }
  70. while (true) {
  71. $command = $this->readline();
  72. if (false === $command) {
  73. $this->output->writeln("\n");
  74. break;
  75. }
  76. if ($this->hasReadline) {
  77. readline_add_history($command);
  78. readline_write_history($this->history);
  79. }
  80. if ($this->processIsolation) {
  81. $pb = new ProcessBuilder();
  82. $process = $pb
  83. ->add($php)
  84. ->add($_SERVER['argv'][0])
  85. ->add($command)
  86. ->inheritEnvironmentVariables(true)
  87. ->getProcess()
  88. ;
  89. $output = $this->output;
  90. $process->run(function ($type, $data) use ($output) {
  91. $output->writeln($data);
  92. });
  93. $ret = $process->getExitCode();
  94. } else {
  95. $ret = $this->application->run(new StringInput($command), $this->output);
  96. }
  97. if (0 !== $ret) {
  98. $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
  99. }
  100. }
  101. }
  102. /**
  103. * Returns the shell header.
  104. *
  105. * @return string The header string
  106. */
  107. protected function getHeader()
  108. {
  109. return <<<EOF
  110. Welcome to the <info>{$this->application->getName()}</info> shell (<comment>{$this->application->getVersion()}</comment>).
  111. At the prompt, type <comment>help</comment> for some help,
  112. or <comment>list</comment> to get a list of available commands.
  113. To exit the shell, type <comment>^D</comment>.
  114. EOF;
  115. }
  116. /**
  117. * Renders a prompt.
  118. *
  119. * @return string The prompt
  120. */
  121. protected function getPrompt()
  122. {
  123. // using the formatter here is required when using readline
  124. return $this->output->getFormatter()->format($this->application->getName().' > ');
  125. }
  126. protected function getOutput()
  127. {
  128. return $this->output;
  129. }
  130. protected function getApplication()
  131. {
  132. return $this->application;
  133. }
  134. /**
  135. * Tries to return autocompletion for the current entered text.
  136. *
  137. * @param string $text The last segment of the entered text
  138. *
  139. * @return bool|array A list of guessed strings or true
  140. */
  141. private function autocompleter($text)
  142. {
  143. $info = readline_info();
  144. $text = substr($info['line_buffer'], 0, $info['end']);
  145. if ($info['point'] !== $info['end']) {
  146. return true;
  147. }
  148. // task name?
  149. if (false === strpos($text, ' ') || !$text) {
  150. return array_keys($this->application->all());
  151. }
  152. // options and arguments?
  153. try {
  154. $command = $this->application->find(substr($text, 0, strpos($text, ' ')));
  155. } catch (\Exception $e) {
  156. return true;
  157. }
  158. $list = array('--help');
  159. foreach ($command->getDefinition()->getOptions() as $option) {
  160. $list[] = '--'.$option->getName();
  161. }
  162. return $list;
  163. }
  164. /**
  165. * Reads a single line from standard input.
  166. *
  167. * @return string The single line from standard input
  168. */
  169. private function readline()
  170. {
  171. if ($this->hasReadline) {
  172. $line = readline($this->getPrompt());
  173. } else {
  174. $this->output->write($this->getPrompt());
  175. $line = fgets(STDIN, 1024);
  176. $line = (false === $line || '' === $line) ? false : rtrim($line);
  177. }
  178. return $line;
  179. }
  180. public function getProcessIsolation()
  181. {
  182. return $this->processIsolation;
  183. }
  184. public function setProcessIsolation($processIsolation)
  185. {
  186. $this->processIsolation = (bool) $processIsolation;
  187. if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
  188. throw new \RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
  189. }
  190. }
  191. }