QuestionHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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\Cursor;
  12. use Symfony\Component\Console\Exception\MissingInputException;
  13. use Symfony\Component\Console\Exception\RuntimeException;
  14. use Symfony\Component\Console\Formatter\OutputFormatter;
  15. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  16. use Symfony\Component\Console\Input\InputInterface;
  17. use Symfony\Component\Console\Input\StreamableInputInterface;
  18. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  19. use Symfony\Component\Console\Output\ConsoleSectionOutput;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use Symfony\Component\Console\Question\ChoiceQuestion;
  22. use Symfony\Component\Console\Question\Question;
  23. use Symfony\Component\Console\Terminal;
  24. use function Symfony\Component\String\s;
  25. /**
  26. * The QuestionHelper class provides helpers to interact with the user.
  27. *
  28. * @author Fabien Potencier <fabien@symfony.com>
  29. */
  30. class QuestionHelper extends Helper
  31. {
  32. private $inputStream;
  33. private static $shell;
  34. private static $stty = true;
  35. private static $stdinIsInteractive;
  36. /**
  37. * Asks a question to the user.
  38. *
  39. * @return mixed The user answer
  40. *
  41. * @throws RuntimeException If there is no data to read in the input stream
  42. */
  43. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  44. {
  45. if ($output instanceof ConsoleOutputInterface) {
  46. $output = $output->getErrorOutput();
  47. }
  48. if (!$input->isInteractive()) {
  49. return $this->getDefaultAnswer($question);
  50. }
  51. if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
  52. $this->inputStream = $stream;
  53. }
  54. try {
  55. if (!$question->getValidator()) {
  56. return $this->doAsk($output, $question);
  57. }
  58. $interviewer = function () use ($output, $question) {
  59. return $this->doAsk($output, $question);
  60. };
  61. return $this->validateAttempts($interviewer, $output, $question);
  62. } catch (MissingInputException $exception) {
  63. $input->setInteractive(false);
  64. if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
  65. throw $exception;
  66. }
  67. return $fallbackOutput;
  68. }
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function getName()
  74. {
  75. return 'question';
  76. }
  77. /**
  78. * Prevents usage of stty.
  79. */
  80. public static function disableStty()
  81. {
  82. self::$stty = false;
  83. }
  84. /**
  85. * Asks the question to the user.
  86. *
  87. * @return bool|mixed|string|null
  88. *
  89. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  90. */
  91. private function doAsk(OutputInterface $output, Question $question)
  92. {
  93. $this->writePrompt($output, $question);
  94. $inputStream = $this->inputStream ?: \STDIN;
  95. $autocomplete = $question->getAutocompleterCallback();
  96. if (\function_exists('sapi_windows_cp_set')) {
  97. // Codepage used by cmd.exe on Windows to allow special characters (éàüñ).
  98. @sapi_windows_cp_set(1252);
  99. }
  100. if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
  101. $ret = false;
  102. if ($question->isHidden()) {
  103. try {
  104. $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
  105. $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
  106. } catch (RuntimeException $e) {
  107. if (!$question->isHiddenFallback()) {
  108. throw $e;
  109. }
  110. }
  111. }
  112. if (false === $ret) {
  113. $ret = $this->readInput($inputStream, $question);
  114. if (false === $ret) {
  115. throw new MissingInputException('Aborted.');
  116. }
  117. if ($question->isTrimmable()) {
  118. $ret = trim($ret);
  119. }
  120. }
  121. } else {
  122. $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
  123. $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
  124. }
  125. if ($output instanceof ConsoleSectionOutput) {
  126. $output->addContent($ret);
  127. }
  128. $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
  129. if ($normalizer = $question->getNormalizer()) {
  130. return $normalizer($ret);
  131. }
  132. return $ret;
  133. }
  134. /**
  135. * @return mixed
  136. */
  137. private function getDefaultAnswer(Question $question)
  138. {
  139. $default = $question->getDefault();
  140. if (null === $default) {
  141. return $default;
  142. }
  143. if ($validator = $question->getValidator()) {
  144. return \call_user_func($question->getValidator(), $default);
  145. } elseif ($question instanceof ChoiceQuestion) {
  146. $choices = $question->getChoices();
  147. if (!$question->isMultiselect()) {
  148. return $choices[$default] ?? $default;
  149. }
  150. $default = explode(',', $default);
  151. foreach ($default as $k => $v) {
  152. $v = $question->isTrimmable() ? trim($v) : $v;
  153. $default[$k] = $choices[$v] ?? $v;
  154. }
  155. }
  156. return $default;
  157. }
  158. /**
  159. * Outputs the question prompt.
  160. */
  161. protected function writePrompt(OutputInterface $output, Question $question)
  162. {
  163. $message = $question->getQuestion();
  164. if ($question instanceof ChoiceQuestion) {
  165. $output->writeln(array_merge([
  166. $question->getQuestion(),
  167. ], $this->formatChoiceQuestionChoices($question, 'info')));
  168. $message = $question->getPrompt();
  169. }
  170. $output->write($message);
  171. }
  172. /**
  173. * @return string[]
  174. */
  175. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag)
  176. {
  177. $messages = [];
  178. $maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
  179. foreach ($choices as $key => $value) {
  180. $padding = str_repeat(' ', $maxWidth - self::strlen($key));
  181. $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
  182. }
  183. return $messages;
  184. }
  185. /**
  186. * Outputs an error message.
  187. */
  188. protected function writeError(OutputInterface $output, \Exception $error)
  189. {
  190. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  191. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  192. } else {
  193. $message = '<error>'.$error->getMessage().'</error>';
  194. }
  195. $output->writeln($message);
  196. }
  197. /**
  198. * Autocompletes a question.
  199. *
  200. * @param resource $inputStream
  201. */
  202. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  203. {
  204. $cursor = new Cursor($output, $inputStream);
  205. $fullChoice = '';
  206. $ret = '';
  207. $i = 0;
  208. $ofs = -1;
  209. $matches = $autocomplete($ret);
  210. $numMatches = \count($matches);
  211. $sttyMode = shell_exec('stty -g');
  212. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  213. shell_exec('stty -icanon -echo');
  214. // Add highlighted text style
  215. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  216. // Read a keypress
  217. while (!feof($inputStream)) {
  218. $c = fread($inputStream, 1);
  219. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  220. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  221. shell_exec(sprintf('stty %s', $sttyMode));
  222. throw new MissingInputException('Aborted.');
  223. } elseif ("\177" === $c) { // Backspace Character
  224. if (0 === $numMatches && 0 !== $i) {
  225. --$i;
  226. $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false));
  227. $fullChoice = self::substr($fullChoice, 0, $i);
  228. }
  229. if (0 === $i) {
  230. $ofs = -1;
  231. $matches = $autocomplete($ret);
  232. $numMatches = \count($matches);
  233. } else {
  234. $numMatches = 0;
  235. }
  236. // Pop the last character off the end of our string
  237. $ret = self::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 = (string) $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 = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
  261. $matches = array_filter(
  262. $autocomplete($ret),
  263. function ($match) use ($ret) {
  264. return '' === $ret || 0 === strpos($match, $ret);
  265. }
  266. );
  267. $numMatches = \count($matches);
  268. $ofs = -1;
  269. }
  270. if ("\n" === $c) {
  271. $output->write($c);
  272. break;
  273. }
  274. $numMatches = 0;
  275. }
  276. continue;
  277. } else {
  278. if ("\x80" <= $c) {
  279. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  280. }
  281. $output->write($c);
  282. $ret .= $c;
  283. $fullChoice .= $c;
  284. ++$i;
  285. $tempRet = $ret;
  286. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  287. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  288. }
  289. $numMatches = 0;
  290. $ofs = 0;
  291. foreach ($autocomplete($ret) as $value) {
  292. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  293. if (0 === strpos($value, $tempRet)) {
  294. $matches[$numMatches++] = $value;
  295. }
  296. }
  297. }
  298. $cursor->clearLineAfter();
  299. if ($numMatches > 0 && -1 !== $ofs) {
  300. $cursor->savePosition();
  301. // Write highlighted text, complete the partially entered response
  302. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  303. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  304. $cursor->restorePosition();
  305. }
  306. }
  307. // Reset stty so it behaves normally again
  308. shell_exec(sprintf('stty %s', $sttyMode));
  309. return $fullChoice;
  310. }
  311. private function mostRecentlyEnteredValue(string $entered): string
  312. {
  313. // Determine the most recent value that the user entered
  314. if (false === strpos($entered, ',')) {
  315. return $entered;
  316. }
  317. $choices = explode(',', $entered);
  318. if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
  319. return $lastChoice;
  320. }
  321. return $entered;
  322. }
  323. /**
  324. * Gets a hidden response from user.
  325. *
  326. * @param resource $inputStream The handler resource
  327. * @param bool $trimmable Is the answer trimmable
  328. *
  329. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  330. */
  331. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  332. {
  333. if ('\\' === \DIRECTORY_SEPARATOR) {
  334. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  335. // handle code running from a phar
  336. if ('phar:' === substr(__FILE__, 0, 5)) {
  337. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  338. copy($exe, $tmpExe);
  339. $exe = $tmpExe;
  340. }
  341. $sExec = shell_exec('"'.$exe.'"');
  342. $value = $trimmable ? rtrim($sExec) : $sExec;
  343. $output->writeln('');
  344. if (isset($tmpExe)) {
  345. unlink($tmpExe);
  346. }
  347. return $value;
  348. }
  349. if (self::$stty && Terminal::hasSttyAvailable()) {
  350. $sttyMode = shell_exec('stty -g');
  351. shell_exec('stty -echo');
  352. } elseif ($this->isInteractiveInput($inputStream)) {
  353. throw new RuntimeException('Unable to hide the response.');
  354. }
  355. $value = fgets($inputStream, 4096);
  356. if (self::$stty && Terminal::hasSttyAvailable()) {
  357. shell_exec(sprintf('stty %s', $sttyMode));
  358. }
  359. if (false === $value) {
  360. throw new MissingInputException('Aborted.');
  361. }
  362. if ($trimmable) {
  363. $value = trim($value);
  364. }
  365. $output->writeln('');
  366. return $value;
  367. }
  368. /**
  369. * Validates an attempt.
  370. *
  371. * @param callable $interviewer A callable that will ask for a question and return the result
  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 $question->getValidator()($interviewer());
  387. } catch (RuntimeException $e) {
  388. throw $e;
  389. } catch (\Exception $error) {
  390. }
  391. }
  392. throw $error;
  393. }
  394. private function isInteractiveInput($inputStream): bool
  395. {
  396. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  397. return false;
  398. }
  399. if (null !== self::$stdinIsInteractive) {
  400. return self::$stdinIsInteractive;
  401. }
  402. if (\function_exists('stream_isatty')) {
  403. return self::$stdinIsInteractive = stream_isatty(fopen('php://stdin', 'r'));
  404. }
  405. if (\function_exists('posix_isatty')) {
  406. return self::$stdinIsInteractive = posix_isatty(fopen('php://stdin', 'r'));
  407. }
  408. if (!\function_exists('exec')) {
  409. return self::$stdinIsInteractive = true;
  410. }
  411. exec('stty 2> /dev/null', $output, $status);
  412. return self::$stdinIsInteractive = 1 !== $status;
  413. }
  414. /**
  415. * Reads one or more lines of input and returns what is read.
  416. *
  417. * @param resource $inputStream The handler resource
  418. * @param Question $question The question being asked
  419. *
  420. * @return string|bool The input received, false in case input could not be read
  421. */
  422. private function readInput($inputStream, Question $question)
  423. {
  424. if (!$question->isMultiline()) {
  425. return fgets($inputStream, 4096);
  426. }
  427. $multiLineStreamReader = $this->cloneInputStream($inputStream);
  428. if (null === $multiLineStreamReader) {
  429. return false;
  430. }
  431. $ret = '';
  432. while (false !== ($char = fgetc($multiLineStreamReader))) {
  433. if (\PHP_EOL === "{$ret}{$char}") {
  434. break;
  435. }
  436. $ret .= $char;
  437. }
  438. return $ret;
  439. }
  440. /**
  441. * Clones an input stream in order to act on one instance of the same
  442. * stream without affecting the other instance.
  443. *
  444. * @param resource $inputStream The handler resource
  445. *
  446. * @return resource|null The cloned resource, null in case it could not be cloned
  447. */
  448. private function cloneInputStream($inputStream)
  449. {
  450. $streamMetaData = stream_get_meta_data($inputStream);
  451. $seekable = $streamMetaData['seekable'] ?? false;
  452. $mode = $streamMetaData['mode'] ?? 'rb';
  453. $uri = $streamMetaData['uri'] ?? null;
  454. if (null === $uri) {
  455. return null;
  456. }
  457. $cloneStream = fopen($uri, $mode);
  458. // For seekable and writable streams, add all the same data to the
  459. // cloned stream and then seek to the same offset.
  460. if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'])) {
  461. $offset = ftell($inputStream);
  462. rewind($inputStream);
  463. stream_copy_to_stream($inputStream, $cloneStream);
  464. fseek($inputStream, $offset);
  465. fseek($cloneStream, $offset);
  466. }
  467. return $cloneStream;
  468. }
  469. }