QuestionHelper.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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\ConsoleSectionOutput;
  18. use Symfony\Component\Console\Output\OutputInterface;
  19. use Symfony\Component\Console\Question\ChoiceQuestion;
  20. use Symfony\Component\Console\Question\Question;
  21. /**
  22. * The QuestionHelper class provides helpers to interact with the user.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. */
  26. class QuestionHelper extends Helper
  27. {
  28. private $inputStream;
  29. private static $shell;
  30. private static $stty;
  31. /**
  32. * Asks a question to the user.
  33. *
  34. * @return mixed 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. $default = $question->getDefault();
  45. if (null === $default) {
  46. return $default;
  47. }
  48. if ($validator = $question->getValidator()) {
  49. return \call_user_func($question->getValidator(), $default);
  50. } elseif ($question instanceof ChoiceQuestion) {
  51. $choices = $question->getChoices();
  52. if (!$question->isMultiselect()) {
  53. return isset($choices[$default]) ? $choices[$default] : $default;
  54. }
  55. $default = explode(',', $default);
  56. foreach ($default as $k => $v) {
  57. $v = trim($v);
  58. $default[$k] = isset($choices[$v]) ? $choices[$v] : $v;
  59. }
  60. }
  61. return $default;
  62. }
  63. if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
  64. $this->inputStream = $stream;
  65. }
  66. if (!$question->getValidator()) {
  67. return $this->doAsk($output, $question);
  68. }
  69. $interviewer = function () use ($output, $question) {
  70. return $this->doAsk($output, $question);
  71. };
  72. return $this->validateAttempts($interviewer, $output, $question);
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function getName()
  78. {
  79. return 'question';
  80. }
  81. /**
  82. * Prevents usage of stty.
  83. */
  84. public static function disableStty()
  85. {
  86. self::$stty = false;
  87. }
  88. /**
  89. * Asks the question to the user.
  90. *
  91. * @return bool|mixed|string|null
  92. *
  93. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  94. */
  95. private function doAsk(OutputInterface $output, Question $question)
  96. {
  97. $this->writePrompt($output, $question);
  98. $inputStream = $this->inputStream ?: STDIN;
  99. $autocomplete = $question->getAutocompleterCallback();
  100. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  101. $ret = false;
  102. if ($question->isHidden()) {
  103. try {
  104. $ret = trim($this->getHiddenResponse($output, $inputStream));
  105. } catch (RuntimeException $e) {
  106. if (!$question->isHiddenFallback()) {
  107. throw $e;
  108. }
  109. }
  110. }
  111. if (false === $ret) {
  112. $ret = fgets($inputStream, 4096);
  113. if (false === $ret) {
  114. throw new RuntimeException('Aborted.');
  115. }
  116. $ret = trim($ret);
  117. }
  118. } else {
  119. $ret = trim($this->autocomplete($output, $question, $inputStream, $autocomplete));
  120. }
  121. if ($output instanceof ConsoleSectionOutput) {
  122. $output->addContent($ret);
  123. }
  124. $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
  125. if ($normalizer = $question->getNormalizer()) {
  126. return $normalizer($ret);
  127. }
  128. return $ret;
  129. }
  130. /**
  131. * Outputs the question prompt.
  132. */
  133. protected function writePrompt(OutputInterface $output, Question $question)
  134. {
  135. $message = $question->getQuestion();
  136. if ($question instanceof ChoiceQuestion) {
  137. $maxWidth = max(array_map([$this, 'strlen'], array_keys($question->getChoices())));
  138. $messages = (array) $question->getQuestion();
  139. foreach ($question->getChoices() as $key => $value) {
  140. $width = $maxWidth - $this->strlen($key);
  141. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  142. }
  143. $output->writeln($messages);
  144. $message = $question->getPrompt();
  145. }
  146. $output->write($message);
  147. }
  148. /**
  149. * Outputs an error message.
  150. */
  151. protected function writeError(OutputInterface $output, \Exception $error)
  152. {
  153. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  154. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  155. } else {
  156. $message = '<error>'.$error->getMessage().'</error>';
  157. }
  158. $output->writeln($message);
  159. }
  160. /**
  161. * Autocompletes a question.
  162. *
  163. * @param resource $inputStream
  164. */
  165. private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
  166. {
  167. $fullChoice = '';
  168. $ret = '';
  169. $i = 0;
  170. $ofs = -1;
  171. $matches = $autocomplete($ret);
  172. $numMatches = \count($matches);
  173. $sttyMode = shell_exec('stty -g');
  174. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  175. shell_exec('stty -icanon -echo');
  176. // Add highlighted text style
  177. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  178. // Read a keypress
  179. while (!feof($inputStream)) {
  180. $c = fread($inputStream, 1);
  181. // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
  182. if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
  183. shell_exec(sprintf('stty %s', $sttyMode));
  184. throw new RuntimeException('Aborted.');
  185. } elseif ("\177" === $c) { // Backspace Character
  186. if (0 === $numMatches && 0 !== $i) {
  187. --$i;
  188. $fullChoice = substr($fullChoice, 0, -1);
  189. // Move cursor backwards
  190. $output->write("\033[1D");
  191. }
  192. if (0 === $i) {
  193. $ofs = -1;
  194. $matches = $autocomplete($ret);
  195. $numMatches = \count($matches);
  196. } else {
  197. $numMatches = 0;
  198. }
  199. // Pop the last character off the end of our string
  200. $ret = substr($ret, 0, $i);
  201. } elseif ("\033" === $c) {
  202. // Did we read an escape sequence?
  203. $c .= fread($inputStream, 2);
  204. // A = Up Arrow. B = Down Arrow
  205. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  206. if ('A' === $c[2] && -1 === $ofs) {
  207. $ofs = 0;
  208. }
  209. if (0 === $numMatches) {
  210. continue;
  211. }
  212. $ofs += ('A' === $c[2]) ? -1 : 1;
  213. $ofs = ($numMatches + $ofs) % $numMatches;
  214. }
  215. } elseif (\ord($c) < 32) {
  216. if ("\t" === $c || "\n" === $c) {
  217. if ($numMatches > 0 && -1 !== $ofs) {
  218. $ret = (string) $matches[$ofs];
  219. // Echo out remaining chars for current match
  220. $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
  221. $output->write($remainingCharacters);
  222. $fullChoice .= $remainingCharacters;
  223. $i = \strlen($fullChoice);
  224. $matches = array_filter(
  225. $autocomplete($ret),
  226. function ($match) use ($ret) {
  227. return '' === $ret || 0 === strpos($match, $ret);
  228. }
  229. );
  230. $numMatches = \count($matches);
  231. $ofs = -1;
  232. }
  233. if ("\n" === $c) {
  234. $output->write($c);
  235. break;
  236. }
  237. }
  238. continue;
  239. } else {
  240. if ("\x80" <= $c) {
  241. $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
  242. }
  243. $output->write($c);
  244. $ret .= $c;
  245. $fullChoice .= $c;
  246. ++$i;
  247. $tempRet = $ret;
  248. if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
  249. $tempRet = $this->mostRecentlyEnteredValue($fullChoice);
  250. }
  251. $numMatches = 0;
  252. $ofs = 0;
  253. foreach ($autocomplete($ret) as $value) {
  254. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  255. if (0 === strpos($value, $tempRet)) {
  256. $matches[$numMatches++] = $value;
  257. }
  258. }
  259. }
  260. // Erase characters from cursor to end of line
  261. $output->write("\033[K");
  262. if ($numMatches > 0 && -1 !== $ofs) {
  263. // Save cursor position
  264. $output->write("\0337");
  265. // Write highlighted text, complete the partially entered response
  266. $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
  267. $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
  268. // Restore cursor position
  269. $output->write("\0338");
  270. }
  271. }
  272. // Reset stty so it behaves normally again
  273. shell_exec(sprintf('stty %s', $sttyMode));
  274. return $fullChoice;
  275. }
  276. private function mostRecentlyEnteredValue($entered)
  277. {
  278. // Determine the most recent value that the user entered
  279. if (false === strpos($entered, ',')) {
  280. return $entered;
  281. }
  282. $choices = explode(',', $entered);
  283. if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
  284. return $lastChoice;
  285. }
  286. return $entered;
  287. }
  288. /**
  289. * Gets a hidden response from user.
  290. *
  291. * @param OutputInterface $output An Output instance
  292. * @param resource $inputStream The handler resource
  293. *
  294. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  295. */
  296. private function getHiddenResponse(OutputInterface $output, $inputStream): string
  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 = 'csh' === $shell ? '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 $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 (['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. private function hasSttyAvailable(): bool
  389. {
  390. if (null !== self::$stty) {
  391. return self::$stty;
  392. }
  393. exec('stty 2>&1', $output, $exitcode);
  394. return self::$stty = 0 === $exitcode;
  395. }
  396. }