From f7b5169f405d491eb9fe6939ba8034c374a63598 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Sun, 22 Dec 2024 12:09:11 +0100 Subject: [PATCH 1/2] Constraints cache with private properties --- validation/custom_constraint.rst | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 9d3fb920d6d..3fd1afbeddc 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -66,6 +66,46 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required:: } } +Constraint with private properties +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Constraints are cached for efficiency, but private properties are not supported +by default. + +So if you're using private properties in your constraint, you must override default +``__sleep`` method :: + + // src/Validator/ContainsAlphanumeric.php + namespace App\Validator; + + use Symfony\Component\Validator\Attribute\HasNamedArguments; + use Symfony\Component\Validator\Constraint; + + #[\Attribute] + class ContainsAlphanumeric extends Constraint + { + public string $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.'; + + #[HasNamedArguments] + public function __construct( + private string $mode, + ?array $groups = null, + mixed $payload = null, + ) { + parent::__construct([], $groups, $payload); + } + + public function __sleep(): array + { + return array_merge( + parent::__sleep(), + [ + 'mode' + ] + ); + } + } + Creating the Validator itself ----------------------------- From c4e7c728d066864c3140c3c0da0ae1d3a3f5269b Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Fri, 3 Jan 2025 13:31:54 +0100 Subject: [PATCH 2/2] Reword --- validation/custom_constraint.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 3fd1afbeddc..5f0740885d5 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -66,14 +66,15 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required:: } } -Constraint with private properties +Constraint with Private Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Constraints are cached for efficiency, but private properties are not supported -by default. +Constraints are cached for performance reasons. To achieve this, the base +``Constraint`` class uses PHP's :phpfunction:`get_object_vars()` function, which +excludes private properties of child classes. -So if you're using private properties in your constraint, you must override default -``__sleep`` method :: +If your constraint defines private properties, you must explicitly include them +in the ``__sleep()`` method to ensure they are serialized correctly:: // src/Validator/ContainsAlphanumeric.php namespace App\Validator;