4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Helper;
14 use Symfony\Component\Console\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\RuntimeException;
16 use Symfony\Component\Console\Formatter\OutputFormatter;
17 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
18 use Symfony\Component\Console\Input\InputInterface;
19 use Symfony\Component\Console\Input\StreamableInputInterface;
20 use Symfony\Component\Console\Output\ConsoleOutputInterface;
21 use Symfony\Component\Console\Output\OutputInterface;
22 use Symfony\Component\Console\Question\ChoiceQuestion;
23 use Symfony\Component\Console\Question\Question;
26 * The QuestionHelper class provides helpers to interact with the user.
28 * @author Fabien Potencier <fabien@symfony.com>
30 class QuestionHelper extends Helper
33 private static $shell;
37 * Asks a question to the user.
39 * @return mixed The user answer
41 * @throws RuntimeException If there is no data to read in the input stream
43 public function ask(InputInterface $input, OutputInterface $output, Question $question)
45 if ($output instanceof ConsoleOutputInterface) {
46 $output = $output->getErrorOutput();
49 if (!$input->isInteractive()) {
50 $default = $question->getDefault();
52 if (null !== $default && $question instanceof ChoiceQuestion) {
53 $choices = $question->getChoices();
55 if (!$question->isMultiselect()) {
56 return isset($choices[$default]) ? $choices[$default] : $default;
59 $default = explode(',', $default);
60 foreach ($default as $k => $v) {
62 $default[$k] = isset($choices[$v]) ? $choices[$v] : $v;
69 if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
70 $this->inputStream = $stream;
73 if (!$question->getValidator()) {
74 return $this->doAsk($output, $question);
77 $interviewer = function () use ($output, $question) {
78 return $this->doAsk($output, $question);
81 return $this->validateAttempts($interviewer, $output, $question);
85 * Sets the input stream to read from when interacting with the user.
87 * This is mainly useful for testing purpose.
89 * @deprecated since version 3.2, to be removed in 4.0. Use
90 * StreamableInputInterface::setStream() instead.
92 * @param resource $stream The input stream
94 * @throws InvalidArgumentException In case the stream is not a resource
96 public function setInputStream($stream)
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);
100 if (!\is_resource($stream)) {
101 throw new InvalidArgumentException('Input stream must be a valid resource.');
104 $this->inputStream = $stream;
108 * Returns the helper's input stream.
110 * @deprecated since version 3.2, to be removed in 4.0. Use
111 * StreamableInputInterface::getStream() instead.
115 public function getInputStream()
117 if (0 === \func_num_args() || func_get_arg(0)) {
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);
121 return $this->inputStream;
127 public function getName()
133 * Prevents usage of stty.
135 public static function disableStty()
141 * Asks the question to the user.
143 * @return bool|mixed|string|null
145 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
147 private function doAsk(OutputInterface $output, Question $question)
149 $this->writePrompt($output, $question);
151 $inputStream = $this->inputStream ?: STDIN;
152 $autocomplete = $question->getAutocompleterValues();
154 if (null === $autocomplete || !$this->hasSttyAvailable()) {
156 if ($question->isHidden()) {
158 $ret = trim($this->getHiddenResponse($output, $inputStream));
159 } catch (RuntimeException $e) {
160 if (!$question->isHiddenFallback()) {
166 if (false === $ret) {
167 $ret = fgets($inputStream, 4096);
168 if (false === $ret) {
169 throw new RuntimeException('Aborted');
174 $ret = trim($this->autocomplete($output, $question, $inputStream, \is_array($autocomplete) ? $autocomplete : iterator_to_array($autocomplete, false)));
177 $ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
179 if ($normalizer = $question->getNormalizer()) {
180 return $normalizer($ret);
187 * Outputs the question prompt.
189 protected function writePrompt(OutputInterface $output, Question $question)
191 $message = $question->getQuestion();
193 if ($question instanceof ChoiceQuestion) {
194 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
196 $messages = (array) $question->getQuestion();
197 foreach ($question->getChoices() as $key => $value) {
198 $width = $maxWidth - $this->strlen($key);
199 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
202 $output->writeln($messages);
204 $message = $question->getPrompt();
207 $output->write($message);
211 * Outputs an error message.
213 protected function writeError(OutputInterface $output, \Exception $error)
215 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
216 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
218 $message = '<error>'.$error->getMessage().'</error>';
221 $output->writeln($message);
225 * Autocompletes a question.
227 * @param OutputInterface $output
228 * @param Question $question
229 * @param resource $inputStream
230 * @param array $autocomplete
234 private function autocomplete(OutputInterface $output, Question $question, $inputStream, array $autocomplete)
240 $matches = $autocomplete;
241 $numMatches = \count($matches);
243 $sttyMode = shell_exec('stty -g');
245 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
246 shell_exec('stty -icanon -echo');
248 // Add highlighted text style
249 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
252 while (!feof($inputStream)) {
253 $c = fread($inputStream, 1);
255 // Backspace Character
257 if (0 === $numMatches && 0 !== $i) {
259 // Move cursor backwards
260 $output->write("\033[1D");
265 $matches = $autocomplete;
266 $numMatches = \count($matches);
271 // Pop the last character off the end of our string
272 $ret = substr($ret, 0, $i);
273 } elseif ("\033" === $c) {
274 // Did we read an escape sequence?
275 $c .= fread($inputStream, 2);
277 // A = Up Arrow. B = Down Arrow
278 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
279 if ('A' === $c[2] && -1 === $ofs) {
283 if (0 === $numMatches) {
287 $ofs += ('A' === $c[2]) ? -1 : 1;
288 $ofs = ($numMatches + $ofs) % $numMatches;
290 } elseif (\ord($c) < 32) {
291 if ("\t" === $c || "\n" === $c) {
292 if ($numMatches > 0 && -1 !== $ofs) {
293 $ret = $matches[$ofs];
294 // Echo out remaining chars for current match
295 $output->write(substr($ret, $i));
316 foreach ($autocomplete as $value) {
317 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
318 if (0 === strpos($value, $ret)) {
319 $matches[$numMatches++] = $value;
324 // Erase characters from cursor to end of line
325 $output->write("\033[K");
327 if ($numMatches > 0 && -1 !== $ofs) {
328 // Save cursor position
329 $output->write("\0337");
330 // Write highlighted text
331 $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $i)).'</hl>');
332 // Restore cursor position
333 $output->write("\0338");
337 // Reset stty so it behaves normally again
338 shell_exec(sprintf('stty %s', $sttyMode));
344 * Gets a hidden response from user.
346 * @param OutputInterface $output An Output instance
347 * @param resource $inputStream The handler resource
349 * @return string The answer
351 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
353 private function getHiddenResponse(OutputInterface $output, $inputStream)
355 if ('\\' === \DIRECTORY_SEPARATOR) {
356 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
358 // handle code running from a phar
359 if ('phar:' === substr(__FILE__, 0, 5)) {
360 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
365 $value = rtrim(shell_exec($exe));
366 $output->writeln('');
368 if (isset($tmpExe)) {
375 if ($this->hasSttyAvailable()) {
376 $sttyMode = shell_exec('stty -g');
378 shell_exec('stty -echo');
379 $value = fgets($inputStream, 4096);
380 shell_exec(sprintf('stty %s', $sttyMode));
382 if (false === $value) {
383 throw new RuntimeException('Aborted');
386 $value = trim($value);
387 $output->writeln('');
392 if (false !== $shell = $this->getShell()) {
393 $readCmd = 'csh' === $shell ? 'set mypassword = $<' : 'read -r mypassword';
394 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
395 $value = rtrim(shell_exec($command));
396 $output->writeln('');
401 throw new RuntimeException('Unable to hide the response.');
405 * Validates an attempt.
407 * @param callable $interviewer A callable that will ask for a question and return the result
408 * @param OutputInterface $output An Output instance
409 * @param Question $question A Question instance
411 * @return mixed The validated response
413 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
415 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
418 $attempts = $question->getMaxAttempts();
419 while (null === $attempts || $attempts--) {
420 if (null !== $error) {
421 $this->writeError($output, $error);
425 return \call_user_func($question->getValidator(), $interviewer());
426 } catch (RuntimeException $e) {
428 } catch (\Exception $error) {
436 * Returns a valid unix shell.
438 * @return string|bool The valid shell name, false in case no valid shell is found
440 private function getShell()
442 if (null !== self::$shell) {
446 self::$shell = false;
448 if (file_exists('/usr/bin/env')) {
449 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
450 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
451 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
452 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
463 * Returns whether Stty is available or not.
467 private function hasSttyAvailable()
469 if (null !== self::$stty) {
473 exec('stty 2>&1', $output, $exitcode);
475 return self::$stty = 0 === $exitcode;