diff --git a/src/Symfony/Component/Validator/CHANGELOG.md b/src/Symfony/Component/Validator/CHANGELOG.md index b9af46e493aa9..6b5be184c0101 100644 --- a/src/Symfony/Component/Validator/CHANGELOG.md +++ b/src/Symfony/Component/Validator/CHANGELOG.md @@ -12,6 +12,7 @@ CHANGELOG * Add the `WordCount` constraint * Add the `Week` constraint * Add `CompoundConstraintTestCase` to ease testing Compound Constraints + * Add context variable to `WhenValidator` 7.1 --- diff --git a/src/Symfony/Component/Validator/Constraints/WhenValidator.php b/src/Symfony/Component/Validator/Constraints/WhenValidator.php index c02a450e8c399..b41ba83ff48df 100644 --- a/src/Symfony/Component/Validator/Constraints/WhenValidator.php +++ b/src/Symfony/Component/Validator/Constraints/WhenValidator.php @@ -33,6 +33,7 @@ public function validate(mixed $value, Constraint $constraint): void $variables = $constraint->values; $variables['value'] = $value; $variables['this'] = $context->getObject(); + $variables['context'] = $context; if ($this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) { $context->getValidator()->inContext($context) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/WhenValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/WhenValidatorTest.php index cba81b25af34a..f79d530319b44 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/WhenValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/WhenValidatorTest.php @@ -85,6 +85,31 @@ public function testConstraintsAreExecutedWithObject() ])); } + public function testConstraintsAreExecutedWithNestedObject() + { + $parent = new \stdClass(); + $parent->child = new \stdClass(); + $parent->ok = true; + + $number = new \stdClass(); + $number->value = 1; + + $this->setObject($parent); + $this->setPropertyPath('child.value'); + $this->setRoot($parent); + + $constraints = [ + new PositiveOrZero(), + ]; + + $this->expectValidateValue(0, $number->value, $constraints); + + $this->validator->validate($number->value, new When([ + 'expression' => 'context.getRoot().ok === true', + 'constraints' => $constraints, + ])); + } + public function testConstraintsAreExecutedWithValue() { $constraints = [