49 lines
1.2 KiB
PHP
49 lines
1.2 KiB
PHP
<?php
|
|
class Metier_Util_Luhn
|
|
{
|
|
private $sumTable = array(
|
|
array(0,1,2,3,4,5,6,7,8,9),
|
|
array(0,2,4,6,8,1,3,5,7,9)
|
|
);
|
|
|
|
/**
|
|
* Calculate check digit according to Luhn's algorithm
|
|
* New method (suggested by H.Johnson),
|
|
* see http://www.phpclasses.org/discuss/package/8471/thread/1/
|
|
*
|
|
* @param string $number
|
|
* @return integer
|
|
*/
|
|
public function calculate(string $number)
|
|
{
|
|
$length = strlen($number);
|
|
$sum = 0;
|
|
$flip = 1;
|
|
// Sum digits (last one is check digit, which is not in parameter)
|
|
for($i=$length-1;$i>=0;--$i) {
|
|
$sum += $this->sumTable[$flip++ & 0x1][$number[$i]];
|
|
}
|
|
// Multiply by 9
|
|
$sum *= 9;
|
|
// Last digit of sum is check digit
|
|
return (int)substr($sum,-1,1);
|
|
}
|
|
|
|
/**
|
|
* Validate number against check digit
|
|
*
|
|
* @param string $number
|
|
* @param integer $digit
|
|
* @return boolean
|
|
*/
|
|
public function validate(string $number, int $digit)
|
|
{
|
|
$calculated = $this->calculate($number);
|
|
if($digit == $calculated) {
|
|
return true;
|
|
}
|
|
else {
|
|
return false;
|
|
}
|
|
}
|
|
} |