Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 756103d

Browse files
committed
[Console] Added the ability to return the default answer in a question
1 parent a469c56 commit 756103d

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/Symfony/Component/Console/Question/Question.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class Question
2525
private $autocompleterValues;
2626
private $validator;
2727
private $default;
28+
private $showDefault = false;
2829
private $normalizer;
2930

3031
/**
@@ -46,6 +47,10 @@ public function __construct($question, $default = null)
4647
*/
4748
public function getQuestion()
4849
{
50+
if ($this->showDefault) {
51+
return sprintf('%s [%s]', $this->question, $this->default);
52+
}
53+
4954
return $this->question;
5055
}
5156

@@ -59,6 +64,20 @@ public function getDefault()
5964
return $this->default;
6065
}
6166

67+
/**
68+
* Sets whether the default answer should be shown to the user in the quetion
69+
*
70+
* @param bool $showDefault
71+
*
72+
* @return Question The current instance
73+
*/
74+
public function setShowDefault($showDefault)
75+
{
76+
$this->showDefault = (bool) $showDefault;
77+
78+
return $this;
79+
}
80+
6281
/**
6382
* Returns whether the user response must be hidden.
6483
*

src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,24 @@ public function testAskChoice()
7575
$this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
7676
}
7777

78+
public function testAskWithShowDefaults()
79+
{
80+
$dialog = new QuestionHelper();
81+
82+
$dialog->setInputStream($this->getInputStream("\n8AM\n"));
83+
84+
$question = new Question('What time is it?', '2PM');
85+
$question->setShowDefault(true);
86+
$this->assertEquals('2PM', $dialog->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
87+
88+
$question = new Question('What time is it?', '2PM');
89+
$question->setShowDefault(true);
90+
$this->assertEquals('8AM', $dialog->ask($this->createInputInterfaceMock(), $output = $this->createOutputInterface(), $question));
91+
92+
rewind($output->getStream());
93+
$this->assertEquals('What time is it? [2PM]', stream_get_contents($output->getStream()));
94+
}
95+
7896
public function testAsk()
7997
{
8098
$dialog = new QuestionHelper();

0 commit comments

Comments
 (0)