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\Input\InputInterface;
17 use Symfony\Component\Console\Input\StreamableInputInterface;
18 use Symfony\Component\Console\Output\ConsoleOutputInterface;
19 use Symfony\Component\Console\Output\OutputInterface;
20 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
21 use Symfony\Component\Console\Question\Question;
22 use Symfony\Component\Console\Question\ChoiceQuestion;
25 * The QuestionHelper class provides helpers to interact with the user.
27 * @author Fabien Potencier <fabien@symfony.com>
29 class QuestionHelper extends Helper
32 private static $shell;
36 * Asks a question to the user.
38 * @param InputInterface $input An InputInterface instance
39 * @param OutputInterface $output An OutputInterface instance
40 * @param Question $question The question to ask
42 * @return mixed The user answer
44 * @throws RuntimeException If there is no data to read in the input stream
46 public function ask(InputInterface $input, OutputInterface $output, Question $question)
48 if ($output instanceof ConsoleOutputInterface) {
49 $output = $output->getErrorOutput();
52 if (!$input->isInteractive()) {
53 return $question->getDefault();
56 if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
57 $this->inputStream = $stream;
60 if (!$question->getValidator()) {
61 return $this->doAsk($output, $question);
64 $interviewer = function () use ($output, $question) {
65 return $this->doAsk($output, $question);
68 return $this->validateAttempts($interviewer, $output, $question);
72 * Sets the input stream to read from when interacting with the user.
74 * This is mainly useful for testing purpose.
76 * @deprecated since version 3.2, to be removed in 4.0. Use
77 * StreamableInputInterface::setStream() instead.
79 * @param resource $stream The input stream
81 * @throws InvalidArgumentException In case the stream is not a resource
83 public function setInputStream($stream)
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);
87 if (!is_resource($stream)) {
88 throw new InvalidArgumentException('Input stream must be a valid resource.');
91 $this->inputStream = $stream;
95 * Returns the helper's input stream.
97 * @deprecated since version 3.2, to be removed in 4.0. Use
98 * StreamableInputInterface::getStream() instead.
102 public function getInputStream()
104 if (0 === func_num_args() || func_get_arg(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);
108 return $this->inputStream;
114 public function getName()
120 * Asks the question to the user.
122 * @param OutputInterface $output
123 * @param Question $question
125 * @return bool|mixed|null|string
127 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
129 private function doAsk(OutputInterface $output, Question $question)
131 $this->writePrompt($output, $question);
133 $inputStream = $this->inputStream ?: STDIN;
134 $autocomplete = $question->getAutocompleterValues();
136 if (null === $autocomplete || !$this->hasSttyAvailable()) {
138 if ($question->isHidden()) {
140 $ret = trim($this->getHiddenResponse($output, $inputStream));
141 } catch (RuntimeException $e) {
142 if (!$question->isHiddenFallback()) {
148 if (false === $ret) {
149 $ret = fgets($inputStream, 4096);
150 if (false === $ret) {
151 throw new RuntimeException('Aborted');
156 $ret = trim($this->autocomplete($output, $question, $inputStream));
159 $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
161 if ($normalizer = $question->getNormalizer()) {
162 return $normalizer($ret);
169 * Outputs the question prompt.
171 * @param OutputInterface $output
172 * @param Question $question
174 protected function writePrompt(OutputInterface $output, Question $question)
176 $message = $question->getQuestion();
178 if ($question instanceof ChoiceQuestion) {
179 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
181 $messages = (array) $question->getQuestion();
182 foreach ($question->getChoices() as $key => $value) {
183 $width = $maxWidth - $this->strlen($key);
184 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
187 $output->writeln($messages);
189 $message = $question->getPrompt();
192 $output->write($message);
196 * Outputs an error message.
198 * @param OutputInterface $output
199 * @param \Exception $error
201 protected function writeError(OutputInterface $output, \Exception $error)
203 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
204 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
206 $message = '<error>'.$error->getMessage().'</error>';
209 $output->writeln($message);
213 * Autocompletes a question.
215 * @param OutputInterface $output
216 * @param Question $question
217 * @param resource $inputStream
221 private function autocomplete(OutputInterface $output, Question $question, $inputStream)
223 $autocomplete = $question->getAutocompleterValues();
228 $matches = $autocomplete;
229 $numMatches = count($matches);
231 $sttyMode = shell_exec('stty -g');
233 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
234 shell_exec('stty -icanon -echo');
236 // Add highlighted text style
237 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
240 while (!feof($inputStream)) {
241 $c = fread($inputStream, 1);
243 // Backspace Character
245 if (0 === $numMatches && 0 !== $i) {
247 // Move cursor backwards
248 $output->write("\033[1D");
253 $matches = $autocomplete;
254 $numMatches = count($matches);
259 // Pop the last character off the end of our string
260 $ret = substr($ret, 0, $i);
261 } elseif ("\033" === $c) {
262 // Did we read an escape sequence?
263 $c .= fread($inputStream, 2);
265 // A = Up Arrow. B = Down Arrow
266 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
267 if ('A' === $c[2] && -1 === $ofs) {
271 if (0 === $numMatches) {
275 $ofs += ('A' === $c[2]) ? -1 : 1;
276 $ofs = ($numMatches + $ofs) % $numMatches;
278 } elseif (ord($c) < 32) {
279 if ("\t" === $c || "\n" === $c) {
280 if ($numMatches > 0 && -1 !== $ofs) {
281 $ret = $matches[$ofs];
282 // Echo out remaining chars for current match
283 $output->write(substr($ret, $i));
304 foreach ($autocomplete as $value) {
305 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
306 if (0 === strpos($value, $ret) && $i !== strlen($value)) {
307 $matches[$numMatches++] = $value;
312 // Erase characters from cursor to end of line
313 $output->write("\033[K");
315 if ($numMatches > 0 && -1 !== $ofs) {
316 // Save cursor position
317 $output->write("\0337");
318 // Write highlighted text
319 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
320 // Restore cursor position
321 $output->write("\0338");
325 // Reset stty so it behaves normally again
326 shell_exec(sprintf('stty %s', $sttyMode));
332 * Gets a hidden response from user.
334 * @param OutputInterface $output An Output instance
335 * @param resource $inputStream The handler resource
337 * @return string The answer
339 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
341 private function getHiddenResponse(OutputInterface $output, $inputStream)
343 if ('\\' === DIRECTORY_SEPARATOR) {
344 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
346 // handle code running from a phar
347 if ('phar:' === substr(__FILE__, 0, 5)) {
348 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
353 $value = rtrim(shell_exec($exe));
354 $output->writeln('');
356 if (isset($tmpExe)) {
363 if ($this->hasSttyAvailable()) {
364 $sttyMode = shell_exec('stty -g');
366 shell_exec('stty -echo');
367 $value = fgets($inputStream, 4096);
368 shell_exec(sprintf('stty %s', $sttyMode));
370 if (false === $value) {
371 throw new RuntimeException('Aborted');
374 $value = trim($value);
375 $output->writeln('');
380 if (false !== $shell = $this->getShell()) {
381 $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
382 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
383 $value = rtrim(shell_exec($command));
384 $output->writeln('');
389 throw new RuntimeException('Unable to hide the response.');
393 * Validates an attempt.
395 * @param callable $interviewer A callable that will ask for a question and return the result
396 * @param OutputInterface $output An Output instance
397 * @param Question $question A Question instance
399 * @return mixed The validated response
401 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
403 private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
406 $attempts = $question->getMaxAttempts();
407 while (null === $attempts || $attempts--) {
408 if (null !== $error) {
409 $this->writeError($output, $error);
413 return call_user_func($question->getValidator(), $interviewer());
414 } catch (RuntimeException $e) {
416 } catch (\Exception $error) {
424 * Returns a valid unix shell.
426 * @return string|bool The valid shell name, false in case no valid shell is found
428 private function getShell()
430 if (null !== self::$shell) {
434 self::$shell = false;
436 if (file_exists('/usr/bin/env')) {
437 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
438 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
439 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
440 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
451 * Returns whether Stty is available or not.
455 private function hasSttyAvailable()
457 if (null !== self::$stty) {
461 exec('stty 2>&1', $output, $exitcode);
463 return self::$stty = $exitcode === 0;