Keine Beschreibung

QuestionHelper.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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\Exception\MissingInputException;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Input\StreamableInputInterface;
  17. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  18. use Symfony\Component\Console\Output\ConsoleSectionOutput;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Symfony\Component\Console\Question\ChoiceQuestion;
  21. use Symfony\Component\Console\Question\Question;
  22. use Symfony\Component\Console\Terminal;
  23. /**
  24. * The QuestionHelper class provides helpers to interact with the user.
  25. *
  26. * @author Fabien Potencier <fabien@symfony.com>
  27. */
  28. class QuestionHelper extends Helper
  29. {
  30. private $inputStream;
  31. private static $shell;
  32. private static $stty = true;
  33. private static $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)
  42. {
  43. if ($output instanceof ConsoleOutputInterface) {
  44. $output = $output->getErrorOutput();
  45. }
  46. if (!$input->isInteractive()) {
  47. return $this->getDefaultAnswer($question);
  48. }
  49. if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
  50. $this->inputStream = $stream;
  51. }
  52. try {
  53. if (!$question->getValidator()) {
  54. return $this->doAsk($output, $question);
  55. }
  56. $interviewer = function () use ($output, $question) {
  57. return $this->doAsk($output, $question);
  58. };
  59. return $this->validateAttempts($interviewer, $output, $question);
  60. } catch (MissingInputException $exception) {
  61. $input->setInteractive(false);
  62. if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
  63. throw $exception;
  64. }
  65. return $fallbackOutput;
  66. }
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. public function getName()
  72. {
  73. return 'question';
  74. }
  75. /**
  76. * Prevents usage of stty.
  77. */
  78. public static function disableStty()
  79. {
  80. self::$stty = false;
  81. }
  82. /**
  83. * Asks the question to the user.
  84. *
  85. * @return mixed
  86. *
  87. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  88. */
  89. private function doAsk(OutputInterface $output, Question $question)
  90. {
  91. $this->writePrompt($output, $question);
  92. $inputStream = $this->inputStream ?: \STDIN;
  93. $autocomplete = $question->getAutocompleterCallback();
  94. if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
  95. $ret = false;
  96. if ($question->isHidden()) {
  97. try {
  98. $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
  99. $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
  100. } catch (RuntimeException $e) {
  101. if (!$question->isHiddenFallback()) {
  102. throw $e;
  103. }
  104. }
  105. }
  106. if (false === $ret) {
  107. $cp = $this->setIOCodepage();
  108. $ret = fgets($inputStream, 4096);
  109. $ret = $this->resetIOCodepage($cp, $ret);
  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. * @param string $tag
  170. *
  171. * @return string[]
  172. */
  173. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, $tag)
  174. {
  175. $messages = [];
  176. $maxWidth = max(array_map([__CLASS__, 'strlen'], array_keys($choices = $question->getChoices())));
  177. foreach ($choices as $key => $value) {
  178. $padding = str_repeat(' ', $maxWidth - self::strlen($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. $fullChoice = '';
  203. $ret = '';
  204. $i = 0;
  205. $ofs = -1;
  206. $matches = $autocomplete($ret);
  207. $numMatches = \count($matches);
  208. $sttyMode = shell_exec('stty -g');
  209. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  210. shell_exec('stty -icanon -echo');
  211. // Add highlighted text style
  212. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  213. // Read a keypress
  214. while (!feof($inputStream)) {
  215. $c = fread($inputStream, 1);
  216. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  217. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  218. shell_exec(sprintf('stty %s', $sttyMode));
  219. throw new MissingInputException('Aborted.');
  220. } elseif ("\177" === $c) { // Backspace Character
  221. if (0 === $numMatches && 0 !== $i) {
  222. --$i;
  223. $fullChoice = self::substr($fullChoice, 0, $i);
  224. // Move cursor backwards
  225. $output->write("\033[1D");
  226. }
  227. if (0 === $i) {
  228. $ofs = -1;
  229. $matches = $autocomplete($ret);
  230. $numMatches = \count($matches);
  231. } else {
  232. $numMatches = 0;
  233. }
  234. // Pop the last character off the end of our string
  235. $ret = self::substr($ret, 0, $i);
  236. } elseif ("\033" === $c) {
  237. // Did we read an escape sequence?
  238. $c .= fread($inputStream, 2);
  239. // A = Up Arrow. B = Down Arrow
  240. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  241. if ('A' === $c[2] && -1 === $ofs) {
  242. $ofs = 0;
  243. }
  244. if (0 === $numMatches) {
  245. continue;
  246. }
  247. $ofs += ('A' === $c[2]) ? -1 : 1;
  248. $ofs = ($numMatches + $ofs) % $numMatches;
  249. }
  250. } elseif (\ord($c) < 32) {
  251. if ("\t" === $c || "\n" === $c) {
  252. if ($numMatches > 0 && -1 !== $ofs) {
  253. $ret = (string) $matches[$ofs];
  254. // Echo out remaining chars for current match
  255. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  256. $output->write($remainingCharacters);
  257. $fullChoice .= $remainingCharacters;
  258. $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding);
  259. $matches = array_filter(
  260. $autocomplete($ret),
  261. function ($match) use ($ret) {
  262. return '' === $ret || str_starts_with($match, $ret);
  263. }
  264. );
  265. $numMatches = \count($matches);
  266. $ofs = -1;
  267. }
  268. if ("\n" === $c) {
  269. $output->write($c);
  270. break;
  271. }
  272. $numMatches = 0;
  273. }
  274. continue;
  275. } else {
  276. if ("\x80" <= $c) {
  277. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  278. }
  279. $output->write($c);
  280. $ret .= $c;
  281. $fullChoice .= $c;
  282. ++$i;
  283. $tempRet = $ret;
  284. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  285. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  286. }
  287. $numMatches = 0;
  288. $ofs = 0;
  289. foreach ($autocomplete($ret) as $value) {
  290. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  291. if (str_starts_with($value, $tempRet)) {
  292. $matches[$numMatches++] = $value;
  293. }
  294. }
  295. }
  296. // Erase characters from cursor to end of line
  297. $output->write("\033[K");
  298. if ($numMatches > 0 && -1 !== $ofs) {
  299. // Save cursor position
  300. $output->write("\0337");
  301. // Write highlighted text, complete the partially entered response
  302. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  303. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  304. // Restore cursor position
  305. $output->write("\0338");
  306. }
  307. }
  308. // Reset stty so it behaves normally again
  309. shell_exec(sprintf('stty %s', $sttyMode));
  310. return $fullChoice;
  311. }
  312. private function mostRecentlyEnteredValue(string $entered): string
  313. {
  314. // Determine the most recent value that the user entered
  315. if (!str_contains($entered, ',')) {
  316. return $entered;
  317. }
  318. $choices = explode(',', $entered);
  319. if ('' !== $lastChoice = trim($choices[\count($choices) - 1])) {
  320. return $lastChoice;
  321. }
  322. return $entered;
  323. }
  324. /**
  325. * Gets a hidden response from user.
  326. *
  327. * @param resource $inputStream The handler resource
  328. * @param bool $trimmable Is the answer trimmable
  329. *
  330. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  331. */
  332. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  333. {
  334. if ('\\' === \DIRECTORY_SEPARATOR) {
  335. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  336. // handle code running from a phar
  337. if ('phar:' === substr(__FILE__, 0, 5)) {
  338. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  339. copy($exe, $tmpExe);
  340. $exe = $tmpExe;
  341. }
  342. $sExec = shell_exec('"'.$exe.'"');
  343. $value = $trimmable ? rtrim($sExec) : $sExec;
  344. $output->writeln('');
  345. if (isset($tmpExe)) {
  346. unlink($tmpExe);
  347. }
  348. return $value;
  349. }
  350. if (self::$stty && Terminal::hasSttyAvailable()) {
  351. $sttyMode = shell_exec('stty -g');
  352. shell_exec('stty -echo');
  353. } elseif ($this->isInteractiveInput($inputStream)) {
  354. throw new RuntimeException('Unable to hide the response.');
  355. }
  356. $value = fgets($inputStream, 4096);
  357. if (self::$stty && Terminal::hasSttyAvailable()) {
  358. shell_exec(sprintf('stty %s', $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. * @return mixed The validated response
  375. *
  376. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  377. */
  378. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
  379. {
  380. $error = null;
  381. $attempts = $question->getMaxAttempts();
  382. while (null === $attempts || $attempts--) {
  383. if (null !== $error) {
  384. $this->writeError($output, $error);
  385. }
  386. try {
  387. return $question->getValidator()($interviewer());
  388. } catch (RuntimeException $e) {
  389. throw $e;
  390. } catch (\Exception $error) {
  391. }
  392. }
  393. throw $error;
  394. }
  395. private function isInteractiveInput($inputStream): bool
  396. {
  397. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  398. return false;
  399. }
  400. if (null !== self::$stdinIsInteractive) {
  401. return self::$stdinIsInteractive;
  402. }
  403. if (\function_exists('stream_isatty')) {
  404. return self::$stdinIsInteractive = @stream_isatty(fopen('php://stdin', 'r'));
  405. }
  406. if (\function_exists('posix_isatty')) {
  407. return self::$stdinIsInteractive = @posix_isatty(fopen('php://stdin', 'r'));
  408. }
  409. if (!\function_exists('exec')) {
  410. return self::$stdinIsInteractive = true;
  411. }
  412. exec('stty 2> /dev/null', $output, $status);
  413. return self::$stdinIsInteractive = 1 !== $status;
  414. }
  415. /**
  416. * Sets console I/O to the host code page.
  417. *
  418. * @return int Previous code page in IBM/EBCDIC format
  419. */
  420. private function setIOCodepage(): int
  421. {
  422. if (\function_exists('sapi_windows_cp_set')) {
  423. $cp = sapi_windows_cp_get();
  424. sapi_windows_cp_set(sapi_windows_cp_get('oem'));
  425. return $cp;
  426. }
  427. return 0;
  428. }
  429. /**
  430. * Sets console I/O to the specified code page and converts the user input.
  431. *
  432. * @param string|false $input
  433. *
  434. * @return string|false
  435. */
  436. private function resetIOCodepage(int $cp, $input)
  437. {
  438. if (0 !== $cp) {
  439. sapi_windows_cp_set($cp);
  440. if (false !== $input && '' !== $input) {
  441. $input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
  442. }
  443. }
  444. return $input;
  445. }
  446. }