feature #29658 [Validator] Choices constraint improvement (nikophil)

This PR was merged into the 4.3-dev branch.

Discussion
----------

[Validator] Choices constraint improvement

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT

Hi,

here is a little improvement for the choice constraint:  expose a new `choices` wildcard for the messages, in order to provide a way to display easily the valid choices to the user.

thanks.

Commits
-------

71dfa35a21 add new `choices` wildcard in message
This commit is contained in:
Fabien Potencier 2019-01-02 10:34:24 +01:00
commit c7d6bda56a
2 changed files with 7 additions and 0 deletions

View File

@ -68,6 +68,7 @@ class ChoiceValidator extends ConstraintValidator
if (!\in_array($_value, $choices, true)) {
$this->context->buildViolation($constraint->multipleMessage)
->setParameter('{{ value }}', $this->formatValue($_value))
->setParameter('{{ choices }}', $this->formatValues($choices))
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->setInvalidValue($_value)
->addViolation();
@ -100,6 +101,7 @@ class ChoiceValidator extends ConstraintValidator
} elseif (!\in_array($value, $choices, true)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ choices }}', $this->formatValues($choices))
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->addViolation();
}

View File

@ -169,6 +169,7 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setParameter('{{ choices }}', '"foo", "bar"')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
@ -186,6 +187,7 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setParameter('{{ choices }}', '')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
@ -202,6 +204,7 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setParameter('{{ choices }}', '"foo", "bar"')
->setInvalidValue('baz')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
@ -275,6 +278,7 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"2"')
->setParameter('{{ choices }}', '1, 2')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
@ -291,6 +295,7 @@ class ChoiceValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"3"')
->setParameter('{{ choices }}', '1, 2, 3')
->setInvalidValue('3')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();