PHP code example of cryonighter / validation-override-bundle

1. Go to this page and download the library: Download cryonighter/validation-override-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cryonighter / validation-override-bundle example snippets


// config/bundles.php
return [
    // ...
    Cryonighter\ValidationOverrideBundle\ValidationOverrideBundle::class => ['all' => true],
];

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);
        // ...
    }
}