QuestionHelper.php 14 KB

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