UniqueEntityValidator.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Doctrine\Validator\Constraints;
  11. use Symfony\Bridge\Doctrine\RegistryInterface;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  15. use Symfony\Component\Validator\ConstraintValidator;
  16. /**
  17. * Unique Entity Validator checks if one or a set of fields contain unique values.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class UniqueEntityValidator extends ConstraintValidator
  22. {
  23. /**
  24. * @var RegistryInterface
  25. */
  26. private $registry;
  27. /**
  28. * @param RegistryInterface $registry
  29. */
  30. public function __construct(RegistryInterface $registry)
  31. {
  32. $this->registry = $registry;
  33. }
  34. /**
  35. * @param object $entity
  36. * @param Constraint $constraint
  37. * @return bool
  38. */
  39. public function isValid($entity, Constraint $constraint)
  40. {
  41. if (!is_array($constraint->fields) && !is_string($constraint->fields)) {
  42. throw new UnexpectedTypeException($constraint->fields, 'array');
  43. }
  44. $fields = (array)$constraint->fields;
  45. if (count($fields) == 0) {
  46. throw new ConstraintDefinitionException("At least one field has to be specified.");
  47. }
  48. $em = $this->registry->getEntityManager($constraint->em);
  49. $className = $this->context->getCurrentClass();
  50. $class = $em->getClassMetadata($className);
  51. $criteria = array();
  52. foreach ($fields as $fieldName) {
  53. if (!isset($class->reflFields[$fieldName])) {
  54. throw new ConstraintDefinitionException("Only field names mapped by Doctrine can be validated for uniqueness.");
  55. }
  56. $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity);
  57. if ($criteria[$fieldName] === null) {
  58. return true;
  59. }
  60. }
  61. $repository = $em->getRepository($className);
  62. $result = $repository->findBy($criteria);
  63. if (count($result) > 0 && $result[0] !== $entity) {
  64. $oldPath = $this->context->getPropertyPath();
  65. $this->context->setPropertyPath( empty($oldPath) ? $fields[0] : $oldPath.".".$fields[0]);
  66. $this->context->addViolation($constraint->message, array(), $criteria[$fields[0]]);
  67. $this->context->setPropertyPath($oldPath);
  68. }
  69. return true; // all true, we added the violation already!
  70. }
  71. }