Passed
Push — main ( e3944e...891487 )
by Michael
55s queued 11s
created

TaxNumberFormatter::cleanupTaxNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\Formatters\Collection;
6
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
use MichaelRubel\Formatters\Formatter;
10
11
class TaxNumberFormatter implements Formatter
12
{
13
    /**
14
     * @var string
15
     */
16
    public string $number_key = 'tax_number';
17
18
    /**
19
     * @var string
20
     */
21
    public string $country_key = 'country_iso';
22
23
    /**
24
     * Format the Tax Number.
25
     *
26
     * @param Collection $items
27
     *
28
     * @return string
29
     */
30 12
    public function format(Collection $items): string
31
    {
32 12
        $tax_number = $this->cleanupTaxNumber($items);
33
34 12
        return empty($items->get($this->country_key))
35 3
            ? $tax_number
36 9
            : $this->getFullTaxNumber(
37 9
                $tax_number,
38 12
                $this->getCountry($items)
39
            );
40
    }
41
42
    /**
43
     * @param Collection $items
44
     * @return string
45
     */
46 9
    private function getCountry(Collection $items): string
47
    {
48 9
        return (string) Str::of(
49 9
            $items->get($this->country_key)
50 9
        )->upper();
51
    }
52
53
    /**
54
     * @param string $tax_number
55
     * @return string
56
     */
57 9
    private function getPrefix(string $tax_number): string
58
    {
59 9
        return (string) Str::of($tax_number)
60 9
            ->substr(0, 2)
61 9
            ->upper();
62
    }
63
64
    /**
65
     * @param string $tax_number
66
     * @param string $country
67
     * @return string
68
     */
69 9
    private function getFullTaxNumber(string $tax_number, string $country): string
70
    {
71 9
        return Str::of(
72 9
            $this->getPrefix($tax_number)
73 9
        )->startsWith($country)
74 2
            ? (string) Str::of($tax_number)
75 2
                ->substr(2)
76 2
                ->start($country)
77 7
            : (string) Str::of($tax_number)
78 9
                ->start($country);
79
    }
80
81
    /**
82
     * @param Collection $items
83
     * @return string
84
     */
85 12
    private function cleanupTaxNumber(Collection $items): string
86
    {
87 12
        return preg_replace_array(
88 12
            '/[^\d\w]/',
89 12
            [],
90 12
            $items->get($this->number_key)
91
        );
92
    }
93
}
94