File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -62,6 +62,47 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required::
6262 }
6363 }
6464
65+ Constraint with Private Properties
66+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67+
68+ Constraints are cached for performance reasons. To achieve this, the base
69+ ``Constraint `` class uses PHP's :phpfunction: `get_object_vars() ` function, which
70+ excludes private properties of child classes.
71+
72+ If your constraint defines private properties, you must explicitly include them
73+ in the ``__sleep() `` method to ensure they are serialized correctly::
74+
75+ // src/Validator/ContainsAlphanumeric.php
76+ namespace App\Validator;
77+
78+ use Symfony\Component\Validator\Attribute\HasNamedArguments;
79+ use Symfony\Component\Validator\Constraint;
80+
81+ #[\Attribute]
82+ class ContainsAlphanumeric extends Constraint
83+ {
84+ public string $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
85+
86+ #[HasNamedArguments]
87+ public function __construct(
88+ private string $mode,
89+ ?array $groups = null,
90+ mixed $payload = null,
91+ ) {
92+ parent::__construct([], $groups, $payload);
93+ }
94+
95+ public function __sleep(): array
96+ {
97+ return array_merge(
98+ parent::__sleep(),
99+ [
100+ 'mode'
101+ ]
102+ );
103+ }
104+ }
105+
65106Creating the Validator itself
66107-----------------------------
67108
You can’t perform that action at this time.
0 commit comments