annotate vendor/symfony/console/Helper/QuestionHelper.php @ 19:fa3358dc1485 tip

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