Nav apraksta

QuestionHelper.php 14KB

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