|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ICanBoogie\CLDR; |
|
4
|
|
|
|
|
5
|
|
|
use ICanBoogie\CLDR\Locale\ListPattern; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Formats variable-length lists of things such as "Monday, Tuesday, Friday, and Saturday". |
|
9
|
|
|
* |
|
10
|
|
|
* @see http://www.unicode.org/reports/tr35/tr35-general.html#ListPatterns |
|
11
|
|
|
* |
|
12
|
|
|
* @implements Localizable<ListFormatter, LocalizedListFormatter> |
|
13
|
|
|
*/ |
|
14
|
|
|
final class ListFormatter implements Formatter, Localizable |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Formats variable-length lists of scalars. |
|
18
|
|
|
* |
|
19
|
|
|
* @param scalar[] $list |
|
20
|
|
|
*/ |
|
21
|
|
|
public function format(array $list, ListPattern $list_pattern): string |
|
22
|
|
|
{ |
|
23
|
|
|
$list = array_values($list); |
|
24
|
|
|
|
|
25
|
|
|
return match (count($list)) { |
|
26
|
|
|
0 => "", |
|
27
|
|
|
1 => (string)current($list), |
|
28
|
|
|
2 => $this->format_two($list, $list_pattern), |
|
29
|
|
|
default => $this->format_many($list, $list_pattern), |
|
30
|
|
|
}; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param scalar[] $list |
|
35
|
|
|
*/ |
|
36
|
|
|
private function format_two(array $list, ListPattern $list_pattern): string |
|
37
|
|
|
{ |
|
38
|
|
|
return $this->format_pattern($list_pattern->two, (string)$list[0], (string)$list[1]); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param scalar[] $list |
|
43
|
|
|
*/ |
|
44
|
|
|
private function format_many(array $list, ListPattern $list_pattern): string |
|
45
|
|
|
{ |
|
46
|
|
|
$n = count($list) - 1; |
|
47
|
|
|
$v1 = (string)$list[$n]; |
|
48
|
|
|
|
|
49
|
|
|
for ($i = $n - 1; $i > -1; $i--) { |
|
50
|
|
|
$v0 = $list[$i]; |
|
51
|
|
|
|
|
52
|
|
|
$pattern = match ($i) { |
|
53
|
|
|
0 => $list_pattern->start, |
|
54
|
|
|
$n - 1 => $list_pattern->end, |
|
55
|
|
|
default => $list_pattern->middle, |
|
56
|
|
|
}; |
|
57
|
|
|
|
|
58
|
|
|
$v1 = $this->format_pattern($pattern, (string)$v0, (string)$v1); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $v1; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
private function format_pattern(string $pattern, string $v0, string $v1): string |
|
65
|
|
|
{ |
|
66
|
|
|
return strtr($pattern, [ |
|
67
|
|
|
'{0}' => $v0, |
|
68
|
|
|
'{1}' => $v1 |
|
69
|
|
|
]); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
public function localized(Locale $locale): LocalizedListFormatter |
|
73
|
|
|
{ |
|
74
|
|
|
return new LocalizedListFormatter($this, $locale); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|