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

TaxNumberFormatter::getPrefix()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 1
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 $key_number = 'tax_number';
17
18
    /**
19
     * @var string
20
     */
21
    public string $key_country = 'country_iso';
22
23
    /**
24
     * Format the Tax Number.
25
     *
26
     * @param Collection $items
27
     *
28
     * @return string
29
     */
30 10
    public function format(Collection $items): string
31
    {
32 10
        $tax_number = $this->getCleanTaxNumber($items);
33
34 10
        if (empty($items->get($this->key_country))) {
35 3
            return $tax_number;
36
        }
37
38 7
        return $this->getFullTaxNumber(
39 7
            $tax_number,
40 7
            $this->getCountry($items)
41
        );
42
    }
43
44
    /**
45
     * @param Collection $items
46
     * @return string
47
     */
48 7
    private function getCountry(Collection $items): string
49
    {
50 7
        return (string) Str::of($items->get($this->key_country))
51 7
            ->upper();
52
    }
53
54
    /**
55
     * @param string $tax_number
56
     * @return string
57
     */
58 7
    private function getPrefix(string $tax_number): string
59
    {
60 7
        return (string) Str::of($tax_number)
61 7
            ->substr(0, 2)
62 7
            ->upper();
63
    }
64
65
    /**
66
     * @param string $tax_number
67
     * @param string $country
68
     * @return string
69
     */
70 7
    private function getFullTaxNumber(string $tax_number, string $country): string
71
    {
72 7
        $prefix = $this->getPrefix($tax_number);
73
74 7
        return Str::of($prefix)->startsWith($country)
75 2
            ? (string) Str::of($tax_number)
76 2
                ->substr(2)
77 2
                ->start($country)
78 5
            : (string) Str::of($tax_number)
79 7
                ->start($country);
80
    }
81
82
    /**
83
     * @param Collection $items
84
     * @return string
85
     */
86 10
    private function getCleanTaxNumber(Collection $items): string
87
    {
88 10
        return preg_replace_array(
89 10
            '/[^\d\w]/',
90 10
            [],
91 10
            $items->get($this->key_number)
92
        );
93
    }
94
}
95