IbanCalculator::alphaToNumberCallback()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace DummyGenerator\Core\Calculator;
6
7
use DummyGenerator\Definitions\Calculator\IbanCalculatorInterface;
8
9
/**
10
 * Utility class for working with IBAN numbers
11
 */
12
class IbanCalculator implements IbanCalculatorInterface
13
{
14 6
    public function checksum(string $iban): string
15
    {
16
        // Move first four digits to end and set checksum to '00'
17 6
        $checkString = substr($iban, 4) . substr($iban, 0, 2) . '00';
18
19
        // Replace all letters with their number equivalents
20 6
        $checkString = preg_replace_callback('/[A-Z]/', fn (array $a) => $this->alphaToNumberCallback($a), $checkString) ?? '';
21
22
        // Perform mod 97 and subtract from 98
23 6
        $checksum = 98 - $this->mod97($checkString);
24
25 6
        return str_pad((string) $checksum, 2, '0', STR_PAD_LEFT);
26
    }
27
28 1
    public function isValid(string $iban): bool
29
    {
30 1
        return $this->checksum($iban) === substr($iban, 2, 2);
31
    }
32
33
    /**
34
     * Convert a letter to a number.
35
     *
36
     * @param array<int|string, string> $match
37
     */
38 6
    protected function alphaToNumberCallback(array $match): string
39
    {
40 6
        return (string) $this->alphaToNumber($match[0]);
41
    }
42
43
    /**
44
     * Converts letter to number
45
     */
46 6
    protected function alphaToNumber(string $char): int
47
    {
48 6
        return ord($char) - 55;
49
    }
50
51
    /**
52
     * Calculates mod97 number on a numeric string
53
     */
54 6
    protected function mod97(string $number): int
55
    {
56 6
        $checksum = (int) $number[0];
57
58 6
        for ($i = 1, $size = strlen($number); $i < $size; ++$i) {
59 6
            $checksum = (10 * $checksum + (int) $number[$i]) % 97;
60
        }
61
62 6
        return $checksum;
63
    }
64
}
65