CountValidator.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class CountValidator extends ConstraintValidator
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function validate($value, Constraint $constraint)
  24. {
  25. if (!$constraint instanceof Count) {
  26. throw new UnexpectedTypeException($constraint, Count::class);
  27. }
  28. if (null === $value) {
  29. return;
  30. }
  31. if (!\is_array($value) && !$value instanceof \Countable) {
  32. throw new UnexpectedValueException($value, 'array|\Countable');
  33. }
  34. $count = \count($value);
  35. if (null !== $constraint->max && $count > $constraint->max) {
  36. $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
  37. ->setParameter('{{ count }}', $count)
  38. ->setParameter('{{ limit }}', $constraint->max)
  39. ->setInvalidValue($value)
  40. ->setPlural((int) $constraint->max)
  41. ->setCode(Count::TOO_MANY_ERROR)
  42. ->addViolation();
  43. return;
  44. }
  45. if (null !== $constraint->min && $count < $constraint->min) {
  46. $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)
  47. ->setParameter('{{ count }}', $count)
  48. ->setParameter('{{ limit }}', $constraint->min)
  49. ->setInvalidValue($value)
  50. ->setPlural((int) $constraint->min)
  51. ->setCode(Count::TOO_FEW_ERROR)
  52. ->addViolation();
  53. return;
  54. }
  55. if (null !== $constraint->divisibleBy) {
  56. $this->context
  57. ->getValidator()
  58. ->inContext($this->context)
  59. ->validate($count, [
  60. new DivisibleBy([
  61. 'value' => $constraint->divisibleBy,
  62. 'message' => $constraint->divisibleByMessage,
  63. ]),
  64. ], $this->context->getGroup());
  65. }
  66. }
  67. }