QuestionHelper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. */
  194. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  195. {
  196. $cursor = new Cursor($output, $inputStream);
  197. $fullChoice = '';
  198. $ret = '';
  199. $i = 0;
  200. $ofs = -1;
  201. $matches = $autocomplete($ret);
  202. $numMatches = \count($matches);
  203. $sttyMode = shell_exec('stty -g');
  204. $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null);
  205. $r = [$inputStream];
  206. $w = [];
  207. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  208. shell_exec('stty -icanon -echo');
  209. // Add highlighted text style
  210. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  211. // Read a keypress
  212. while (!feof($inputStream)) {
  213. while ($isStdin && 0 === @stream_select($r, $w, $w, 0, 100)) {
  214. // Give signal handlers a chance to run
  215. $r = [$inputStream];
  216. }
  217. $c = fread($inputStream, 1);
  218. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  219. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  220. shell_exec('stty '.$sttyMode);
  221. throw new MissingInputException('Aborted.');
  222. } elseif ("\177" === $c) { // Backspace Character
  223. if (0 === $numMatches && 0 !== $i) {
  224. --$i;
  225. $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false));
  226. $fullChoice = self::substr($fullChoice, 0, $i);
  227. }
  228. if (0 === $i) {
  229. $ofs = -1;
  230. $matches = $autocomplete($ret);
  231. $numMatches = \count($matches);
  232. } else {
  233. $numMatches = 0;
  234. }
  235. // Pop the last character off the end of our string
  236. $ret = self::substr($ret, 0, $i);
  237. } elseif ("\033" === $c) {
  238. // Did we read an escape sequence?
  239. $c .= fread($inputStream, 2);
  240. // A = Up Arrow. B = Down Arrow
  241. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  242. if ('A' === $c[2] && -1 === $ofs) {
  243. $ofs = 0;
  244. }
  245. if (0 === $numMatches) {
  246. continue;
  247. }
  248. $ofs += ('A' === $c[2]) ? -1 : 1;
  249. $ofs = ($numMatches + $ofs) % $numMatches;
  250. }
  251. } elseif (\ord($c) < 32) {
  252. if ("\t" === $c || "\n" === $c) {
  253. if ($numMatches > 0 && -1 !== $ofs) {
  254. $ret = (string) $matches[$ofs];
  255. // Echo out remaining chars for current match
  256. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  257. $output->write($remainingCharacters);
  258. $fullChoice .= $remainingCharacters;
  259. $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
  260. $matches = array_filter(
  261. $autocomplete($ret),
  262. fn ($match) => '' === $ret || str_starts_with($match, $ret)
  263. );
  264. $numMatches = \count($matches);
  265. $ofs = -1;
  266. }
  267. if ("\n" === $c) {
  268. $output->write($c);
  269. break;
  270. }
  271. $numMatches = 0;
  272. }
  273. continue;
  274. } else {
  275. if ("\x80" <= $c) {
  276. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  277. }
  278. $output->write($c);
  279. $ret .= $c;
  280. $fullChoice .= $c;
  281. ++$i;
  282. $tempRet = $ret;
  283. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  284. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  285. }
  286. $numMatches = 0;
  287. $ofs = 0;
  288. foreach ($autocomplete($ret) as $value) {
  289. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  290. if (str_starts_with($value, $tempRet)) {
  291. $matches[$numMatches++] = $value;
  292. }
  293. }
  294. }
  295. $cursor->clearLineAfter();
  296. if ($numMatches > 0 && -1 !== $ofs) {
  297. $cursor->savePosition();
  298. // Write highlighted text, complete the partially entered response
  299. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  300. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  301. $cursor->restorePosition();
  302. }
  303. }
  304. // Reset stty so it behaves normally again
  305. shell_exec('stty '.$sttyMode);
  306. return $fullChoice;
  307. }
  308. private function mostRecentlyEnteredValue(string $entered): string
  309. {
  310. // Determine the most recent value that the user entered
  311. if (!str_contains($entered, ',')) {
  312. return $entered;
  313. }
  314. $choices = explode(',', $entered);
  315. if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) {
  316. return $lastChoice;
  317. }
  318. return $entered;
  319. }
  320. /**
  321. * Gets a hidden response from user.
  322. *
  323. * @param resource $inputStream The handler resource
  324. * @param bool $trimmable Is the answer trimmable
  325. *
  326. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  327. */
  328. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  329. {
  330. if ('\\' === \DIRECTORY_SEPARATOR) {
  331. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  332. // handle code running from a phar
  333. if (str_starts_with(__FILE__, 'phar:')) {
  334. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  335. copy($exe, $tmpExe);
  336. $exe = $tmpExe;
  337. }
  338. $sExec = shell_exec('"'.$exe.'"');
  339. $value = $trimmable ? rtrim($sExec) : $sExec;
  340. $output->writeln('');
  341. if (isset($tmpExe)) {
  342. unlink($tmpExe);
  343. }
  344. return $value;
  345. }
  346. if (self::$stty && Terminal::hasSttyAvailable()) {
  347. $sttyMode = shell_exec('stty -g');
  348. shell_exec('stty -echo');
  349. } elseif ($this->isInteractiveInput($inputStream)) {
  350. throw new RuntimeException('Unable to hide the response.');
  351. }
  352. $value = fgets($inputStream, 4096);
  353. if (4095 === \strlen($value)) {
  354. $errOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
  355. $errOutput->warning('The value was possibly truncated by your shell or terminal emulator');
  356. }
  357. if (self::$stty && Terminal::hasSttyAvailable()) {
  358. shell_exec('stty '.$sttyMode);
  359. }
  360. if (false === $value) {
  361. throw new MissingInputException('Aborted.');
  362. }
  363. if ($trimmable) {
  364. $value = trim($value);
  365. }
  366. $output->writeln('');
  367. return $value;
  368. }
  369. /**
  370. * Validates an attempt.
  371. *
  372. * @param callable $interviewer A callable that will ask for a question and return the result
  373. *
  374. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  375. */
  376. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question): mixed
  377. {
  378. $error = null;
  379. $attempts = $question->getMaxAttempts();
  380. while (null === $attempts || $attempts--) {
  381. if (null !== $error) {
  382. $this->writeError($output, $error);
  383. }
  384. try {
  385. return $question->getValidator()($interviewer());
  386. } catch (RuntimeException $e) {
  387. throw $e;
  388. } catch (\Exception $error) {
  389. }
  390. }
  391. throw $error;
  392. }
  393. private function isInteractiveInput($inputStream): bool
  394. {
  395. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  396. return false;
  397. }
  398. if (isset(self::$stdinIsInteractive)) {
  399. return self::$stdinIsInteractive;
  400. }
  401. return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
  402. }
  403. /**
  404. * Reads one or more lines of input and returns what is read.
  405. *
  406. * @param resource $inputStream The handler resource
  407. * @param Question $question The question being asked
  408. */
  409. private function readInput($inputStream, Question $question): string|false
  410. {
  411. if (!$question->isMultiline()) {
  412. $cp = $this->setIOCodepage();
  413. $ret = fgets($inputStream, 4096);
  414. return $this->resetIOCodepage($cp, $ret);
  415. }
  416. $multiLineStreamReader = $this->cloneInputStream($inputStream);
  417. if (null === $multiLineStreamReader) {
  418. return false;
  419. }
  420. $ret = '';
  421. $cp = $this->setIOCodepage();
  422. while (false !== ($char = fgetc($multiLineStreamReader))) {
  423. if (\PHP_EOL === "{$ret}{$char}") {
  424. break;
  425. }
  426. $ret .= $char;
  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'])) {
  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. }