QuestionHelper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 bool $stty = true;
  37. private static bool $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): mixed
  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(): string
  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. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  90. */
  91. private function doAsk(OutputInterface $output, Question $question): mixed
  92. {
  93. $this->writePrompt($output, $question);
  94. $inputStream = $this->inputStream ?: \STDIN;
  95. $autocomplete = $question->getAutocompleterCallback();
  96. if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
  97. $ret = false;
  98. if ($question->isHidden()) {
  99. try {
  100. $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
  101. $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
  102. } catch (RuntimeException $e) {
  103. if (!$question->isHiddenFallback()) {
  104. throw $e;
  105. }
  106. }
  107. }
  108. if (false === $ret) {
  109. $ret = $this->readInput($inputStream, $question);
  110. if (false === $ret) {
  111. throw new MissingInputException('Aborted.');
  112. }
  113. if ($question->isTrimmable()) {
  114. $ret = trim($ret);
  115. }
  116. }
  117. } else {
  118. $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
  119. $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
  120. }
  121. if ($output instanceof ConsoleSectionOutput) {
  122. $output->addContent($ret);
  123. }
  124. $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
  125. if ($normalizer = $question->getNormalizer()) {
  126. return $normalizer($ret);
  127. }
  128. return $ret;
  129. }
  130. private function getDefaultAnswer(Question $question): mixed
  131. {
  132. $default = $question->getDefault();
  133. if (null === $default) {
  134. return $default;
  135. }
  136. if ($validator = $question->getValidator()) {
  137. return \call_user_func($question->getValidator(), $default);
  138. } elseif ($question instanceof ChoiceQuestion) {
  139. $choices = $question->getChoices();
  140. if (!$question->isMultiselect()) {
  141. return $choices[$default] ?? $default;
  142. }
  143. $default = explode(',', $default);
  144. foreach ($default as $k => $v) {
  145. $v = $question->isTrimmable() ? trim($v) : $v;
  146. $default[$k] = $choices[$v] ?? $v;
  147. }
  148. }
  149. return $default;
  150. }
  151. /**
  152. * Outputs the question prompt.
  153. */
  154. protected function writePrompt(OutputInterface $output, Question $question)
  155. {
  156. $message = $question->getQuestion();
  157. if ($question instanceof ChoiceQuestion) {
  158. $output->writeln(array_merge([
  159. $question->getQuestion(),
  160. ], $this->formatChoiceQuestionChoices($question, 'info')));
  161. $message = $question->getPrompt();
  162. }
  163. $output->write($message);
  164. }
  165. /**
  166. * @return string[]
  167. */
  168. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag): array
  169. {
  170. $messages = [];
  171. $maxWidth = max(array_map([__CLASS__, 'width'], array_keys($choices = $question->getChoices())));
  172. foreach ($choices as $key => $value) {
  173. $padding = str_repeat(' ', $maxWidth - self::width($key));
  174. $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
  175. }
  176. return $messages;
  177. }
  178. /**
  179. * Outputs an error message.
  180. */
  181. protected function writeError(OutputInterface $output, \Exception $error)
  182. {
  183. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  184. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  185. } else {
  186. $message = '<error>'.$error->getMessage().'</error>';
  187. }
  188. $output->writeln($message);
  189. }
  190. /**
  191. * Autocompletes a question.
  192. *
  193. * @param resource $inputStream
  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. $sttyMode = shell_exec('stty -g');
  205. $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null);
  206. $r = [$inputStream];
  207. $w = [];
  208. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  209. shell_exec('stty -icanon -echo');
  210. // Add highlighted text style
  211. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  212. // Read a keypress
  213. while (!feof($inputStream)) {
  214. while ($isStdin && 0 === @stream_select($r, $w, $w, 0, 100)) {
  215. // Give signal handlers a chance to run
  216. $r = [$inputStream];
  217. }
  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('stty '.$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 || str_starts_with($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 (str_starts_with($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('stty '.$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 (!str_contains($entered, ',')) {
  315. return $entered;
  316. }
  317. $choices = explode(',', $entered);
  318. if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) {
  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('stty '.$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. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  374. */
  375. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question): mixed
  376. {
  377. $error = null;
  378. $attempts = $question->getMaxAttempts();
  379. while (null === $attempts || $attempts--) {
  380. if (null !== $error) {
  381. $this->writeError($output, $error);
  382. }
  383. try {
  384. return $question->getValidator()($interviewer());
  385. } catch (RuntimeException $e) {
  386. throw $e;
  387. } catch (\Exception $error) {
  388. }
  389. }
  390. throw $error;
  391. }
  392. private function isInteractiveInput($inputStream): bool
  393. {
  394. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  395. return false;
  396. }
  397. if (isset(self::$stdinIsInteractive)) {
  398. return self::$stdinIsInteractive;
  399. }
  400. if (\function_exists('stream_isatty')) {
  401. return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
  402. }
  403. if (\function_exists('posix_isatty')) {
  404. return self::$stdinIsInteractive = @posix_isatty(fopen('php://stdin', 'r'));
  405. }
  406. if (!\function_exists('exec')) {
  407. return self::$stdinIsInteractive = true;
  408. }
  409. exec('stty 2> /dev/null', $output, $status);
  410. return self::$stdinIsInteractive = 1 !== $status;
  411. }
  412. /**
  413. * Reads one or more lines of input and returns what is read.
  414. *
  415. * @param resource $inputStream The handler resource
  416. * @param Question $question The question being asked
  417. */
  418. private function readInput($inputStream, Question $question): string|false
  419. {
  420. if (!$question->isMultiline()) {
  421. $cp = $this->setIOCodepage();
  422. $ret = fgets($inputStream, 4096);
  423. return $this->resetIOCodepage($cp, $ret);
  424. }
  425. $multiLineStreamReader = $this->cloneInputStream($inputStream);
  426. if (null === $multiLineStreamReader) {
  427. return false;
  428. }
  429. $ret = '';
  430. $cp = $this->setIOCodepage();
  431. while (false !== ($char = fgetc($multiLineStreamReader))) {
  432. if (\PHP_EOL === "{$ret}{$char}") {
  433. break;
  434. }
  435. $ret .= $char;
  436. }
  437. return $this->resetIOCodepage($cp, $ret);
  438. }
  439. private function setIOCodepage(): int
  440. {
  441. if (\function_exists('sapi_windows_cp_set')) {
  442. $cp = sapi_windows_cp_get();
  443. sapi_windows_cp_set(sapi_windows_cp_get('oem'));
  444. return $cp;
  445. }
  446. return 0;
  447. }
  448. /**
  449. * Sets console I/O to the specified code page and converts the user input.
  450. */
  451. private function resetIOCodepage(int $cp, string|false $input): string|false
  452. {
  453. if (0 !== $cp) {
  454. sapi_windows_cp_set($cp);
  455. if (false !== $input && '' !== $input) {
  456. $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
  457. }
  458. }
  459. return $input;
  460. }
  461. /**
  462. * Clones an input stream in order to act on one instance of the same
  463. * stream without affecting the other instance.
  464. *
  465. * @param resource $inputStream The handler resource
  466. *
  467. * @return resource|null The cloned resource, null in case it could not be cloned
  468. */
  469. private function cloneInputStream($inputStream)
  470. {
  471. $streamMetaData = stream_get_meta_data($inputStream);
  472. $seekable = $streamMetaData['seekable'] ?? false;
  473. $mode = $streamMetaData['mode'] ?? 'rb';
  474. $uri = $streamMetaData['uri'] ?? null;
  475. if (null === $uri) {
  476. return null;
  477. }
  478. $cloneStream = fopen($uri, $mode);
  479. // For seekable and writable streams, add all the same data to the
  480. // cloned stream and then seek to the same offset.
  481. if (true === $seekable && !\in_array($mode, ['r', 'rb', 'rt'])) {
  482. $offset = ftell($inputStream);
  483. rewind($inputStream);
  484. stream_copy_to_stream($inputStream, $cloneStream);
  485. fseek($inputStream, $offset);
  486. fseek($cloneStream, $offset);
  487. }
  488. return $cloneStream;
  489. }
  490. }