No Description

QuestionHelper.php 12KB

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