annotate vendor/symfony/console/Helper/QuestionHelper.php @ 12:7a779792577d

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