QuestionHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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\Helper;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  17. use Symfony\Component\Console\Output\OutputInterface;
  18. use Symfony\Component\Console\Question\Question;
  19. use Symfony\Component\Console\Question\ChoiceQuestion;
  20. /**
  21. * The QuestionHelper class provides helpers to interact with the user.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. class QuestionHelper extends Helper
  26. {
  27. private $inputStream;
  28. private static $shell;
  29. private static $stty;
  30. /**
  31. * Asks a question to the user.
  32. *
  33. * @return mixed The user answer
  34. *
  35. * @throws RuntimeException If there is no data to read in the input stream
  36. */
  37. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  38. {
  39. if ($output instanceof ConsoleOutputInterface) {
  40. $output = $output->getErrorOutput();
  41. }
  42. if (!$input->isInteractive()) {
  43. if ($question instanceof ChoiceQuestion) {
  44. $choices = $question->getChoices();
  45. return $choices[$question->getDefault()];
  46. }
  47. return $question->getDefault();
  48. }
  49. if (!$question->getValidator()) {
  50. return $this->doAsk($output, $question);
  51. }
  52. $that = $this;
  53. $interviewer = function () use ($output, $question, $that) {
  54. return $that->doAsk($output, $question);
  55. };
  56. return $this->validateAttempts($interviewer, $output, $question);
  57. }
  58. /**
  59. * Sets the input stream to read from when interacting with the user.
  60. *
  61. * This is mainly useful for testing purpose.
  62. *
  63. * @param resource $stream The input stream
  64. *
  65. * @throws InvalidArgumentException In case the stream is not a resource
  66. */
  67. public function setInputStream($stream)
  68. {
  69. if (!is_resource($stream)) {
  70. throw new InvalidArgumentException('Input stream must be a valid resource.');
  71. }
  72. $this->inputStream = $stream;
  73. }
  74. /**
  75. * Returns the helper's input stream.
  76. *
  77. * @return resource
  78. */
  79. public function getInputStream()
  80. {
  81. return $this->inputStream;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function getName()
  87. {
  88. return 'question';
  89. }
  90. /**
  91. * Asks the question to the user.
  92. *
  93. * This method is public for PHP 5.3 compatibility, it should be private.
  94. *
  95. * @return bool|mixed|null|string
  96. *
  97. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  98. */
  99. public function doAsk(OutputInterface $output, Question $question)
  100. {
  101. $this->writePrompt($output, $question);
  102. $inputStream = $this->inputStream ?: STDIN;
  103. $autocomplete = $question->getAutocompleterValues();
  104. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  105. $ret = false;
  106. if ($question->isHidden()) {
  107. try {
  108. $ret = trim($this->getHiddenResponse($output, $inputStream));
  109. } catch (RuntimeException $e) {
  110. if (!$question->isHiddenFallback()) {
  111. throw $e;
  112. }
  113. }
  114. }
  115. if (false === $ret) {
  116. $ret = fgets($inputStream, 4096);
  117. if (false === $ret) {
  118. throw new RuntimeException('Aborted');
  119. }
  120. $ret = trim($ret);
  121. }
  122. } else {
  123. $ret = trim($this->autocomplete($output, $question, $inputStream, is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
  124. }
  125. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  126. if ($normalizer = $question->getNormalizer()) {
  127. return $normalizer($ret);
  128. }
  129. return $ret;
  130. }
  131. /**
  132. * Outputs the question prompt.
  133. */
  134. protected function writePrompt(OutputInterface $output, Question $question)
  135. {
  136. $message = $question->getQuestion();
  137. if ($question instanceof ChoiceQuestion) {
  138. $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
  139. $messages = (array) $question->getQuestion();
  140. foreach ($question->getChoices() as $key => $value) {
  141. $width = $maxWidth - $this->strlen($key);
  142. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  143. }
  144. $output->writeln($messages);
  145. $message = $question->getPrompt();
  146. }
  147. $output->write($message);
  148. }
  149. /**
  150. * Outputs an error message.
  151. */
  152. protected function writeError(OutputInterface $output, \Exception $error)
  153. {
  154. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  155. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  156. } else {
  157. $message = '<error>'.$error->getMessage().'</error>';
  158. }
  159. $output->writeln($message);
  160. }
  161. /**
  162. * Autocompletes a question.
  163. *
  164. * @param OutputInterface $output
  165. * @param Question $question
  166. * @param resource $inputStream
  167. * @param array $autocomplete
  168. *
  169. * @return string
  170. */
  171. private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete)
  172. {
  173. $ret = '';
  174. $i = 0;
  175. $ofs = -1;
  176. $matches = $autocomplete;
  177. $numMatches = count($matches);
  178. $sttyMode = shell_exec('stty -g');
  179. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  180. shell_exec('stty -icanon -echo');
  181. // Add highlighted text style
  182. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  183. // Read a keypress
  184. while (!feof($inputStream)) {
  185. $c = fread($inputStream, 1);
  186. // Backspace Character
  187. if ("\177" === $c) {
  188. if (0 === $numMatches && 0 !== $i) {
  189. --$i;
  190. // Move cursor backwards
  191. $output->write("\033[1D");
  192. }
  193. if (0 === $i) {
  194. $ofs = -1;
  195. $matches = $autocomplete;
  196. $numMatches = count($matches);
  197. } else {
  198. $numMatches = 0;
  199. }
  200. // Pop the last character off the end of our string
  201. $ret = substr($ret, 0, $i);
  202. } elseif ("\033" === $c) {
  203. // Did we read an escape sequence?
  204. $c .= fread($inputStream, 2);
  205. // A = Up Arrow. B = Down Arrow
  206. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  207. if ('A' === $c[2] && -1 === $ofs) {
  208. $ofs = 0;
  209. }
  210. if (0 === $numMatches) {
  211. continue;
  212. }
  213. $ofs += ('A' === $c[2]) ? -1 : 1;
  214. $ofs = ($numMatches + $ofs) % $numMatches;
  215. }
  216. } elseif (ord($c) < 32) {
  217. if ("\t" === $c || "\n" === $c) {
  218. if ($numMatches > 0 && -1 !== $ofs) {
  219. $ret = $matches[$ofs];
  220. // Echo out remaining chars for current match
  221. $output->write(substr($ret, $i));
  222. $i = strlen($ret);
  223. }
  224. if ("\n" === $c) {
  225. $output->write($c);
  226. break;
  227. }
  228. $numMatches = 0;
  229. }
  230. continue;
  231. } else {
  232. $output->write($c);
  233. $ret .= $c;
  234. ++$i;
  235. $numMatches = 0;
  236. $ofs = 0;
  237. foreach ($autocomplete as $value) {
  238. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  239. if (0 === strpos($value, $ret)) {
  240. $matches[$numMatches++] = $value;
  241. }
  242. }
  243. }
  244. // Erase characters from cursor to end of line
  245. $output->write("\033[K");
  246. if ($numMatches > 0 && -1 !== $ofs) {
  247. // Save cursor position
  248. $output->write("\0337");
  249. // Write highlighted text
  250. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $i)).'</hl>');
  251. // Restore cursor position
  252. $output->write("\0338");
  253. }
  254. }
  255. // Reset stty so it behaves normally again
  256. shell_exec(sprintf('stty %s', $sttyMode));
  257. return $ret;
  258. }
  259. /**
  260. * Gets a hidden response from user.
  261. *
  262. * @param OutputInterface $output An Output instance
  263. * @param resource $inputStream The handler resource
  264. *
  265. * @return string The answer
  266. *
  267. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  268. */
  269. private function getHiddenResponse(OutputInterface $output, $inputStream)
  270. {
  271. if ('\\' === DIRECTORY_SEPARATOR) {
  272. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  273. // handle code running from a phar
  274. if ('phar:' === substr(__FILE__, 0, 5)) {
  275. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  276. copy($exe, $tmpExe);
  277. $exe = $tmpExe;
  278. }
  279. $value = rtrim(shell_exec($exe));
  280. $output->writeln('');
  281. if (isset($tmpExe)) {
  282. unlink($tmpExe);
  283. }
  284. return $value;
  285. }
  286. if ($this->hasSttyAvailable()) {
  287. $sttyMode = shell_exec('stty -g');
  288. shell_exec('stty -echo');
  289. $value = fgets($inputStream, 4096);
  290. shell_exec(sprintf('stty %s', $sttyMode));
  291. if (false === $value) {
  292. throw new RuntimeException('Aborted');
  293. }
  294. $value = trim($value);
  295. $output->writeln('');
  296. return $value;
  297. }
  298. if (false !== $shell = $this->getShell()) {
  299. $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
  300. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  301. $value = rtrim(shell_exec($command));
  302. $output->writeln('');
  303. return $value;
  304. }
  305. throw new RuntimeException('Unable to hide the response.');
  306. }
  307. /**
  308. * Validates an attempt.
  309. *
  310. * @param callable $interviewer A callable that will ask for a question and return the result
  311. * @param OutputInterface $output An Output instance
  312. * @param Question $question A Question instance
  313. *
  314. * @return mixed The validated response
  315. *
  316. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  317. */
  318. private function validateAttempts($interviewer, OutputInterface $output, Question $question)
  319. {
  320. $error = null;
  321. $attempts = $question->getMaxAttempts();
  322. while (null === $attempts || $attempts--) {
  323. if (null !== $error) {
  324. $this->writeError($output, $error);
  325. }
  326. try {
  327. return call_user_func($question->getValidator(), $interviewer());
  328. } catch (RuntimeException $e) {
  329. throw $e;
  330. } catch (\Exception $error) {
  331. }
  332. }
  333. throw $error;
  334. }
  335. /**
  336. * Returns a valid unix shell.
  337. *
  338. * @return string|bool The valid shell name, false in case no valid shell is found
  339. */
  340. private function getShell()
  341. {
  342. if (null !== self::$shell) {
  343. return self::$shell;
  344. }
  345. self::$shell = false;
  346. if (file_exists('/usr/bin/env')) {
  347. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  348. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  349. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  350. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  351. self::$shell = $sh;
  352. break;
  353. }
  354. }
  355. }
  356. return self::$shell;
  357. }
  358. /**
  359. * Returns whether Stty is available or not.
  360. *
  361. * @return bool
  362. */
  363. private function hasSttyAvailable()
  364. {
  365. if (null !== self::$stty) {
  366. return self::$stty;
  367. }
  368. exec('stty 2>&1', $output, $exitcode);
  369. return self::$stty = 0 === $exitcode;
  370. }
  371. }