<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class ValidDNIValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ValidDNI) {
throw new UnexpectedTypeException($constraint, ValidDNI::class);
}
// custom constraints should ignore null and empty values to allow
// other constraints (NotBlank, NotNull, etc.) take care of that
if (null === $value || '' === $value) {
return;
}
if (!is_string($value)) {
// throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
throw new UnexpectedValueException($value, 'string');
// separate multiple types using pipes
// throw new UnexpectedValueException($value, 'string|int');
}
$value = strtoupper($value);
if (!preg_match('/^[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKET]$/i', $value, $matches)) {
// the argument must be a string or an object implementing __toString()
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value)
->addViolation();
}
//Separa letra y numero del DNI y comprueba su validez
$validChars = 'TRWAGMYFPDXBNJZSQVHLCKET';
$charIndex = (int)substr($value, 0, 8) % 23;
$letter = substr($value, -1);
if (!($validChars{$charIndex} === $letter)){
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value)
->addViolation();
}
}
}