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

Modulo10   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A calculateCheckDigit() 0 14 2
A calculateSum() 0 13 4
A isValid() 0 4 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