QuestionHelper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 RuntimeException In case the fallback is deactivated and the response cannot be hidden
  118. */
  119. private function doAsk(OutputInterface $output, Question $question)
  120. {
  121. $this->writePrompt($output, $question);
  122. $inputStream = $this->inputStream ?: STDIN;
  123. $autocomplete = $question->getAutocompleterValues();
  124. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  125. $ret = false;
  126. if ($question->isHidden()) {
  127. try {
  128. $ret = trim($this->getHiddenResponse($output, $inputStream));
  129. } catch (RuntimeException $e) {
  130. if (!$question->isHiddenFallback()) {
  131. throw $e;
  132. }
  133. }
  134. }
  135. if (false === $ret) {
  136. $ret = fgets($inputStream, 4096);
  137. if (false === $ret) {
  138. throw new RuntimeException('Aborted');
  139. }
  140. $ret = trim($ret);
  141. }
  142. } else {
  143. $ret = trim($this->autocomplete($output, $question, $inputStream));
  144. }
  145. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  146. if ($normalizer = $question->getNormalizer()) {
  147. return $normalizer($ret);
  148. }
  149. return $ret;
  150. }
  151. /**
  152. * Outputs the question prompt.
  153. *
  154. * @param OutputInterface $output
  155. * @param Question $question
  156. */
  157. protected function writePrompt(OutputInterface $output, Question $question)
  158. {
  159. $message = $question->getQuestion();
  160. if ($question instanceof ChoiceQuestion) {
  161. $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
  162. $messages = (array) $question->getQuestion();
  163. foreach ($question->getChoices() as $key => $value) {
  164. $width = $maxWidth - $this->strlen($key);
  165. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  166. }
  167. $output->writeln($messages);
  168. $message = $question->getPrompt();
  169. }
  170. $output->write($message);
  171. }
  172. /**
  173. * Outputs an error message.
  174. *
  175. * @param OutputInterface $output
  176. * @param \Exception $error
  177. */
  178. protected function writeError(OutputInterface $output, \Exception $error)
  179. {
  180. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  181. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  182. } else {
  183. $message = '<error>'.$error->getMessage().'</error>';
  184. }
  185. $output->writeln($message);
  186. }
  187. /**
  188. * Autocompletes a question.
  189. *
  190. * @param OutputInterface $output
  191. * @param Question $question
  192. * @param resource $inputStream
  193. *
  194. * @return string
  195. */
  196. private function autocomplete(OutputInterface $output, Question $question, $inputStream)
  197. {
  198. $autocomplete = $question->getAutocompleterValues();
  199. $ret = '';
  200. $i = 0;
  201. $ofs = -1;
  202. $matches = $autocomplete;
  203. $numMatches = count($matches);
  204. $sttyMode = shell_exec('stty -g');
  205. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  206. shell_exec('stty -icanon -echo');
  207. // Add highlighted text style
  208. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  209. // Read a keypress
  210. while (!feof($inputStream)) {
  211. $c = fread($inputStream, 1);
  212. // Backspace Character
  213. if ("\177" === $c) {
  214. if (0 === $numMatches && 0 !== $i) {
  215. --$i;
  216. // Move cursor backwards
  217. $output->write("\033[1D");
  218. }
  219. if ($i === 0) {
  220. $ofs = -1;
  221. $matches = $autocomplete;
  222. $numMatches = count($matches);
  223. } else {
  224. $numMatches = 0;
  225. }
  226. // Pop the last character off the end of our string
  227. $ret = substr($ret, 0, $i);
  228. } elseif ("\033" === $c) {
  229. // Did we read an escape sequence?
  230. $c .= fread($inputStream, 2);
  231. // A = Up Arrow. B = Down Arrow
  232. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  233. if ('A' === $c[2] && -1 === $ofs) {
  234. $ofs = 0;
  235. }
  236. if (0 === $numMatches) {
  237. continue;
  238. }
  239. $ofs += ('A' === $c[2]) ? -1 : 1;
  240. $ofs = ($numMatches + $ofs) % $numMatches;
  241. }
  242. } elseif (ord($c) < 32) {
  243. if ("\t" === $c || "\n" === $c) {
  244. if ($numMatches > 0 && -1 !== $ofs) {
  245. $ret = $matches[$ofs];
  246. // Echo out remaining chars for current match
  247. $output->write(substr($ret, $i));
  248. $i = strlen($ret);
  249. }
  250. if ("\n" === $c) {
  251. $output->write($c);
  252. break;
  253. }
  254. $numMatches = 0;
  255. }
  256. continue;
  257. } else {
  258. $output->write($c);
  259. $ret .= $c;
  260. ++$i;
  261. $numMatches = 0;
  262. $ofs = 0;
  263. foreach ($autocomplete as $value) {
  264. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  265. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  266. $matches[$numMatches++] = $value;
  267. }
  268. }
  269. }
  270. // Erase characters from cursor to end of line
  271. $output->write("\033[K");
  272. if ($numMatches > 0 && -1 !== $ofs) {
  273. // Save cursor position
  274. $output->write("\0337");
  275. // Write highlighted text
  276. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  277. // Restore cursor position
  278. $output->write("\0338");
  279. }
  280. }
  281. // Reset stty so it behaves normally again
  282. shell_exec(sprintf('stty %s', $sttyMode));
  283. return $ret;
  284. }
  285. /**
  286. * Gets a hidden response from user.
  287. *
  288. * @param OutputInterface $output An Output instance
  289. * @param resource $inputStream The handler resource
  290. *
  291. * @return string The answer
  292. *
  293. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  294. */
  295. private function getHiddenResponse(OutputInterface $output, $inputStream)
  296. {
  297. if ('\\' === DIRECTORY_SEPARATOR) {
  298. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  299. // handle code running from a phar
  300. if ('phar:' === substr(__FILE__, 0, 5)) {
  301. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  302. copy($exe, $tmpExe);
  303. $exe = $tmpExe;
  304. }
  305. $value = rtrim(shell_exec($exe));
  306. $output->writeln('');
  307. if (isset($tmpExe)) {
  308. unlink($tmpExe);
  309. }
  310. return $value;
  311. }
  312. if ($this->hasSttyAvailable()) {
  313. $sttyMode = shell_exec('stty -g');
  314. shell_exec('stty -echo');
  315. $value = fgets($inputStream, 4096);
  316. shell_exec(sprintf('stty %s', $sttyMode));
  317. if (false === $value) {
  318. throw new RuntimeException('Aborted');
  319. }
  320. $value = trim($value);
  321. $output->writeln('');
  322. return $value;
  323. }
  324. if (false !== $shell = $this->getShell()) {
  325. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  326. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  327. $value = rtrim(shell_exec($command));
  328. $output->writeln('');
  329. return $value;
  330. }
  331. throw new RuntimeException('Unable to hide the response.');
  332. }
  333. /**
  334. * Validates an attempt.
  335. *
  336. * @param callable $interviewer A callable that will ask for a question and return the result
  337. * @param OutputInterface $output An Output instance
  338. * @param Question $question A Question instance
  339. *
  340. * @return mixed The validated response
  341. *
  342. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  343. */
  344. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
  345. {
  346. $error = null;
  347. $attempts = $question->getMaxAttempts();
  348. while (null === $attempts || $attempts--) {
  349. if (null !== $error) {
  350. $this->writeError($output, $error);
  351. }
  352. try {
  353. return call_user_func($question->getValidator(), $interviewer());
  354. } catch (RuntimeException $e) {
  355. throw $e;
  356. } catch (\Exception $error) {
  357. }
  358. }
  359. throw $error;
  360. }
  361. /**
  362. * Returns a valid unix shell.
  363. *
  364. * @return string|bool The valid shell name, false in case no valid shell is found
  365. */
  366. private function getShell()
  367. {
  368. if (null !== self::$shell) {
  369. return self::$shell;
  370. }
  371. self::$shell = false;
  372. if (file_exists('/usr/bin/env')) {
  373. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  374. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  375. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  376. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  377. self::$shell = $sh;
  378. break;
  379. }
  380. }
  381. }
  382. return self::$shell;
  383. }
  384. /**
  385. * Returns whether Stty is available or not.
  386. *
  387. * @return bool
  388. */
  389. private function hasSttyAvailable()
  390. {
  391. if (null !== self::$stty) {
  392. return self::$stty;
  393. }
  394. exec('stty 2>&1', $output, $exitcode);
  395. return self::$stty = $exitcode === 0;
  396. }
  397. }