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

TaxNumberFormatter::getPrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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