4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * Validates a PAN using the LUHN Algorithm.
21 * For a list of example card numbers that are used to test this
22 * class, please see the LuhnValidatorTest class.
24 * @see http://en.wikipedia.org/wiki/Luhn_algorithm
26 * @author Tim Nagel <t.nagel@infinite.net.au>
27 * @author Greg Knapp http://gregk.me/2011/php-implementation-of-bank-card-luhn-algorithm/
28 * @author Bernhard Schussek <bschussek@gmail.com>
30 class LuhnValidator extends ConstraintValidator
33 * Validates a credit card number with the Luhn algorithm.
36 * @param Constraint $constraint
38 * @throws UnexpectedTypeException when the given credit card number is no string
40 public function validate($value, Constraint $constraint)
42 if (!$constraint instanceof Luhn) {
43 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Luhn');
46 if (null === $value || '' === $value) {
50 // Work with strings only, because long numbers are represented as floats
51 // internally and don't work with strlen()
52 if (!\is_string($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
53 throw new UnexpectedTypeException($value, 'string');
56 $value = (string) $value;
58 if (!ctype_digit($value)) {
59 $this->context->buildViolation($constraint->message)
60 ->setParameter('{{ value }}', $this->formatValue($value))
61 ->setCode(Luhn::INVALID_CHARACTERS_ERROR)
68 $length = \strlen($value);
70 // Starting with the last digit and walking left, add every second
71 // digit to the check sum
72 // e.g. 7 9 9 2 7 3 9 8 7 1 3
74 // = 7 + 9 + 7 + 9 + 7 + 3
75 for ($i = $length - 1; $i >= 0; $i -= 2) {
76 $checkSum += $value[$i];
79 // Starting with the second last digit and walking left, double every
80 // second digit and add it to the check sum
81 // For doubles greater than 9, sum the individual digits
82 // e.g. 7 9 9 2 7 3 9 8 7 1 3
84 // = 1+8 + 4 + 6 + 1+6 + 2
85 for ($i = $length - 2; $i >= 0; $i -= 2) {
86 $checkSum += array_sum(str_split($value[$i] * 2));
89 if (0 === $checkSum || 0 !== $checkSum % 10) {
90 $this->context->buildViolation($constraint->message)
91 ->setParameter('{{ value }}', $this->formatValue($value))
92 ->setCode(Luhn::CHECKSUM_FAILED_ERROR)