annotate vendor/symfony/console/Helper/QuestionHelper.php @ 8:50b0d041100e

Further files for download
author Chris Cannam
date Mon, 05 Feb 2018 10:56:40 +0000
parents 4c8ae668cc8c
children 7a779792577d
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@0 127 * @throws \Exception
Chris@0 128 * @throws \RuntimeException
Chris@0 129 */
Chris@0 130 private function doAsk(OutputInterface $output, Question $question)
Chris@0 131 {
Chris@0 132 $this->writePrompt($output, $question);
Chris@0 133
Chris@0 134 $inputStream = $this->inputStream ?: STDIN;
Chris@0 135 $autocomplete = $question->getAutocompleterValues();
Chris@0 136
Chris@0 137 if (null === $autocomplete || !$this->hasSttyAvailable()) {
Chris@0 138 $ret = false;
Chris@0 139 if ($question->isHidden()) {
Chris@0 140 try {
Chris@0 141 $ret = trim($this->getHiddenResponse($output, $inputStream));
Chris@0 142 } catch (\RuntimeException $e) {
Chris@0 143 if (!$question->isHiddenFallback()) {
Chris@0 144 throw $e;
Chris@0 145 }
Chris@0 146 }
Chris@0 147 }
Chris@0 148
Chris@0 149 if (false === $ret) {
Chris@0 150 $ret = fgets($inputStream, 4096);
Chris@0 151 if (false === $ret) {
Chris@0 152 throw new RuntimeException('Aborted');
Chris@0 153 }
Chris@0 154 $ret = trim($ret);
Chris@0 155 }
Chris@0 156 } else {
Chris@0 157 $ret = trim($this->autocomplete($output, $question, $inputStream));
Chris@0 158 }
Chris@0 159
Chris@0 160 $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
Chris@0 161
Chris@0 162 if ($normalizer = $question->getNormalizer()) {
Chris@0 163 return $normalizer($ret);
Chris@0 164 }
Chris@0 165
Chris@0 166 return $ret;
Chris@0 167 }
Chris@0 168
Chris@0 169 /**
Chris@0 170 * Outputs the question prompt.
Chris@0 171 *
Chris@0 172 * @param OutputInterface $output
Chris@0 173 * @param Question $question
Chris@0 174 */
Chris@0 175 protected function writePrompt(OutputInterface $output, Question $question)
Chris@0 176 {
Chris@0 177 $message = $question->getQuestion();
Chris@0 178
Chris@0 179 if ($question instanceof ChoiceQuestion) {
Chris@0 180 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
Chris@0 181
Chris@0 182 $messages = (array) $question->getQuestion();
Chris@0 183 foreach ($question->getChoices() as $key => $value) {
Chris@0 184 $width = $maxWidth - $this->strlen($key);
Chris@0 185 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
Chris@0 186 }
Chris@0 187
Chris@0 188 $output->writeln($messages);
Chris@0 189
Chris@0 190 $message = $question->getPrompt();
Chris@0 191 }
Chris@0 192
Chris@0 193 $output->write($message);
Chris@0 194 }
Chris@0 195
Chris@0 196 /**
Chris@0 197 * Outputs an error message.
Chris@0 198 *
Chris@0 199 * @param OutputInterface $output
Chris@0 200 * @param \Exception $error
Chris@0 201 */
Chris@0 202 protected function writeError(OutputInterface $output, \Exception $error)
Chris@0 203 {
Chris@0 204 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
Chris@0 205 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
Chris@0 206 } else {
Chris@0 207 $message = '<error>'.$error->getMessage().'</error>';
Chris@0 208 }
Chris@0 209
Chris@0 210 $output->writeln($message);
Chris@0 211 }
Chris@0 212
Chris@0 213 /**
Chris@0 214 * Autocompletes a question.
Chris@0 215 *
Chris@0 216 * @param OutputInterface $output
Chris@0 217 * @param Question $question
Chris@0 218 * @param resource $inputStream
Chris@0 219 *
Chris@0 220 * @return string
Chris@0 221 */
Chris@0 222 private function autocomplete(OutputInterface $output, Question $question, $inputStream)
Chris@0 223 {
Chris@0 224 $autocomplete = $question->getAutocompleterValues();
Chris@0 225 $ret = '';
Chris@0 226
Chris@0 227 $i = 0;
Chris@0 228 $ofs = -1;
Chris@0 229 $matches = $autocomplete;
Chris@0 230 $numMatches = count($matches);
Chris@0 231
Chris@0 232 $sttyMode = shell_exec('stty -g');
Chris@0 233
Chris@0 234 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
Chris@0 235 shell_exec('stty -icanon -echo');
Chris@0 236
Chris@0 237 // Add highlighted text style
Chris@0 238 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
Chris@0 239
Chris@0 240 // Read a keypress
Chris@0 241 while (!feof($inputStream)) {
Chris@0 242 $c = fread($inputStream, 1);
Chris@0 243
Chris@0 244 // Backspace Character
Chris@0 245 if ("\177" === $c) {
Chris@0 246 if (0 === $numMatches && 0 !== $i) {
Chris@0 247 --$i;
Chris@0 248 // Move cursor backwards
Chris@0 249 $output->write("\033[1D");
Chris@0 250 }
Chris@0 251
Chris@0 252 if ($i === 0) {
Chris@0 253 $ofs = -1;
Chris@0 254 $matches = $autocomplete;
Chris@0 255 $numMatches = count($matches);
Chris@0 256 } else {
Chris@0 257 $numMatches = 0;
Chris@0 258 }
Chris@0 259
Chris@0 260 // Pop the last character off the end of our string
Chris@0 261 $ret = substr($ret, 0, $i);
Chris@0 262 } elseif ("\033" === $c) {
Chris@0 263 // Did we read an escape sequence?
Chris@0 264 $c .= fread($inputStream, 2);
Chris@0 265
Chris@0 266 // A = Up Arrow. B = Down Arrow
Chris@0 267 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
Chris@0 268 if ('A' === $c[2] && -1 === $ofs) {
Chris@0 269 $ofs = 0;
Chris@0 270 }
Chris@0 271
Chris@0 272 if (0 === $numMatches) {
Chris@0 273 continue;
Chris@0 274 }
Chris@0 275
Chris@0 276 $ofs += ('A' === $c[2]) ? -1 : 1;
Chris@0 277 $ofs = ($numMatches + $ofs) % $numMatches;
Chris@0 278 }
Chris@0 279 } elseif (ord($c) < 32) {
Chris@0 280 if ("\t" === $c || "\n" === $c) {
Chris@0 281 if ($numMatches > 0 && -1 !== $ofs) {
Chris@0 282 $ret = $matches[$ofs];
Chris@0 283 // Echo out remaining chars for current match
Chris@0 284 $output->write(substr($ret, $i));
Chris@0 285 $i = strlen($ret);
Chris@0 286 }
Chris@0 287
Chris@0 288 if ("\n" === $c) {
Chris@0 289 $output->write($c);
Chris@0 290 break;
Chris@0 291 }
Chris@0 292
Chris@0 293 $numMatches = 0;
Chris@0 294 }
Chris@0 295
Chris@0 296 continue;
Chris@0 297 } else {
Chris@0 298 $output->write($c);
Chris@0 299 $ret .= $c;
Chris@0 300 ++$i;
Chris@0 301
Chris@0 302 $numMatches = 0;
Chris@0 303 $ofs = 0;
Chris@0 304
Chris@0 305 foreach ($autocomplete as $value) {
Chris@0 306 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
Chris@0 307 if (0 === strpos($value, $ret) && $i !== strlen($value)) {
Chris@0 308 $matches[$numMatches++] = $value;
Chris@0 309 }
Chris@0 310 }
Chris@0 311 }
Chris@0 312
Chris@0 313 // Erase characters from cursor to end of line
Chris@0 314 $output->write("\033[K");
Chris@0 315
Chris@0 316 if ($numMatches > 0 && -1 !== $ofs) {
Chris@0 317 // Save cursor position
Chris@0 318 $output->write("\0337");
Chris@0 319 // Write highlighted text
Chris@0 320 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
Chris@0 321 // Restore cursor position
Chris@0 322 $output->write("\0338");
Chris@0 323 }
Chris@0 324 }
Chris@0 325
Chris@0 326 // Reset stty so it behaves normally again
Chris@0 327 shell_exec(sprintf('stty %s', $sttyMode));
Chris@0 328
Chris@0 329 return $ret;
Chris@0 330 }
Chris@0 331
Chris@0 332 /**
Chris@0 333 * Gets a hidden response from user.
Chris@0 334 *
Chris@0 335 * @param OutputInterface $output An Output instance
Chris@0 336 * @param resource $inputStream The handler resource
Chris@0 337 *
Chris@0 338 * @return string The answer
Chris@0 339 *
Chris@0 340 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
Chris@0 341 */
Chris@0 342 private function getHiddenResponse(OutputInterface $output, $inputStream)
Chris@0 343 {
Chris@0 344 if ('\\' === DIRECTORY_SEPARATOR) {
Chris@0 345 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
Chris@0 346
Chris@0 347 // handle code running from a phar
Chris@0 348 if ('phar:' === substr(__FILE__, 0, 5)) {
Chris@0 349 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
Chris@0 350 copy($exe, $tmpExe);
Chris@0 351 $exe = $tmpExe;
Chris@0 352 }
Chris@0 353
Chris@0 354 $value = rtrim(shell_exec($exe));
Chris@0 355 $output->writeln('');
Chris@0 356
Chris@0 357 if (isset($tmpExe)) {
Chris@0 358 unlink($tmpExe);
Chris@0 359 }
Chris@0 360
Chris@0 361 return $value;
Chris@0 362 }
Chris@0 363
Chris@0 364 if ($this->hasSttyAvailable()) {
Chris@0 365 $sttyMode = shell_exec('stty -g');
Chris@0 366
Chris@0 367 shell_exec('stty -echo');
Chris@0 368 $value = fgets($inputStream, 4096);
Chris@0 369 shell_exec(sprintf('stty %s', $sttyMode));
Chris@0 370
Chris@0 371 if (false === $value) {
Chris@0 372 throw new RuntimeException('Aborted');
Chris@0 373 }
Chris@0 374
Chris@0 375 $value = trim($value);
Chris@0 376 $output->writeln('');
Chris@0 377
Chris@0 378 return $value;
Chris@0 379 }
Chris@0 380
Chris@0 381 if (false !== $shell = $this->getShell()) {
Chris@0 382 $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
Chris@0 383 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
Chris@0 384 $value = rtrim(shell_exec($command));
Chris@0 385 $output->writeln('');
Chris@0 386
Chris@0 387 return $value;
Chris@0 388 }
Chris@0 389
Chris@0 390 throw new RuntimeException('Unable to hide the response.');
Chris@0 391 }
Chris@0 392
Chris@0 393 /**
Chris@0 394 * Validates an attempt.
Chris@0 395 *
Chris@0 396 * @param callable $interviewer A callable that will ask for a question and return the result
Chris@0 397 * @param OutputInterface $output An Output instance
Chris@0 398 * @param Question $question A Question instance
Chris@0 399 *
Chris@0 400 * @return mixed The validated response
Chris@0 401 *
Chris@0 402 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
Chris@0 403 */
Chris@0 404 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
Chris@0 405 {
Chris@0 406 $error = null;
Chris@0 407 $attempts = $question->getMaxAttempts();
Chris@0 408 while (null === $attempts || $attempts--) {
Chris@0 409 if (null !== $error) {
Chris@0 410 $this->writeError($output, $error);
Chris@0 411 }
Chris@0 412
Chris@0 413 try {
Chris@0 414 return call_user_func($question->getValidator(), $interviewer());
Chris@0 415 } catch (RuntimeException $e) {
Chris@0 416 throw $e;
Chris@0 417 } catch (\Exception $error) {
Chris@0 418 }
Chris@0 419 }
Chris@0 420
Chris@0 421 throw $error;
Chris@0 422 }
Chris@0 423
Chris@0 424 /**
Chris@0 425 * Returns a valid unix shell.
Chris@0 426 *
Chris@0 427 * @return string|bool The valid shell name, false in case no valid shell is found
Chris@0 428 */
Chris@0 429 private function getShell()
Chris@0 430 {
Chris@0 431 if (null !== self::$shell) {
Chris@0 432 return self::$shell;
Chris@0 433 }
Chris@0 434
Chris@0 435 self::$shell = false;
Chris@0 436
Chris@0 437 if (file_exists('/usr/bin/env')) {
Chris@0 438 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
Chris@0 439 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
Chris@0 440 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
Chris@0 441 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
Chris@0 442 self::$shell = $sh;
Chris@0 443 break;
Chris@0 444 }
Chris@0 445 }
Chris@0 446 }
Chris@0 447
Chris@0 448 return self::$shell;
Chris@0 449 }
Chris@0 450
Chris@0 451 /**
Chris@0 452 * Returns whether Stty is available or not.
Chris@0 453 *
Chris@0 454 * @return bool
Chris@0 455 */
Chris@0 456 private function hasSttyAvailable()
Chris@0 457 {
Chris@0 458 if (null !== self::$stty) {
Chris@0 459 return self::$stty;
Chris@0 460 }
Chris@0 461
Chris@0 462 exec('stty 2>&1', $output, $exitcode);
Chris@0 463
Chris@0 464 return self::$stty = $exitcode === 0;
Chris@0 465 }
Chris@0 466 }