namespace App\Validator;
use App\Dto\MyDto;
use Cryonighter\ValidationOverrideBundle\Validator\DynamicRulesProviderInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class MyClassRulesProvider implements DynamicRulesProviderInterface
{
public function supports(string $className): bool
{
return $className === MyDto::class;
}
public function modify(ClassMetadata $metadata): void
{
// Add a constraint
$metadata->addPropertyConstraint('email', new Assert\Email());
// Remove a constraint type from a property
$this->removeConstraint($metadata, 'name', Assert\NotBlank::class);
}
private function removeConstraint(ClassMetadata $metadata, string $property, string $constraintClass): void
{
foreach ($metadata->getPropertyMetadata($property) as $memberMetadata) {
$ref = new \ReflectionClass(\Symfony\Component\Validator\Mapping\GenericMetadata::class);
$constraintsProp = $ref->getProperty('constraints');
$constraintsProp->setValue($memberMetadata, array_values(array_filter(
$constraintsProp->getValue($memberMetadata),
fn($c) => !($c instanceof $constraintClass),
)));
$byGroupProp = $ref->getProperty('constraintsByGroup');
$byGroup = $byGroupProp->getValue($memberMetadata);
foreach ($byGroup as $group => $groupConstraints) {
$byGroup[$group] = array_values(array_filter(
$groupConstraints,
fn($c) => !($c instanceof $constraintClass),
));
}
$byGroupProp->setValue($memberMetadata, $byGroup);
}
}
}
use Symfony\Component\Validator\Validator\ValidatorInterface;
class MyService
{
public function __construct(private readonly ValidatorInterface $validator) {}
public function process(MyDto $dto): void
{
$violations = $this->validator->validate($dto);
// ...
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.