QuestionHelper.php 15 KB

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