Skip to content

Instantly share code, notes, and snippets.

@rmrfself
Created June 7, 2012 06:53
Show Gist options
  • Save rmrfself/2887026 to your computer and use it in GitHub Desktop.
Save rmrfself/2887026 to your computer and use it in GitHub Desktop.
@unique annotation support for Symfony 2 Validator with Nette, for more info see: http://docs.symfony-reloaded.org/guides/validator.html
<?php
namespace Symfony\Component\Validator\Constraints;
class Unique extends \Symfony\Component\Validator\Constraint
{
public $message = 'Entity with this property %value% already exists'; # 'Symfony.Validator.Unique.message';
}
<?php
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UniqueValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
/* @var $context Symfony\Component\Validator\ValidationContext */
$context = $this->context;
/* @var $entity Models\Entities\Base */
$entity = $context->getRoot();
$property = $context->getCurrentProperty();
$originalEntityData = $this->getEntityManager()->getUnitOfWork()->getOriginalEntityData($entity);
$originalValue = isset($originalEntityData[$property]) ? $originalEntityData[$property] : NULL;
if ($originalValue === $value) { // check if attribute was changed
return TRUE;
}
$class = $entity->getReflection()->getName();
/* @var $repo Models\Repositories\Base */
$repo = $this->getEntityManager()->getRepository($class);
$valid = $repo->exists(array($property => $value)) == FALSE;
if ($valid) {
return true;
} else {
$this->setMessage($constraint->message, array('value' => $value));
return false;
}
}
/**
* @return Doctrine\ORM\EntityManager
*/
private function getEntityManager()
{
return \Nette\Environment::getEntityManager();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment