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\Output\ConsoleOutputInterface;
18 use Symfony\Component\Console\Output\OutputInterface;
19 use Symfony\Component\Console\Formatter\OutputFormatterStyle;
20 use Symfony\Component\Console\Question\Question;
21 use Symfony\Component\Console\Question\ChoiceQuestion;
24 * The QuestionHelper class provides helpers to interact with the user.
26 * @author Fabien Potencier <fabien@symfony.com>
28 class QuestionHelper extends Helper
31 private static $shell;
35 * Asks a question to the user.
37 * @param InputInterface $input An InputInterface instance
38 * @param OutputInterface $output An OutputInterface instance
39 * @param Question $question The question to ask
41 * @return mixed The user answer
43 * @throws RuntimeException If there is no data to read in the input stream
45 public function ask(InputInterface $input, OutputInterface $output, Question $question)
47 if ($output instanceof ConsoleOutputInterface) {
48 $output = $output->getErrorOutput();
51 if (!$input->isInteractive()) {
52 return $question->getDefault();
55 if (!$question->getValidator()) {
56 return $this->doAsk($output, $question);
61 $interviewer = function () use ($output, $question, $that) {
62 return $that->doAsk($output, $question);
65 return $this->validateAttempts($interviewer, $output, $question);
69 * Sets the input stream to read from when interacting with the user.
71 * This is mainly useful for testing purpose.
73 * @param resource $stream The input stream
75 * @throws InvalidArgumentException In case the stream is not a resource
77 public function setInputStream($stream)
79 if (!is_resource($stream)) {
80 throw new InvalidArgumentException('Input stream must be a valid resource.');
83 $this->inputStream = $stream;
87 * Returns the helper's input stream.
91 public function getInputStream()
93 return $this->inputStream;
99 public function getName()
105 * Asks the question to the user.
107 * This method is public for PHP 5.3 compatibility, it should be private.
109 * @param OutputInterface $output
110 * @param Question $question
112 * @return bool|mixed|null|string
115 * @throws \RuntimeException
117 public function doAsk(OutputInterface $output, Question $question)
119 $this->writePrompt($output, $question);
121 $inputStream = $this->inputStream ?: STDIN;
122 $autocomplete = $question->getAutocompleterValues();
124 if (null === $autocomplete || !$this->hasSttyAvailable()) {
126 if ($question->isHidden()) {
128 $ret = trim($this->getHiddenResponse($output, $inputStream));
129 } catch (\RuntimeException $e) {
130 if (!$question->isHiddenFallback()) {
136 if (false === $ret) {
137 $ret = fgets($inputStream, 4096);
138 if (false === $ret) {
139 throw new RuntimeException('Aborted');
144 $ret = trim($this->autocomplete($output, $question, $inputStream));
147 $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
149 if ($normalizer = $question->getNormalizer()) {
150 return $normalizer($ret);
157 * Outputs the question prompt.
159 * @param OutputInterface $output
160 * @param Question $question
162 protected function writePrompt(OutputInterface $output, Question $question)
164 $message = $question->getQuestion();
166 if ($question instanceof ChoiceQuestion) {
167 $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
169 $messages = (array) $question->getQuestion();
170 foreach ($question->getChoices() as $key => $value) {
171 $width = $maxWidth - $this->strlen($key);
172 $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
175 $output->writeln($messages);
177 $message = $question->getPrompt();
180 $output->write($message);
184 * Outputs an error message.
186 * @param OutputInterface $output
187 * @param \Exception $error
189 protected function writeError(OutputInterface $output, \Exception $error)
191 if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
192 $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
194 $message = '<error>'.$error->getMessage().'</error>';
197 $output->writeln($message);
201 * Autocompletes a question.
203 * @param OutputInterface $output
204 * @param Question $question
205 * @param resource $inputStream
209 private function autocomplete(OutputInterface $output, Question $question, $inputStream)
211 $autocomplete = $question->getAutocompleterValues();
216 $matches = $autocomplete;
217 $numMatches = count($matches);
219 $sttyMode = shell_exec('stty -g');
221 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
222 shell_exec('stty -icanon -echo');
224 // Add highlighted text style
225 $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
228 while (!feof($inputStream)) {
229 $c = fread($inputStream, 1);
231 // Backspace Character
233 if (0 === $numMatches && 0 !== $i) {
235 // Move cursor backwards
236 $output->write("\033[1D");
241 $matches = $autocomplete;
242 $numMatches = count($matches);
247 // Pop the last character off the end of our string
248 $ret = substr($ret, 0, $i);
249 } elseif ("\033" === $c) {
250 // Did we read an escape sequence?
251 $c .= fread($inputStream, 2);
253 // A = Up Arrow. B = Down Arrow
254 if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
255 if ('A' === $c[2] && -1 === $ofs) {
259 if (0 === $numMatches) {
263 $ofs += ('A' === $c[2]) ? -1 : 1;
264 $ofs = ($numMatches + $ofs) % $numMatches;
266 } elseif (ord($c) < 32) {
267 if ("\t" === $c || "\n" === $c) {
268 if ($numMatches > 0 && -1 !== $ofs) {
269 $ret = $matches[$ofs];
270 // Echo out remaining chars for current match
271 $output->write(substr($ret, $i));
292 foreach ($autocomplete as $value) {
293 // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
294 if (0 === strpos($value, $ret) && $i !== strlen($value)) {
295 $matches[$numMatches++] = $value;
300 // Erase characters from cursor to end of line
301 $output->write("\033[K");
303 if ($numMatches > 0 && -1 !== $ofs) {
304 // Save cursor position
305 $output->write("\0337");
306 // Write highlighted text
307 $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
308 // Restore cursor position
309 $output->write("\0338");
313 // Reset stty so it behaves normally again
314 shell_exec(sprintf('stty %s', $sttyMode));
320 * Gets a hidden response from user.
322 * @param OutputInterface $output An Output instance
323 * @param resource $inputStream The handler resource
325 * @return string The answer
327 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
329 private function getHiddenResponse(OutputInterface $output, $inputStream)
331 if ('\\' === DIRECTORY_SEPARATOR) {
332 $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
334 // handle code running from a phar
335 if ('phar:' === substr(__FILE__, 0, 5)) {
336 $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
341 $value = rtrim(shell_exec($exe));
342 $output->writeln('');
344 if (isset($tmpExe)) {
351 if ($this->hasSttyAvailable()) {
352 $sttyMode = shell_exec('stty -g');
354 shell_exec('stty -echo');
355 $value = fgets($inputStream, 4096);
356 shell_exec(sprintf('stty %s', $sttyMode));
358 if (false === $value) {
359 throw new RuntimeException('Aborted');
362 $value = trim($value);
363 $output->writeln('');
368 if (false !== $shell = $this->getShell()) {
369 $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
370 $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
371 $value = rtrim(shell_exec($command));
372 $output->writeln('');
377 throw new RuntimeException('Unable to hide the response.');
381 * Validates an attempt.
383 * @param callable $interviewer A callable that will ask for a question and return the result
384 * @param OutputInterface $output An Output instance
385 * @param Question $question A Question instance
387 * @return mixed The validated response
389 * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
391 private function validateAttempts($interviewer, OutputInterface $output, Question $question)
394 $attempts = $question->getMaxAttempts();
395 while (null === $attempts || $attempts--) {
396 if (null !== $error) {
397 $this->writeError($output, $error);
401 return call_user_func($question->getValidator(), $interviewer());
402 } catch (RuntimeException $e) {
404 } catch (\Exception $error) {
412 * Returns a valid unix shell.
414 * @return string|bool The valid shell name, false in case no valid shell is found
416 private function getShell()
418 if (null !== self::$shell) {
422 self::$shell = false;
424 if (file_exists('/usr/bin/env')) {
425 // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
426 $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
427 foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
428 if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
439 * Returns whether Stty is available or not.
443 private function hasSttyAvailable()
445 if (null !== self::$stty) {
449 exec('stty 2>&1', $output, $exitcode);
451 return self::$stty = $exitcode === 0;