QuestionHelper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 bool|mixed|string|null
  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 (\function_exists('sapi_windows_cp_set')) {
  95. // Codepage used by cmd.exe on Windows to allow special characters (éàüñ).
  96. @sapi_windows_cp_set(1252);
  97. }
  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 = fgets($inputStream, 4096);
  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 isset($choices[$default]) ? $choices[$default] : $default;
  147. }
  148. $default = explode(',', $default);
  149. foreach ($default as $k => $v) {
  150. $v = $question->isTrimmable() ? trim($v) : $v;
  151. $default[$k] = isset($choices[$v]) ? $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. * @param string $tag
  172. *
  173. * @return string[]
  174. */
  175. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, $tag)
  176. {
  177. $messages = [];
  178. $maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
  179. foreach ($choices as $key => $value) {
  180. $padding = str_repeat(' ', $maxWidth - self::strlen($key));
  181. $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
  182. }
  183. return $messages;
  184. }
  185. /**
  186. * Outputs an error message.
  187. */
  188. protected function writeError(OutputInterface $output, \Exception $error)
  189. {
  190. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  191. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  192. } else {
  193. $message = '<error>'.$error->getMessage().'</error>';
  194. }
  195. $output->writeln($message);
  196. }
  197. /**
  198. * Autocompletes a question.
  199. *
  200. * @param resource $inputStream
  201. */
  202. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  203. {
  204. $fullChoice = '';
  205. $ret = '';
  206. $i = 0;
  207. $ofs = -1;
  208. $matches = $autocomplete($ret);
  209. $numMatches = \count($matches);
  210. $sttyMode = shell_exec('stty -g');
  211. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  212. shell_exec('stty -icanon -echo');
  213. // Add highlighted text style
  214. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  215. // Read a keypress
  216. while (!feof($inputStream)) {
  217. $c = fread($inputStream, 1);
  218. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  219. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  220. shell_exec(sprintf('stty %s', $sttyMode));
  221. throw new MissingInputException('Aborted.');
  222. } elseif ("\177" === $c) { // Backspace Character
  223. if (0 === $numMatches && 0 !== $i) {
  224. --$i;
  225. $fullChoice = self::substr($fullChoice, 0, $i);
  226. // Move cursor backwards
  227. $output->write("\033[1D");
  228. }
  229. if (0 === $i) {
  230. $ofs = -1;
  231. $matches = $autocomplete($ret);
  232. $numMatches = \count($matches);
  233. } else {
  234. $numMatches = 0;
  235. }
  236. // Pop the last character off the end of our string
  237. $ret = self::substr($ret, 0, $i);
  238. } elseif ("\033" === $c) {
  239. // Did we read an escape sequence?
  240. $c .= fread($inputStream, 2);
  241. // A = Up Arrow. B = Down Arrow
  242. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  243. if ('A' === $c[2] && -1 === $ofs) {
  244. $ofs = 0;
  245. }
  246. if (0 === $numMatches) {
  247. continue;
  248. }
  249. $ofs += ('A' === $c[2]) ? -1 : 1;
  250. $ofs = ($numMatches + $ofs) % $numMatches;
  251. }
  252. } elseif (\ord($c) < 32) {
  253. if ("\t" === $c || "\n" === $c) {
  254. if ($numMatches > 0 && -1 !== $ofs) {
  255. $ret = (string) $matches[$ofs];
  256. // Echo out remaining chars for current match
  257. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  258. $output->write($remainingCharacters);
  259. $fullChoice .= $remainingCharacters;
  260. $i = self::strlen($fullChoice);
  261. $matches = array_filter(
  262. $autocomplete($ret),
  263. function ($match) use ($ret) {
  264. return '' === $ret || 0 === strpos($match, $ret);
  265. }
  266. );
  267. $numMatches = \count($matches);
  268. $ofs = -1;
  269. }
  270. if ("\n" === $c) {
  271. $output->write($c);
  272. break;
  273. }
  274. $numMatches = 0;
  275. }
  276. continue;
  277. } else {
  278. if ("\x80" <= $c) {
  279. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  280. }
  281. $output->write($c);
  282. $ret .= $c;
  283. $fullChoice .= $c;
  284. ++$i;
  285. $tempRet = $ret;
  286. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  287. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  288. }
  289. $numMatches = 0;
  290. $ofs = 0;
  291. foreach ($autocomplete($ret) as $value) {
  292. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  293. if (0 === strpos($value, $tempRet)) {
  294. $matches[$numMatches++] = $value;
  295. }
  296. }
  297. }
  298. // Erase characters from cursor to end of line
  299. $output->write("\033[K");
  300. if ($numMatches > 0 && -1 !== $ofs) {
  301. // Save cursor position
  302. $output->write("\0337");
  303. // Write highlighted text, complete the partially entered response
  304. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  305. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  306. // Restore cursor position
  307. $output->write("\0338");
  308. }
  309. }
  310. // Reset stty so it behaves normally again
  311. shell_exec(sprintf('stty %s', $sttyMode));
  312. return $fullChoice;
  313. }
  314. private function mostRecentlyEnteredValue(string $entered): string
  315. {
  316. // Determine the most recent value that the user entered
  317. if (false === strpos($entered, ',')) {
  318. return $entered;
  319. }
  320. $choices = explode(',', $entered);
  321. if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
  322. return $lastChoice;
  323. }
  324. return $entered;
  325. }
  326. /**
  327. * Gets a hidden response from user.
  328. *
  329. * @param resource $inputStream The handler resource
  330. * @param bool $trimmable Is the answer trimmable
  331. *
  332. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  333. */
  334. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  335. {
  336. if ('\\' === \DIRECTORY_SEPARATOR) {
  337. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  338. // handle code running from a phar
  339. if ('phar:' === substr(__FILE__, 0, 5)) {
  340. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  341. copy($exe, $tmpExe);
  342. $exe = $tmpExe;
  343. }
  344. $sExec = shell_exec($exe);
  345. $value = $trimmable ? rtrim($sExec) : $sExec;
  346. $output->writeln('');
  347. if (isset($tmpExe)) {
  348. unlink($tmpExe);
  349. }
  350. return $value;
  351. }
  352. if (self::$stty && Terminal::hasSttyAvailable()) {
  353. $sttyMode = shell_exec('stty -g');
  354. shell_exec('stty -echo');
  355. } elseif ($this->isInteractiveInput($inputStream)) {
  356. throw new RuntimeException('Unable to hide the response.');
  357. }
  358. $value = fgets($inputStream, 4096);
  359. if (self::$stty && Terminal::hasSttyAvailable()) {
  360. shell_exec(sprintf('stty %s', $sttyMode));
  361. }
  362. if (false === $value) {
  363. throw new MissingInputException('Aborted.');
  364. }
  365. if ($trimmable) {
  366. $value = trim($value);
  367. }
  368. $output->writeln('');
  369. return $value;
  370. }
  371. /**
  372. * Validates an attempt.
  373. *
  374. * @param callable $interviewer A callable that will ask for a question and return the result
  375. *
  376. * @return mixed The validated response
  377. *
  378. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  379. */
  380. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
  381. {
  382. $error = null;
  383. $attempts = $question->getMaxAttempts();
  384. while (null === $attempts || $attempts--) {
  385. if (null !== $error) {
  386. $this->writeError($output, $error);
  387. }
  388. try {
  389. return $question->getValidator()($interviewer());
  390. } catch (RuntimeException $e) {
  391. throw $e;
  392. } catch (\Exception $error) {
  393. }
  394. }
  395. throw $error;
  396. }
  397. private function isInteractiveInput($inputStream): bool
  398. {
  399. if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
  400. return false;
  401. }
  402. if (null !== self::$stdinIsInteractive) {
  403. return self::$stdinIsInteractive;
  404. }
  405. if (\function_exists('stream_isatty')) {
  406. return self::$stdinIsInteractive = stream_isatty(fopen('php://stdin', 'r'));
  407. }
  408. if (\function_exists('posix_isatty')) {
  409. return self::$stdinIsInteractive = posix_isatty(fopen('php://stdin', 'r'));
  410. }
  411. if (!\function_exists('exec')) {
  412. return self::$stdinIsInteractive = true;
  413. }
  414. exec('stty 2> /dev/null', $output, $status);
  415. return self::$stdinIsInteractive = 1 !== $status;
  416. }
  417. }