SIAlgorithm::isFollowRules()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace LeKoala\Tin\Algo;
4
5
use LeKoala\Tin\Util\NumberUtil;
6
use LeKoala\Tin\Util\StringUtil;
7
8
/**
9
 * Slovenia
10
 */
11
class SIAlgorithm extends TINAlgorithm
12
{
13
    const LENGTH = 8;
14
    const PATTERN = "[1-9]\\d{7}";
15
16
    public function validate(string $tin)
17
    {
18
        if (!$this->isFollowLength($tin)) {
19
            return StatusCode::INVALID_LENGTH;
20
        }
21
        if (!$this->isFollowPattern($tin)) {
22
            return StatusCode::INVALID_PATTERN;
23
        }
24
        if (!$this->isFollowRules($tin)) {
25
            return StatusCode::INVALID_SYNTAX;
26
        }
27
        return StatusCode::VALID;
28
    }
29
30
    public function isFollowLength(string $tin)
31
    {
32
        return StringUtil::isFollowLength($tin, self::LENGTH);
33
    }
34
35
    public function isFollowPattern(string $tin)
36
    {
37
        return StringUtil::isFollowPattern($tin, self::PATTERN);
38
    }
39
40
    public function isFollowRules(string $tin)
41
    {
42
        return $this->isFollowRangeRule($tin) && $this->isFollowSloveniaRule($tin);
43
    }
44
45
    public function isFollowRangeRule(string $tin)
46
    {
47
        $intTIN = intval(StringUtil::substring($tin, 0, 7));
48
        return NumberUtil::isInRange($intTIN, 999999, 10000000);
49
    }
50
51
    public function isFollowSloveniaRule(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);
61
        $sum = $c1 * 8 + $c2 * 7 + $c3 * 6 + $c4 * 5 + $c5 * 4 + $c6 * 3 + $c7 * 2;
62
        $remainderBy11 = $sum % 11;
63
        return $c8 == 11 - $remainderBy11 || (11 - $remainderBy11 == 10 && $c8 == 0);
64
    }
65
}
66