Inn::validateTenDigits()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 10
c 1
b 0
f 1
nc 4
nop 1
dl 0
loc 18
rs 9.9332
1
<?php
2
3
namespace Kontrolio\Rules\Core;
4
5
use Kontrolio\Rules\AbstractRule;
6
7
class Inn extends AbstractRule
8
{
9
    /**
10
     * Validates input.
11
     *
12
     * @param mixed $input
13
     *
14
     * @return bool
15
     */
16
    public function isValid($input = null)
17
    {
18
        if (!is_numeric($input)) {
19
            $this->violations[] = 'numeric';
20
21
            return false;
22
        }
23
24
        $input = (string) $input;
25
26
        switch (strlen($input)) {
27
            case 10:
28
                return $this->validateTenDigits($input);
29
30
            case 12:
31
                return $this->validateTwelveDigits($input);
32
33
            default:
34
                $this->violations[] = 'length';
35
                return false;
36
        }
37
    }
38
39
    /**
40
     * Validates ten digits INN.
41
     *
42
     * @param string $input
43
     *
44
     * @return bool
45
     */
46
    protected function validateTenDigits($input)
47
    {
48
        $factor = [2, 4, 10, 3, 5, 9, 4, 6, 8, 0];
49
        $index = 0;
50
        $checksum = 0;
51
52
        while ($index <= 9) {
53
            $checksum = $checksum + intval($input[$index]) * $factor[$index];
54
            $index++;
55
        }
56
57
        $value = $checksum % 11;
58
59
        if ($value > 9) {
60
            $value = $value % 10;
61
        }
62
63
        return $input[9] == $value;
64
    }
65
66
    protected function validateTwelveDigits($input)
67
    {
68
        $factor = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0];
69
        $index = 0;
70
        $checksum = 0;
71
72
        while ($index <= 10) {
73
            $checksum = $checksum + intval($input[$index]) * $factor[$index + 1];
74
            $index++;
75
        }
76
77
        $value = $checksum % 11;
78
79
        if ($value > 9) {
80
            $value = $value % 10;
81
        }
82
83
        $index = 0;
84
        $checksum2 = 0;
85
86
        while ($index <= 11) {
87
            $checksum2 = $checksum2 + intval($input[$index]) * $factor[$index];
88
            $index++;
89
        }
90
91
        $value2 = $checksum2 % 11;
92
93
        if ($value2 > 9) {
94
            $value2 = $value2 % 10;
95
        }
96
97
        return $input[10] == $value && $input[11] == $value2;
98
    }
99
}
100