[Doctrine] Add Unique Validator

This commit is contained in:
Benjamin Eberlei 2011-05-17 23:04:13 +02:00
parent a965a5ce32
commit cfc2471109
3 changed files with 88 additions and 0 deletions

View File

@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class UniqueEntity extends \Symfony\Component\Validator\Constraint
{
public $message = 'This value is already used.';
public $entityManagerName = false;
public $fields = array();
/**
* {@inheritDoc}
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Validator;
class UniqueEntityValidator extends ConstraintValidator
{
/**
* @var Registry
*/
private $registry;
public function __construct(Registry $registry)
{
$this->registry = $registry;
}
public function isValid($entity, Constraint $constraint)
{
$emName = $constraint->entityManagerName ?: $this->registry->getDefaultConnectionName();
$em = $this->registry->getEntityManager($emName);
$className = $this->context->getCurrentClass();
$class = $em->getClassMetadata($className);
$criteria = array();
foreach ($contraint->fields AS $fieldName) {
$criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity);
}
$repository = $em->getRepository($className);
$result = $repository->findBy($criteria);
if (count($result) > 0 && $result[0] !== $entity) {
$this->setMessage($constraint->message);
return false;
}
return true;
}
}

View File

@ -13,8 +13,17 @@ namespace Symfony\Component\Validator;
abstract class ConstraintValidator implements ConstraintValidatorInterface
{
/**
* @var ExecutionContext
*/
protected $context;
/**
* @var string
*/
private $messageTemplate;
/**
* @var array
*/
private $messageParameters;
/**