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\LogicException;
15 use Symfony\Component\Console\Input\InputInterface;
16 use Symfony\Component\Console\Output\OutputInterface;
17 use Symfony\Component\Console\Question\ChoiceQuestion;
18 use Symfony\Component\Console\Question\ConfirmationQuestion;
19 use Symfony\Component\Console\Question\Question;
20 use Symfony\Component\Console\Style\SymfonyStyle;
21 use Symfony\Component\Console\Formatter\OutputFormatter;
24 * Symfony Style Guide compliant question helper.
26 * @author Kevin Bond <kevinbond@gmail.com>
28 class SymfonyQuestionHelper extends QuestionHelper
33 public function ask(InputInterface $input, OutputInterface $output, Question $question)
35 $validator = $question->getValidator();
36 $question->setValidator(function ($value) use ($validator) {
37 if (null !== $validator) {
38 $value = $validator($value);
41 if (!is_array($value) && !is_bool($value) && 0 === strlen($value)) {
42 throw new LogicException('A value is required.');
49 return parent::ask($input, $output, $question);
55 protected function writePrompt(OutputInterface $output, Question $question)
57 $text = OutputFormatter::escapeTrailingBackslash($question->getQuestion());
58 $default = $question->getDefault();
61 case null === $default:
62 $text = sprintf(' <info>%s</info>:', $text);
66 case $question instanceof ConfirmationQuestion:
67 $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
71 case $question instanceof ChoiceQuestion && $question->isMultiselect():
72 $choices = $question->getChoices();
73 $default = explode(',', $default);
75 foreach ($default as $key => $value) {
76 $default[$key] = $choices[trim($value)];
79 $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape(implode(', ', $default)));
83 case $question instanceof ChoiceQuestion:
84 $choices = $question->getChoices();
85 $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($choices[$default]));
90 $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, OutputFormatter::escape($default));
93 $output->writeln($text);
95 if ($question instanceof ChoiceQuestion) {
96 $width = max(array_map('strlen', array_keys($question->getChoices())));
98 foreach ($question->getChoices() as $key => $value) {
99 $output->writeln(sprintf(" [<comment>%-${width}s</comment>] %s", $key, $value));
103 $output->write(' > ');
109 protected function writeError(OutputInterface $output, \Exception $error)
111 if ($output instanceof SymfonyStyle) {
113 $output->error($error->getMessage());
118 parent::writeError($output, $error);