You are here

public function CountValidator::validate in Plug 7

Checks if the passed value is valid.

@api

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ConstraintValidatorInterface::validate

File

lib/Symfony/validator/Symfony/Component/Validator/Constraints/CountValidator.php, line 26

Class

CountValidator
@author Bernhard Schussek <bschussek@gmail.com>

Namespace

Symfony\Component\Validator\Constraints

Code

public function validate($value, Constraint $constraint) {
  if (null === $value) {
    return;
  }
  if (!is_array($value) && !$value instanceof \Countable) {
    throw new UnexpectedTypeException($value, 'array or \\Countable');
  }
  $count = count($value);
  if (null !== $constraint->max && $count > $constraint->max) {
    $this
      ->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
      ->setParameter('{{ count }}', $count)
      ->setParameter('{{ limit }}', $constraint->max)
      ->setInvalidValue($value)
      ->setPlural((int) $constraint->max)
      ->setCode(Count::TOO_MANY_ERROR)
      ->addViolation();
    return;
  }
  if (null !== $constraint->min && $count < $constraint->min) {
    $this
      ->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)
      ->setParameter('{{ count }}', $count)
      ->setParameter('{{ limit }}', $constraint->min)
      ->setInvalidValue($value)
      ->setPlural((int) $constraint->min)
      ->setCode(Count::TOO_FEW_ERROR)
      ->addViolation();
  }
}