ListFormatter::localized()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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