Passed
Pull Request — master (#99)
by Def
02:34
created

ErrorMessage   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
dl 0
loc 54
ccs 27
cts 30
cp 0.9
rs 10
c 1
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 14 5
A withTranslator() 0 8 2
A __construct() 0 5 1
A __toString() 0 3 1
A getMessage() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
9
final class ErrorMessage
10
{
11
    public string $message = '';
12
    public array $params = [];
13
14
    private ?TranslatorInterface $translator;
15
16 175
    public function __construct(string $message, ?array $params = null, ?TranslatorInterface $translator = null)
17
    {
18 175
        $this->message = $message;
19 175
        $this->params = $params?? [];
20 175
        $this->translator = $translator;
21 175
    }
22
23 41
    public function withTranslator(?TranslatorInterface $translator = null): self
24
    {
25 41
        if ($translator !== null) {
26 1
            $new = clone $this;
27 1
            $new->translator = $translator;
28 1
            return $new;
29
        }
30 40
        return $this;
31
    }
32
33 76
    public function getMessage(?TranslatorInterface $translator = null): string
34
    {
35 76
        if ($translator === null) {
36 69
            $translator = $this->translator;
37
        }
38 76
        if ($translator !== null) {
39 8
            return $translator->translate($this->message, $this->params);
40
        }
41 68
        return $this->format($this->message, $this->params);
42
    }
43
44 64
    public function __toString(): string
45
    {
46 64
        return $this->getMessage();
47
    }
48
49 68
    private function format(string $message, array $params = []): string
50
    {
51 68
        $replacements = [];
52 68
        foreach ($params as $key => $value) {
53 37
            if (is_array($value)) {
54
                $value = 'array';
55 37
            } elseif (is_object($value)) {
56
                $value = 'object';
57 37
            } elseif (is_resource($value)) {
58
                $value = 'resource';
59
            }
60 37
            $replacements['{' . $key . '}'] = $value;
61
        }
62 68
        return strtr($message, $replacements);
63
    }
64
}
65