Passed
Push — master ( 2b1ac9...97cf13 )
by Mihail
02:13
created

GettextCatalog   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 19
c 3
b 0
f 0
dl 0
loc 41
ccs 17
cts 18
cp 0.9444
rs 10
wmc 9

4 Methods

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