QuestionHelper.php 14 KB

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