Completed
Push — master ( c756b3...e0ace5 )
by Hannes
17s
created

Modulo10::calculateCheckDigit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace byrokrat\checkdigit;
6
7
/**
8
 * Modulo10 calculator
9
 */
10
class Modulo10 implements Calculator
11
{
12
    use AssertionsTrait;
13
14
    /**
15
     * Check if the last digit of number is a valid modulo 10 check digit
16
     */
17 9
    public function isValid(string $number): bool
18
    {
19 9
        return substr($number, -1) === $this->calculateCheckDigit(substr($number, 0, -1) ?: '');
20
    }
21
22
    /**
23
     * Calculate the modulo 10 check digit for number
24
     */
25 18
    public function calculateCheckDigit(string $number): string
26
    {
27 18
        $this->assertNumber($number);
28
29 6
        $sum = $this->calculateSum($number);
30
31 6
        $ceil = $sum;
32
33 6
        while ($ceil % 10 != 0) {
34 6
            $ceil++;
35
        }
36
37 6
        return (string)($ceil-$sum);
38
    }
39
40 4
    protected function calculateSum(string $number): int
41
    {
42 4
        $weight = 2;
43 4
        $sum = 0;
44
45 4
        for ($pos=strlen($number)-1; $pos>=0; $pos--) {
46 4
            $tmp = $number[$pos] * $weight;
47 4
            $sum += ($tmp > 9) ? (1 + ($tmp % 10)) : $tmp;
48 4
            $weight = ($weight == 2) ? 1 : 2;
49
        }
50
51 4
        return $sum;
52
    }
53
}
54