annotate vendor/symfony/console/Helper/QuestionHelper.php @ 17:129ea1e6d783

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