QuestionHelper.php 14 KB

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