UniqueEntityValidator.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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\Persistence\ManagerRegistry;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  15. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  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. private $registry;
  24. public function __construct(ManagerRegistry $registry)
  25. {
  26. $this->registry = $registry;
  27. }
  28. /**
  29. * @param object $entity
  30. *
  31. * @throws UnexpectedTypeException
  32. * @throws ConstraintDefinitionException
  33. */
  34. public function validate($entity, Constraint $constraint)
  35. {
  36. if (!$constraint instanceof UniqueEntity) {
  37. throw new UnexpectedTypeException($constraint, UniqueEntity::class);
  38. }
  39. if (!\is_array($constraint->fields) && !\is_string($constraint->fields)) {
  40. throw new UnexpectedTypeException($constraint->fields, 'array');
  41. }
  42. if (null !== $constraint->errorPath && !\is_string($constraint->errorPath)) {
  43. throw new UnexpectedTypeException($constraint->errorPath, 'string or null');
  44. }
  45. $fields = (array) $constraint->fields;
  46. if (0 === \count($fields)) {
  47. throw new ConstraintDefinitionException('At least one field has to be specified.');
  48. }
  49. if (null === $entity) {
  50. return;
  51. }
  52. if ($constraint->em) {
  53. $em = $this->registry->getManager($constraint->em);
  54. if (!$em) {
  55. throw new ConstraintDefinitionException(sprintf('Object manager "%s" does not exist.', $constraint->em));
  56. }
  57. } else {
  58. $em = $this->registry->getManagerForClass(\get_class($entity));
  59. if (!$em) {
  60. throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', get_debug_type($entity)));
  61. }
  62. }
  63. $class = $em->getClassMetadata(\get_class($entity));
  64. $criteria = [];
  65. $hasNullValue = false;
  66. foreach ($fields as $fieldName) {
  67. if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) {
  68. throw new ConstraintDefinitionException(sprintf('The field "%s" is not mapped by Doctrine, so it cannot be validated for uniqueness.', $fieldName));
  69. }
  70. $fieldValue = $class->reflFields[$fieldName]->getValue($entity);
  71. if (null === $fieldValue) {
  72. $hasNullValue = true;
  73. }
  74. if ($constraint->ignoreNull && null === $fieldValue) {
  75. continue;
  76. }
  77. $criteria[$fieldName] = $fieldValue;
  78. if (null !== $criteria[$fieldName] && $class->hasAssociation($fieldName)) {
  79. /* Ensure the Proxy is initialized before using reflection to
  80. * read its identifiers. This is necessary because the wrapped
  81. * getter methods in the Proxy are being bypassed.
  82. */
  83. $em->initializeObject($criteria[$fieldName]);
  84. }
  85. }
  86. // validation doesn't fail if one of the fields is null and if null values should be ignored
  87. if ($hasNullValue && $constraint->ignoreNull) {
  88. return;
  89. }
  90. // skip validation if there are no criteria (this can happen when the
  91. // "ignoreNull" option is enabled and fields to be checked are null
  92. if (empty($criteria)) {
  93. return;
  94. }
  95. if (null !== $constraint->entityClass) {
  96. /* Retrieve repository from given entity name.
  97. * We ensure the retrieved repository can handle the entity
  98. * by checking the entity is the same, or subclass of the supported entity.
  99. */
  100. $repository = $em->getRepository($constraint->entityClass);
  101. $supportedClass = $repository->getClassName();
  102. if (!$entity instanceof $supportedClass) {
  103. throw new ConstraintDefinitionException(sprintf('The "%s" entity repository does not support the "%s" entity. The entity should be an instance of or extend "%s".', $constraint->entityClass, $class->getName(), $supportedClass));
  104. }
  105. } else {
  106. $repository = $em->getRepository(\get_class($entity));
  107. }
  108. $result = $repository->{$constraint->repositoryMethod}($criteria);
  109. if ($result instanceof \IteratorAggregate) {
  110. $result = $result->getIterator();
  111. }
  112. /* If the result is a MongoCursor, it must be advanced to the first
  113. * element. Rewinding should have no ill effect if $result is another
  114. * iterator implementation.
  115. */
  116. if ($result instanceof \Iterator) {
  117. $result->rewind();
  118. if ($result instanceof \Countable && 1 < \count($result)) {
  119. $result = [$result->current(), $result->current()];
  120. } else {
  121. $result = $result->valid() && null !== $result->current() ? [$result->current()] : [];
  122. }
  123. } elseif (\is_array($result)) {
  124. reset($result);
  125. } else {
  126. $result = null === $result ? [] : [$result];
  127. }
  128. /* If no entity matched the query criteria or a single entity matched,
  129. * which is the same as the entity being validated, the criteria is
  130. * unique.
  131. */
  132. if (!$result || (1 === \count($result) && current($result) === $entity)) {
  133. return;
  134. }
  135. $errorPath = null !== $constraint->errorPath ? $constraint->errorPath : $fields[0];
  136. $invalidValue = $criteria[$errorPath] ?? $criteria[$fields[0]];
  137. $this->context->buildViolation($constraint->message)
  138. ->atPath($errorPath)
  139. ->setParameter('{{ value }}', $this->formatWithIdentifiers($em, $class, $invalidValue))
  140. ->setInvalidValue($invalidValue)
  141. ->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
  142. ->setCause($result)
  143. ->addViolation();
  144. }
  145. private function formatWithIdentifiers($em, $class, $value)
  146. {
  147. if (!\is_object($value) || $value instanceof \DateTimeInterface) {
  148. return $this->formatValue($value, self::PRETTY_DATE);
  149. }
  150. if (method_exists($value, '__toString')) {
  151. return (string) $value;
  152. }
  153. if ($class->getName() !== $idClass = \get_class($value)) {
  154. // non unique value might be a composite PK that consists of other entity objects
  155. if ($em->getMetadataFactory()->hasMetadataFor($idClass)) {
  156. $identifiers = $em->getClassMetadata($idClass)->getIdentifierValues($value);
  157. } else {
  158. // this case might happen if the non unique column has a custom doctrine type and its value is an object
  159. // in which case we cannot get any identifiers for it
  160. $identifiers = [];
  161. }
  162. } else {
  163. $identifiers = $class->getIdentifierValues($value);
  164. }
  165. if (!$identifiers) {
  166. return sprintf('object("%s")', $idClass);
  167. }
  168. array_walk($identifiers, function (&$id, $field) {
  169. if (!\is_object($id) || $id instanceof \DateTimeInterface) {
  170. $idAsString = $this->formatValue($id, self::PRETTY_DATE);
  171. } else {
  172. $idAsString = sprintf('object("%s")', \get_class($id));
  173. }
  174. $id = sprintf('%s => %s', $field, $idAsString);
  175. });
  176. return sprintf('object("%s") identified by (%s)', $idClass, implode(', ', $identifiers));
  177. }
  178. }