Skip to content

[Validator] New feature: Choice validator / enum struct for choices #21356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/Constraints/Choice.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class Choice extends Constraint

public $choices;
public $callback;
public $enum;
public $multiple = false;
public $strict = true;
public $min;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function choice_callback()

class ChoiceValidatorTest extends ConstraintValidatorTestCase
{
const FOO = 'foo';
const BAR = 'bar';

protected function createValidator()
{
return new ChoiceValidator();
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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(
Expand Down