PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Streaming-Safe-for-Kids/vendor/symfony/console/Helper/QuestionHelper.php

https://gitlab.com/rocs/Streaming-Safe-for-Kids
PHP | 449 lines | 301 code | 50 blank | 98 comment | 39 complexity | 2f8a5a7c883d1f0e829bb8f60bc8b02d 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. $interviewer = function () use ($output, $question) {
  52. return $this->doAsk($output, $question);
  53. };
  54. return $this->validateAttempts($interviewer, $output, $question);
  55. }
  56. /**
  57. * Sets the input stream to read from when interacting with the user.
  58. *
  59. * This is mainly useful for testing purpose.
  60. *
  61. * @param resource $stream The input stream
  62. *
  63. * @throws InvalidArgumentException In case the stream is not a resource
  64. */
  65. public function setInputStream($stream)
  66. {
  67. if (!is_resource($stream)) {
  68. throw new InvalidArgumentException('Input stream must be a valid resource.');
  69. }
  70. $this->inputStream = $stream;
  71. }
  72. /**
  73. * Returns the helper's input stream.
  74. *
  75. * @return resource
  76. */
  77. public function getInputStream()
  78. {
  79. return $this->inputStream;
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function getName()
  85. {
  86. return 'question';
  87. }
  88. /**
  89. * Asks the question to the user.
  90. *
  91. * @param OutputInterface $output
  92. * @param Question $question
  93. *
  94. * @return bool|mixed|null|string
  95. *
  96. * @throws \Exception
  97. * @throws \RuntimeException
  98. */
  99. private function doAsk(OutputInterface $output, Question $question)
  100. {
  101. $this->writePrompt($output, $question);
  102. $inputStream = $this->inputStream ?: STDIN;
  103. $autocomplete = $question->getAutocompleterValues();
  104. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  105. $ret = false;
  106. if ($question->isHidden()) {
  107. try {
  108. $ret = trim($this->getHiddenResponse($output, $inputStream));
  109. } catch (\RuntimeException $e) {
  110. if (!$question->isHiddenFallback()) {
  111. throw $e;
  112. }
  113. }
  114. }
  115. if (false === $ret) {
  116. $ret = fgets($inputStream, 4096);
  117. if (false === $ret) {
  118. throw new RuntimeException('Aborted');
  119. }
  120. $ret = trim($ret);
  121. }
  122. } else {
  123. $ret = trim($this->autocomplete($output, $question, $inputStream));
  124. }
  125. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  126. if ($normalizer = $question->getNormalizer()) {
  127. return $normalizer($ret);
  128. }
  129. return $ret;
  130. }
  131. /**
  132. * Outputs the question prompt.
  133. *
  134. * @param OutputInterface $output
  135. * @param Question $question
  136. */
  137. protected function writePrompt(OutputInterface $output, Question $question)
  138. {
  139. $message = $question->getQuestion();
  140. if ($question instanceof ChoiceQuestion) {
  141. $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
  142. $messages = (array) $question->getQuestion();
  143. foreach ($question->getChoices() as $key => $value) {
  144. $width = $maxWidth - $this->strlen($key);
  145. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  146. }
  147. $output->writeln($messages);
  148. $message = $question->getPrompt();
  149. }
  150. $output->write($message);
  151. }
  152. /**
  153. * Outputs an error message.
  154. *
  155. * @param OutputInterface $output
  156. * @param \Exception $error
  157. */
  158. protected function writeError(OutputInterface $output, \Exception $error)
  159. {
  160. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  161. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  162. } else {
  163. $message = '<error>'.$error->getMessage().'</error>';
  164. }
  165. $output->writeln($message);
  166. }
  167. /**
  168. * Autocompletes a question.
  169. *
  170. * @param OutputInterface $output
  171. * @param Question $question
  172. * @param resource $inputStream
  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. * @param resource $inputStream The handler resource
  270. *
  271. * @return string The answer
  272. *
  273. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  274. */
  275. private function getHiddenResponse(OutputInterface $output, $inputStream)
  276. {
  277. if ('\\' === DIRECTORY_SEPARATOR) {
  278. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  279. // handle code running from a phar
  280. if ('phar:' === substr(__FILE__, 0, 5)) {
  281. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  282. copy($exe, $tmpExe);
  283. $exe = $tmpExe;
  284. }
  285. $value = rtrim(shell_exec($exe));
  286. $output->writeln('');
  287. if (isset($tmpExe)) {
  288. unlink($tmpExe);
  289. }
  290. return $value;
  291. }
  292. if ($this->hasSttyAvailable()) {
  293. $sttyMode = shell_exec('stty -g');
  294. shell_exec('stty -echo');
  295. $value = fgets($inputStream, 4096);
  296. shell_exec(sprintf('stty %s', $sttyMode));
  297. if (false === $value) {
  298. throw new RuntimeException('Aborted');
  299. }
  300. $value = trim($value);
  301. $output->writeln('');
  302. return $value;
  303. }
  304. if (false !== $shell = $this->getShell()) {
  305. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  306. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  307. $value = rtrim(shell_exec($command));
  308. $output->writeln('');
  309. return $value;
  310. }
  311. throw new RuntimeException('Unable to hide the response.');
  312. }
  313. /**
  314. * Validates an attempt.
  315. *
  316. * @param callable $interviewer A callable that will ask for a question and return the result
  317. * @param OutputInterface $output An Output instance
  318. * @param Question $question A Question instance
  319. *
  320. * @return string The validated response
  321. *
  322. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  323. */
  324. private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
  325. {
  326. $error = null;
  327. $attempts = $question->getMaxAttempts();
  328. while (null === $attempts || $attempts--) {
  329. if (null !== $error) {
  330. $this->writeError($output, $error);
  331. }
  332. try {
  333. return call_user_func($question->getValidator(), $interviewer());
  334. } catch (RuntimeException $e) {
  335. throw $e;
  336. } catch (\Exception $error) {
  337. }
  338. }
  339. throw $error;
  340. }
  341. /**
  342. * Returns a valid unix shell.
  343. *
  344. * @return string|bool The valid shell name, false in case no valid shell is found
  345. */
  346. private function getShell()
  347. {
  348. if (null !== self::$shell) {
  349. return self::$shell;
  350. }
  351. self::$shell = false;
  352. if (file_exists('/usr/bin/env')) {
  353. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  354. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  355. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  356. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  357. self::$shell = $sh;
  358. break;
  359. }
  360. }
  361. }
  362. return self::$shell;
  363. }
  364. /**
  365. * Returns whether Stty is available or not.
  366. *
  367. * @return bool
  368. */
  369. private function hasSttyAvailable()
  370. {
  371. if (null !== self::$stty) {
  372. return self::$stty;
  373. }
  374. exec('stty 2>&1', $output, $exitcode);
  375. return self::$stty = $exitcode === 0;
  376. }
  377. }