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 LengthValidator extends ConstraintValidator
26 public function validate($value, Constraint $constraint)
28 if (!$constraint instanceof Length) {
29 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Length');
32 if (null === $value || '' === $value) {
36 if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
37 throw new UnexpectedTypeException($value, 'string');
40 $stringValue = (string) $value;
42 if (!$invalidCharset = !@mb_check_encoding($stringValue, $constraint->charset)) {
43 $length = mb_strlen($stringValue, $constraint->charset);
46 if ($invalidCharset) {
47 $this->context->buildViolation($constraint->charsetMessage)
48 ->setParameter('{{ value }}', $this->formatValue($stringValue))
49 ->setParameter('{{ charset }}', $constraint->charset)
50 ->setInvalidValue($value)
51 ->setCode(Length::INVALID_CHARACTERS_ERROR)
57 if (null !== $constraint->max && $length > $constraint->max) {
58 $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
59 ->setParameter('{{ value }}', $this->formatValue($stringValue))
60 ->setParameter('{{ limit }}', $constraint->max)
61 ->setInvalidValue($value)
62 ->setPlural((int) $constraint->max)
63 ->setCode(Length::TOO_LONG_ERROR)
69 if (null !== $constraint->min && $length < $constraint->min) {
70 $this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)
71 ->setParameter('{{ value }}', $this->formatValue($stringValue))
72 ->setParameter('{{ limit }}', $constraint->min)
73 ->setInvalidValue($value)
74 ->setPlural((int) $constraint->min)
75 ->setCode(Length::TOO_SHORT_ERROR)