[Validator] Simplified IssnValidator
This commit is contained in:
parent
224e70f709
commit
bff09f210b
@ -37,26 +37,35 @@ class IssnValidator extends ConstraintValidator
|
|||||||
throw new UnexpectedTypeException($value, 'string');
|
throw new UnexpectedTypeException($value, 'string');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$value = (string) $value;
|
||||||
|
|
||||||
// Compose regex pattern
|
// Compose regex pattern
|
||||||
$digitsPattern = $constraint->requireHyphen ? '\d{4}-\d{3}' : '\d{4}-?\d{3}';
|
$digitsPattern = $constraint->requireHyphen ? '\d{4}-\d{3}' : '\d{4}-?\d{3}';
|
||||||
$checksumPattern = $constraint->caseSensitive ? '[\d|X]' : '[\d|X|x]';
|
$checkSumPattern = $constraint->caseSensitive ? '[\d|X]' : '[\d|X|x]';
|
||||||
$pattern = "/^".$digitsPattern.$checksumPattern."$/";
|
$pattern = "/^".$digitsPattern.$checkSumPattern."$/";
|
||||||
|
|
||||||
if (!preg_match($pattern, $value)) {
|
if (!preg_match($pattern, $value)) {
|
||||||
$this->context->addViolation($constraint->message);
|
$this->context->addViolation($constraint->message, array(
|
||||||
} else {
|
'{{ value }}' => $value,
|
||||||
$digits = str_split(strtoupper(str_replace('-', '', $value)));
|
));
|
||||||
|
|
||||||
$sum = 0;
|
return;
|
||||||
for ($i = 8; $i > 1; $i--) {
|
|
||||||
$sum += $i * (int) array_shift($digits);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$checksum = 'X' == reset($digits) ? 10 : (int) reset($digits);
|
$canonical = strtoupper(str_replace('-', '', $value));
|
||||||
|
|
||||||
if (0 != ($sum + $checksum) % 11) {
|
// Calculate a checksum. "X" equals 10.
|
||||||
$this->context->addViolation($constraint->message);
|
$checkSum = 'X' === $canonical{7} ? 10 : $canonical{7};
|
||||||
}
|
|
||||||
|
for ($i = 0; $i < 7; ++$i) {
|
||||||
|
// Multiply the first digit by 8, the second by 7, etc.
|
||||||
|
$checkSum += (8-$i) * $canonical{$i};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (0 !== $checkSum % 11) {
|
||||||
|
$this->context->addViolation($constraint->message, array(
|
||||||
|
'{{ value }}' => $value,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user