Algo Luhn
This commit is contained in:
parent
81fd319fbf
commit
0fa5e6b3af
49
library/Metier/Util/Luhn.php
Normal file
49
library/Metier/Util/Luhn.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user