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

SimpleMessageFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 27
c 2
b 0
f 0
dl 0
loc 47
ccs 27
cts 27
cp 1
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 35 5
A pluralize() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Translator;
6
7
class SimpleMessageFormatter implements MessageFormatterInterface
8
{
9 8
    public function format(string $message, array $parameters, string $locale): string
10
    {
11 8
        preg_match_all('/{((?>[^{}]+)|(?R))*}/', $message, $matches);
12 8
        $replacements = [];
13
14 8
        foreach ($matches[0] as $match) {
15 8
            $parts = explode(',', $match);
16 8
            $parameter = trim($parts[0], '{}');
17 8
            $value = $parameters[$parameter];
18
19 8
            if (!is_scalar($value)) {
20 1
                continue;
21
            }
22
23 7
            if (count($parts) === 1) {
24 3
                $replacements[$match] = $value;
25
26 3
                continue;
27
            }
28
29 5
            $format = ltrim($parts[1]);
30 5
            $format = rtrim($format, '}');
31
32 5
            switch ($format) {
33 5
                case 'plural':
34 4
                    $options = $parts[2];
35 4
                    $replacements[$match] = self::pluralize($value, $options);
36
37 4
                    break;
38
                default:
39 2
                    $replacements[$match] = $value;
40
            }
41
        }
42
43 8
        return strtr($message, $replacements);
44
    }
45
46 4
    private static function pluralize(int $value, string $options): string
47
    {
48 4
        preg_match_all('/([^{}\s]+)({(.*?)})/', $options, $pluralMatches);
49 4
        $map = array_combine($pluralMatches[1], $pluralMatches[3]);
50 4
        $formattedValue = $value . ' ';
51 4
        $formattedValue .= $value === 1 ? $map['one'] : $map['other'];
52
53 4
        return $formattedValue;
54
    }
55
}
56