Skip to content

Commit 4d3fed6

Browse files
[Validator] Add support for closures in the When constraint
1 parent 903614c commit 4d3fed6

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

reference/constraints/When.rst

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,11 +174,12 @@ Options
174174
``expression``
175175
~~~~~~~~~~~~~~
176176

177-
**type**: ``string``
177+
**type**: ``string|Closure``
178178

179-
The condition written with the expression language syntax that will be evaluated.
180-
If the expression evaluates to a falsey value (i.e. using ``==``, not ``===``),
181-
validation of constraints won't be triggered.
179+
The condition as a closure or written with the expression language syntax
180+
that will be evaluated. If the the closure return value or the evaluated expression
181+
is a falsey value (i.e. using ``==``, not ``===``), validation of constraints won't
182+
be triggered.
182183

183184
To learn more about the expression language syntax, see
184185
:doc:`/reference/formats/expression_language`.
@@ -200,6 +201,13 @@ in your expression:
200201

201202
The ``context`` variable in expressions was introduced in Symfony 7.2.
202203

204+
When using a closure, the first argument is the object being validated.
205+
206+
.. versionadded:: 7.3
207+
208+
The support for closure in the ``expression`` option was introduced in Symfony 7.3
209+
and requires PHP 8.5.
210+
203211
The ``value`` variable can be used when you want to execute more complex
204212
validation based on its value:
205213

@@ -215,11 +223,22 @@ validation based on its value:
215223
216224
class Discount
217225
{
226+
// using an expression
218227
#[Assert\When(
219228
expression: 'value == "percent"',
220229
constraints: [new Assert\Callback('doComplexValidation')],
221230
)]
222231
private ?string $type;
232+
233+
// using a closure
234+
#[Assert\When(
235+
expression: static function (Discount $discount) {
236+
return $discount->getType() === 'percent';
237+
},
238+
constraints: [new Assert\Callback('doComplexValidation')],
239+
)]
240+
private ?int $amount;
241+
223242
// ...
224243
225244
public function doComplexValidation(ExecutionContextInterface $context, $payload): void

0 commit comments

Comments
 (0)