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