QuestionHelper.php 13KB

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