Completed
Push — master ( a004d3...9bce71 )
by Hannes
03:41 queued 02:35
created

Modulo10   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 1
dl 0
loc 46
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 4 2
B calculateCheckDigit() 0 25 6
1
<?php
2
3
namespace byrokrat\id;
4
5
/**
6
 * Modulo10 checkdigit calculator
7
 */
8
class Modulo10
9
{
10
    /**
11
     * Check if the last digit of number is a valid modulo 10 check digit
12
     *
13
     * @param  string $number
14
     * @return bool
15
     */
16 99
    public static function isValid($number)
17
    {
18 99
        return substr($number, -1) === self::calculateCheckDigit(substr($number, 0, -1) ?: '');
19
    }
20
21
    /**
22
     * Calculate the modulo 10 check digit for number
23
     *
24
     * @param  string $number
25
     * @return string
26
     * @throws Exception\InvalidStructureException If $number is not numerical
27
     */
28 103
    public static function calculateCheckDigit($number)
29
    {
30 103
        if (!ctype_digit($number)) {
31 6
            throw new Exception\InvalidStructureException(
32 6
                "Number can only contain numerical characters, found: $number"
33
            );
34
        }
35
36 97
        $weight = 2;
37 97
        $sum = 0;
38
39 97
        for ($pos=strlen($number)-1; $pos>=0; $pos--) {
40 97
            $tmp = $number[$pos] * $weight;
41 97
            $sum += ($tmp > 9) ? (1 + ($tmp % 10)) : $tmp;
42 97
            $weight = ($weight == 2) ? 1 : 2;
43
        }
44
45 97
        $ceil = $sum;
46
47 97
        while ($ceil % 10 != 0) {
48 96
            $ceil++;
49
        }
50
51 97
        return (string)($ceil-$sum);
52
    }
53
}
54