1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Translator\Message\Gettext; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Translator\MessageReaderInterface; |
8
|
|
|
|
9
|
|
|
final class MessageSource implements MessageReaderInterface |
10
|
|
|
{ |
11
|
|
|
private string $path; |
12
|
|
|
private array $boundDomains = []; |
13
|
|
|
|
14
|
31 |
|
public function __construct(string $path) |
15
|
|
|
{ |
16
|
31 |
|
if (!is_dir($path)) { |
17
|
1 |
|
throw new \RuntimeException(sprintf('Directory "%s" does not exist.', $path)); |
18
|
|
|
} |
19
|
30 |
|
$this->path = $path; |
20
|
30 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* {@inheritdoc} |
24
|
|
|
* |
25
|
|
|
* We use first parameter as `$n` for plurals if its value type is int. |
26
|
|
|
*/ |
27
|
29 |
|
public function getMessage(string $id, string $category, string $locale, array $parameters = []): ?string |
28
|
|
|
{ |
29
|
29 |
|
$this->bindDomain($category); |
30
|
29 |
|
$this->setLocale($locale); |
31
|
28 |
|
$n = current($parameters); |
32
|
28 |
|
if (is_int($n) === false) { |
33
|
8 |
|
return dgettext($category, $id); |
34
|
|
|
} |
35
|
20 |
|
return dngettext($category, $id, $id, $n); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
public function getMessages(string $category, string $locale): array |
39
|
|
|
{ |
40
|
1 |
|
throw new \RuntimeException('Function not allowed for this package.'); |
41
|
|
|
} |
42
|
|
|
|
43
|
29 |
|
private function bindDomain(string $category): void |
44
|
|
|
{ |
45
|
29 |
|
if (!isset($this->boundDomains[$category])) { |
46
|
29 |
|
bindtextdomain($category, $this->path); |
47
|
|
|
} |
48
|
29 |
|
} |
49
|
|
|
|
50
|
29 |
|
private function setLocale(string $locale): void |
51
|
|
|
{ |
52
|
29 |
|
if (!setlocale(LC_ALL, $locale)) { |
53
|
1 |
|
throw new \RuntimeException(sprintf('Locale "%s" cannot be set.', $locale)); |
54
|
|
|
} |
55
|
28 |
|
} |
56
|
|
|
} |
57
|
|
|
|