PHP code example of ensostudio / doctrine-entity-validator

1. Go to this page and download the library: Download ensostudio/doctrine-entity-validator 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/ */

    

ensostudio / doctrine-entity-validator example snippets


use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use \EnsoStudio\Doctrine\ORM\ColumnValidators;
use EnsoStudio\Doctrine\ORM\EntityValidator;
use EnsoStudio\Doctrine\ORM\EntityValidationException;

#[ORM\Entity]
#[ORM\Table(name: 'products')]
#[ORM\HasLifecycleCallbacks]
class Product
{
    ...

    #[ORM\Column(type: Types::STRING, length: 200)]
    #[ColumnValidators\MinLength(2)]
    #[ColumnValidators\Slug]
    private string $slug;

    #[ORM\Column(type: Types::STRING, length: 150)]
    #[ColumnValidators\Type('print')]
    private string $name;

    #[ORM\PrePersist]
    public function beforeInsert(): void
    {
        $validator = new EntityValidator($this);
        // Callback same to ColumnValidators\MinLength(3)
        $validator->addValidator(
            'name', 
            static function (string $propertyValue, string $propertyName, object $entity) {
                if (mb_strlen($propertyValue) < 3) {
                    throw new EntityValidationException(
                        ['% less than 3 characters', $propertyName],
                        $propertyName,
                        $entity
                    );
                }
            }
        );
        $validator->validate();
    }

    #[ORM\PreUpdate]
    public function beforeUpdate(): void
    {
        $validator = new EntityValidator($this);
        ...
        $validator->validate(true);
    }
}

use Doctrine\ORM\EntityManager;
use EnsoStudio\Doctrine\ORM\EntityValidationSubscriber;

...
$entityManager = new EntityManager($connection, $config);
$entityManager->getEventManager()
    ->addEventSubscriber(new EntityValidationSubscriber(true));