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

SimpleMessageFormatter::format()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 25
c 1
b 0
f 0
nc 6
nop 3
dl 0
loc 39
ccs 25
cts 25
cp 1
crap 6
rs 8.8977
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Translator;
6
7
class SimpleMessageFormatter implements MessageFormatterInterface
8
{
9 4
    public function format(string $message, array $parameters, string $locale): string
10
    {
11 4
        preg_match_all('/{((?>[^{}]+)|(?R))*}/', $message, $matches);
12 4
        $replacements = [];
13
14 4
        foreach ($matches[0] as $match) {
15 4
            $parts = explode(',', $match);
16 4
            $parameter = trim($parts[0], '{}');
17 4
            $value = $parameters[$parameter];
18
19 4
            if (!is_scalar($value)) {
20 1
                continue;
21
            }
22
23 3
            if (count($parts) === 1) {
24 3
                $replacements[$match] = $value;
25
26 3
                continue;
27
            }
28
29 1
            $format = ltrim($parts[1]);
30 1
            $format = rtrim($format, '}');
31
32 1
            switch ($format) {
33 1
                case 'plural':
34 1
                    $options = $parts[2];
35 1
                    preg_match_all('/([^{}\s]+)({(.*?)})/', $options, $pluralMatches);
36 1
                    $map = array_combine($pluralMatches[1], $pluralMatches[3]);
37 1
                    $formattedValue = $value . ' ';
38 1
                    $formattedValue .= $value === 1 ? $map['one'] : $map['other'];
39 1
                    $replacements[$match] = $formattedValue;
40
41 1
                    break;
42
                default:
43 1
                    $replacements[$match] = $value;
44
            }
45
        }
46
47 4
        return strtr($message, $replacements);
48
    }
49
}
50