Completed
Push — master ( 73210d...396474 )
by Antonio Oertel
03:23 queued 31s
created

PisPasep::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
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
    const FORMAT_REGEX = '/^[\d]{3}\.[\d]{5}\.[\d]{2}-[\d]{1}$/';
16
17
    /**
18
     * @var string
19
     */
20
    private $pispasep;
21
22
    protected $mask = '000.00000.00-0';
23
24
    /**
25
     * PisPasep constructor.
26
     *
27
     * @param $number
28
     */
29 11
    public function __construct($number)
30
    {
31 11
        $number = preg_replace('/\D/', '', $number);
32 11
        $this->validate($number);
33 4
        $this->pispasep = $number;
34 4
    }
35
36 11
    private function validate($number)
37
    {
38 11
        if (empty($number)) {
39 3
            throw InvalidDocument::notEmpty(static::LABEL);
40
        }
41 8
        if (!$this->isValidCV($number)) {
42 4
            throw InvalidDocument::isNotValid(static::LABEL, $number);
43
        }
44 4
    }
45
46 8
    private function isValidCV($number)
47
    {
48 8
        if (strlen($number) != static::LENGTH) {
49 1
            return false;
50
        }
51
52 7
        if (preg_match("/^{$number[0]}{" . static::LENGTH . '}$/', $number)) {
53 1
            return false;
54
        }
55
56 6
        return (new Modulo11(1, 9))->validate($number);
57
    }
58
59
    /**
60
     * Formats PIS/PASEP number
61
     *
62
     * @return string Returns formatted number, such as: 00.00000.00-0
63
     */
64 2
    public function format()
65
    {
66 2
        return preg_replace(static::REGEX, '$1.$2.$3-$4', $this->pispasep);
67
    }
68
69 2
    public function __toString()
70
    {
71 2
        return (string) $this->pispasep;
72
    }
73
}
74