Passed
Pull Request — master (#148)
by Wilmer
02:11
created

Formatter::format()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7.0084

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 17
nc 11
nop 3
dl 0
loc 28
ccs 17
cts 18
cp 0.9444
crap 7.0084
rs 8.8333
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use MessageFormatter;
8
9
use function is_array;
10
use function is_object;
11
use function is_resource;
12
13
final class Formatter implements FormatterInterface
14
{
15
    private ?string $locale = null;
16
17
    /**
18
     * This method uses \MessageFormatter::format()
19
     *
20
     * @link https://php.net/manual/en/messageformatter.format.php
21
     */
22 176
    public function format(string $message, array $parameters, string $locale = 'en-US'): string
23
    {
24 176
        if ($parameters === []) {
25 114
            return $message;
26
        }
27
28 78
        $replacements = [];
29
30 78
        foreach ($parameters as $key => $value) {
31 78
            if (is_array($value)) {
32 1
                $value = 'array';
33 77
            } elseif (is_object($value)) {
34 2
                $value = 'object';
35 75
            } elseif (is_resource($value)) {
36 1
                $value = 'resource';
37
            }
38 78
            $replacements[$key] = $value;
39
        }
40
41 78
        $locale = $this->locale ?? $locale;
42 78
        $formatter = new MessageFormatter($locale, $message);
43 78
        $result = $formatter->format($replacements);
44
45 78
        if ($result === false) {
46
            return $message;
47
        }
48
49 78
        return $result;
50
    }
51
52
    /**
53
     * Set the locale to use for formatting.
54
     *
55
     * @param string $locale The locale to use for formatting.
56
     *
57
     * @return self
58
     */
59 2
    public function locale(string $locale): self
60
    {
61 2
        $new = clone $this;
62 2
        $new->locale = $locale;
63 2
        return $new;
64
    }
65
}
66