AtLeastOneOfValidator.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /**
  15. * @author Przemysław Bogusz <przemyslaw.bogusz@tubotax.pl>
  16. */
  17. class AtLeastOneOfValidator extends ConstraintValidator
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function validate($value, Constraint $constraint)
  23. {
  24. if (!$constraint instanceof AtLeastOneOf) {
  25. throw new UnexpectedTypeException($constraint, AtLeastOneOf::class);
  26. }
  27. $validator = $this->context->getValidator();
  28. $messages = [$constraint->message];
  29. foreach ($constraint->constraints as $key => $item) {
  30. $executionContext = clone $this->context;
  31. $executionContext->setNode($value, $this->context->getObject(), $this->context->getMetadata(), $this->context->getPropertyPath());
  32. $violations = $validator->inContext($executionContext)->validate($value, $item, $this->context->getGroup())->getViolations();
  33. if (\count($this->context->getViolations()) === \count($violations)) {
  34. return;
  35. }
  36. if ($constraint->includeInternalMessages) {
  37. $message = ' ['.($key + 1).'] ';
  38. if ($item instanceof All || $item instanceof Collection) {
  39. $message .= $constraint->messageCollection;
  40. } else {
  41. $message .= $violations->get(\count($violations) - 1)->getMessage();
  42. }
  43. $messages[] = $message;
  44. }
  45. }
  46. $this->context->buildViolation(implode('', $messages))
  47. ->setCode(AtLeastOneOf::AT_LEAST_ONE_OF_ERROR)
  48. ->addViolation()
  49. ;
  50. }
  51. }