Completed
Push — master ( 5d18c7...cabcf3 )
by Hannes
16s queued 13s
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
cc 6
eloc 14
nc 11
nop 1
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
ccs 14
cts 14
cp 1
crap 6
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace byrokrat\banking\Validator;
6
7
use byrokrat\banking\Exception\LogicException;
8
9
/**
10
 * Modulo10 calculator
11
 */
12
class Modulo10
13
{
14
    /**
15
     * Calculate the modulo 10 check digit for number
16
     *
17
     * @throws LogicException If $number is not numerical
18
     */
19 97
    public static function calculateCheckDigit(string $number): string
20
    {
21 97
        if (!ctype_digit($number)) {
22 3
            throw new LogicException(
23 3
                "Number can only contain numerical characters, found '$number'"
24
            );
25
        }
26
27 94
        $weight = 2;
28 94
        $sum = 0;
29
30 94
        for ($pos=strlen($number)-1; $pos>=0; $pos--) {
31 94
            $tmp = $number[$pos] * $weight;
32 94
            $sum += ($tmp > 9) ? (1 + ($tmp % 10)) : $tmp;
33 94
            $weight = ($weight == 2) ? 1 : 2;
34
        }
35
36 94
        $ceil = $sum;
37
38 94
        while ($ceil % 10 != 0) {
39 94
            $ceil++;
40
        }
41
42 94
        return (string)($ceil-$sum);
43
    }
44
}
45