8000 feature #58512 [Validator] Pass context to expressions used in `When`… · symfony/symfony@6e9c993 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6e9c993

Browse files
committed
feature #58512 [Validator] Pass context to expressions used in When constraints (KoNekoD)
This PR was squashed before being merged into the 7.2 branch. Discussion ---------- [Validator] Pass context to expressions used in `When` constraints | Q | A | ------------- | --- | Branch? | 7.2 | Bug fix? | no | New feature? | yes | Deprecations? | no | Issues | Fix #58511 | License | MIT I encountered a problem with validation of nested entities and I needed to validate by parent field, if draft true then no validation is needed Commits ------- f05ce63 [Validator] Pass context to expressions used in `When` constraints
2 parents 5763273 + f05ce63 commit 6e9c993

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

src/Symfony/Component/Validator/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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

Lines changed: 25 additions & 0 deletions
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)
0