Skip to content

[Validator] [Choice] Fix callback option if not array returned #58615

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

Merged
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ public function validate($value, Constraint $constraint)
throw new ConstraintDefinitionException('The Choice constraint expects a valid callback.');
}
$choices = $choices();
if (!is_array($choices)) {
throw new ConstraintDefinitionException(sprintf('The Choice constraint callback "%s" is expected to return an array, but returned "%s".', trim($this->formatValue($constraint->callback), '"'), get_debug_type($choices)));
}
} else {
$choices = $constraint->choices;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ public function objectMethodCallback()
return ['foo', 'bar'];
}

public static function staticCallbackInvalid()
{
return null;
}

public function testExpectArrayIfMultipleIsTrue()
{
$this->expectException(UnexpectedValueException::class);
Expand Down Expand Up @@ -134,6 +139,19 @@ public function testValidChoiceCallbackContextMethod()
$this->assertNoViolation();
}

public function testInvalidChoiceCallbackContextMethod()
{
$this->expectException(ConstraintDefinitionException::class);
$this->expectExceptionMessage('The Choice constraint callback "staticCallbackInvalid" is expected to return an array, but returned "null".');

// search $this for "staticCallbackInvalid"
$this->setObject($this);

$constraint = new Choice(['callback' => 'staticCallbackInvalid']);

$this->validator->validate('bar', $constraint);
}

public function testValidChoiceCallbackContextObjectMethod()
{
// search $this for "objectMethodCallback"
Expand Down