This repository has been archived by the owner on Jan 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Modulo11.php
87 lines (72 loc) · 1.96 KB
/
Modulo11.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types = 1);
namespace byrokrat\checkdigit;
/**
* Modulo11 calculator
*/
class Modulo11 implements Calculator
{
use AssertionsTrait;
/**
* @var array Map modulo 11 remainder to check digit
*/
private static $remainderToCheck = [
0 => '0',
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => 'X',
11 => '0',
];
/**
* Check if the last digit of number is a valid modulo 11 check digit
*/
public function isValid(string $number): bool
{
if (!preg_match("/^\d*(X|\d){1}$/", $number)) {
throw new InvalidStructureException(
"Number must consist of characters 0-9 and optionally end with X"
);
}
$sum = 0;
foreach (array_reverse(str_split($number)) as $pos => $digit) {
$digit = ($digit == 'X') ? 10 : $digit;
$sum += $digit * $this->getWeight($pos);
}
// If remainder is 0 check digit is valid
return $sum % 11 === 0;
}
/**
* Calculate the modulo 11 check digit for number
*/
public function calculateCheckDigit(string $number): string
{
$this->assertNumber($number);
$sum = 0;
foreach (array_reverse(str_split($number)) as $pos => $digit) {
$sum += $digit * $this->getWeight($pos, 2);
}
// Calculate check digit from remainder
return self::$remainderToCheck[11 - $sum % 11];
}
/**
* Calculate weight based on position in number
*
* @param int $pos Position in number (starts from 0)
* @param int $start Start value for weight calculation (value of position 0)
*/
protected function getWeight(int $pos, int $start = 1): int
{
$pos += $start;
while ($pos > 10) {
$pos -= 10;
}
return $pos;
}
}