forked from kornrunner/CLDR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListFormatter.php
More file actions
90 lines (74 loc) · 1.72 KB
/
ListFormatter.php
File metadata and controls
90 lines (74 loc) · 1.72 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\CLDR;
use ICanBoogie\CLDR\Locale\ListPattern;
/**
* Formats variable-length lists of things such as "Monday, Tuesday, Friday, and Saturday".
*
* @see http://www.unicode.org/reports/tr35/tr35-general.html#ListPatterns
*/
class ListFormatter implements Formatter
{
/**
* Formats a variable-length lists of scalars.
*
* @param scalar[] $list
*/
public function __invoke(array $list, ListPattern $list_pattern): string
{
return $this->format($list, $list_pattern);
}
/**
* Formats a variable-length lists of scalars.
*
* @param scalar[] $list
*/
public function format(array $list, ListPattern $list_pattern): string
{
$list = array_values($list);
switch (count($list))
{
case 0:
return "";
case 1:
return (string) current($list);
case 2:
return $this->format_pattern($list_pattern->two, (string) $list[0], (string) $list[1]);
default:
$n = count($list) - 1;
$v1 = $list[$n];
for ($i = $n - 1 ; $i > -1 ; $i--)
{
$v0 = $list[$i];
if ($i === 0)
{
$pattern = $list_pattern->start;
}
else if ($i + 1 === $n)
{
$pattern = $list_pattern->end;
}
else
{
$pattern = $list_pattern->middle;
}
$v1 = $this->format_pattern($pattern, (string) $v0, (string) $v1);
}
return $v1;
}
}
private function format_pattern(string $pattern, string $v0, string $v1): string
{
return strtr($pattern, [
'{0}' => $v0,
'{1}' => $v1
]);
}
}