Created
January 1, 2011 22:56
-
-
Save janmarek/762075 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
nutno použít stable verzi Doctriny, jinak to vybouchne |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Symfony\Component\Validator\Constraints; | |
/** | |
* @author Roman Sklenář, Jan Marek | |
* @link https://gist.github.com/664454 | |
*/ | |
class Unique extends \Symfony\Component\Validator\Constraint | |
{ | |
public $message = 'This value should be unique'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Symfony\Component\Validator\Constraints; | |
use Doctrine\ORM\UnitOfWork; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
/** | |
* @author Roman Sklenář, Jan Marek | |
* @link https://gist.github.com/664454 | |
*/ | |
class UniqueValidator extends ConstraintValidator | |
{ | |
public function isValid($value, Constraint $constraint) | |
{ | |
/* @var $context Symfony\Component\Validator\ValidationContext */ | |
$context = $this->context; | |
$property = $context->getCurrentProperty(); | |
$em = \Nette\Environment::getService('Doctrine\ORM\EntityManager'); | |
$entity = $context->getRoot(); | |
$qb = $em->getRepository(get_class($entity))->createQueryBuilder('e'); | |
$qb->select('count(e.id)')->where("e.$property = ?1")->setParameter('1', $value); | |
if ($entity->getId()) { | |
$qb->andWhere('e.id <> ?2')->setParameter('2', $entity->getId()); | |
} | |
$count = $qb->getQuery()->getSingleScalarResult(); | |
$valid = (int) $count === 0; | |
if ($valid) { | |
return true; | |
} else { | |
$this->setMessage($constraint->message, array('value' => $value)); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment