QuestionHelper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. /**
  33. * @var resource|null
  34. */
  35. private $inputStream;
  36. private static $stty = true;
  37. private static $stdinIsInteractive;
  38. /**
  39. * Asks a question to the user.
  40. *
  41. * @return mixed The user answer
  42. *
  43. * @throws RuntimeException If there is no data to read in the input stream
  44. */
  45. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  46. {
  47. if ($output instanceof ConsoleOutputInterface) {
  48. $output = $output->getErrorOutput();
  49. }
  50. if (!$input->isInteractive()) {
  51. return $this->getDefaultAnswer($question);
  52. }
  53. if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
  54. $this->inputStream = $stream;
  55. }
  56. try {
  57. if (!$question->getValidator()) {
  58. return $this->doAsk($output, $question);
  59. }
  60. $interviewer = function () use ($output, $question) {
  61. return $this->doAsk($output, $question);
  62. };
  63. return $this->validateAttempts($interviewer, $output, $question);
  64. } catch (MissingInputException $exception) {
  65. $input->setInteractive(false);
  66. if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
  67. throw $exception;
  68. }
  69. return $fallbackOutput;
  70. }
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function getName()
  76. {
  77. return 'question';
  78. }
  79. /**
  80. * Prevents usage of stty.
  81. */
  82. public static function disableStty()
  83. {
  84. self::$stty = false;
  85. }
  86. /**
  87. * Asks the question to the user.
  88. *
  89. * @return mixed
  90. *
  91. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  92. */
  93. private function doAsk(OutputInterface $output, Question $question)
  94. {
  95. $this->writePrompt($output, $question);
  96. $inputStream = $this->inputStream ?: \STDIN;
  97. $autocomplete = $question->getAutocompleterCallback();
  98. if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
  99. $ret = false;
  100. if ($question->isHidden()) {
  101. try {
  102. $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
  103. $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
  104. } catch (RuntimeException $e) {
  105. if (!$question->isHiddenFallback()) {
  106. throw $e;
  107. }
  108. }
  109. }
  110. if (false === $ret) {
  111. $isBlocked = stream_get_meta_data($inputStream)['blocked'] ?? true;
  112. if (!$isBlocked) {
  113. stream_set_blocking($inputStream, true);
  114. }
  115. $ret = $this->readInput($inputStream, $question);
  116. if (!$isBlocked) {
  117. stream_set_blocking($inputStream, false);
  118. }
  119. if (false === $ret) {
  120. throw new MissingInputException('Aborted.');
  121. }
  122. if ($question->isTrimmable()) {
  123. $ret = trim($ret);
  124. }
  125. }
  126. } else {
  127. $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
  128. $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
  129. }
  130. if ($output instanceof ConsoleSectionOutput) {
  131. $output->addContent($ret);
  132. }
  133. $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
  134. if ($normalizer = $question->getNormalizer()) {
  135. return $normalizer($ret);
  136. }
  137. return $ret;
  138. }
  139. /**
  140. * @return mixed
  141. */
  142. private function getDefaultAnswer(Question $question)
  143. {
  144. $default = $question->getDefault();
  145. if (null === $default) {
  146. return $default;
  147. }
  148. if ($validator = $question->getValidator()) {
  149. return \call_user_func($question->getValidator(), $default);
  150. } elseif ($question instanceof ChoiceQuestion) {
  151. $choices = $question->getChoices();
  152. if (!$question->isMultiselect()) {
  153. return $choices[$default] ?? $default;
  154. }
  155. $default = explode(',', $default);
  156. foreach ($default as $k => $v) {
  157. $v = $question->isTrimmable() ? trim($v) : $v;
  158. $default[$k] = $choices[$v] ?? $v;
  159. }
  160. }
  161. return $default;
  162. }
  163. /**
  164. * Outputs the question prompt.
  165. */
  166. protected function writePrompt(OutputInterface $output, Question $question)
  167. {
  168. $message = $question->getQuestion();
  169. if ($question instanceof ChoiceQuestion) {
  170. $output->writeln(array_merge([
  171. $question->getQuestion(),
  172. ], $this->formatChoiceQuestionChoices($question, 'info')));
  173. $message = $question->getPrompt();
  174. }
  175. $output->write($message);
  176. }
  177. /**
  178. * @return string[]
  179. */
  180. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag)
  181. {
  182. $messages = [];
  183. $maxWidth = max(array_map([__CLASS__, 'width'], array_keys($choices = $question->getChoices())));
  184. foreach ($choices as $key => $value) {
  185. $padding = str_repeat(' ', $maxWidth - self::width($key));
  186. $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
  187. }
  188. return $messages;
  189. }
  190. /**
  191. * Outputs an error message.
  192. */
  193. protected function writeError(OutputInterface $output, \Exception $error)
  194. {
  195. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  196. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  197. } else {
  198. $message = '<error>'.$error->getMessage().'</error>';
  199. }
  200. $output->writeln($message);
  201. }
  202. /**
  203. * Autocompletes a question.
  204. *
  205. * @param resource $inputStream
  206. */
  207. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  208. {
  209. $cursor = new Cursor($output, $inputStream);
  210. $fullChoice = '';
  211. $ret = '';
  212. $i = 0;
  213. $ofs = -1;
  214. $matches = $autocomplete($ret);
  215. $numMatches = \count($matches);
  216. $sttyMode = shell_exec('stty -g');
  217. $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null);
  218. $r = [$inputStream];
  219. $w = [];
  220. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  221. shell_exec('stty -icanon -echo');
  222. // Add highlighted text style
  223. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  224. // Read a keypress
  225. while (!feof($inputStream)) {
  226. while ($isStdin && 0 === @stream_select($r, $w, $w, 0, 100)) {
  227. // Give signal handlers a chance to run
  228. $r = [$inputStream];
  229. }
  230. $c = fread($inputStream, 1);
  231. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  232. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  233. shell_exec('stty '.$sttyMode);
  234. throw new MissingInputException('Aborted.');
  235. } elseif ("\177" === $c) { // Backspace Character
  236. if (0 === $numMatches && 0 !== $i) {
  237. --$i;
  238. $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false));
  239. $fullChoice = self::substr($fullChoice, 0, $i);
  240. }
  241. if (0 === $i) {
  242. $ofs = -1;
  243. $matches = $autocomplete($ret);
  244. $numMatches = \count($matches);
  245. } else {
  246. $numMatches = 0;
  247. }
  248. // Pop the last character off the end of our string
  249. $ret = self::substr($ret, 0, $i);
  250. } elseif ("\033" === $c) {
  251. // Did we read an escape sequence?
  252. $c .= fread($inputStream, 2);
  253. // A = Up Arrow. B = Down Arrow
  254. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  255. if ('A' === $c[2] && -1 === $ofs) {
  256. $ofs = 0;
  257. }
  258. if (0 === $numMatches) {
  259. continue;
  260. }
  261. $ofs += ('A' === $c[2]) ? -1 : 1;
  262. $ofs = ($numMatches + $ofs) % $numMatches;
  263. }
  264. } elseif (\ord($c) < 32) {
  265. if ("\t" === $c || "\n" === $c) {
  266. if ($numMatches > 0 && -1 !== $ofs) {
  267. $ret = (string) $matches[$ofs];
  268. // Echo out remaining chars for current match
  269. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  270. $output->write($remainingCharacters);
  271. $fullChoice .= $remainingCharacters;
  272. $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
  273. $matches = array_filter(
  274. $autocomplete($ret),
  275. function ($match) use ($ret) {
  276. return '' === $ret || str_starts_with($match, $ret);
  277. }
  278. );
  279. $numMatches = \count($matches);
  280. $ofs = -1;
  281. }
  282. if ("\n" === $c) {
  283. $output->write($c);
  284. break;
  285. }
  286. $numMatches = 0;
  287. }
  288. continue;
  289. } else {
  290. if ("\x80" <= $c) {
  291. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  292. }
  293. $output->write($c);
  294. $ret .= $c;
  295. $fullChoice .= $c;
  296. ++$i;
  297. $tempRet = $ret;
  298. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  299. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  300. }
  301. $numMatches = 0;
  302. $ofs = 0;
  303. foreach ($autocomplete($ret) as $value) {
  304. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  305. if (str_starts_with($value, $tempRet)) {
  306. $matches[$numMatches++] = $value;
  307. }
  308. }
  309. }
  310. $cursor->clearLineAfter();
  311. if ($numMatches > 0 && -1 !== $ofs) {
  312. $cursor->savePosition();
  313. // Write highlighted text, complete the partially entered response
  314. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  315. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  316. $cursor->restorePosition();
  317. }
  318. }
  319. // Reset stty so it behaves normally again
  320. shell_exec('stty '.$sttyMode);
  321. return $fullChoice;
  322. }
  323. private function mostRecentlyEnteredValue(string $entered): string
  324. {
  325. // Determine the most recent value that the user entered
  326. if (!str_contains($entered, ',')) {
  327. return $entered;
  328. }
  329. $choices = explode(',', $entered);
  330. if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) {
  331. return $lastChoice;
  332. }
  333. return $entered;
  334. }
  335. /**
  336. * Gets a hidden response from user.
  337. *
  338. * @param resource $inputStream The handler resource
  339. * @param bool $trimmable Is the answer trimmable
  340. *
  341. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  342. */
  343. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  344. {
  345. if ('\\' === \DIRECTORY_SEPARATOR) {
  346. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  347. // handle code running from a phar
  348. if ('phar:' === substr(__FILE__, 0, 5)) {
  349. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  350. copy($exe, $tmpExe);
  351. $exe = $tmpExe;
  352. }
  353. $sExec = shell_exec('"'.$exe.'"');
  354. $value = $trimmable ? rtrim($sExec) : $sExec;
  355. $output->writeln('');
  356. if (isset($tmpExe)) {
  357. unlink($tmpExe);
  358. }
  359. return $value;
  360. }
  361. if (self::$stty && Terminal::hasSttyAvailable()) {
  362. $sttyMode = shell_exec('stty -g');
  363. shell_exec('stty -echo');
  364. } elseif ($this->isInteractiveInput($inputStream)) {
  365. throw new RuntimeException('Unable to hide the response.');
  366. }
  367. $value = fgets($inputStream, 4096);
  368. if (self::$stty && Terminal::hasSttyAvailable()) {
  369. shell_exec('stty '.$sttyMode);
  370. }
  371. if (false === $value) {
  372. throw new MissingInputException('Aborted.');
  373. }
  374. if ($trimmable) {
  375. $value = trim($value);
  376. }
  377. $output->writeln('');
  378. return $value;
  379. }
  380. /**
  381. * Validates an attempt.
  382. *
  383. * @param callable $interviewer A callable that will ask for a question and return the result
  384. *
  385. * @return mixed The validated response
  386. *
  387. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  388. */
  389. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
  390. {
  391. $error = null;
  392. $attempts = $question->getMaxAttempts();
  393. while (null === $attempts || $attempts--) {
  394. if (null !== $error) {
  395. $this->writeError($output, $error);
  396. }
  397. try {
  398. return $question->getValidator()($interviewer());
  399. } catch (RuntimeException $e) {
  400. throw $e;
  401. } catch (\Exception $error) {
  402. }
  403. }
  404. throw $error;
  405. }
  406. private function isInteractiveInput($inputStream): bool
  407. {
  408. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  409. return false;
  410. }
  411. if (null !== self::$stdinIsInteractive) {
  412. return self::$stdinIsInteractive;
  413. }
  414. if (\function_exists('stream_isatty')) {
  415. return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
  416. }
  417. if (\function_exists('posix_isatty')) {
  418. return self::$stdinIsInteractive = @posix_isatty(fopen('php://stdin', 'r'));
  419. }
  420. if (!\function_exists('shell_exec')) {
  421. return self::$stdinIsInteractive = true;
  422. }
  423. return self::$stdinIsInteractive = (bool) shell_exec('stty 2> '.('\\' === \DIRECTORY_SEPARATOR ? 'NUL' : '/dev/null'));
  424. }
  425. /**
  426. * Reads one or more lines of input and returns what is read.
  427. *
  428. * @param resource $inputStream The handler resource
  429. * @param Question $question The question being asked
  430. *
  431. * @return string|false The input received, false in case input could not be read
  432. */
  433. private function readInput($inputStream, Question $question)
  434. {
  435. if (!$question->isMultiline()) {
  436. $cp = $this->setIOCodepage();
  437. $ret = fgets($inputStream, 4096);
  438. return $this->resetIOCodepage($cp, $ret);
  439. }
  440. $multiLineStreamReader = $this->cloneInputStream($inputStream);
  441. if (null === $multiLineStreamReader) {
  442. return false;
  443. }
  444. $ret = '';
  445. $cp = $this->setIOCodepage();
  446. while (false !== ($char = fgetc($multiLineStreamReader))) {
  447. if (\PHP_EOL === "{$ret}{$char}") {
  448. break;
  449. }
  450. $ret .= $char;
  451. }
  452. return $this->resetIOCodepage($cp, $ret);
  453. }
  454. /**
  455. * Sets console I/O to the host code page.
  456. *
  457. * @return int Previous code page in IBM/EBCDIC format
  458. */
  459. private function setIOCodepage(): int
  460. {
  461. if (\function_exists('sapi_windows_cp_set')) {
  462. $cp = sapi_windows_cp_get();
  463. sapi_windows_cp_set(sapi_windows_cp_get('oem'));
  464. return $cp;
  465. }
  466. return 0;
  467. }
  468. /**
  469. * Sets console I/O to the specified code page and converts the user input.
  470. *
  471. * @param string|false $input
  472. *
  473. * @return string|false
  474. */
  475. private function resetIOCodepage(int $cp, $input)
  476. {
  477. if (0 !== $cp) {
  478. sapi_windows_cp_set($cp);
  479. if (false !== $input && '' !== $input) {
  480. $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
  481. }
  482. }
  483. return $input;
  484. }
  485. /**
  486. * Clones an input stream in order to act on one instance of the same
  487. * stream without affecting the other instance.
  488. *
  489. * @param resource $inputStream The handler resource
  490. *
  491. * @return resource|null The cloned resource, null in case it could not be cloned
  492. */
  493. private function cloneInputStream($inputStream)
  494. {
  495. $streamMetaData = stream_get_meta_data($inputStream);
  496. $seekable = $streamMetaData['seekable'] ?? false;
  497. $mode = $streamMetaData['mode'] ?? 'rb';
  498. $uri = $streamMetaData['uri'] ?? null;
  499. if (null === $uri) {
  500. return null;
  501. }
  502. $cloneStream = fopen($uri, $mode);
  503. // For seekable and writable streams, add all the same data to the
  504. // cloned stream and then seek to the same offset.
  505. if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'])) {
  506. $offset = ftell($inputStream);
  507. rewind($inputStream);
  508. stream_copy_to_stream($inputStream, $cloneStream);
  509. fseek($inputStream, $offset);
  510. fseek($cloneStream, $offset);
  511. }
  512. return $cloneStream;
  513. }
  514. }