|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Translator; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Represents message category. |
|
9
|
|
|
*/ |
|
10
|
|
|
final class CategorySource |
|
11
|
|
|
{ |
|
12
|
|
|
private string $name; |
|
13
|
|
|
private MessageReaderInterface $reader; |
|
14
|
|
|
private MessageFormatterInterface $formatter; |
|
15
|
|
|
|
|
16
|
41 |
|
public function __construct(string $name, MessageReaderInterface $reader, MessageFormatterInterface $formatter) |
|
17
|
|
|
{ |
|
18
|
41 |
|
if (!preg_match('/^[a-z0-9_-]+$/i', $name)) { |
|
19
|
1 |
|
throw new \RuntimeException('Category name is invalid. Only letters and numbers are allowed.'); |
|
20
|
|
|
} |
|
21
|
40 |
|
$this->name = $name; |
|
22
|
40 |
|
$this->reader = $reader; |
|
23
|
40 |
|
$this->formatter = $formatter; |
|
24
|
40 |
|
} |
|
25
|
|
|
|
|
26
|
39 |
|
public function getName(): string |
|
27
|
|
|
{ |
|
28
|
39 |
|
return $this->name; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Get a message with ID, locale and parameters specified. |
|
33
|
|
|
* |
|
34
|
|
|
* @param string $id Message ID. |
|
35
|
|
|
* @param string $locale Locale to get message for. |
|
36
|
|
|
* @param array $parameters Message parameters. |
|
37
|
|
|
* |
|
38
|
|
|
* @return string|null Message string or null if message was not found. |
|
39
|
|
|
*/ |
|
40
|
35 |
|
public function getMessage(string $id, string $locale, array $parameters = []): ?string |
|
41
|
|
|
{ |
|
42
|
35 |
|
return $this->reader->getMessage($id, $this->name, $locale, $parameters); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Format the message given parameters and locale. |
|
47
|
|
|
* |
|
48
|
|
|
* @param string $message Message to be formatted. |
|
49
|
|
|
* @param array $parameters Parameters to use. |
|
50
|
|
|
* @param string $locale Locale to use. Usually affects formatting numbers, dates etc. |
|
51
|
|
|
* |
|
52
|
|
|
* @return string Formatted message. |
|
53
|
|
|
*/ |
|
54
|
35 |
|
public function format(string $message, array $parameters, string $locale): string |
|
55
|
|
|
{ |
|
56
|
35 |
|
return $this->formatter->format($message, $parameters, $locale); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|