diff --git a/src/Symfony/Component/Console/Question/Question.php b/src/Symfony/Component/Console/Question/Question.php index 3003f19c551dd..cfb2e400beb16 100644 --- a/src/Symfony/Component/Console/Question/Question.php +++ b/src/Symfony/Component/Console/Question/Question.php @@ -25,6 +25,7 @@ class Question private $autocompleterValues; private $validator; private $default; + private $showDefault = false; private $normalizer; /** @@ -46,6 +47,10 @@ public function __construct($question, $default = null) */ public function getQuestion() { + if ($this->showDefault) { + return sprintf('%s [%s]', $this->question, $this->default); + } + return $this->question; } @@ -59,6 +64,20 @@ public function getDefault() return $this->default; } + /** + * Sets whether the default answer should be shown to the user in the question + * + * @param bool $showDefault + * + * @return Question The current instance + */ + public function setShowDefault($showDefault) + { + $this->showDefault = (bool) $showDefault; + + return $this; + } + /** * Returns whether the user response must be hidden. * diff --git a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php index bba25375dc742..9189d952314ee 100644 --- a/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php @@ -75,6 +75,24 @@ public function testAskChoice() $this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); } + public function testAskWithShowDefaults() + { + $dialog = new QuestionHelper(); + + $dialog->setInputStream($this->getInputStream("\n8AM\n")); + + $question = new Question('What time is it?', '2PM'); + $question->setShowDefault(true); + $this->assertEquals('2PM', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question)); + + $question = new Question('What time is it?', '2PM'); + $question->setShowDefault(true); + $this->assertEquals('8AM', $dialog->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question)); + + rewind($output->getStream()); + $this->assertEquals('What time is it? [2PM]', stream_get_contents($output->getStream())); + } + public function testAsk() { $dialog = new QuestionHelper();