PHP code example of atournayre / entity-validation

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

    

atournayre / entity-validation example snippets


namespace App\Entity;

use Atournayre\EntityValidation\ValidableEntityTrait;

class YourEntity implements ValidableEntityInterface
{
    // Your code
    
    use ValidableEntityTrait;
}



namespace App\Entity\YourEntity;

use Atournayre\EntityValidation\ConstraintViolationListCollectionBuilder;
use Atournayre\EntityValidation\ConstraintValidator;
use Atournayre\EntityValidation\ConstraintViolationListCollection;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints as Assert;

class YourEntityConstraintValidator extends ConstraintValidator
{
    /**
     * @throws \Exception
     */
    public function __construct()
    {
        $this->throwExceptionIfConstraintClassDoNotExists(__CLASS__);
    }

    /**
     * @param YourEntity $value
     * @param Constraint|null $constraint
     * @return ConstraintViolationListCollection
     */
    public function validate($value, Constraint $constraint = null): ConstraintViolationListCollection
    {
        $constraintViolationListCollectionBuilder = ConstraintViolationListCollectionBuilder::create();

        if (!$value instanceof YourEntity) {
            return $constraintViolationListCollectionBuilder->build();
        }

        return $constraintViolationListCollectionBuilder
            // Suppose YourEntity has method getEmail()
            ->add($value->getEmail(), new Assert\Email())
            // You can also specify propertyPath to get error attached properly in the form
            //->add($value->getEmail(), new Assert\Email(), 'email')
            ->build();
    }
}

$entity = new YourEntity();

// To perform manual validation
/** @var ConstraintViolationListCollection $constraintViolationListCollection */
$constraintViolationListCollection = $entity->validate();

// Check if entity has violations
$hasViolations = $constraintViolationListCollection->count() != 0;

// To get only messages
$messages = $constraintViolationListCollection->getMessages();

// To get only invalid properties
$invalidProperties = $constraintViolationListCollection->getPropertiesPaths();

// To get only invalid properties without brackets
$invalidProperties = $constraintViolationListCollection->getPropertiesPaths(true);

// Before $form->isValid(), call the line below, it will add errors to form for invalid values
EntityValidationHelper::form($form);