Completed
Pull Request — master (#5)
by
unknown
08:52
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
rs 10
c 0
b 0
f 0
ccs 16
cts 16
cp 1

3 Methods

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