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/
Expanded class hierarchy of LuhnValidator
http://en.wikipedia.org/wiki/Luhn_algorithm
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);
}
}
}
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ConstraintValidator:: |
protected | property | ||
ConstraintValidator:: |
public | function |
Initializes the constraint validator. Overrides ConstraintValidatorInterface:: |
1 |
LuhnValidator:: |
public | function |
Validates a creditcard number with the Luhn algorithm. Overrides ConstraintValidatorInterface:: |