[Validator] Simplified and explained the LuhnValidator
This commit is contained in:
parent
bff09f210b
commit
f3295522ef
@ -39,28 +39,48 @@ class LuhnValidator extends ConstraintValidator
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Work with strings only, because long numbers are represented as floats
|
||||||
* need to work with strings only because long numbers are treated as floats and don't work with strlen
|
// internally and don't work with strlen()
|
||||||
*/
|
if (!is_string($value) && !(is_object($value) && method_exists($value, '__toString'))) {
|
||||||
if (!is_string($value)) {
|
|
||||||
throw new UnexpectedTypeException($value, 'string');
|
throw new UnexpectedTypeException($value, 'string');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!is_numeric($value)) {
|
$value = (string) $value;
|
||||||
$this->context->addViolation($constraint->message);
|
|
||||||
|
if (!ctype_digit($value)) {
|
||||||
|
$this->context->addViolation($constraint->message, array(
|
||||||
|
'{{ value }}' => $value,
|
||||||
|
));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$checkSum = 0;
|
||||||
$length = strlen($value);
|
$length = strlen($value);
|
||||||
$oddLength = $length % 2;
|
|
||||||
for ($sum = 0, $i = $length - 1; $i >= 0; $i--) {
|
// Starting with the last digit and walking left, add every second
|
||||||
$digit = (int) $value[$i];
|
// digit to the check sum
|
||||||
$sum += (($i % 2) === $oddLength) ? array_sum(str_split($digit * 2)) : $digit;
|
// e.g. 7 9 9 2 7 3 9 8 7 1 3
|
||||||
|
// ^ ^ ^ ^ ^ ^
|
||||||
|
// = 7 + 9 + 7 + 9 + 7 + 3
|
||||||
|
for ($i = $length - 1; $i >= 0; $i -= 2) {
|
||||||
|
$checkSum += $value{$i};
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($sum === 0 || ($sum % 10) !== 0) {
|
// Starting with the second last digit and walking left, double every
|
||||||
$this->context->addViolation($constraint->message);
|
// second digit and add it to the check sum
|
||||||
|
// For doubles greater than 9, sum the individual digits
|
||||||
|
// e.g. 7 9 9 2 7 3 9 8 7 1 3
|
||||||
|
// ^ ^ ^ ^ ^
|
||||||
|
// = 1+8 + 4 + 6 + 1+6 + 2
|
||||||
|
for ($i = $length - 2; $i >= 0; $i -= 2) {
|
||||||
|
$checkSum += array_sum(str_split($value{$i} * 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (0 === $checkSum || 0 !== $checkSum % 10) {
|
||||||
|
$this->context->addViolation($constraint->message, array(
|
||||||
|
'{{ value }}' => $value,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user