Passed
Pull Request — master (#64)
by
unknown
02:20
created

SimpleMessageFormatter::format()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 23
c 2
b 0
f 0
nc 6
nop 3
dl 0
loc 40
ccs 23
cts 23
cp 1
crap 6
rs 8.9297
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Translator;
6
7
use InvalidArgumentException;
8
9
class SimpleMessageFormatter implements MessageFormatterInterface
10
{
11
    private const PLURAL_ONE = 'one';
12
    private const PLURAL_OTHER = 'other';
13
    private const PLURAL_KEYS = [self::PLURAL_ONE, self::PLURAL_OTHER];
14
15 11
    public function format(string $message, array $parameters, string $locale = 'en_US'): string
16
    {
17 11
        preg_match_all('/{((?>[^{}]+)|(?R))*}/', $message, $matches);
18 11
        $replacements = [];
19
20 11
        foreach ($matches[0] as $match) {
21 11
            $parts = explode(',', $match);
22 11
            $parameter = trim($parts[0], '{}');
23
24 11
            if (!isset($parameters[$parameter])) {
25 1
                throw new InvalidArgumentException("\"$parameter\" parameter's value is missing.");
26
            }
27
28 10
            $value = $parameters[$parameter];
29
30 10
            if (!is_scalar($value)) {
31 1
                continue;
32
            }
33
34 9
            if (count($parts) === 1) {
35 3
                $replacements[$match] = $value;
36
37 3
                continue;
38
            }
39
40 7
            $format = ltrim($parts[1]);
41 7
            $format = rtrim($format, '}');
42
43 7
            switch ($format) {
44 7
                case 'plural':
45 6
                    $options = $parts[2];
46 6
                    $replacements[$match] = self::pluralize($value, $options);
47
48 5
                    break;
49
                default:
50 2
                    $replacements[$match] = $value;
51
            }
52
        }
53
54 9
        return strtr($message, $replacements);
55
    }
56
57 6
    private static function pluralize(int $value, string $options): string
58
    {
59 6
        preg_match_all('/([^{}\s]+)({(.*?)})/', $options, $pluralMatches);
60
61 6
        foreach ($pluralMatches[1] as $match) {
62 6
            if (!in_array($match, self::PLURAL_KEYS, true)) {
63 1
                $keysStr = implode(', ', array_map(fn (string $value): string => '"' . $value . '"', self::PLURAL_KEYS));
64
65 1
                throw new InvalidArgumentException("Invalid plural key - \"$match\". The valid keys are $keysStr.");
66
            }
67
        }
68
69 5
        $map = array_combine($pluralMatches[1], $pluralMatches[3]);
70 5
        $formattedValue = $value . ' ';
71 5
        $formattedValue .= $value === 1 ? $map[self::PLURAL_ONE] : $map[self::PLURAL_OTHER];
72
73 5
        return $formattedValue;
74
    }
75
}
76