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

Locale::getTokens()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 2
cts 2
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 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