QuestionHelper.php 21 KB

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