Passed
Push — master ( 97cf13...6b5bbb )
by Mihail
12:34
created

GettextCatalog   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 95%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 20
c 4
b 0
f 1
dl 0
loc 46
ccs 19
cts 20
cp 0.95
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 3 1
A message() 0 6 2
A bindDomain() 0 8 2
A language() 0 3 1
A initialize() 0 14 4
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