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

Cns::calculateDigit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 10
c 1
b 0
f 1
1
<?php
2
3
namespace Brazanation\Documents;
4
5
use Brazanation\Documents\Cns\CnsCalculator;
6
use Brazanation\Documents\Cns\TemporaryCalculator;
7
8
final class Cns extends AbstractDocument
9
{
10
    const LENGTH = 15;
11
12
    const LABEL = 'CNS';
13
14
    const REGEX = '/^([\d]{3})([\d]{4})([\d]{4})([\d]{4})$/';
15
16
    const FORMAT = '$1 $2 $3 $4';
17
18
    const NUMBER_OF_DIGITS = 1;
19
20
    /**
21
     * CNS constructor.
22
     *
23
     * @param string $number
24
     */
25 22
    public function __construct(string $number)
26
    {
27 22
        $number = preg_replace('/\D/', '', $number);
28 22
        parent::__construct($number, self::LENGTH, self::NUMBER_OF_DIGITS, self::LABEL);
29
    }
30
31 11
    public static function createFromString(string $number)
32
    {
33 11
        return parent::tryCreateFromString(self::class, $number, self::LENGTH, self::NUMBER_OF_DIGITS, self::LABEL);
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 2
    public function format() : string
40
    {
41 2
        return preg_replace(self::REGEX, self::FORMAT, "{$this}");
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     *
47
     * Based on given number, it will decide what kind of calculator will use.
48
     *
49
     * For numbers starting with 7, 8 or 9 will use TemporaryCalculator,
50
     * otherwise CnsCalculator.
51
     */
52 22
    public function calculateDigit(string $baseNumber) : string
53
    {
54 22
        $calculator = new CnsCalculator();
55
56 22
        if (in_array(substr($baseNumber, 0, 1), [7, 8, 9])) {
57 2
            $calculator = new TemporaryCalculator();
58
        }
59
60 22
        $digit = $calculator->calculateDigit($baseNumber);
61
62 22
        return "{$digit}";
63
    }
64
}
65