QuestionHelper.php 13 KB

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