Shell.php 6.3 KB

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