PTAlgorithm::isFollowPattern()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace LeKoala\Tin\Algo;
4
5
use LeKoala\Tin\Util\StringUtil;
6
7
/**
8
 * Portugal
9
 */
10
class PTAlgorithm extends TINAlgorithm
11
{
12
    const LENGTH = 9;
13
    const PATTERN = "\\d{9}";
14
15
    public function validate(string $tin)
16
    {
17
        if (!$this->isFollowLength($tin)) {
18
            return StatusCode::INVALID_LENGTH;
19
        }
20
        if (!$this->isFollowPattern($tin)) {
21
            return StatusCode::INVALID_PATTERN;
22
        }
23
        if (!$this->isFollowRules($tin)) {
24
            return StatusCode::INVALID_SYNTAX;
25
        }
26
        return StatusCode::VALID;
27
    }
28
29
    public function isFollowLength(string $tin)
30
    {
31
        return StringUtil::isFollowLength($tin, self::LENGTH);
32
    }
33
34
    public function isFollowPattern(string $tin)
35
    {
36
        return StringUtil::isFollowPattern($tin, self::PATTERN);
37
    }
38
39
    public function isFollowRules(string $tin)
40
    {
41
        $c1 = StringUtil::digitAt($tin, 0);
42
        $c2 = StringUtil::digitAt($tin, 1);
43
        $c3 = StringUtil::digitAt($tin, 2);
44
        $c4 = StringUtil::digitAt($tin, 3);
45
        $c5 = StringUtil::digitAt($tin, 4);
46
        $c6 = StringUtil::digitAt($tin, 5);
47
        $c7 = StringUtil::digitAt($tin, 6);
48
        $c8 = StringUtil::digitAt($tin, 7);
49
        $c9 = StringUtil::digitAt($tin, 8);
50
        $sum = $c1 * 9 + $c2 * 8 + $c3 * 7 + $c4 * 6 + $c5 * 5 + $c6 * 4 + $c7 * 3 + $c8 * 2;
51
        $remainderBy11 = $sum % 11;
52
        $checkDigit = 11 - $remainderBy11;
53
        if ($checkDigit <= 9) {
54
            return $checkDigit == $c9;
55
        }
56
        if ($checkDigit == 10) {
57
            return 0 == $c9;
58
        }
59
        return 0 == $c9;
60
    }
61
}
62