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