UniqueEntityValidator.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 Doctrine\Common\Persistence\ManagerRegistry;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  15. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  16. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  17. /**
  18. * Unique Entity Validator checks if one or a set of fields contain unique values.
  19. *
  20. * @author Benjamin Eberlei <kontakt@beberlei.de>
  21. */
  22. class UniqueEntityValidator extends ConstraintValidator
  23. {
  24. private $registry;
  25. public function __construct(ManagerRegistry $registry)
  26. {
  27. $this->registry = $registry;
  28. }
  29. /**
  30. * @param object $entity
  31. * @param Constraint $constraint
  32. *
  33. * @throws UnexpectedTypeException
  34. * @throws ConstraintDefinitionException
  35. */
  36. public function validate($entity, Constraint $constraint)
  37. {
  38. if (!$constraint instanceof UniqueEntity) {
  39. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\UniqueEntity');
  40. }
  41. if (!\is_array($constraint->fields) && !\is_string($constraint->fields)) {
  42. throw new UnexpectedTypeException($constraint->fields, 'array');
  43. }
  44. if (null !== $constraint->errorPath && !\is_string($constraint->errorPath)) {
  45. throw new UnexpectedTypeException($constraint->errorPath, 'string or null');
  46. }
  47. $fields = (array) $constraint->fields;
  48. if (0 === \count($fields)) {
  49. throw new ConstraintDefinitionException('At least one field has to be specified.');
  50. }
  51. if (null === $entity) {
  52. return;
  53. }
  54. if ($constraint->em) {
  55. $em = $this->registry->getManager($constraint->em);
  56. if (!$em) {
  57. throw new ConstraintDefinitionException(sprintf('Object manager "%s" does not exist.', $constraint->em));
  58. }
  59. } else {
  60. $em = $this->registry->getManagerForClass(\get_class($entity));
  61. if (!$em) {
  62. throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', \get_class($entity)));
  63. }
  64. }
  65. $class = $em->getClassMetadata(\get_class($entity));
  66. /* @var $class \Doctrine\Common\Persistence\Mapping\ClassMetadata */
  67. $criteria = array();
  68. $hasNullValue = false;
  69. foreach ($fields as $fieldName) {
  70. if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) {
  71. throw new ConstraintDefinitionException(sprintf('The field "%s" is not mapped by Doctrine, so it cannot be validated for uniqueness.', $fieldName));
  72. }
  73. $fieldValue = $class->reflFields[$fieldName]->getValue($entity);
  74. if (null === $fieldValue) {
  75. $hasNullValue = true;
  76. }
  77. if ($constraint->ignoreNull && null === $fieldValue) {
  78. continue;
  79. }
  80. $criteria[$fieldName] = $fieldValue;
  81. if (null !== $criteria[$fieldName] && $class->hasAssociation($fieldName)) {
  82. /* Ensure the Proxy is initialized before using reflection to
  83. * read its identifiers. This is necessary because the wrapped
  84. * getter methods in the Proxy are being bypassed.
  85. */
  86. $em->initializeObject($criteria[$fieldName]);
  87. }
  88. }
  89. // validation doesn't fail if one of the fields is null and if null values should be ignored
  90. if ($hasNullValue && $constraint->ignoreNull) {
  91. return;
  92. }
  93. // skip validation if there are no criteria (this can happen when the
  94. // "ignoreNull" option is enabled and fields to be checked are null
  95. if (empty($criteria)) {
  96. return;
  97. }
  98. $repository = $em->getRepository(\get_class($entity));
  99. $result = $repository->{$constraint->repositoryMethod}($criteria);
  100. if ($result instanceof \IteratorAggregate) {
  101. $result = $result->getIterator();
  102. }
  103. /* If the result is a MongoCursor, it must be advanced to the first
  104. * element. Rewinding should have no ill effect if $result is another
  105. * iterator implementation.
  106. */
  107. if ($result instanceof \Iterator) {
  108. $result->rewind();
  109. if ($result instanceof \Countable && 1 < \count($result)) {
  110. $result = array($result->current(), $result->current());
  111. } else {
  112. $result = $result->current();
  113. $result = null === $result ? array() : array($result);
  114. }
  115. } elseif (\is_array($result)) {
  116. reset($result);
  117. } else {
  118. $result = null === $result ? array() : array($result);
  119. }
  120. /* If no entity matched the query criteria or a single entity matched,
  121. * which is the same as the entity being validated, the criteria is
  122. * unique.
  123. */
  124. if (!$result || (1 === \count($result) && current($result) === $entity)) {
  125. return;
  126. }
  127. $errorPath = null !== $constraint->errorPath ? $constraint->errorPath : $fields[0];
  128. $invalidValue = isset($criteria[$errorPath]) ? $criteria[$errorPath] : $criteria[$fields[0]];
  129. if ($this->context instanceof ExecutionContextInterface) {
  130. $this->context->buildViolation($constraint->message)
  131. ->atPath($errorPath)
  132. ->setInvalidValue($invalidValue)
  133. ->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
  134. ->addViolation();
  135. } else {
  136. $this->buildViolation($constraint->message)
  137. ->atPath($errorPath)
  138. ->setInvalidValue($invalidValue)
  139. ->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
  140. ->addViolation();
  141. }
  142. }
  143. }