Modulo10   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 2
dl 0
loc 36
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateCheckDigit() 0 8 3
A calculateCheckDigit() 0 19 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\id\Helper;
6
7
use byrokrat\id\IdInterface;
8
use byrokrat\id\Exception\InvalidCheckDigitException;
9
10
class Modulo10
11
{
12
    /**
13
     * Verify that the last digit of id is a valid modulo 10 check digit
14
     *
15
     * @throws InvalidCheckDigitException If check digit is not valid
16
     */
17
    public static function validateCheckDigit(IdInterface $id): void
18
    {
19
        $number = (string)preg_replace('/[^0-9]/', '', $id->getId());
20
21
        if (substr($number, -1) !== self::calculateCheckDigit(substr($number, 0, -1) ?: '')) {
22
            throw new InvalidCheckDigitException("Invalid check digit in {$id->getId()}");
23
        }
24
    }
25
26
    private static function calculateCheckDigit(string $number): string
27
    {
28
        $weight = 2;
29
        $sum = 0;
30
31
        for ($pos = strlen($number) - 1; $pos >= 0; $pos--) {
32
            $tmp = (int)$number[$pos] * $weight;
33
            $sum += ($tmp > 9) ? (1 + ($tmp % 10)) : $tmp;
34
            $weight = ($weight == 2) ? 1 : 2;
35
        }
36
37
        $ceil = $sum;
38
39
        while ($ceil % 10 != 0) {
40
            $ceil++;
41
        }
42
43
        return (string)($ceil - $sum);
44
    }
45
}
46