QuestionHelper.php 19 KB

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