Completed
Pull Request — master (#19)
by Antonio Oertel
03:06
created

Urban::calculateDigit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Brazanation\Documents\StateRegistration\SaoPaulo;
4
5
use Brazanation\Documents\DigitCalculator;
6
use Brazanation\Documents\StateRegistration\SaoPaulo;
7
use Brazanation\Documents\StateRegistration\State;
8
9
class Urban extends State
10
{
11
    const REGEX = '/^(\d{3})(\d{3})(\d{3})(\d{3})$/';
12
13
    const FORMAT = '$1.$2.$3.$4';
14
15
    const LENGTH = 12;
16
17
    const DIGITS_COUNT = 1;
18
19 7
    public function __construct()
20
    {
21 7
        parent::__construct(SaoPaulo::LONG_NAME, self::LENGTH, self::DIGITS_COUNT, self::REGEX, self::FORMAT);
22 7
    }
23
24
    /**
25
     * {@inheritdoc}
26
     *
27
     * No extract any digit
28
     */
29 4
    public function extractBaseNumber($number)
30
    {
31 4
        return $number;
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 5
    public function extractCheckerDigit($number)
38
    {
39 5
        return substr($number, self::LENGTH - 4, 1) . substr($number, -1);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     *
45
     * @see http://www.sintegra.gov.br/Cad_Estados/cad_SP.html
46
     */
47 3
    public function calculateDigit($baseNumber)
48
    {
49 3
        $firstBaseNumber = substr($baseNumber, 0, 8);
50
51 3
        $firstDigit = $this->calculateFirstDigit($firstBaseNumber);
52
53 3
        $secondBaseNumber = "{$firstBaseNumber}{$firstDigit}" . substr($baseNumber, -3, 2);
54
55 3
        $secondDigit = $this->calculateSecondDigit($secondBaseNumber);
56
57 3
        return "{$firstDigit}{$secondDigit}";
58
    }
59
60 3
    private function calculateFirstDigit($baseNumber)
61
    {
62 3
        $calculator = new DigitCalculator($baseNumber);
63 3
        $calculator->withMultipliers([10, 8, 7, 6, 5, 4, 3, 1]);
64 3
        $calculator->replaceWhen('0', 10);
65 3
        $calculator->replaceWhen('1', 11);
66 3
        $calculator->withModule(DigitCalculator::MODULE_11);
67 3
        $digit = $calculator->calculate();
68
69 3
        return "{$digit}";
70
    }
71
72 3
    private function calculateSecondDigit($baseNumber)
73
    {
74 3
        $calculator = new DigitCalculator($baseNumber);
75 3
        $calculator->withMultipliersInterval(2, 10);
76 3
        $calculator->replaceWhen('0', 10);
77 3
        $calculator->replaceWhen('1', 11);
78 3
        $calculator->withModule(DigitCalculator::MODULE_11);
79 3
        $digit = $calculator->calculate();
80
81 3
        return "{$digit}";
82
    }
83
}
84