Issues (11)

src/Algo/IEAlgorithm.php (1 issue)

Severity
1
<?php
2
3
namespace LeKoala\Tin\Algo;
4
5
use LeKoala\Tin\Util\StringUtil;
6
7
/**
8
 * Ireland
9
 */
10
class IEAlgorithm extends TINAlgorithm
11
{
12
    const LENGTH_1 = 9;
13
    const PATTERN_1 = "\\d{7}[a-wA-W]([a-iA-I]|W)";
14
    const LENGTH_2 = 8;
15
    const PATTERN_2 = "\\d{7}[a-wA-W]";
16
17
    public function validate(string $tin)
18
    {
19
        if (!$this->isFollowLength1($tin) && !$this->isFollowLength2($tin)) {
20
            return StatusCode::INVALID_LENGTH;
21
        }
22
        if (($this->isFollowLength1($tin) && !$this->isFollowPattern1($tin)) || ($this->isFollowLength2($tin) && !$this->isFollowPattern2($tin))) {
23
            return StatusCode::INVALID_PATTERN;
24
        }
25
        if (!$this->isFollowRules($tin)) {
26
            return StatusCode::INVALID_SYNTAX;
27
        }
28
        return StatusCode::VALID;
29
    }
30
31
    public function isFollowLength1(string $tin)
32
    {
33
        return StringUtil::isFollowLength($tin, self::LENGTH_1);
34
    }
35
36
    public function isFollowPattern1(string $tin)
37
    {
38
        return StringUtil::isFollowPattern($tin, self::PATTERN_1);
39
    }
40
41
    public function isFollowLength2(string $tin)
42
    {
43
        return StringUtil::isFollowLength($tin, self::LENGTH_2);
44
    }
45
46
    public function isFollowPattern2(string $tin)
47
    {
48
        return StringUtil::isFollowPattern($tin, self::PATTERN_2);
49
    }
50
51
    public function isFollowRules(string $tin)
52
    {
53
        $c1 = StringUtil::digitAt($tin, 0);
54
        $c2 = StringUtil::digitAt($tin, 1);
55
        $c3 = StringUtil::digitAt($tin, 2);
56
        $c4 = StringUtil::digitAt($tin, 3);
57
        $c5 = StringUtil::digitAt($tin, 4);
58
        $c6 = StringUtil::digitAt($tin, 5);
59
        $c7 = StringUtil::digitAt($tin, 6);
60
        $c8 = StringUtil::digitAt($tin, 7);
0 ignored issues
show
The assignment to $c8 is dead and can be removed.
Loading history...
61
        $c9 = (strlen($tin) >= 9) ? self::letterToNumber($tin[8]) : 0;
62
        $c8 = $tin[7];
63
        $sum = $c9 * 9 + $c1 * 8 + $c2 * 7 + $c3 * 6 + $c4 * 5 + $c5 * 4 + $c6 * 3 + $c7 * 2;
64
        $remainderBy23 = $sum % 23;
65
        if ($remainderBy23 != 0) {
66
            return StringUtil::getAlphabeticalPosition($c8) == $remainderBy23;
67
        }
68
        return $c8 == 'W' || $c8 == 'w';
69
    }
70
71
    public static function letterToNumber(string $toConv)
72
    {
73
        if (!$toConv) {
74
            return 0;
75
        }
76
        if ($toConv == 'W' || $toConv == 'w') {
77
            return 0;
78
        }
79
        return StringUtil::getAlphabeticalPosition($toConv);
80
    }
81
}
82