Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Validator] Constraints cache with private properties #20488

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions validation/custom_constraint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------------------

Expand Down
Loading