PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/console/Helper/QuestionHelper.php

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