Passed
Push — 6.0 ( 0273cf...b92eee )
by liu
02:41
created

Lang::setLangSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
/**
16
 * 多语言管理类
17
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
18
class Lang
19
{
20
    /**
21
     * 配置参数
22
     * @var array
23
     */
24
    protected $config = [
25
        // 默认语言
26
        'default_lang'    => 'zh-cn',
27
        // 允许的语言列表
28
        'allow_lang_list' => [],
29
        // 自动侦测和切换
30
        'auto_detect'     => false,
31
        // 是否使用Cookie记录
32
        'use_cookie'      => true,
33
        // 扩展语言包
34
        'extend_list'     => [],
35
        // 多语言cookie变量
36
        'cookie_var'      => 'think_lang',
37
        // 多语言自动侦测变量名
38
        'detect_var'      => 'lang',
39
        // Accept-Language转义为对应语言包名称
40
        'accept_language' => [
41
            'zh-hans-cn' => 'zh-cn',
42
        ],
43
        // 是否支持语言分组
44
        'allow_group'     => false,
45
    ];
46
47
    /**
48
     * 多语言信息
49
     * @var array
50
     */
51
    private $lang = [];
0 ignored issues
show
Coding Style introduced by
Private member variable "lang" must be prefixed with an underscore
Loading history...
52
53
    /**
54
     * 当前语言
55
     * @var string
56
     */
57
    private $range = 'zh-cn';
0 ignored issues
show
Coding Style introduced by
Private member variable "range" must be prefixed with an underscore
Loading history...
58
59
    /**
60
     * Request对象
61
     * @var Request
62
     */
63
    protected $request;
64
65
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $request should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $config should have a doc-comment as per coding-style.
Loading history...
66
     * 构造方法
67
     * @access public
68
     */
69 6
    public function __construct(Request $request, array $config = [])
70
    {
71 6
        $this->request = $request;
72 6
        $this->config  = array_merge($this->config, array_change_key_case($config));
73 6
        $this->range   = $this->config['default_lang'];
74 6
    }
75
76 6
    public static function __make(Request $request, Config $config)
2 ignored issues
show
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
Coding Style introduced by
Method name "Lang::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Public method name "Lang::__make" must not be prefixed with an underscore
Loading history...
77
    {
78 6
        return new static($request, $config->get('lang'));
0 ignored issues
show
Bug introduced by
It seems like $config->get('lang') can also be of type null; however, parameter $config of think\Lang::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
        return new static($request, /** @scrutinizer ignore-type */ $config->get('lang'));
Loading history...
79
    }
80
81
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $lang should have a doc-comment as per coding-style.
Loading history...
82
     * 设置当前语言
83
     * @access public
84
     * @param  string $name 语言
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $name does not match actual variable name $lang
Loading history...
85
     * @return void
86
     */
87
    public function setLangSet(string $lang): void
88
    {
89
        $this->range = $lang;
90
    }
91
92
    /**
93
     * 获取当前语言
94
     * @access public
95
     * @return string
96
     */
97
    public function getLangSet(): string
98
    {
99
        return $this->range;
100
    }
101
102
    /**
103
     * 获取默认语言
104
     * @access public
105
     * @return string
106
     */
107 6
    public function defaultLangSet()
108
    {
109 6
        return $this->config['default_lang'];
110
    }
111
112
    /**
113
     * 加载语言定义(不区分大小写)
114
     * @access public
115
     * @param  string|array $file   语言文件
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 3 found
Loading history...
116
     * @param  string       $range  语言作用域
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
117
     * @return array
118
     */
119 6
    public function load($file, $range = ''): array
120
    {
121 6
        $range = $range ?: $this->range;
122 6
        if (!isset($this->lang[$range])) {
123 6
            $this->lang[$range] = [];
124
        }
125
126 6
        $lang = [];
127
128 6
        foreach ((array) $file as $_file) {
129 6
            if (is_file($_file)) {
130
                // 记录加载信息
131 1
                $_lang = include $_file;
132 1
                if (is_array($_lang)) {
133 1
                    $lang = array_change_key_case($_lang) + $lang;
134
                }
135
            }
136
        }
137
138 6
        if (!empty($lang)) {
139 1
            $this->lang[$range] = $lang + $this->lang[$range];
140
        }
141
142 6
        return $this->lang[$range];
143
    }
