1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Koded\I18n; |
4
|
|
|
|
5
|
|
|
use function bind_textdomain_codeset; |
6
|
|
|
use function bindtextdomain; |
7
|
|
|
use function dgettext; |
8
|
|
|
use function dngettext; |
9
|
|
|
use function extension_loaded; |
10
|
|
|
use function setlocale; |
11
|
|
|
use function textdomain; |
12
|
|
|
|
13
|
|
|
final class GettextCatalog extends I18nCatalog |
14
|
|
|
{ |
15
|
|
|
private array $domains = []; |
16
|
|
|
|
17
|
3 |
|
protected function message(string $domain, string $string, int $n): string |
18
|
|
|
{ |
19
|
3 |
|
$domain = $this->bindDomain($domain); |
20
|
3 |
|
return $n > 0 |
21
|
|
|
? dngettext($domain, $string, $string, $n) // TODO plural string |
22
|
3 |
|
: dgettext($domain, $string); |
23
|
|
|
} |
24
|
|
|
|
25
|
6 |
|
protected function supports(string $locale): bool |
26
|
|
|
{ |
27
|
6 |
|
return $locale === $this->locale; |
28
|
|
|
} |
29
|
|
|
|
30
|
6 |
|
protected function initialize(string $locale): string|false |
31
|
|
|
{ |
32
|
|
|
// @codeCoverageIgnoreStart |
33
|
|
|
if (false === extension_loaded('gettext')) { |
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
if (false === extension_loaded('intl')) { |
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
// @codeCoverageIgnoreEnd |
40
|
6 |
|
$this->bindDomain('messages'); |
41
|
6 |
|
return setlocale(LC_MESSAGES, [$locale, "$locale.UTF-8", "$locale.UTF8"]) |
42
|
6 |
|
? $locale |
43
|
6 |
|
: false; |
44
|
|
|
} |
45
|
|
|
|
46
|
6 |
|
private function bindDomain(string $domain): string |
47
|
|
|
{ |
48
|
6 |
|
if (false === isset($this->domains[$domain])) { |
49
|
6 |
|
$this->directory = bindtextdomain($domain, $this->directory); |
50
|
6 |
|
$this->domains[$domain = textdomain($domain)] = true; |
51
|
6 |
|
bind_textdomain_codeset($domain, 'UTF-8'); |
52
|
|
|
} |
53
|
6 |
|
return $domain; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|