class LuhnValidator

Validates a PAN using the LUHN Algorithm

For a list of example card numbers that are used to test this class, please see the LuhnValidatorTest class.

@author Tim Nagel <t.nagel@infinite.net.au> @author Greg Knapp http://gregk.me/2011/php-implementation-of-bank-card-luhn-algorithm/

Hierarchy

Expanded class hierarchy of LuhnValidator

See also

http://en.wikipedia.org/wiki/Luhn_algorithm

1 file declares its use of LuhnValidator
LuhnValidatorTest.php in drupal/core/vendor/symfony/validator/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php

File

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

Namespace

Symfony\Component\Validator\Constraints
View source
class LuhnValidator extends ConstraintValidator {

  /**
   * Validates a creditcard number with the Luhn algorithm.
   *
   * @param mixed      $value
   * @param Constraint $constraint
   */
  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);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConstraintValidator::$context protected property
ConstraintValidator::initialize public function Initializes the constraint validator. Overrides ConstraintValidatorInterface::initialize 1
LuhnValidator::validate public function Validates a creditcard number with the Luhn algorithm. Overrides ConstraintValidatorInterface::validate