Passed
Pull Request — main (#9)
by
unknown
03:05
created

TaxNumberFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 8
Bugs 0 Features 1
Metric Value
eloc 25
c 8
b 0
f 1
dl 0
loc 83
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 6 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
        )
53 9
        ->upper();
54
    }
55
56
    /**
57
     * @param string $tax_number
58
     * @return string
59
     */
60 9
    private function getPrefix(string $tax_number): string
61
    {
62 9
        return (string) Str::of($tax_number)
63 9
            ->substr(0, 2)
64 9
            ->upper();
65
    }
66
67
    /**
68
     * @param string $tax_number
69
     * @param string $country
70
     * @return string
71
     */
72 9
    private function getFullTaxNumber(string $tax_number, string $country): string
73
    {
74 9
        $prefix = $this->getPrefix($tax_number);
75
76 9
        return Str::of($prefix)->startsWith($country)
77 2
            ? (string) Str::of($tax_number)
78 2
                ->substr(2)
79 2
                ->start($country)
80 7
            : (string) Str::of($tax_number)
81 9
                ->start($country);
82
    }
83
84
    /**
85
     * @param Collection $items
86
     * @return string
87
     */
88 12
    private function cleanupTaxNumber(Collection $items): string
89
    {
90 12
        return preg_replace_array(
91 12
            '/[^\d\w]/',
92 12
            [],
93 12
            $items->get($this->number_key)
94
        );
95
    }
96
}
97