InnValue::__construct()   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
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
4
namespace talismanfr\psbbank\shared;
5
6
7
use InvalidArgumentException;
8
9
class InnValue
10
{
11
    /** @var string */
12
    private $inn;
13
14
    public function __construct(string $inn)
15
    {
16
        $this->setInn($inn);
17
    }
18
19
    /**
20
     * @return string
21
     */
22
    public function getInn(): string
23
    {
24
        return $this->inn;
25
    }
26
27
    /**
28
     * @param string $inn
29
     */
30
    private function setInn(string $inn): void
31
    {
32
        if ($this->isValid($inn)) {
33
            $this->inn = $inn;
34
        } else {
35
            throw new InvalidArgumentException('INN not valid');
36
        }
37
    }
38
39
    /**
40
     *
41
     * @param string $inn 10-ти или 12-ти значное целое число
42
     * @return  bool    TRUE, если ИНН корректен и FALSE в противном случае
43
     */
44
    private function isValid(string $inn): bool
45
    {
46
        if (preg_match('/[^0-9]/', $inn)) {
47
            return false; //'ИНН может состоять только из цифр';
48
        }
49
50
        if (!in_array($inn_length = strlen($inn), [10, 12])) {
51
            return false;// 'ИНН может состоять только из 10 или 12 цифр';
52
        }
53
54
        switch ($inn_length) {
55
            case 10:
56
                $n10 = $this->checkDigit($inn, [2, 4, 10, 3, 5, 9, 4, 6, 8]);
57
                if ($n10 === (int)$inn{9}) {
58
                    return true;
59
                }
60
                break;
61
            case 12:
62
                $n11 = $this->checkDigit($inn, [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]);
63
                $n12 = $this->checkDigit($inn, [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]);
64
                if (($n11 === (int)$inn{10}) && ($n12 === (int)$inn{11})) {
65
                    return true;
66
                }
67
                break;
68
        }
69
70
        return false;
71
    }
72
73
    /**
74
     * @param string $inn
75
     * @param array $coefficients
76
     * @return bool
77
     */
78
    private function checkDigit(string $inn, array $coefficients): int
79
    {
80
        $n = 0;
81
        foreach ($coefficients as $i => $k) {
82
            $n += $k * (int)$inn{$i};
83
        }
84
        return $n % 11 % 10;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $n % 11 % 10 returns the type integer which is incompatible with the documented return type boolean.
Loading history...
85
    }
86
87
    public function __toString()
88
    {
89
        return $this->getInn();
90
    }
91
92
}