Passed
Branch main (274970)
by Antonio Oertel
03:05
created

Bahia::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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