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
|
|
|
|