public function LuhnValidator::validate

Validates a creditcard number with the Luhn algorithm.

Parameters

mixed $value:

Constraint $constraint:

Overrides ConstraintValidatorInterface::validate

File

drupal/core/vendor/symfony/validator/Symfony/Component/Validator/Constraints/LuhnValidator.php, line 35

Class

LuhnValidator
Validates a PAN using the LUHN Algorithm

Namespace

Symfony\Component\Validator\Constraints

Code

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);
  }
}