QuestionHelper.php 16 KB

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