Passed
Push — master ( ca838e...76d3e9 )
by Radu
01:16
created

I18n::getLanguages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
namespace WebServCo\Framework\Libraries;
3
4
final class I18n extends \WebServCo\Framework\AbstractLibrary
5
{
6
    protected $langs;
7
    protected $domain;
8
    
9
    protected $lang;
10
    
11
    protected $locale;
12
    
13
    protected $translationsPath;
14
    
15
    public function __construct($config)
16
    {
17
        parent::__construct($config);
18
        
19
        $this->langs = $this->setting('langs', []);
20
        $this->domain = $this->setting('domain', 'messages');
21
    }
22
    
23
    public function init($projectPath)
24
    {
25
        $this->translationsPath = $projectPath . 'resources/translations';
26
        
27
        $defaultLang = $this->setting('lang', 'en');
28
        $this->setLanguage($defaultLang);
29
        
30
        return true;
31
    }
32
    
33
    public function setLanguage($lang)
34
    {
35
        if (!array_key_exists($lang, $this->langs)) {
36
            throw new \ErrorException('Language not available');
37
        }
38
        
39
        $this->lang = $lang;
40
        $this->locale = $this->langs[$this->lang]['locale'];
41
42
        $this->setLocale($this->locale);
43
        $this->setDomain($this->domain, $this->translationsPath);
44
        
45
        return true;
46
    }
47
    
48
    public function getLanguage()
49
    {
50
        return $this->lang;
51
    }
52
    
53
    public function getLanguages()
54
    {
55
        return $this->langs;
56
    }
57
    
58
    protected function setLocale($locale)
59
    {
60
        /**
61
         * Rumored to allow using a locale regardless of server locale setup.
62
         * putenv("LANGUAGE=" . $locale);
63
         */
64
65
        /**
66
         * Rumored to be needed on Win.
67
         * putenv("LANG=" . $locale);
68
         */
69
70
        /**
71
         * Do not use LC_ALL, in order to skip LC_NUMERIC.
72
         */
73
        setlocale(LC_COLLATE, $locale);
74
        setlocale(LC_CTYPE, $locale);
75
        setlocale(LC_MONETARY, $locale);
76
        setlocale(LC_TIME, $locale);
77
        setlocale(LC_MESSAGES, $locale);
78
        
79
        return true;
80
    }
81
    
82
    protected function setDomain($domain, $directory)
83
    {
84
        bindtextdomain($domain, $directory);
85
        textdomain($domain);
86
        bind_textdomain_codeset($domain, 'UTF8');
87
        
88
        return true;
89
    }
90
}
91