Passed
Pull Request — master (#64)
by Alexander
04:35 queued 02:06
created

SimpleMessageFormatter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 34
c 2
b 0
f 0
dl 0
loc 60
ccs 31
cts 31
cp 1
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 35 5
A pluralize() 0 17 4
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 9
    public function format(string $message, array $parameters, string $locale = 'en_US'): string
16
    {
17 9
        preg_match_all('/{((?>[^{}]+)|(?R))*}/', $message, $matches);
18 9
        $replacements = [];
19
20 9
        foreach ($matches[0] as $match) {
21 9
            $parts = explode(',', $match);
22 9
            $parameter = trim($parts[0], '{}');
23 9
            $value = $parameters[$parameter];
24
25 9
            if (!is_scalar($value)) {
26 1
                continue;
27
            }
28
29 8
            if (count($parts) === 1) {
30 3
                $replacements[$match] = $value;
31
32 3
                continue;
33
            }
34
35 6
            $format = ltrim($parts[1]);
36 6
            $format = rtrim($format, '}');
37
38 6
            switch ($format) {
39 6
                case 'plural':
40 5
                    $options = $parts[2];
41 5
                    $replacements[$match] = self::pluralize($value, $options);
42
43 4
                    break;
44
                default:
45 2
                    $replacements[$match] = $value;
46
            }
47
        }
48
49 8
        return strtr($message, $replacements);
50
    }
51
52 5
    private static function pluralize(int $value, string $options): string
53
    {
54 5
        preg_match_all('/([^{}\s]+)({(.*?)})/', $options, $pluralMatches);
55
56 5
        foreach ($pluralMatches[1] as $match) {
57 5
            if (!in_array($match, self::PLURAL_KEYS, true)) {
58 1
                $keysStr = implode(', ', array_map(fn (string $value): string => '"' . $value . '"', self::PLURAL_KEYS));
59
60 1
                throw new InvalidArgumentException("Invalid plural key - \"$match\". The valid keys are $keysStr.");
61
            }
62
        }
63
64 4
        $map = array_combine($pluralMatches[1], $pluralMatches[3]);
65 4
        $formattedValue = $value . ' ';
66 4
        $formattedValue .= $value === 1 ? $map[self::PLURAL_ONE] : $map[self::PLURAL_OTHER];
67
68 4
        return $formattedValue;
69
    }
70
}
71