PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/martinstti/silex-microframework-rest
PHP | 449 lines | 300 code | 51 blank | 98 comment | 39 complexity | 5183c152ef1e75f299efa777cb06b263 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 = fgets($inputStream, 4096);
  120. if (false === $ret) {
  121. throw new \RuntimeException('Aborted');
  122. }
  123. $ret = trim($ret);
  124. }
  125. } else {
  126. $ret = trim($this->autocomplete($output, $question, $inputStream));
  127. }
  128. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  129. if ($normalizer = $question->getNormalizer()) {
  130. return $normalizer($ret);
  131. }
  132. return $ret;
  133. }
  134. /**
  135. * Outputs the question prompt.
  136. *
  137. * @param OutputInterface $output
  138. * @param Question $question
  139. */
  140. protected function writePrompt(OutputInterface $output, Question $question)
  141. {
  142. $message = $question->getQuestion();
  143. if ($question instanceof ChoiceQuestion) {
  144. $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
  145. $messages = (array) $question->getQuestion();
  146. foreach ($question->getChoices() as $key => $value) {
  147. $width = $maxWidth - $this->strlen($key);
  148. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  149. }
  150. $output->writeln($messages);
  151. $message = $question->getPrompt();
  152. }
  153. $output->write($message);
  154. }
  155. /**
  156. * Outputs an error message.
  157. *
  158. * @param OutputInterface $output
  159. * @param \Exception $error
  160. */
  161. protected function writeError(OutputInterface $output, \Exception $error)
  162. {
  163. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  164. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  165. } else {
  166. $message = '<error>'.$error->getMessage().'</error>';
  167. }
  168. $output->writeln($message);
  169. }
  170. /**
  171. * Autocompletes a question.
  172. *
  173. * @param OutputInterface $output
  174. * @param Question $question
  175. *
  176. * @return string
  177. */
  178. private function autocomplete(OutputInterface $output, Question $question, $inputStream)
  179. {
  180. $autocomplete = $question->getAutocompleterValues();
  181. $ret = '';
  182. $i = 0;
  183. $ofs = -1;
  184. $matches = $autocomplete;
  185. $numMatches = count($matches);
  186. $sttyMode = shell_exec('stty -g');
  187. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  188. shell_exec('stty -icanon -echo');
  189. // Add highlighted text style
  190. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  191. // Read a keypress
  192. while (!feof($inputStream)) {
  193. $c = fread($inputStream, 1);
  194. // Backspace Character
  195. if ("\177" === $c) {
  196. if (0 === $numMatches && 0 !== $i) {
  197. --$i;
  198. // Move cursor backwards
  199. $output->write("\033[1D");
  200. }
  201. if ($i === 0) {
  202. $ofs = -1;
  203. $matches = $autocomplete;
  204. $numMatches = count($matches);
  205. } else {
  206. $numMatches = 0;
  207. }
  208. // Pop the last character off the end of our string
  209. $ret = substr($ret, 0, $i);
  210. } elseif ("\033" === $c) {
  211. // Did we read an escape sequence?
  212. $c .= fread($inputStream, 2);
  213. // A = Up Arrow. B = Down Arrow
  214. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  215. if ('A' === $c[2] && -1 === $ofs) {
  216. $ofs = 0;
  217. }
  218. if (0 === $numMatches) {
  219. continue;
  220. }
  221. $ofs += ('A' === $c[2]) ? -1 : 1;
  222. $ofs = ($numMatches + $ofs) % $numMatches;
  223. }
  224. } elseif (ord($c) < 32) {
  225. if ("\t" === $c || "\n" === $c) {
  226. if ($numMatches > 0 && -1 !== $ofs) {
  227. $ret = $matches[$ofs];
  228. // Echo out remaining chars for current match
  229. $output->write(substr($ret, $i));
  230. $i = strlen($ret);
  231. }
  232. if ("\n" === $c) {
  233. $output->write($c);
  234. break;
  235. }
  236. $numMatches = 0;
  237. }
  238. continue;
  239. } else {
  240. $output->write($c);
  241. $ret .= $c;
  242. ++$i;
  243. $numMatches = 0;
  244. $ofs = 0;
  245. foreach ($autocomplete as $value) {
  246. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  247. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  248. $matches[$numMatches++] = $value;
  249. }
  250. }
  251. }
  252. // Erase characters from cursor to end of line
  253. $output->write("\033[K");
  254. if ($numMatches > 0 && -1 !== $ofs) {
  255. // Save cursor position
  256. $output->write("\0337");
  257. // Write highlighted text
  258. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  259. // Restore cursor position
  260. $output->write("\0338");
  261. }
  262. }
  263. // Reset stty so it behaves normally again
  264. shell_exec(sprintf('stty %s', $sttyMode));
  265. return $ret;
  266. }
  267. /**
  268. * Gets a hidden response from user.
  269. *
  270. * @param OutputInterface $output An Output instance
  271. *
  272. * @return string The answer
  273. *
  274. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  275. */
  276. private function getHiddenResponse(OutputInterface $output, $inputStream)
  277. {
  278. if ('\\' === DIRECTORY_SEPARATOR) {
  279. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  280. // handle code running from a phar
  281. if ('phar:' === substr(__FILE__, 0, 5)) {
  282. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  283. copy($exe, $tmpExe);
  284. $exe = $tmpExe;
  285. }
  286. $value = rtrim(shell_exec($exe));
  287. $output->writeln('');
  288. if (isset($tmpExe)) {
  289. unlink($tmpExe);
  290. }
  291. return $value;
  292. }
  293. if ($this->hasSttyAvailable()) {
  294. $sttyMode = shell_exec('stty -g');
  295. shell_exec('stty -echo');
  296. $value = fgets($inputStream, 4096);
  297. shell_exec(sprintf('stty %s', $sttyMode));
  298. if (false === $value) {
  299. throw new RuntimeException('Aborted');
  300. }
  301. $value = trim($value);
  302. $output->writeln('');
  303. return $value;
  304. }
  305. if (false !== $shell = $this->getShell()) {
  306. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  307. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  308. $value = rtrim(shell_exec($command));
  309. $output->writeln('');
  310. return $value;
  311. }
  312. throw new RuntimeException('Unable to hide the response.');
  313. }
  314. /**
  315. * Validates an attempt.
  316. *
  317. * @param callable $interviewer A callable that will ask for a question and return the result
  318. * @param OutputInterface $output An Output instance
  319. * @param Question $question A Question instance
  320. *
  321. * @return string The validated response
  322. *
  323. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  324. */
  325. private function validateAttempts($interviewer, OutputInterface $output, Question $question)
  326. {
  327. $error = null;
  328. $attempts = $question->getMaxAttempts();
  329. while (null === $attempts || $attempts--) {
  330. if (null !== $error) {
  331. $this->writeError($output, $error);
  332. }
  333. try {
  334. return call_user_func($question->getValidator(), $interviewer());
  335. } catch (\Exception $error) {
  336. }
  337. }
  338. throw $error;
  339. }
  340. /**
  341. * Returns a valid unix shell.
  342. *
  343. * @return string|bool The valid shell name, false in case no valid shell is found
  344. */
  345. private function getShell()
  346. {
  347. if (null !== self::$shell) {
  348. return self::$shell;
  349. }
  350. self::$shell = false;
  351. if (file_exists('/usr/bin/env')) {
  352. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  353. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  354. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  355. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  356. self::$shell = $sh;
  357. break;
  358. }
  359. }
  360. }
  361. return self::$shell;
  362. }
  363. /**
  364. * Returns whether Stty is available or not.
  365. *
  366. * @return bool
  367. */
  368. private function hasSttyAvailable()
  369. {
  370. if (null !== self::$stty) {
  371. return self::$stty;
  372. }
  373. exec('stty 2>&1', $output, $exitcode);
  374. return self::$stty = $exitcode === 0;
  375. }
  376. }