Completed
Push — master ( fd6c7c...1f9fde )
by Matze
09:32
created

Locale   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 88.89%

Importance

Changes 5
Bugs 0 Features 3
Metric Value
wmc 5
c 5
b 0
f 3
lcom 1
cbo 0
dl 0
loc 57
ccs 8
cts 9
cp 0.8889
rs 10

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\Annotations\Annotations\Inject;
6
use BrainExe\Annotations\Annotations\Service;
7
use BrainExe\Core\Translation\ServiceTranslationProvider;
8
9
/**
10
 * @Service("Core.Locale", public=true)
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({"%locales%", "%application.defaultLocale%"});
25
     * @param string[] $locales
26
     * @param string $defaultLocale
27
     */
28 3
    public function __construct(array $locales, string $defaultLocale = '')
29
    {
30 3
        $this->locales = $locales;
31
32 3
        if ($defaultLocale) {
33
            $this->setLocale($defaultLocale);
34
        }
35 3
    }
36
37
    /**
38
     * @return string[]
39
     */
40 1
    public function getLocales() : array
41
    {
42 1
        return $this->locales;
43
    }
44
45
    /**
46
     * @param string $locale
47
     * @codeCoverageIgnore
48
     */
49
    public function setLocale(string $locale)
50
    {
51
        putenv(sprintf('LANG=%s.UTF-8', $locale));
52
        setlocale(LC_MESSAGES, sprintf('%s.UTF-8', $locale));
53
54
        bindtextdomain(self::DOMAIN, self::LANG_DIR);
55
        bind_textdomain_codeset(self::DOMAIN, 'UTF-8');
56
        textdomain(self::DOMAIN);
57
    }
58
59
    /**
60
     * @return string[]
61
     */
62
    public function getTokens()
63
    {
64 2
        return array_map(function (string $locale) {
65
            return 'locale.' . $locale;
66 2
        }, $this->locales);
67
    }
68
}
69