QuestionHelper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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;
  33. /**
  34. * Asks a question to the user.
  35. *
  36. * @return mixed The user answer
  37. *
  38. * @throws RuntimeException If there is no data to read in the input stream
  39. */
  40. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  41. {
  42. if ($output instanceof ConsoleOutputInterface) {
  43. $output = $output->getErrorOutput();
  44. }
  45. if (!$input->isInteractive()) {
  46. return $this->getDefaultAnswer($question);
  47. }
  48. if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
  49. $this->inputStream = $stream;
  50. }
  51. try {
  52. if (!$question->getValidator()) {
  53. return $this->doAsk($output, $question);
  54. }
  55. $interviewer = function () use ($output, $question) {
  56. return $this->doAsk($output, $question);
  57. };
  58. return $this->validateAttempts($interviewer, $output, $question);
  59. } catch (MissingInputException $exception) {
  60. $input->setInteractive(false);
  61. if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
  62. throw $exception;
  63. }
  64. return $fallbackOutput;
  65. }
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function getName()
  71. {
  72. return 'question';
  73. }
  74. /**
  75. * Prevents usage of stty.
  76. */
  77. public static function disableStty()
  78. {
  79. self::$stty = false;
  80. }
  81. /**
  82. * Asks the question to the user.
  83. *
  84. * @return bool|mixed|string|null
  85. *
  86. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  87. */
  88. private function doAsk(OutputInterface $output, Question $question)
  89. {
  90. $this->writePrompt($output, $question);
  91. $inputStream = $this->inputStream ?: STDIN;
  92. $autocomplete = $question->getAutocompleterCallback();
  93. if (null === $autocomplete || !Terminal::hasSttyAvailable()) {
  94. $ret = false;
  95. if ($question->isHidden()) {
  96. try {
  97. $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
  98. $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
  99. } catch (RuntimeException $e) {
  100. if (!$question->isHiddenFallback()) {
  101. throw $e;
  102. }
  103. }
  104. }
  105. if (false === $ret) {
  106. $ret = fgets($inputStream, 4096);
  107. if (false === $ret) {
  108. throw new MissingInputException('Aborted.');
  109. }
  110. if ($question->isTrimmable()) {
  111. $ret = trim($ret);
  112. }
  113. }
  114. } else {
  115. $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
  116. $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
  117. }
  118. if ($output instanceof ConsoleSectionOutput) {
  119. $output->addContent($ret);
  120. }
  121. $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
  122. if ($normalizer = $question->getNormalizer()) {
  123. return $normalizer($ret);
  124. }
  125. return $ret;
  126. }
  127. /**
  128. * @return mixed
  129. */
  130. private function getDefaultAnswer(Question $question)
  131. {
  132. $default = $question->getDefault();
  133. if (null === $default) {
  134. return $default;
  135. }
  136. if ($validator = $question->getValidator()) {
  137. return \call_user_func($question->getValidator(), $default);
  138. } elseif ($question instanceof ChoiceQuestion) {
  139. $choices = $question->getChoices();
  140. if (!$question->isMultiselect()) {
  141. return isset($choices[$default]) ? $choices[$default] : $default;
  142. }
  143. $default = explode(',', $default);
  144. foreach ($default as $k => $v) {
  145. $v = $question->isTrimmable() ? trim($v) : $v;
  146. $default[$k] = isset($choices[$v]) ? $choices[$v] : $v;
  147. }
  148. }
  149. return $default;
  150. }
  151. /**
  152. * Outputs the question prompt.
  153. */
  154. protected function writePrompt(OutputInterface $output, Question $question)
  155. {
  156. $message = $question->getQuestion();
  157. if ($question instanceof ChoiceQuestion) {
  158. $output->writeln(array_merge([
  159. $question->getQuestion(),
  160. ], $this->formatChoiceQuestionChoices($question, 'info')));
  161. $message = $question->getPrompt();
  162. }
  163. $output->write($message);
  164. }
  165. /**
  166. * @param string $tag
  167. *
  168. * @return string[]
  169. */
  170. protected function formatChoiceQuestionChoices(ChoiceQuestion $question, $tag)
  171. {
  172. $messages = [];
  173. $maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
  174. foreach ($choices as $key => $value) {
  175. $padding = str_repeat(' ', $maxWidth - self::strlen($key));
  176. $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
  177. }
  178. return $messages;
  179. }
  180. /**
  181. * Outputs an error message.
  182. */
  183. protected function writeError(OutputInterface $output, \Exception $error)
  184. {
  185. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  186. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  187. } else {
  188. $message = '<error>'.$error->getMessage().'</error>';
  189. }
  190. $output->writeln($message);
  191. }
  192. /**
  193. * Autocompletes a question.
  194. *
  195. * @param resource $inputStream
  196. */
  197. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  198. {
  199. $fullChoice = '';
  200. $ret = '';
  201. $i = 0;
  202. $ofs = -1;
  203. $matches = $autocomplete($ret);
  204. $numMatches = \count($matches);
  205. $sttyMode = shell_exec('stty -g');
  206. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  207. shell_exec('stty -icanon -echo');
  208. // Add highlighted text style
  209. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  210. // Read a keypress
  211. while (!feof($inputStream)) {
  212. $c = fread($inputStream, 1);
  213. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  214. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  215. shell_exec(sprintf('stty %s', $sttyMode));
  216. throw new MissingInputException('Aborted.');
  217. } elseif ("\177" === $c) { // Backspace Character
  218. if (0 === $numMatches && 0 !== $i) {
  219. --$i;
  220. $fullChoice = self::substr($fullChoice, 0, $i);
  221. // Move cursor backwards
  222. $output->write("\033[1D");
  223. }
  224. if (0 === $i) {
  225. $ofs = -1;
  226. $matches = $autocomplete($ret);
  227. $numMatches = \count($matches);
  228. } else {
  229. $numMatches = 0;
  230. }
  231. // Pop the last character off the end of our string
  232. $ret = self::substr($ret, 0, $i);
  233. } elseif ("\033" === $c) {
  234. // Did we read an escape sequence?
  235. $c .= fread($inputStream, 2);
  236. // A = Up Arrow. B = Down Arrow
  237. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  238. if ('A' === $c[2] && -1 === $ofs) {
  239. $ofs = 0;
  240. }
  241. if (0 === $numMatches) {
  242. continue;
  243. }
  244. $ofs += ('A' === $c[2]) ? -1 : 1;
  245. $ofs = ($numMatches + $ofs) % $numMatches;
  246. }
  247. } elseif (\ord($c) < 32) {
  248. if ("\t" === $c || "\n" === $c) {
  249. if ($numMatches > 0 && -1 !== $ofs) {
  250. $ret = (string) $matches[$ofs];
  251. // Echo out remaining chars for current match
  252. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  253. $output->write($remainingCharacters);
  254. $fullChoice .= $remainingCharacters;
  255. $i = self::strlen($fullChoice);
  256. $matches = array_filter(
  257. $autocomplete($ret),
  258. function ($match) use ($ret) {
  259. return '' === $ret || 0 === strpos($match, $ret);
  260. }
  261. );
  262. $numMatches = \count($matches);
  263. $ofs = -1;
  264. }
  265. if ("\n" === $c) {
  266. $output->write($c);
  267. break;
  268. }
  269. $numMatches = 0;
  270. }
  271. continue;
  272. } else {
  273. if ("\x80" <= $c) {
  274. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  275. }
  276. $output->write($c);
  277. $ret .= $c;
  278. $fullChoice .= $c;
  279. ++$i;
  280. $tempRet = $ret;
  281. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  282. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  283. }
  284. $numMatches = 0;
  285. $ofs = 0;
  286. foreach ($autocomplete($ret) as $value) {
  287. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  288. if (0 === strpos($value, $tempRet)) {
  289. $matches[$numMatches++] = $value;
  290. }
  291. }
  292. }
  293. // Erase characters from cursor to end of line
  294. $output->write("\033[K");
  295. if ($numMatches > 0 && -1 !== $ofs) {
  296. // Save cursor position
  297. $output->write("\0337");
  298. // Write highlighted text, complete the partially entered response
  299. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  300. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  301. // Restore cursor position
  302. $output->write("\0338");
  303. }
  304. }
  305. // Reset stty so it behaves normally again
  306. shell_exec(sprintf('stty %s', $sttyMode));
  307. return $fullChoice;
  308. }
  309. private function mostRecentlyEnteredValue(string $entered): string
  310. {
  311. // Determine the most recent value that the user entered
  312. if (false === strpos($entered, ',')) {
  313. return $entered;
  314. }
  315. $choices = explode(',', $entered);
  316. if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
  317. return $lastChoice;
  318. }
  319. return $entered;
  320. }
  321. /**
  322. * Gets a hidden response from user.
  323. *
  324. * @param resource $inputStream The handler resource
  325. * @param bool $trimmable Is the answer trimmable
  326. *
  327. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  328. */
  329. private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
  330. {
  331. if ('\\' === \DIRECTORY_SEPARATOR) {
  332. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  333. // handle code running from a phar
  334. if ('phar:' === substr(__FILE__, 0, 5)) {
  335. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  336. copy($exe, $tmpExe);
  337. $exe = $tmpExe;
  338. }
  339. $sExec = shell_exec($exe);
  340. $value = $trimmable ? rtrim($sExec) : $sExec;
  341. $output->writeln('');
  342. if (isset($tmpExe)) {
  343. unlink($tmpExe);
  344. }
  345. return $value;
  346. }
  347. if (Terminal::hasSttyAvailable()) {
  348. $sttyMode = shell_exec('stty -g');
  349. shell_exec('stty -echo');
  350. $value = fgets($inputStream, 4096);
  351. shell_exec(sprintf('stty %s', $sttyMode));
  352. if (false === $value) {
  353. throw new MissingInputException('Aborted.');
  354. }
  355. if ($trimmable) {
  356. $value = trim($value);
  357. }
  358. $output->writeln('');
  359. return $value;
  360. }
  361. if (false !== $shell = $this->getShell()) {
  362. $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
  363. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  364. $sCommand = shell_exec($command);
  365. $value = $trimmable ? rtrim($sCommand) : $sCommand;
  366. $output->writeln('');
  367. return $value;
  368. }
  369. throw new RuntimeException('Unable to hide the response.');
  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. /**
  398. * Returns a valid unix shell.
  399. *
  400. * @return string|bool The valid shell name, false in case no valid shell is found
  401. */
  402. private function getShell()
  403. {
  404. if (null !== self::$shell) {
  405. return self::$shell;
  406. }
  407. self::$shell = false;
  408. if (file_exists('/usr/bin/env')) {
  409. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  410. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  411. foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
  412. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  413. self::$shell = $sh;
  414. break;
  415. }
  416. }
  417. }
  418. return self::$shell;
  419. }
  420. }