QuestionHelper.php 19 KB

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