Completed
Push — master ( 97f6b5...9ef69c )
by Matze
08:25
created

Locale   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 90%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 60
ccs 9
cts 10
cp 0.9
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A getLocales() 0 4 1
A setLocale() 0 9 1
A getTokens() 0 6 1
1
<?php
2
3
namespace BrainExe\Core\Application;
4
5
use BrainExe\Core\Annotations\Inject;
6
use BrainExe\Core\Annotations\Service;
7
use BrainExe\Core\Translation\ServiceTranslationProvider;
8
9
/**
10
 * @Service
11
 */
12
class Locale implements ServiceTranslationProvider
13
{
14
15
    const DOMAIN   = 'messages';
16
    const LANG_DIR = ROOT . '/cache/lang/';
17
18
    /**
19
     * @var string[]
20
     */
21
    private $locales;
22
23
    /**
24
     * @Inject({
25
     *     "%locales%",
26
     *     "%application.defaultLocale%"
27
     * });
28
     * @param string[] $locales
29
     * @param string $defaultLocale
30
     */
31 2
    public function __construct(array $locales, string $defaultLocale = '')
32
    {
33 2
        $this->locales = $locales;
34
35 2
        if ($defaultLocale) {
36 1
            $this->setLocale($defaultLocale);
37
        }
38 2
    }
39
40
    /**
41
     * @return string[]
42
     */
43 1
    public function getLocales() : array
44
    {
45 1
        return $this->locales;
46
    }
47
48
    /**
49
     * @param string $locale
50
     * @codeCoverageIgnore
51
     */
52
    public function setLocale(string $locale) : void
53
    {
54
        putenv(sprintf('LANG=%s.UTF-8', $locale));
55
        setlocale(LC_MESSAGES, sprintf('%s.UTF-8', $locale));
56
57
        bindtextdomain(self::DOMAIN, self::LANG_DIR);
58
        bind_textdomain_codeset(self::DOMAIN, 'UTF-8');
59
        textdomain(self::DOMAIN);
60
    }
61
62
    /**
63
     * @return string[]
64
     */
65
    public function getTokens()
66
    {
67 1
        return array_map(function (string $locale) {
68
            return 'locale.' . $locale;
69 1
        }, $this->locales);
70
    }
71
}
72