144
145
    /**
146
     * 判断是否存在语言定义(不区分大小写)
147
     * @access public
148
     * @param  string|null $name 语言变量
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
149
     * @param  string      $range 语言作用域
150
     * @return bool
151
     */
152
    public function has(string $name, string $range = ''): bool
153
    {
154
        $range = $range ?: $this->range;
155
156
        if ($this->config['allow_group'] && strpos($name, '.')) {
157
            list($name1, $name2) = explode('.', $name, 2);
158
            return isset($this->lang[$range][strtolower($name1)][$name2]);
159
        }
160
161
        return isset($this->lang[$range][strtolower($name)]);
162
    }
163
164
    /**
165
     * 获取语言定义(不区分大小写)
166
     * @access public
167
     * @param  string|null $name 语言变量
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
168
     * @param  array       $vars 变量替换
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
169
     * @param  string      $range 语言作用域
170
     * @return mixed
171
     */
172
    public function get(string $name = null, array $vars = [], string $range = '')
173
    {
174
        $range = $range ?: $this->range;
175
176
        // 空参数返回所有定义
177
        if (is_null($name)) {
178
            return $this->lang[$range] ?? [];
179
        }
180
181
        if ($this->config['allow_group'] && strpos($name, '.')) {
182
            list($name1, $name2) = explode('.', $name, 2);
183
184
            $value = $this->lang[$range][strtolower($name1)][$name2] ?? $name;
185
        } else {
186
            $value = $this->lang[$range][strtolower($name)] ?? $name;
187
        }
188
189
        // 变量解析
190
        if (!empty($vars) && is_array($vars)) {
191
            /**
192
             * Notes:
193
             * 为了检测的方便,数字索引的判断仅仅是参数数组的第一个元素的key为数字0
194
             * 数字索引采用的是系统的 sprintf 函数替换,用法请参考 sprintf 函数
195
             */
196
            if (key($vars) === 0) {
197
                // 数字索引解析
198
                array_unshift($vars, $value);
199
                $value = call_user_func_array('sprintf', $vars);
200
            } else {
201
                // 关联索引解析
202
                $replace = array_keys($vars);
203
                foreach ($replace as &$v) {
204
                    $v = "{:{$v}}";
205
                }
206
                $value = str_replace($replace, $vars, $value);
207
            }
208
        }
209
210
        return $value;
211
    }
212
213
    /**
214
     * 自动侦测设置获取语言选择
215
     * @access public
216
     * @return string
217
     */
218
    public function detect(): string
219
    {
220
        // 自动侦测设置获取语言选择
221
        $langSet = '';
222
223
        if ($this->request->get($this->config['detect_var'])) {
224
            // url中设置了语言变量
225
            $langSet = strtolower($this->request->get($this->config['detect_var']));
226
        } elseif ($this->request->cookie($this->config['cookie_var'])) {
227
            // Cookie中设置了语言变量
228
            $langSet = strtolower($this->request->cookie($this->config['cookie_var']));
229
        } elseif ($this->request->server('HTTP_ACCEPT_LANGUAGE')) {
230
            // 自动侦测浏览器语言
231
            preg_match('/^([a-z\d\-]+)/i', $this->request->server('HTTP_ACCEPT_LANGUAGE'), $matches);
232
            $langSet = strtolower($matches[1]);
233
234
            if (isset($this->config['accept_language'][$langSet])) {
235
                $langSet = $this->config['accept_language'][$langSet];
236
            }
237
        }
238
239
        if (empty($this->config['allow_lang_list']) || in_array($langSet, $this->config['allow_lang_list'])) {
240
            // 合法的语言
241
            $this->range = $langSet;
242
        }
243
244
        return $this->range;
245
    }
246
247
    /**
248
     * 保存当前语言到Cookie
249
     * @access public
250
     * @param  Cookie $cookie Cookie对象
251
     * @return void
252
     */
253
    public function saveToCookie(Cookie $cookie)
254
    {
255
        if ($this->config['use_cookie']) {
256
            $cookie->set($this->config['cookie_var'], $this->range);
257
        }
258
    }
259
260
}
261