LuhnCalculator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 8
eloc 16
dl 0
loc 41
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checksum() 0 14 3
A computeCheckDigit() 0 9 2
A isValid() 0 3 1
A generateLuhnNumber() 0 7 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace DummyGenerator\Core\Calculator;
6
7
use DummyGenerator\Definitions\Calculator\LuhnCalculatorInterface;
8
use DummyGenerator\Definitions\Extension\Exception\ExtensionArgumentException;
9
10
/**
11
 * Utility class for validating LUHN numbers
12
 */
13
class LuhnCalculator implements LuhnCalculatorInterface
14
{
15 6
    protected function checksum(string $number): int
16
    {
17 6
        $length = strlen($number);
18 6
        $sum = 0;
19
20 6
        for ($i = $length - 1; $i >= 0; $i -= 2) {
21 6
            $sum += (int) $number[$i];
22
        }
23
24 6
        for ($i = $length - 2; $i >= 0; $i -= 2) {
25 6
            $sum += array_sum(str_split((string) ((int) $number[$i] * 2)));
0 ignored issues
show
Bug introduced by
It seems like str_split((string)(int)$number[$i] * 2) can also be of type true; however, parameter $array of array_sum() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

25
            $sum += array_sum(/** @scrutinizer ignore-type */ str_split((string) ((int) $number[$i] * 2)));
Loading history...
26
        }
27
28 6
        return $sum % 10;
29
    }
30
31 5
    public function computeCheckDigit(string $partialNumber): string
32
    {
33 5
        $checkDigit = $this->checksum($partialNumber . '0');
34
35 5
        if ($checkDigit === 0) {
36
            return '0';
37
        }
38
39 5
        return (string) (10 - $checkDigit);
40
    }
41
42 1
    public function isValid(string $number): bool
43
    {
44 1
        return $this->checksum($number) === 0;
45
    }
46
47 1
    public function generateLuhnNumber(string $partialValue): string
48
    {
49 1
        if (!preg_match('/^\d+$/', $partialValue)) {
50
            throw new ExtensionArgumentException('Argument should be an integer.');
51
        }
52
53 1
        return $partialValue . $this->computeCheckDigit($partialValue);
54
    }
55
}
56