Passed
Pull Request — master (#32)
by Antonio Oertel
04:01
created

Bahia::discoverModule()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.0466

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 1
crap 4.0466
1
<?php
2
3
namespace Brazanation\Documents\StateRegistration;
4
5
use Brazanation\Documents\DigitCalculator;
6
7
final class Bahia extends State
8
{
9
    const LONG_NAME = 'Bahia';
10
11
    const SHORT_NAME = 'BA';
12
13
    const REGEX = '/^([\d]{6,7})(\d{2})$/';
14
15
    const FORMAT = '$1-$2';
16
17
    const LENGTH = 9;
18
19
    const DIGITS_COUNT = 2;
20
21 11
    public function __construct()
22
    {
23 11
        parent::__construct(self::LONG_NAME, self::LENGTH, self::DIGITS_COUNT, self::REGEX, self::FORMAT);
24 11
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 11
    public function normalizeNumber($number)
30
    {
31 11
        if (!empty($number)) {
32 10
            return str_pad(parent::normalizeNumber($number), $this->getLength(), '0', STR_PAD_LEFT);
33
        }
34
35 1
        return $number;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     *
41
     * @see http://www.sintegra.gov.br/Cad_Estados/cad_BA.html
42
     */
43 9
    public function calculateDigit($baseNumber)
44
    {
45 9
        $calculator = new DigitCalculator($baseNumber);
46 9
        $calculator->useComplementaryInsteadOfModule();
47 9
        $calculator->replaceWhen('0', 10, 11);
48 9
        $calculator->withModule($this->discoverModule($baseNumber));
49
50 9
        $firstDigit = $calculator->calculate();
51 9
        $calculator->addDigit($firstDigit);
52 9
        $secondDigit = $calculator->calculate();
53
54 9
        return "{$secondDigit}{$firstDigit}";
55
    }
56
57 9
    private function discoverModule($baseNumber)
58
    {
59 9
        $charToCheck = substr($baseNumber, 1, 1);
60 9
        if (strlen($baseNumber) == 6) {
61
            $charToCheck = substr($baseNumber, 0, 1);
62
        }
63 9
        if (6 <= $charToCheck && $charToCheck <= 9) {
64 3
            return DigitCalculator::MODULE_11;
65
        }
66
67 6
        return DigitCalculator::MODULE_10;
68
    }
69
}
70