Completed
Pull Request — master (#2)
by Klochok
03:31
created

Module   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 3

Test Coverage

Coverage 3.64%

Importance

Changes 0
Metric Value
wmc 25
lcom 3
cbo 3
dl 0
loc 150
ccs 2
cts 55
cp 0.0364
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A setLanguages() 0 4 1
A getLanguages() 0 10 2
A bootstrap() 0 4 1
A saveLanguage() 0 5 1
A initLanguage() 0 14 5
B detectLanguage() 0 19 8
A saveLanguageIntoCookie() 0 9 1
A isValidLanguage() 0 4 2
A setLanguage() 0 10 2
A applyLanguage() 0 5 1
A getInstance() 0 4 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 (($language = Yii::$app->request->get('language')) && $this->isValidLanguage($language)) {
94
            $this->saveLanguage($language);
95
        } else if ($this->isValidLanguage(Yii::$app->request->cookies->getValue($this->cookieName))) {
96
            $this->applyLanguage(Yii::$app->request->cookies->getValue($this->cookieName));
97
        } else {
98
            Yii::$app->response->cookies->remove($this->cookieName);
99
100
            if (($language = $this->detectLanguage()) !== false) {
101
                $this->saveLanguage($language);
102
            }
103
        }
104
    }
105
106
    /**
107
     * Determine language based on UserAgent.
108
     */
109
    public function detectLanguage()
110
    {
111
        $acceptableLanguages = Yii::$app->getRequest()->getAcceptableLanguages();
112
        foreach ($acceptableLanguages as $language) {
113
            if ($this->isValidLanguage($language)) {
114
                return $language;
115
            }
116
        }
117
        foreach ($acceptableLanguages as $language) {
118
            $pattern = preg_quote(substr($language, 0, 2), '/');
119
            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...
120
                if (preg_match('/^' . $pattern . '/', $value) || preg_match('/^' . $pattern . '/', $key)) {
121
                    return $this->isValidLanguage($key) ? $key : $value;
122
                }
123
            }
124
        }
125
126
        return false;
127
    }
128
129
    /**
130
     * Save language into cookie.
131
     * @param string $language
132
     */
133
    private function saveLanguageIntoCookie($language)
134
    {
135
        $cookie = new Cookie([
136
            'name' => $this->cookieName,
137
            'value' => $language,
138
            'expire' => time() + 86400 * $this->expireDays,
139
        ]);
140
        Yii::$app->response->cookies->add($cookie);
141
    }
142
143
    /**
144
     * Determines whether the language received as a parameter can be processed.
145
     * @param string $language
146
     * @return boolean
147
     */
148
    public function isValidLanguage($language)
149
    {
150
        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...
151
    }
152
153
    /**
154
     * @param $language
155
     * @return bool whether the language is correct and saved
156
     */
157
    public function setLanguage($language)
158
    {
159
        if ($this->isValidLanguage($language)) {
160
            $this->saveLanguage($language);
161
162
            return true;
163
        }
164
165
        return false;
166
    }
167
168
    /**
169
     * @param string $language
170
     */
171
    private function applyLanguage($language)
172
    {
173
        Yii::$app->language = $language;
174
        Yii::$app->getFormatter()->locale = $language;
175
    }
176
177
    public static $MODULE_ID = 'language';
178
179 1
    public static function getInstance()
180
    {
181 1
        return Yii::$app->getModule(static::$MODULE_ID);
182
    }
183
}
184