Completed
Push — master ( c4aca4...e136a2 )
by Andrii
02:00
created

Module::getInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

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 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Yii2 module for language switching.
4
 *
5
 * @link      https://github.com/hiqdev/yii2-language
6
 * @package   yii2-language
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\yii2\language;
12
13
use Yii;
14
use yii\base\BootstrapInterface;
15
use yii\web\Cookie;
16
17
/**
18
 * Language Module.
19
 *
20
 * Example application configuration:
21
 *
22
 * ```php
23
 * 'modules' => [
24
 *     'language' => [
25
 *         'class' => \hiqdev\yii2\language\Module::class,
26
 *         'languages' => [
27
 *             'en' => 'English',
28
 *             'ru' => 'Русский',
29
 *         ],
30
 *     ],
31
 * ],
32
 * ```
33
 */
34
class Module extends \yii\base\Module implements BootstrapInterface
35
{
36
    /**
37
     * @var array list of available language codes. More specific patterns should come first, e.g. 'en_us' before 'en'.
38
     * Key is a language code, value is a name of language. For example:
39
     *
40
     * ```php
41
     * [
42
     *     'ru' => 'Русский',
43
     *     'en' => 'English',
44
     * ]
45
     * ```
46
     */
47
    protected $_languages = [];
48
49
    public function setLanguages(array $list)
50
    {
51
        $this->_languages = array_filter($list);
52
    }
53
54
    public function getLanguages()
55
    {
56
        if (!$this->_languages) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->_languages of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
57
            $this->_languages = [
58
                Yii::$app->language => Yii::$app->language,
59
            ];
60
        }
61
62
        return $this->_languages;
63
    }
64
65
    /**
66
     * @var string name of the cookie
67
     */
68
    public $cookieName = 'language';
69
70
    /**
71
     * @var integer expiration date of the cookie storing the language of the site
72
     */
73
    public $expireDays = 30;
74
75
    public function bootstrap($app)
76
    {
77
        $this->initLanguage();
78
    }
79
80
    /**
81
     * Saving language into cookie and database.
82
     * @param string $language - The language to save
83
     * @return static
84
     */
85
    public function saveLanguage($language)
86
    {
87
        $this->applyLanguage($language);
88
        $this->saveLanguageIntoCookie($language);
89
    }
90
91
    private function initLanguage()
92
    {
93
        if ($this->isValidLanguage(Yii::$app->request->cookies->getValue($this->cookieName))) {
94
            $this->applyLanguage(Yii::$app->request->cookies->getValue($this->cookieName));
95
        } else {
96
            Yii::$app->response->cookies->remove($this->cookieName);
97
98
            if (($language = $this->detectLanguage()) !== false) {
99
                $this->saveLanguage($language);
100
            }
101
        }
102
    }
103
104
    /**
105
     * Determine language based on UserAgent.
106
     */
107
    public function detectLanguage()
108
    {
109
        $acceptableLanguages = Yii::$app->getRequest()->getAcceptableLanguages();
110
        foreach ($acceptableLanguages as $language) {
111
            if ($this->isValidLanguage($language)) {
112
                return $language;
113
            }
114
        }
115
        foreach ($acceptableLanguages as $language) {
116
            $pattern = preg_quote(substr($language, 0, 2), '/');
117
            foreach ($this->languages as $key => $value) {
0 ignored issues
show
Bug introduced by
The property languages does not seem to exist. Did you mean _languages?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
118
                if (preg_match('/^' . $pattern . '/', $value) || preg_match('/^' . $pattern . '/', $key)) {
119
                    return $this->isValidLanguage($key) ? $key : $value;
120
                }
121
            }
122
        }
123
124
        return false;
125
    }
126
127
    /**
128
     * Save language into cookie.
129
     * @param string $language
130
     */
131
    private function saveLanguageIntoCookie($language)
132
    {
133
        $cookie = new Cookie([
134
            'name' => $this->cookieName,
135
            'value' => $language,
136
            'expire' => time() + 86400 * $this->expireDays,
137
        ]);
138
        Yii::$app->response->cookies->add($cookie);
139
    }
140
141
    /**
142
     * Determines whether the language received as a parameter can be processed.
143
     * @param string $language
144
     * @return boolean
145
     */
146
    public function isValidLanguage($language)
147
    {
148
        return is_string($language) && isset($this->languages[$language]);
0 ignored issues
show
Bug introduced by
The property languages does not seem to exist. Did you mean _languages?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
149
    }
150
151
    /**
152
     * @param $language
153
     * @return bool whether the language is correct and saved
154
     */
155
    public function setLanguage($language)
156
    {
157
        if ($this->isValidLanguage($language)) {
158
            $this->saveLanguage($language);
159
160
            return true;
161
        }
162
163
        return false;
164
    }
165
166
    /**
167
     * @param string $language
168
     */
169
    private function applyLanguage($language)
170
    {
171
        Yii::$app->language = $language;
172
        Yii::$app->getFormatter()->locale = $language;
173
    }
174
175
    public static $MODULE_ID = 'language';
176
177 1
    public static function getInstance()
178
    {
179 1
        return Yii::$app->getModule(static::$MODULE_ID);
180
    }
181
}
182