QuestionHelper.php 21 KB

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