Skip to content

Commit

Permalink
Merge branch '6.4' into 7.1
Browse files Browse the repository at this point in the history
* 6.4:
  Reword
  Constraints cache with private properties
  • Loading branch information
javiereguiluz committed Jan 3, 2025
2 parents 0910ba0 + c4e7c72 commit fb2b274
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions validation/custom_constraint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,47 @@ You can use ``#[HasNamedArguments]`` to make some constraint options required::
}
}

Constraint with Private Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Constraints are cached for performance reasons. To achieve this, the base
``Constraint`` class uses PHP's :phpfunction:`get_object_vars()` function, which

Check failure on line 69 in validation/custom_constraint.rst

View workflow job for this annotation

GitHub Actions / Lint (DOCtor-RST)

Please do not use () at the end of PHP function
excludes private properties of child classes.

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;

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
-----------------------------

Expand Down

0 comments on commit fb2b274

Please sign in to comment.