I am trying to get Symfony's UniqueEntity validator working for my Doctrine entities. The Symfony validator is already hooked up and working, the UniqueEntity from Symfony\Bridge, however, is more challenging, displaying this error:
PHP Fatal error: Class 'doctrine.orm.validator.unique' not found in /app/vendor/symfony/validator/Symfony/Component/Validator/ConstraintValidatorFactory.php on line 46
It appears as if the ValidatorFactory is requesting the UniqueEntity validator from the Symfony container, which I don't have because I am not using full stack symfony.
My entity looks like this:
<?php
namespace App\Model;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as AssertDoctrine;
/**
* User
*
* @ORM\Table(name="users", uniqueConstraints={@ORM\UniqueConstraint(name="id_UNIQUE", columns={"id"}), @ORM\UniqueConstraint(name="username_UNIQUE", columns={"username"})})
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @AssertDoctrine\UniqueEntity("username")
*/
class User extends AbstractEntity
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=45, unique=true, nullable=false)
* @Assert\Length(min=3, max=45)
*/
protected $username;
/** ... */
}
where AbstractEntity is a mapped superclass including a Trait that provides validation functionality for all entities:
<?php
namespace App\Model\Traits;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Validation;
use App\Utility\Exception\ConstraintViolationException;
/**
* A trait enabling validation of Doctrine entities to ensure invalid entities
* don't reach the persistence layer.
*/
trait ValidatorAwareTrait
{
public function validate()
{
$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();
$violations = $validator->validate($this);
// Count is used as this is not an array but a ConstraintViolationList
if (count($violations) !== 0) {
$message = $violations[0]->getPropertyPath() . ': ' . $violations[0]->getMessage();
throw new ConstraintViolationException($message);
}
return true;
}
}