QuestionHelper.php 19 KB

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