QuestionHelper.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 = Up Arrow. B = Down Arrow
  237. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  238. if ('A' === $c[2] && -1 === $ofs) {
  239. $ofs = 0;
  240. }
  241. if (0 === $numMatches) {
  242. continue;
  243. }
  244. $ofs += ('A' === $c[2]) ? -1 : 1;
  245. $ofs = ($numMatches + $ofs) % $numMatches;
  246. }
  247. } elseif ('' === $c || \ord($c) < 32) {
  248. if ("\t" === $c || "\n" === $c) {
  249. if ($numMatches > 0 && -1 !== $ofs) {
  250. $ret = (string) $matches[$ofs];
  251. // Echo out remaining chars for current match
  252. $remainingCharacters = substr($ret, \strlen($this->mostRecentlyEnteredValue($fullChoice)));
  253. $output->write($remainingCharacters);
  254. $fullChoice .= $remainingCharacters;
  255. $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
  256. $matches = array_filter(
  257. $autocomplete($ret),
  258. fn ($match) => '' === $ret || str_starts_with($match, $ret)
  259. );
  260. $numMatches = \count($matches);
  261. $ofs = -1;
  262. }
  263. if ("\n" === $c) {
  264. $output->write($c);
  265. break;
  266. }
  267. $numMatches = 0;
  268. }
  269. continue;
  270. } else {
  271. if ("\x80" <= $c) {
  272. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  273. }
  274. $output->write($c);
  275. $ret .= $c;
  276. $fullChoice .= $c;
  277. ++$i;
  278. $tempRet = $ret;
  279. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  280. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  281. }
  282. $numMatches = 0;
  283. $ofs = 0;
  284. foreach ($autocomplete($ret) as $value) {
  285. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  286. if (str_starts_with($value, $tempRet)) {
  287. $matches[$numMatches++] = $value;
  288. }
  289. }
  290. }
  291. $cursor->clearLineAfter();
  292. if ($numMatches > 0 && -1 !== $ofs) {
  293. $cursor->savePosition();
  294. // Write highlighted text, complete the partially entered response
  295. $charactersEntered = \strlen($this->mostRecentlyEnteredValue($fullChoice));
  296. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  297. $cursor->restorePosition();
  298. }
  299. }
  300. // Restore the terminal so it behaves normally again
  301. $inputHelper->finish();
  302. return $fullChoice;
  303. }
  304. private function mostRecentlyEnteredValue(string $entered): string
  305. {
  306. // Determine the most recent value that the user entered
  307. if (!str_contains($entered, ',')) {
  308. return $entered;
  309. }
  310. if (false === $lastCommaPos = strrpos($entered, ',')) {
  311. return $entered;
  312. }
  313. $lastChoice = trim(substr($entered, $lastCommaPos + 1));
  314. return '' !== $lastChoice ? $lastChoice : $entered;
  315. }
  316. /**
  317. * Gets a hidden response from user.
  318. *
  319. * @param resource $inputStream The handler resource
  320. * @param bool $trimmable Is the answer trimmable
  321. *
  322. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  323. */
  324. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  325. {
  326. if ('\\' === \DIRECTORY_SEPARATOR) {
  327. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  328. // handle code running from a phar
  329. if (str_starts_with(__FILE__, 'phar:')) {
  330. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  331. copy($exe, $tmpExe);
  332. $exe = $tmpExe;
  333. }
  334. $sExec = shell_exec('"'.$exe.'"');
  335. $value = $trimmable ? rtrim($sExec) : $sExec;
  336. $output->writeln('');
  337. if (isset($tmpExe)) {
  338. unlink($tmpExe);
  339. }
  340. return $value;
  341. }
  342. $inputHelper = null;
  343. if (self::$stty && Terminal::hasSttyAvailable()) {
  344. $inputHelper = new TerminalInputHelper($inputStream);
  345. shell_exec('stty -echo');
  346. } elseif ($this->isInteractiveInput($inputStream)) {
  347. throw new RuntimeException('Unable to hide the response.');
  348. }
  349. $value = $this->doReadInput($inputStream, helper: $inputHelper);
  350. if (4095 === \strlen($value)) {
  351. $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
  352. $errOutput->warning('The value was possibly truncated by your shell or terminal emulator');
  353. }
  354. // Restore the terminal so it behaves normally again
  355. $inputHelper?->finish();
  356. if ($trimmable) {
  357. $value = trim($value);
  358. }
  359. $output->writeln('');
  360. return $value;
  361. }
  362. /**
  363. * Validates an attempt.
  364. *
  365. * @param callable $interviewer A callable that will ask for a question and return the result
  366. *
  367. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  368. */
  369. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question): mixed
  370. {
  371. $error = null;
  372. $attempts = $question->getMaxAttempts();
  373. while (null === $attempts || $attempts--) {
  374. if (null !== $error) {
  375. $this->writeError($output, $error);
  376. }
  377. try {
  378. return $question->getValidator()($interviewer());
  379. } catch (RuntimeException $e) {
  380. throw $e;
  381. } catch (\Exception $error) {
  382. }
  383. }
  384. throw $error;
  385. }
  386. private function isInteractiveInput($inputStream): bool
  387. {
  388. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  389. return false;
  390. }
  391. if (isset(self::$stdinIsInteractive)) {
  392. return self::$stdinIsInteractive;
  393. }
  394. return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
  395. }
  396. /**
  397. * Reads one or more lines of input and returns what is read.
  398. *
  399. * @param resource $inputStream The handler resource
  400. * @param Question $question The question being asked
  401. */
  402. private function readInput($inputStream, Question $question): string|false
  403. {
  404. if (null !== $question->getTimeout() && $this->isInteractiveInput($inputStream)) {
  405. $read = [$inputStream];
  406. $write = null;
  407. $except = null;
  408. $timeoutSeconds = $question->getTimeout();
  409. $changedStreams = stream_select($read, $write, $except, $timeoutSeconds);
  410. if (0 === $changedStreams) {
  411. throw new MissingInputException(\sprintf('Timed out after waiting for input for %d second%s.', $timeoutSeconds, 1 === $timeoutSeconds ? '' : 's'));
  412. }
  413. }
  414. if (!$question->isMultiline()) {
  415. $cp = $this->setIOCodepage();
  416. $ret = $this->doReadInput($inputStream);
  417. return $this->resetIOCodepage($cp, $ret);
  418. }
  419. $multiLineStreamReader = $this->cloneInputStream($inputStream);
  420. if (null === $multiLineStreamReader) {
  421. return false;
  422. }
  423. $cp = $this->setIOCodepage();
  424. $ret = $this->doReadInput($multiLineStreamReader, "\x4");
  425. if (stream_get_meta_data($inputStream)['seekable']) {
  426. fseek($inputStream, ftell($multiLineStreamReader));
  427. }
  428. return $this->resetIOCodepage($cp, $ret);
  429. }
  430. private function setIOCodepage(): int
  431. {
  432. if (\function_exists('sapi_windows_cp_set')) {
  433. $cp = sapi_windows_cp_get();
  434. sapi_windows_cp_set(sapi_windows_cp_get('oem'));
  435. return $cp;
  436. }
  437. return 0;
  438. }
  439. /**
  440. * Sets console I/O to the specified code page and converts the user input.
  441. */
  442. private function resetIOCodepage(int $cp, string|false $input): string|false
  443. {
  444. if (0 !== $cp) {
  445. sapi_windows_cp_set($cp);
  446. if (false !== $input && '' !== $input) {
  447. $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
  448. }
  449. }
  450. return $input;
  451. }
  452. /**
  453. * Clones an input stream in order to act on one instance of the same
  454. * stream without affecting the other instance.
  455. *
  456. * @param resource $inputStream The handler resource
  457. *
  458. * @return resource|null The cloned resource, null in case it could not be cloned
  459. */
  460. private function cloneInputStream($inputStream)
  461. {
  462. $streamMetaData = stream_get_meta_data($inputStream);
  463. $seekable = $streamMetaData['seekable'] ?? false;
  464. $mode = $streamMetaData['mode'] ?? 'rb';
  465. $uri = $streamMetaData['uri'] ?? null;
  466. if (null === $uri) {
  467. return null;
  468. }
  469. $cloneStream = fopen($uri, $mode);
  470. // For seekable and writable streams, add all the same data to the
  471. // cloned stream and then seek to the same offset.
  472. if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'], true)) {
  473. $offset = ftell($inputStream);
  474. rewind($inputStream);
  475. stream_copy_to_stream($inputStream, $cloneStream);
  476. fseek($inputStream, $offset);
  477. fseek($cloneStream, $offset);
  478. }
  479. return $cloneStream;
  480. }
  481. /**
  482. * @param resource $inputStream
  483. */
  484. private function doReadInput($inputStream, ?string $exitChar = null, ?TerminalInputHelper $helper = null): string
  485. {
  486. $ret = '';
  487. $helper ??= new TerminalInputHelper($inputStream, false);
  488. while (!feof($inputStream)) {
  489. $helper->waitForInput();
  490. $char = fread($inputStream, 1);
  491. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  492. if (false === $char || ('' === $ret && '' === $char)) {
  493. throw new MissingInputException('Aborted.');
  494. }
  495. if (\PHP_EOL === "{$ret}{$char}" || $exitChar === $char) {
  496. break;
  497. }
  498. $ret .= $char;
  499. if (null === $exitChar && "\n" === $char) {
  500. break;
  501. }
  502. }
  503. return $ret;
  504. }
  505. }