QuestionHelper.php 16 KB

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