4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class CountValidator extends ConstraintValidator
26 public function validate($value, Constraint $constraint)
28 if (null === $value) {
32 if (!\is_array($value) && !$value instanceof \Countable) {
33 throw new UnexpectedTypeException($value, 'array or \Countable');
36 $count = \count($value);
38 if (null !== $constraint->max && $count > $constraint->max) {
39 $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
40 ->setParameter('{{ count }}', $count)
41 ->setParameter('{{ limit }}', $constraint->max)
42 ->setInvalidValue($value)
43 ->setPlural((int) $constraint->max)
44 ->setCode(Count::TOO_MANY_ERROR)
50 if (null !== $constraint->min && $count < $constraint->min) {
51 $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)
52 ->setParameter('{{ count }}', $count)
53 ->setParameter('{{ limit }}', $constraint->min)
54 ->setInvalidValue($value)
55 ->setPlural((int) $constraint->min)
56 ->setCode(Count::TOO_FEW_ERROR)