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
|
|
|
use NumberFormatter; |
10
|
|
|
|
11
|
|
|
class LocaleNumberFormatter implements Formatter |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* "Locale" key to pass to the collection of $items. |
15
|
|
|
* |
16
|
|
|
* @var string |
17
|
|
|
*/ |
18
|
|
|
public string $locale_key = 'locale'; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* "Number" key to pass to the collection of $items. |
22
|
|
|
* |
23
|
|
|
* @var string |
24
|
|
|
*/ |
25
|
|
|
public string $number_key = 'number'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* "Style" key to pass to the collection of $items. |
29
|
|
|
* |
30
|
|
|
* @var string |
31
|
|
|
*/ |
32
|
|
|
public string $style_key = 'style'; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* "Pattern" key to pass to the collection of $items. |
36
|
|
|
* |
37
|
|
|
* @var string |
38
|
|
|
*/ |
39
|
|
|
public string $pattern_key = 'pattern'; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Extendable fraction digits. |
43
|
|
|
* |
44
|
|
|
* @var int |
45
|
|
|
*/ |
46
|
|
|
public int $fraction_digits = 2; |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Default number if $number_key isn't passed. |
50
|
|
|
* |
51
|
|
|
* @var float |
52
|
|
|
*/ |
53
|
|
|
public float $default_number = 0; |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Format the date and time. |
57
|
|
|
* |
58
|
|
|
* @param Collection $items |
59
|
|
|
* |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
|
|
public function format(Collection $items): string |
63
|
|
|
{ |
64
|
|
|
$formatter = new NumberFormatter( |
65
|
|
|
$items->get($this->locale_key) ?? app()->getLocale(), |
|
|
|
|
66
|
|
|
$items->get($this->style_key) ?? NumberFormatter::DECIMAL, |
67
|
|
|
$items->get($this->pattern_key) ?? null |
68
|
|
|
); |
69
|
|
|
|
70
|
|
|
$formatter->setAttribute( |
71
|
|
|
NumberFormatter::FRACTION_DIGITS, |
72
|
|
|
$this->fraction_digits |
73
|
|
|
); |
74
|
|
|
|
75
|
|
|
return $formatter->format( |
76
|
|
|
(float) $items->get($this->number_key) ?? $this->default_number |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|