[Console] Fix validation of null values using SymfonyStyle::ask()

This commit is contained in:
Robin Chalas 2016-10-03 19:29:11 +02:00
parent 9ed8d576e1
commit a8b910bec2
No known key found for this signature in database
GPG Key ID: 89672113756EE03B
2 changed files with 15 additions and 5 deletions

View File

@ -34,11 +34,11 @@ class SymfonyQuestionHelper extends QuestionHelper
$question->setValidator(function ($value) use ($validator) {
if (null !== $validator) {
$value = $validator($value);
}
// make required
if (!is_array($value) && !is_bool($value) && 0 === strlen($value)) {
throw new \Exception('A value is required.');
} else {
// make required
if (!is_array($value) && !is_bool($value) && 0 === strlen($value)) {
throw new \Exception('A value is required.');
}
}
return $value;

View File

@ -6,6 +6,7 @@ use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Question\ChoiceQuestion;
/**
@ -73,6 +74,15 @@ class SymfonyQuestionHelperTest extends \PHPUnit_Framework_TestCase
$this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output);
}
public function testAskReturnsNullIfValidatorAllowsIt()
{
$questionHelper = new SymfonyQuestionHelper();
$questionHelper->setInputStream($this->getInputStream("\n"));
$question = new Question('What is your favorite superhero?');
$question->setValidator(function ($value) { return $value; });
$this->assertNull($questionHelper->ask($this->createInputInterfaceMock(), $this->createOutputInterface(), $question));
}
protected function getInputStream($input)
{
$stream = fopen('php://memory', 'r+', false);