-
Notifications
You must be signed in to change notification settings - Fork 4
/
IntlNumberFormatter.php
57 lines (45 loc) · 1.15 KB
/
IntlNumberFormatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php declare(strict_types=1);
namespace h4kuna\Format\Number\Formatters;
use h4kuna\Format\Number\Formatter;
use h4kuna\Format\Utils\Space;
use NumberFormatter;
/**
* NumberFormatter default settings:
* - zeroClear: ZeroClear::DECIMALS
* - nbsp: true
*/
final class IntlNumberFormatter implements Formatter
{
public function __construct(
private NumberFormatter $formatter,
public string $emptyValue = '',
public bool $zeroIsEmpty = false,
)
{
$this->emptyValue = Space::nbsp($this->emptyValue);
}
public function modify(
?string $emptyValue = null,
?bool $zeroIsEmpty = null,
): self
{
return new static(
$this->formatter,
$emptyValue ?? $this->emptyValue,
$zeroIsEmpty ?? $this->zeroIsEmpty,
);
}
public function format(string|int|float|null $number): string
{
if (is_numeric($number) === false || ($this->zeroIsEmpty && (int) $number === 0)) {
return $this->emptyValue;
}
$result = $this->formatter->format(is_string($number) ? (float) $number : $number);
assert(is_string($result));
return $result;
}
public function __invoke(float|int|string|null $number): string
{
return $this->format($number);
}
}