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
|
176 |
|
public function __construct(string $message, array $params = [], ?TranslatorInterface $translator = null) |
17
|
|
|
{ |
18
|
176 |
|
$this->message = $message; |
19
|
176 |
|
$this->params = $params; |
20
|
176 |
|
$this->translator = $translator; |
21
|
176 |
|
} |
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
|
41 |
|
return $this; |
31
|
|
|
} |
32
|
|
|
|
33
|
77 |
|
public function getMessage(?TranslatorInterface $translator = null): string |
34
|
|
|
{ |
35
|
77 |
|
if ($translator === null) { |
36
|
70 |
|
$translator = $this->translator; |
37
|
|
|
} |
38
|
77 |
|
if ($translator !== null) { |
39
|
9 |
|
foreach ($this->params as &$value) { |
40
|
5 |
|
if ($value instanceof self) { |
41
|
2 |
|
$value = $value->getMessage($translator); |
42
|
|
|
} |
43
|
|
|
} |
44
|
9 |
|
return $translator->translate($this->message, $this->params); |
45
|
|
|
} |
46
|
69 |
|
return $this->format($this->message, $this->params); |
47
|
|
|
} |
48
|
|
|
|
49
|
65 |
|
public function __toString(): string |
50
|
|
|
{ |
51
|
65 |
|
return $this->getMessage(); |
52
|
|
|
} |
53
|
|
|
|
54
|
69 |
|
private function format(string $message, array $params = []): string |
55
|
|
|
{ |
56
|
69 |
|
$replacements = []; |
57
|
69 |
|
foreach ($params as $key => $value) { |
58
|
38 |
|
if (is_array($value)) { |
59
|
|
|
$value = 'array'; |
60
|
38 |
|
} elseif (is_object($value)) { |
61
|
|
|
$value = 'object'; |
62
|
38 |
|
} elseif (is_resource($value)) { |
63
|
|
|
$value = 'resource'; |
64
|
|
|
} |
65
|
38 |
|
$replacements['{' . $key . '}'] = $value; |
66
|
|
|
} |
67
|
69 |
|
return strtr($message, $replacements); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|