src/Validator/Constraints/ValidDNIValidator.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Validator\Constraints;
  3. use Symfony\Component\Validator\Constraint;
  4. use Symfony\Component\Validator\ConstraintValidator;
  5. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  6. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  7. class ValidDNIValidator extends ConstraintValidator
  8. {
  9.     public function validate($valueConstraint $constraint)
  10.     {
  11.         if (!$constraint instanceof ValidDNI) {
  12.             throw new UnexpectedTypeException($constraintValidDNI::class);
  13.         }
  14.         // custom constraints should ignore null and empty values to allow
  15.         // other constraints (NotBlank, NotNull, etc.) take care of that
  16.         if (null === $value || '' === $value) {
  17.             return;
  18.         }
  19.         if (!is_string($value)) {
  20.             // throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
  21.             throw new UnexpectedValueException($value'string');
  22.             // separate multiple types using pipes
  23.             // throw new UnexpectedValueException($value, 'string|int');
  24.         }
  25.         $value strtoupper($value);
  26.         if (!preg_match('/^[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKET]$/i'$value$matches)) {
  27.             // the argument must be a string or an object implementing __toString()
  28.             $this->context->buildViolation($constraint->message)
  29.                 ->setParameter('{{ string }}'$value)
  30.                 ->addViolation();
  31.         }
  32.         //Separa letra y numero del DNI y comprueba su validez
  33.         $validChars 'TRWAGMYFPDXBNJZSQVHLCKET';
  34.         $charIndex = (int)substr($value08) % 23;
  35.         $letter substr($value, -1);
  36.         if (!($validChars{$charIndex} === $letter)){
  37.             $this->context->buildViolation($constraint->message)
  38.                 ->setParameter('{{ string }}'$value)
  39.                 ->addViolation();
  40.         }
  41.     }
  42. }