Completed
Push — 6.0 ( f7b87a...a83857 )
by liu
03:02
created

Lang::set()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 4
nop 3
dl 0
loc 13
ccs 0
cts 7
cp 0
crap 20
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
class Lang
1 ignored issue
show
Coding Style introduced by
Missing doc comment for class Lang
Loading history...
16
{
17
    /**
18
     * 配置参数
19
     * @var array
20
     */
21
    protected $config = [
22
        // 默认语言
23
        'default_lang'    => 'zh-cn',
24
        // 允许的语言列表
25
        'allow_lang_list' => [],
26
        // 自动侦测和切换
27
        'auto_detect'     => false,
28
        // 是否使用Cookie记录
29
        'use_cookie'      => true,
30
        // 扩展语言包
31
        'extend_list'     => [],
32
        // 多语言cookie变量
33
        'cookie_var'      => 'think_lang',
34
        // 多语言自动侦测变量名
35
        'detect_var'      => 'lang',
36
        // Accept-Language转义为对应语言包名称
37
        'accept_language' => [
38
            'zh-hans-cn' => 'zh-cn',
39
        ],
40
    ];
41
42
    /**
43
     * 多语言信息
44
     * @var array
45
     */
46
    private $lang = [];
0 ignored issues
show
Coding Style introduced by
Private member variable "lang" must be prefixed with an underscore
Loading history...
47
48
    /**
49
     * 当前语言
50
     * @var string
51
     */
52
    private $range = 'zh-cn';
0 ignored issues
show
Coding Style introduced by
Private member variable "range" must be prefixed with an underscore
Loading history...
53
54
    /**
55
     * Request对象
56
     * @var Request
57
     */
58
    protected $request;
59
60
    /**
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...
61
     * 构造方法
62
     * @access public
63
     */
64
    public function __construct(Request $request, array $config = [])
65
    {
66
        $this->request = $request;
67
        $this->config  = array_merge($this->config, array_change_key_case($config));
68
        $this->range   = $this->config['default_lang'];
69
70
        if ($this->config['auto_detect']) {
71
            $this->detect();
72
        }
73
    }
74
75
    public static function __make(Request $request, Config $config)
2 ignored issues
show
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...
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
76
    {
77
        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

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