Passed
Pull Request — main (#9)
by
unknown
02:59
created

TaxNumberFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 9
Bugs 0 Features 1
Metric Value
eloc 25
c 9
b 0
f 1
dl 0
loc 82
ccs 28
cts 28
cp 1
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 11 2
A getFullTaxNumber() 0 10 2
A getCountry() 0 5 1
A cleanupTaxNumber() 0 6 1
A getPrefix() 0 5 1
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
        if (empty($items->get($this->country_key))) {
35 3
            return $tax_number;
36
        }
37
38 9
        return $this->getFullTaxNumber(
39 9
            $tax_number,
40 9
            $this->getCountry($items)
41
        );
42
    }
43
44
    /**
45
     * @param Collection $items
46
     * @return string
47
     */
48 9
    private function getCountry(Collection $items): string
49
    {
50 9
        return (string) Str::of(
51 9
            $items->get($this->country_key)
52 9
        )->upper();
53
    }
54
55
    /**
56
     * @param string $tax_number
57
     * @return string
58
     */
59 9
    private function getPrefix(string $tax_number): string
60
    {
61 9
        return (string) Str::of($tax_number)
62 9
            ->substr(0, 2)
63 9
            ->upper();
64
    }
65
66
    /**
67
     * @param string $tax_number
68
     * @param string $country
69
     * @return string
70
     */
71 9
    private function getFullTaxNumber(string $tax_number, string $country): string
72
    {
73 9
        $prefix = $this->getPrefix($tax_number);
74
75 9
        return Str::of($prefix)->startsWith($country)
76 2
            ? (string) Str::of($tax_number)
77 2
                ->substr(2)
78 2
                ->start($country)
79 7
            : (string) Str::of($tax_number)
80 9
                ->start($country);
81
    }
82
83
    /**
84
     * @param Collection $items
85
     * @return string
86
     */
87 12
    private function cleanupTaxNumber(Collection $items): string
88
    {
89 12
        return preg_replace_array(
90 12
            '/[^\d\w]/',
91 12
            [],
92 12
            $items->get($this->number_key)
93
        );
94
    }
95
}
96