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

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

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