UniqueValidator.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  15. /**
  16. * @author Yevgeniy Zholkevskiy <zhenya.zholkevskiy@gmail.com>
  17. */
  18. class UniqueValidator extends ConstraintValidator
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function validate($value, Constraint $constraint)
  24. {
  25. if (!$constraint instanceof Unique) {
  26. throw new UnexpectedTypeException($constraint, Unique::class);
  27. }
  28. if (null === $value) {
  29. return;
  30. }
  31. if (!\is_array($value) && !$value instanceof \IteratorAggregate) {
  32. throw new UnexpectedValueException($value, 'array|IteratorAggregate');
  33. }
  34. $collectionElements = [];
  35. foreach ($value as $element) {
  36. if (\in_array($element, $collectionElements, true)) {
  37. $this->context->buildViolation($constraint->message)
  38. ->setParameter('{{ value }}', $this->formatValue($value))
  39. ->setCode(Unique::IS_NOT_UNIQUE)
  40. ->addViolation();
  41. return;
  42. }
  43. $collectionElements[] = $element;
  44. }
  45. }
  46. }