Passed
Branch main (0700b3)
by Michael
12:22
created

TaxNumberFormatter::getFullTaxNumber()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\Formatters\Collection;
6
7
use Illuminate\Support\Str;
8
use MichaelRubel\Formatters\Formatter;
9
10
class TaxNumberFormatter implements Formatter
11
{
12
    /**
13
     * @param string|null $tax_number
14
     * @param string|null $country
15
     */
16 15
    public function __construct(
17
        public ?string $tax_number = null,
18
        public ?string $country = null
19
    ) {
20 15
        $filteredTaxNumber = preg_replace_array('/[^\d\w]/', [], (string) $this->tax_number);
21 15
        $this->tax_number  = Str::upper($filteredTaxNumber);
22 15
        $this->country     = Str::upper((string) $this->country);
23
    }
24
25
    /**
26
     * Format the Tax Number.
27
     *
28
     * @return string
29
     */
30 15
    public function format(): string
31
    {
32 15
        return ! blank($this->country)
33 11
            ? $this->getFullTaxNumber()
34 15
            : (string) $this->tax_number;
35
    }
36
37
    /**
38
     * @return string
39
     */
40 11
    private function getPrefix(): string
41
    {
42 11
        return (string) Str::of($this->tax_number)
43 11
            ->substr(0, 2)
44 11
            ->upper();
45
    }
46
47
    /**
48
     * @return string
49
     */
50 11
    private function getFullTaxNumber(): string
51
    {
52 11
        $prefixStartsWithCountry = Str::of($this->getPrefix())
53 11
            ->startsWith($this->country);
54
55 11
        if ($prefixStartsWithCountry) {
56 4
            return (string) Str::of($this->tax_number)
57 4
                ->substr(2)
58 4
                ->start($this->country);
59
        }
60
61 7
        return Str::start($this->tax_number, $this->country);
62
    }
63
}
64