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

Modulo10::calculateCheckDigit()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 11
nop 1
crap 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