Skip to content

Commit f05ce63

Browse files
KoNekoDfabpot
authored andcommitted
[Validator] Pass context to expressions used in When constraints
1 parent 52f1436 commit f05ce63

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

src/Symfony/Component/Validator/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ CHANGELOG
1212
* Add the `WordCount` constraint
1313
* Add the `Week` constraint
1414
* Add `CompoundConstraintTestCase` to ease testing Compound Constraints
15+
* Add context variable to `WhenValidator`
1516

1617
7.1
1718
---

src/Symfony/Component/Validator/Constraints/WhenValidator.php

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public function validate(mixed $value, Constraint $constraint): void
3333
$variables = $constraint->values;
3434
$variables['value'] = $value;
3535
$variables['this'] = $context->getObject();
36+
$variables['context'] = $context;
3637

3738
if ($this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
3839
$context->getValidator()->inContext($context)

src/Symfony/Component/Validator/Tests/Constraints/WhenValidatorTest.php

+25
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,31 @@ public function testConstraintsAreExecutedWithObject()
8585
]));
8686
}
8787

88+
public function testConstraintsAreExecutedWithNestedObject()
89+
{
90+
$parent = new \stdClass();
91+
$parent->child = new \stdClass();
92+
$parent->ok = true;
93+
94+
$number = new \stdClass();
95+
$number->value = 1;
96+
97+
$this->setObject($parent);
98+
$this->setPropertyPath('child.value');
99+
$this->setRoot($parent);
100+
101+
$constraints = [
102+
new PositiveOrZero(),
103+
];
104+
105+
$this->expectValidateValue(0, $number->value, $constraints);
106+
107+
$this->validator->validate($number->value, new When([
108+
'expression' => 'context.getRoot().ok === true',
109+
'constraints' => $constraints,
110+
]));
111+
}
112+
88113
public function testConstraintsAreExecutedWithValue()
89114
{
90115
$constraints = [

0 commit comments

Comments
 (0)