Code

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