Passed
Push — master ( 6a2c86...eb5e70 )
by Antonio Oertel
30s
created

PisPasep::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Brazanation\Documents;
4
5
use Brazanation\Documents\Exception\InvalidDocument;
6
7
final class PisPasep implements DocumentInterface
8
{
9
    const LENGTH = 11;
10
11
    const LABEL = 'PisPasep';
12
13
    const REGEX = '/^([\d]{3})([\d]{5})([\d]{2})([\d]{1})$/';
14
15
    /**
16
     * @var string
17
     */
18
    private $pispasep;
19
20
    /**
21
     * PisPasep constructor.
22
     *
23
     * @param $number
24
     */
25 11
    public function __construct($number)
26
    {
27 11
        $number = preg_replace('/\D/', '', $number);
28 11
        $this->validate($number);
29 4
        $this->pispasep = $number;
30 4
    }
31
32 11
    private function validate($number)
33
    {
34 11
        if (empty($number)) {
35 3
            throw InvalidDocument::notEmpty(static::LABEL);
36
        }
37 8
        if (!$this->isValidCV($number)) {
38 4
            throw InvalidDocument::isNotValid(static::LABEL, $number);
39
        }
40 4
    }
41
42 8
    private function isValidCV($number)
43
    {
44 8
        if (strlen($number) != static::LENGTH) {
45 1
            return false;
46
        }
47
48 7
        if (preg_match("/^{$number[0]}{" . static::LENGTH . '}$/', $number)) {
49 1
            return false;
50
        }
51
52 6
        $digits = $this->calculateDigit(substr($number, 0, -1));
53
54 6
        return $digits === substr($number, -1);
55
    }
56
57
    /**
58
     * Formats PIS/PASEP number
59
     *
60
     * @return string Returns formatted number, such as: 00.00000.00-0
61
     */
62 2
    public function format()
63
    {
64 2
        return preg_replace(static::REGEX, '$1.$2.$3-$4', $this->pispasep);
65
    }
66
67 2
    public function __toString()
68
    {
69 2
        return (string) $this->pispasep;
70
    }
71
72
    /**
73
     * Calculate check digits from base number.
74
     *
75
     * @param string $number Base numeric section to be calculate your digit.
76
     *
77
     * @return string
78
     */
79 6
    private function calculateDigit($number)
80
    {
81 6
        $calculator = new DigitCalculator($number);
82 6
        $calculator->withMultipliersInterval(2, 9);
83 6
        $calculator->useComplementaryInsteadOfModule();
84 6
        $calculator->replaceWhen('0', 10, 11);
85 6
        $calculator->withModule(DigitCalculator::MODULE_11);
86 6
        $digit = $calculator->calculate();
87
88 6
        return "{$digit}";
89
    }
90
}
91