mirror of
https://github.com/Respect/Validation.git
synced 2024-06-29 02:30:06 +02:00
50 lines
1.1 KiB
PHP
50 lines
1.1 KiB
PHP
|
<?php
|
||
|
|
||
|
/*
|
||
|
* This file is part of Respect/Validation.
|
||
|
*
|
||
|
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
|
||
|
*
|
||
|
* For the full copyright and license information, please view the "LICENSE.md"
|
||
|
* file that was distributed with this source code.
|
||
|
*/
|
||
|
|
||
|
namespace Respect\Validation\Rules;
|
||
|
|
||
|
/**
|
||
|
* @link https://en.wikipedia.org/wiki/Luhn_algorithm
|
||
|
*/
|
||
|
class Luhn extends AbstractRule
|
||
|
{
|
||
|
/**
|
||
|
* {@inheritdoc}
|
||
|
*/
|
||
|
public function validate($input)
|
||
|
{
|
||
|
if (!(new Digit())->validate($input)) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
return $this->isValid($input);
|
||
|
}
|
||
|
|
||
|
private function isValid($input): bool
|
||
|
{
|
||
|
$sum = 0;
|
||
|
$numDigits = strlen($input);
|
||
|
$parity = $numDigits % 2;
|
||
|
for ($i = 0; $i < $numDigits; ++$i) {
|
||
|
$digit = substr($input, $i, 1);
|
||
|
if ($parity == ($i % 2)) {
|
||
|
$digit <<= 1;
|
||
|
if (9 < $digit) {
|
||
|
$digit = $digit - 9;
|
||
|
}
|
||
|
}
|
||
|
$sum += $digit;
|
||
|
}
|
||
|
|
||
|
return 0 == ($sum % 10);
|
||
|
}
|
||
|
}
|