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

TaxNumberFormatter::cleanup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A TaxNumberFormatter::getPrefix() 0 5 1
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