annotate vendor/symfony/console/Helper/QuestionHelper.php @ 14:1fec387a4317

Update Drupal core to 8.5.2 via Composer
author Chris Cannam
date Mon, 23 Apr 2018 09:46:53 +0100
parents 7a779792577d
children c2387f117808
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\Console\Helper;
Chris@0 13
Chris@0 14 use Symfony\Component\Console\Exception\InvalidArgumentException;
Chris@0 15 use Symfony\Component\Console\Exception\RuntimeException;
Chris@14 16 use Symfony\Component\Console\Formatter\OutputFormatter;
Chris@14 17 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
Chris@0 18 use Symfony\Component\Console\Input\InputInterface;
Chris@0 19 use Symfony\Component\Console\Input\StreamableInputInterface;
Chris@0 20 use Symfony\Component\Console\Output\ConsoleOutputInterface;
Chris@0 21 use Symfony\Component\Console\Output\OutputInterface;
Chris@0 22 use Symfony\Component\Console\Question\Question;
Chris@0 23 use Symfony\Component\Console\Question\ChoiceQuestion;
Chris@0 24
Chris@0 25 /**
Chris@0 26 * The QuestionHelper class provides helpers to interact with the user.
Chris@0 27 *
Chris@0 28 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 29 */
Chris@0 30 class QuestionHelper extends Helper
Chris@0 31 {
Chris@0 32 private $inputStream;
Chris@0 33 private static $shell;
Chris@0 34 private static $stty;
Chris@0 35
Chris@0 36 /**
Chris@0 37 * Asks a question to the user.
Chris@0 38 *
Chris@0 39 * @return mixed The user answer
Chris@0 40 *
Chris@0 41 * @throws RuntimeException If there is no data to read in the input stream
Chris@0 42 */
Chris@0 43 public function ask(InputInterface $input, OutputInterface $output, Question $question)
Chris@0 44 {
Chris@0 45 if ($output instanceof ConsoleOutputInterface) {
Chris@0 46 $output = $output->getErrorOutput();
Chris@0 47 }
Chris@0 48
Chris@0 49 if (!$input->isInteractive()) {
Chris@14 50 if ($question instanceof ChoiceQuestion) {
Chris@14 51 $choices = $question->getChoices();
Chris@14 52
Chris@14 53 return $choices[$question->getDefault()];
Chris@14 54 }
Chris@14 55
Chris@0 56 return $question->getDefault();
Chris@0 57 }
Chris@0 58
Chris@0 59 if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
Chris@0 60 $this->inputStream = $stream;
Chris@0 61 }
Chris@0 62
Chris@0 63 if (!$question->getValidator()) {
Chris@0 64 return $this->doAsk($output, $question);
Chris@0 65 }
Chris@0 66
Chris@0 67 $interviewer = function () use ($output, $question) {
Chris@0 68 return $this->doAsk($output, $question);
Chris@0 69 };
Chris@0 70
Chris@0 71 return $this->validateAttempts($interviewer, $output, $question);
Chris@0 72 }
Chris@0 73
Chris@0 74 /**
Chris@0 75 * Sets the input stream to read from when interacting with the user.
Chris@0 76 *
Chris@0 77 * This is mainly useful for testing purpose.
Chris@0 78 *
Chris@0 79 * @deprecated since version 3.2, to be removed in 4.0. Use
Chris@0 80 * StreamableInputInterface::setStream() instead.
Chris@0 81 *
Chris@0 82 * @param resource $stream The input stream
Chris@0 83 *
Chris@0 84 * @throws InvalidArgumentException In case the stream is not a resource
Chris@0 85 */
Chris@0 86 public function setInputStream($stream)
Chris@0 87 {
Chris@14 88 @trigger_error(sprintf('The %s() method is deprecated since Symfony 3.2 and will be removed in 4.0. Use %s::setStream() instead.', __METHOD__, StreamableInputInterface::class), E_USER_DEPRECATED);
Chris@0 89
Chris@0 90 if (!is_resource($stream)) {
Chris@0 91 throw new InvalidArgumentException('Input stream must be a valid resource.');
Chris@0 92 }
Chris@0 93
Chris@0 94 $this->inputStream = $stream;
Chris@0 95 }
Chris@0 96
Chris@0 97 /**
Chris@0 98 * Returns the helper's input stream.
Chris@0 99 *
Chris@0 100 * @deprecated since version 3.2, to be removed in 4.0. Use
Chris@0 101 * StreamableInputInterface::getStream() instead.
Chris@0 102 *
Chris@0 103 * @return resource
Chris@0 104 */
Chris@0 105 public function getInputStream()
Chris@0 106 {
Chris@0 107 if (0 === func_num_args() || func_get_arg(0)) {
Chris@14 108 @trigger_error(sprintf('The %s() method is deprecated since Symfony 3.2 and will be removed in 4.0. Use %s::getStream() instead.', __METHOD__, StreamableInputInterface::class), E_USER_DEPRECATED);
Chris@0 109 }
Chris@0 110
Chris@0 111 return $this->inputStream;
Chris@0 112 }
Chris@0 113
Chris@0 114 /**
Chris@0 115 * {@inheritdoc}
Chris@0 116 */
Chris@0 117 public function getName()
Chris@0 118 {
Chris@0 119 return 'question';
Chris@0 120 }
Chris@0 121
Chris@0 122 /**
Chris@14 123 * Prevents usage of stty.
Chris@14 124 */
Chris@14 125 public static function disableStty()
Chris@14 126 {
Chris@14 127 self::$stty = false;
Chris@14 128 }
Chris@14 129
Chris@14 130 /**
Chris@0 131 * Asks the question to the user.
Chris@0 132 *
Chris@0 133 * @return bool|mixed|null|string
Chris@0 134 *
Chris@12 135 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
Chris@0 136 */
Chris@0 137 private function doAsk(OutputInterface $output, Question $question)
Chris@0 138 {
Chris@0 139 $this->writePrompt($output, $question);
Chris@0 140
Chris@0 141 $inputStream = $this->inputStream ?: STDIN;
Chris@0 142 $autocomplete = $question->getAutocompleterValues();
Chris@0 143
Chris@0 144 if (null === $autocomplete || !$this->hasSttyAvailable()) {
Chris@0 145 $ret = false;
Chris@0 146 if ($question->isHidden()) {
Chris@0 147 try {
Chris@0 148 $ret = trim($this->getHiddenResponse($output, $inputStream));
Chris@12 149 } catch (RuntimeException $e) {
Chris@0 150 if (!$question->isHiddenFallback()) {
Chris@0 151 throw $e;
Chris@0 152 }
Chris@0 153 }
Chris@0 154 }
Chris@0 155
Chris@0 156 if (false === $ret) {
Chris@0 157 $ret = fgets($inputStream, 4096);
Chris@0 158 if (false === $ret) {
Chris@0 159 throw new RuntimeException('Aborted');
Chris@0 160 }
Chris@0 161 $ret = trim($ret);
Chris@0 162 }
Chris@0 163 } else {
Chris@14 164 $ret = trim($this->autocomplete($output, $question, $inputStream, is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
Chris@0 165 }
Chris@0 166
Chris@0 167 $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
Chris@0 168
Chris@0 169 if ($normalizer = $question->getNormalizer()) {
Chris@0 170 return $normalizer($ret);
Chris@0 171 }
Chris@0 172
Chris@0 173 return $ret;
Chris@0 174 }
Chris@0 175
Chris@0 176 /**
Chris@0 177 * Outputs the question prompt.
Chris@0 178 */
Chris@0 179 protected function writePrompt(OutputInterface $output, Question $question)
Chris@0 180 {
Chris@0 181 $message = $question->getQuestion();
Chris@0 182
Chris@0 183 if ($question instanceof ChoiceQuestion) {
Chris@0 184 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
Chris@0 185
Chris@0 186 $messages = (array) $question->getQuestion();
Chris@0 187 foreach ($question->getChoices() as $key => $value) {
Chris@0 188 $width = $maxWidth - $this->strlen($key);
Chris@0 189 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
Chris@0 190 }
Chris@0 191
Chris@0 192 $output->writeln($messages);
Chris@0 193
Chris@0 194 $message = $question->getPrompt();
Chris@0 195 }
Chris@0 196
Chris@0 197 $output->write($message);
Chris@0 198 }
Chris@0 199
Chris@0 200 /**
Chris@0 201 * Outputs an error message.
Chris@0 202 */
Chris@0 203 protected function writeError(OutputInterface $output, \Exception $error)
Chris@0 204 {
Chris@0 205 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
Chris@0 206 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
Chris@0 207 } else {
Chris@0 208 $message = '<error>'.$error->getMessage().'</error>';
Chris@0 209 }
Chris@0 210
Chris@0 211 $output->writeln($message);
Chris@0 212 }
Chris@0 213
Chris@0 214 /**
Chris@0 215 * Autocompletes a question.
Chris@0 216 *
Chris@0 217 * @param OutputInterface $output
Chris@0 218 * @param Question $question
Chris@0 219 * @param resource $inputStream
Chris@14 220 * @param array $autocomplete
Chris@0 221 *
Chris@0 222 * @return string
Chris@0 223 */
Chris@14 224 private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete)
Chris@0 225 {
Chris@0 226 $ret = '';
Chris@0 227
Chris@0 228 $i = 0;
Chris@0 229 $ofs = -1;
Chris@0 230 $matches = $autocomplete;
Chris@0 231 $numMatches = count($matches);
Chris@0 232
Chris@0 233 $sttyMode = shell_exec('stty -g');
Chris@0 234
Chris@0 235 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
Chris@0 236 shell_exec('stty -icanon -echo');
Chris@0 237
Chris@0 238 // Add highlighted text style
Chris@0 239 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
Chris@0 240
Chris@0 241 // Read a keypress
Chris@0 242 while (!feof($inputStream)) {
Chris@0 243 $c = fread($inputStream, 1);
Chris@0 244
Chris@0 245 // Backspace Character
Chris@0 246 if ("\177" === $c) {
Chris@0 247 if (0 === $numMatches && 0 !== $i) {
Chris@0 248 --$i;
Chris@0 249 // Move cursor backwards
Chris@0 250 $output->write("\033[1D");
Chris@0 251 }
Chris@0 252
Chris@14 253 if (0 === $i) {
Chris@0 254 $ofs = -1;
Chris@0 255 $matches = $autocomplete;
Chris@0 256 $numMatches = count($matches);
Chris@0 257 } else {
Chris@0 258 $numMatches = 0;
Chris@0 259 }
Chris@0 260
Chris@0 261 // Pop the last character off the end of our string
Chris@0 262 $ret = substr($ret, 0, $i);
Chris@0 263 } elseif ("\033" === $c) {
Chris@0 264 // Did we read an escape sequence?
Chris@0 265 $c .= fread($inputStream, 2);
Chris@0 266
Chris@0 267 // A = Up Arrow. B = Down Arrow
Chris@0 268 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
Chris@0 269 if ('A' === $c[2] && -1 === $ofs) {
Chris@0 270 $ofs = 0;
Chris@0 271 }
Chris@0 272
Chris@0 273 if (0 === $numMatches) {
Chris@0 274 continue;
Chris@0 275 }
Chris@0 276
Chris@0 277 $ofs += ('A' === $c[2]) ? -1 : 1;
Chris@0 278 $ofs = ($numMatches + $ofs) % $numMatches;
Chris@0 279 }
Chris@0 280 } elseif (ord($c) < 32) {
Chris@0 281 if ("\t" === $c || "\n" === $c) {
Chris@0 282 if ($numMatches > 0 && -1 !== $ofs) {
Chris@0 283 $ret = $matches[$ofs];
Chris@0 284 // Echo out remaining chars for current match
Chris@0 285 $output->write(substr($ret, $i));
Chris@0 286 $i = strlen($ret);
Chris@0 287 }
Chris@0 288
Chris@0 289 if ("\n" === $c) {
Chris@0 290 $output->write($c);
Chris@0 291 break;
Chris@0 292 }
Chris@0 293
Chris@0 294 $numMatches = 0;
Chris@0 295 }
Chris@0 296
Chris@0 297 continue;
Chris@0 298 } else {
Chris@0 299 $output->write($c);
Chris@0 300 $ret .= $c;
Chris@0 301 ++$i;
Chris@0 302
Chris@0 303 $numMatches = 0;
Chris@0 304 $ofs = 0;
Chris@0 305
Chris@0 306 foreach ($autocomplete as $value) {
Chris@0 307 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
Chris@0 308 if (0 === strpos($value, $ret) && $i !== strlen($value)) {
Chris@0 309 $matches[$numMatches++] = $value;
Chris@0 310 }
Chris@0 311 }
Chris@0 312 }
Chris@0 313
Chris@0 314 // Erase characters from cursor to end of line
Chris@0 315 $output->write("\033[K");
Chris@0 316
Chris@0 317 if ($numMatches > 0 && -1 !== $ofs) {
Chris@0 318 // Save cursor position
Chris@0 319 $output->write("\0337");
Chris@0 320 // Write highlighted text
Chris@14 321 $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $i)).'</hl>');
Chris@0 322 // Restore cursor position
Chris@0 323 $output->write("\0338");
Chris@0 324 }
Chris@0 325 }
Chris@0 326
Chris@0 327 // Reset stty so it behaves normally again
Chris@0 328 shell_exec(sprintf('stty %s', $sttyMode));
Chris@0 329
Chris@0 330 return $ret;
Chris@0 331 }
Chris@0 332
Chris@0 333 /**
Chris@0 334 * Gets a hidden response from user.
Chris@0 335 *
Chris@0 336 * @param OutputInterface $output An Output instance
Chris@0 337 * @param resource $inputStream The handler resource
Chris@0 338 *
Chris@0 339 * @return string The answer
Chris@0 340 *
Chris@0 341 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
Chris@0 342 */
Chris@0 343 private function getHiddenResponse(OutputInterface $output, $inputStream)
Chris@0 344 {
Chris@0 345 if ('\\' === DIRECTORY_SEPARATOR) {
Chris@0 346 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
Chris@0 347
Chris@0 348 // handle code running from a phar
Chris@0 349 if ('phar:' === substr(__FILE__, 0, 5)) {
Chris@0 350 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
Chris@0 351 copy($exe, $tmpExe);
Chris@0 352 $exe = $tmpExe;
Chris@0 353 }
Chris@0 354
Chris@0 355 $value = rtrim(shell_exec($exe));
Chris@0 356 $output->writeln('');
Chris@0 357
Chris@0 358 if (isset($tmpExe)) {
Chris@0 359 unlink($tmpExe);
Chris@0 360 }
Chris@0 361
Chris@0 362 return $value;
Chris@0 363 }
Chris@0 364
Chris@0 365 if ($this->hasSttyAvailable()) {
Chris@0 366 $sttyMode = shell_exec('stty -g');
Chris@0 367
Chris@0 368 shell_exec('stty -echo');
Chris@0 369 $value = fgets($inputStream, 4096);
Chris@0 370 shell_exec(sprintf('stty %s', $sttyMode));
Chris@0 371
Chris@0 372 if (false === $value) {
Chris@0 373 throw new RuntimeException('Aborted');
Chris@0 374 }
Chris@0 375
Chris@0 376 $value = trim($value);
Chris@0 377 $output->writeln('');
Chris@0 378
Chris@0 379 return $value;
Chris@0 380 }
Chris@0 381
Chris@0 382 if (false !== $shell = $this->getShell()) {
Chris@14 383 $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
Chris@0 384 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
Chris@0 385 $value = rtrim(shell_exec($command));
Chris@0 386 $output->writeln('');
Chris@0 387
Chris@0 388 return $value;
Chris@0 389 }
Chris@0 390
Chris@0 391 throw new RuntimeException('Unable to hide the response.');
Chris@0 392 }
Chris@0 393
Chris@0 394 /**
Chris@0 395 * Validates an attempt.
Chris@0 396 *
Chris@0 397 * @param callable $interviewer A callable that will ask for a question and return the result
Chris@0 398 * @param OutputInterface $output An Output instance
Chris@0 399 * @param Question $question A Question instance
Chris@0 400 *
Chris@0 401 * @return mixed The validated response
Chris@0 402 *
Chris@0 403 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
Chris@0 404 */
Chris@0 405 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
Chris@0 406 {
Chris@0 407 $error = null;
Chris@0 408 $attempts = $question->getMaxAttempts();
Chris@0 409 while (null === $attempts || $attempts--) {
Chris@0 410 if (null !== $error) {
Chris@0 411 $this->writeError($output, $error);
Chris@0 412 }
Chris@0 413
Chris@0 414 try {
Chris@0 415 return call_user_func($question->getValidator(), $interviewer());
Chris@0 416 } catch (RuntimeException $e) {
Chris@0 417 throw $e;
Chris@0 418 } catch (\Exception $error) {
Chris@0 419 }
Chris@0 420 }
Chris@0 421
Chris@0 422 throw $error;
Chris@0 423 }
Chris@0 424
Chris@0 425 /**
Chris@0 426 * Returns a valid unix shell.
Chris@0 427 *
Chris@0 428 * @return string|bool The valid shell name, false in case no valid shell is found
Chris@0 429 */
Chris@0 430 private function getShell()
Chris@0 431 {
Chris@0 432 if (null !== self::$shell) {
Chris@0 433 return self::$shell;
Chris@0 434 }
Chris@0 435
Chris@0 436 self::$shell = false;
Chris@0 437
Chris@0 438 if (file_exists('/usr/bin/env')) {
Chris@0 439 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
Chris@0 440 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
Chris@0 441 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
Chris@0 442 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
Chris@0 443 self::$shell = $sh;
Chris@0 444 break;
Chris@0 445 }
Chris@0 446 }
Chris@0 447 }
Chris@0 448
Chris@0 449 return self::$shell;
Chris@0 450 }
Chris@0 451
Chris@0 452 /**
Chris@0 453 * Returns whether Stty is available or not.
Chris@0 454 *
Chris@0 455 * @return bool
Chris@0 456 */
Chris@0 457 private function hasSttyAvailable()
Chris@0 458 {
Chris@0 459 if (null !== self::$stty) {
Chris@0 460 return self::$stty;
Chris@0 461 }
Chris@0 462
Chris@0 463 exec('stty 2>&1', $output, $exitcode);
Chris@0 464
Chris@14 465 return self::$stty = 0 === $exitcode;
Chris@0 466 }
Chris@0 467 }