From 02d2769914c4953dfa3e926ad8a51ec6a776020d Mon Sep 17 00:00:00 2001 From: symfonyaml <> Date: Mon, 21 Oct 2024 17:02:42 +0200 Subject: [PATCH] [Validator] [Choice] Fix callback option if not array returned --- .../Validator/Constraints/ChoiceValidator.php | 3 +++ .../Tests/Constraints/ChoiceValidatorTest.php | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php index a1c47a6bb22ed..5fa5318ceac39 100644 --- a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php +++ b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php @@ -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; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index 5c3bcc4720353..d625884ecc8f7 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -39,6 +39,11 @@ public function objectMethodCallback() return ['foo', 'bar']; } + public static function staticCallbackInvalid() + { + return null; + } + public function testExpectArrayIfMultipleIsTrue() { $this->expectException(UnexpectedValueException::class); @@ -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"