Passed
Push — main ( 834936...e5772d )
by Michael
11:48
created

TaxNumberFormatter::getCountry()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 3
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
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 14
    public function __construct(
17
        public ?string $tax_number = null,
18
        public ?string $country = null
19
    ) {
20 14
        $this->cleanup();
21
    }
22
23
    /**
24
     * Format the Tax Number.
25
     *
26
     * @return string
27
     */
28 14
    public function format(): string
29
    {
30 14
        return ! blank($this->country)
31 10
            ? $this->getFullTaxNumber()
32 14
            : $this->tax_number ?? '';
33
    }
34
35
    /**
36
     * @return void
37
     */
38 14
    private function cleanup(): void
39
    {
40 14
        $regexedTaxNumber = preg_replace_array(
41
            '/[^\d\w]/',
42 14
            [],
43 14
            $this->tax_number
44
        );
45
46 14
        $this->tax_number = Str::upper($regexedTaxNumber);
47 14
        $this->country    = Str::upper($this->country);
48
    }
49
50
    /**
51
     * @return string
52
     */
53 10
    private function getPrefix(): string
54
    {
55 10
        return (string) Str::of($this->tax_number)
56 10
            ->substr(0, 2)
57 10
            ->upper();
58
    }
59
60
    /**
61
     * @return string
62
     */
63 10
    private function getFullTaxNumber(): string
64
    {
65 10
        $prefixStartsWithCountry = Str::of($this->getPrefix())
66 10
            ->startsWith($this->country);
67
68 10
        if ($prefixStartsWithCountry) {
69 3
            return (string) Str::of($this->tax_number)
70 3
                ->substr(2)
71 3
                ->start($this->country);
72
        }
73
74 7
        return Str::start($this->tax_number, $this->country);
75
    }
76
}
77