diff --git a/src/Symfony/Component/Validator/Constraints/Choice.php b/src/Symfony/Component/Validator/Constraints/Choice.php index 8c4c23ad0ed65..f45b6dc5b3cce 100644 --- a/src/Symfony/Component/Validator/Constraints/Choice.php +++ b/src/Symfony/Component/Validator/Constraints/Choice.php @@ -33,6 +33,7 @@ class Choice extends Constraint public $choices; public $callback; + public $enum; public $multiple = false; public $strict = true; public $min; diff --git a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php index 2dc5b182ff80e..56e90e73de568 100644 --- a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php +++ b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php @@ -34,7 +34,7 @@ public function validate($value, Constraint $constraint) throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Choice'); } - if (!is_array($constraint->choices) && !$constraint->callback) { + if (!is_array($constraint->choices) && !$constraint->callback && !$constraint->enum) { throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice'); } @@ -54,6 +54,9 @@ public function validate($value, Constraint $constraint) throw new ConstraintDefinitionException('The Choice constraint expects a valid callback'); } $choices = call_user_func($choices); + } elseif ($constraint->enum) { + $enum = new \ReflectionClass($constraint->enum); + $choices = $enum->getConstants(); } else { $choices = $constraint->choices; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index 38607bb9a8891..774047420c66a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -22,6 +22,9 @@ function choice_callback() class ChoiceValidatorTest extends ConstraintValidatorTestCase { + const FOO = 'foo'; + const BAR = 'bar'; + protected function createValidator() { return new ChoiceValidator(); @@ -67,7 +70,7 @@ public function testNullIsValid() /** * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ - public function testChoicesOrCallbackExpected() + public function testChoicesOrCallbackOrEnumExpected() { $this->validator->validate('foobar', new Choice()); } @@ -146,6 +149,15 @@ public function testValidChoiceCallbackContextObjectMethod() $this->assertNoViolation(); } + public function testValidChoiceClassConstantsEnum() + { + $constraint = new Choice(array('enum' => __CLASS__)); + + $this->validator->validate('foo', $constraint); + + $this->assertNoViolation(); + } + public function testMultipleChoices() { $constraint = new Choice(array(