Passed
Push — 6.0 ( e17aaf...24c103 )
by Olivier
01:40
created

ListFormatter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 61
rs 10
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 9 1
A format_many() 0 18 2
A localized() 0 3 1
A format_two() 0 3 1
A format_pattern() 0 5 1
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