You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

605 lines
19 KiB

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