QuestionHelper.php 13 KB

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