Validates a creditcard number with the Luhn algorithm.
mixed $value:
Constraint $constraint:
Overrides ConstraintValidatorInterface::validate
public function validate($value, Constraint $constraint) {
if (null === $value || '' === $value) {
return;
}
if (!is_numeric($value)) {
$this->context
->addViolation($constraint->message);
return;
}
$length = strlen($value);
$oddLength = $length % 2;
for ($sum = 0, $i = $length - 1; $i >= 0; $i--) {
$digit = (int) $value[$i];
$sum += $i % 2 === $oddLength ? array_sum(str_split($digit * 2)) : $digit;
}
if ($sum === 0 || $sum % 10 !== 0) {
$this->context
->addViolation($constraint->message);
}
}