Passed
Pull Request — 8.0 (#3055)
by wj
02:23
created

Lang::switchLangSet()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 36
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 14.8028

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 17
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 36
ccs 10
cts 19
cp 0.5263
crap 14.8028
rs 8.4444
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 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
 * @package think
18
 */
19
class Lang
20
{
21
    protected $app;
22
23
    /**
24
     * 配置参数
25
     * @var array
26
     */
27
    protected $config = [
28
        // 默认语言
29
        'default_lang'    => 'zh-cn',
30
        // 允许的语言列表
31
        'allow_lang_list' => [],
32
        // 是否使用Cookie记录
33
        'use_cookie'      => true,
34
        // 扩展语言包
35
        'extend_list'     => [],
36
        // 多语言cookie变量
37
        'cookie_var'      => 'think_lang',
38
        // 多语言header变量
39
        'header_var'      => 'think-lang',
40
        // 多语言自动侦测变量名
41
        'detect_var'      => 'lang',
42
        // Accept-Language转义为对应语言包名称
43
        'accept_language' => [
44
            'zh-hans-cn' => 'zh-cn',
45
        ],
46
        // 是否支持语言分组
47
        'allow_group'     => false,
48
    ];
49
50
    /**
51
     * 多语言信息
52
     * @var array
53
     */
54
    private $lang = [];
55
56
    /**
57
     * 当前语言
58
     * @var string
59
     */
60
    private $range = 'zh-cn';
61
62
    /**
63
     * 构造方法
64
     * @access public
65
     * @param array $config
66
     */
67 18
    public function __construct(App $app, array $config = [])
68
    {
69 18
        $this->config = array_merge($this->config, array_change_key_case($config));
70 18
        $this->range  = $this->config['default_lang'];
71 18
        $this->app    = $app;
72
    }
73
74 3
    public static function __make(App $app, Config $config)
75
    {
76 3
        return new static($app, $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

76
        return new static($app, /** @scrutinizer ignore-type */ $config->get('lang'));
Loading history...
77
    }
78
79
    /**
80
     * 获取当前语言配置
81
     * @access public
82
     * @return array
83
     */
84
    public function getConfig(): array
85
    {
86
        return $this->config;
87
    }
88
89
    /**
90
     * 设置当前语言
91
     * @access public
92
     * @param string $lang 语言
93
     * @return void
94
     */
95 3
    public function setLangSet(string $lang): void
96
    {
97 3
        $this->range = $lang;
98
    }
99
100
    /**
101
     * 获取当前语言
102
     * @access public
103
     * @return string
104
     */
105
    public function getLangSet(): string
106
    {
107
        return $this->range;
108
    }
109
110
    /**
111
     * 获取默认语言
112
     * @access public
113
     * @return string
114
     */
115 3
    public function defaultLangSet()
116
    {
117 3
        return $this->config['default_lang'];
118
    }
119
120
    /**
121
     * 切换语言
122
     * @access public
123
     * @param string $langset 语言
124
     * @return void
125
     */
126 3
    public function switchLangSet(string $langset)
127
    {
128 3
        if (empty($langset)) {
129
            return;
130
        }
131
132 3
        $this->setLangSet($langset);
133
134
        // 加载系统语言包
135 3
        $this->load([
136 3
            $this->app->getThinkPath() . 'lang' . DIRECTORY_SEPARATOR . $langset . '.php',
137 3
        ]);
138
139
        // 加载系统语言包
140 3
        $appLangDir = $this->app->getAppPath() . 'lang' . DIRECTORY_SEPARATOR;
141 3
        if (is_dir($appLangDir)) {
142
            $files = [];
143
144
            foreach (scandir($appLangDir) as $name) {
145
                $path = $appLangDir . $name;
146
147
                if (!str_starts_with($name, $langset) || !is_file($path) || !in_array(pathinfo($name, PATHINFO_EXTENSION), ['php', 'yaml', 'json'])) {
148
                    continue;
149
                }
150
151
                $files[] = $path;
152
            }
153
154
            $this->load($files);
155
        }
156
157
        // 加载扩展(自定义)语言包
158 3
        $list = $this->app->config->get('lang.extend_list', []);
159
160 3
        if (isset($list[$langset])) {
161
            $this->load($list[$langset]);
162
        }
163
    }
164
165
    /**
166
     * 加载语言定义(不区分大小写)
167
     * @access public
168
     * @param string|array $file  语言文件
169
     * @param string       $range 语言作用域
170
     * @return array
171
     */
172 3
    public function load($file, $range = ''): array
173
    {
174 3
        $range = $range ?: $this->range;
175 3
        if (!isset($this->lang[$range])) {
176 3
            $this->lang[$range] = [];
177
        }
178
179 3
        $lang = [];
180
181 3
        foreach ((array) $file as $name) {
182 3
            if (is_file($name)) {
183 3
                $result = $this->parse($name);
184 3
                $lang   = array_change_key_case($result) + $lang;
185
            }
186
        }
187
188 3
        if (!empty($lang)) {
189 3
            $this->lang[$range] = $lang + $this->lang[$range];
190
        }
191
192 3
        return $this->lang[$range];
193
    }
194
195
    /**
196
     * 解析语言文件
197
     * @access protected
198
     * @param string $file 语言文件名
199
     * @return array
200
     */
201 3
    protected function parse(string $file): array
202
    {
203 3
        $type   = pathinfo($file, PATHINFO_EXTENSION);
204 3
        $result = match ($type) {
205 3
            'php'       =>  include $file,
206 3
            'yml','yaml'=>  function_exists('yaml_parse_file') ? yaml_parse_file($file) : [],
207 3
            'json'      =>  json_decode(file_get_contents($file), true),
208 3
            default     =>  [],
209 3
        };
210
211 3
        return is_array($result) ? $result : [];
212
    }
213
214
    /**
215
     * 判断是否存在语言定义(不区分大小写)
216
     * @access public
217
     * @param string|null $name  语言变量
218
     * @param string      $range 语言作用域
219
     * @return bool
220
     */
221 6
    public function has(string $name, string $range = ''): bool
222
    {
223 6
        $range = $range ?: $this->range;
224
225 6
        if ($this->config['allow_group'] && str_contains($name, '.')) {
226
            [$name1, $name2] = explode('.', $name, 2);
227
            return isset($this->lang[$range][strtolower($name1)][$name2]);
228
        }
229
230 6
        return isset($this->lang[$range][strtolower($name)]);
231
    }
232
233
    /**
234
     * 获取语言定义(不区分大小写)
235
     * @access public
236
     * @param string|null $name  语言变量
237
     * @param array       $vars  变量替换
238
     * @param string      $range 语言作用域
239
     * @return mixed
240
     */
241
    public function get(string $name = null, array $vars = [], string $range = '')
242
    {
243
        $range = $range ?: $this->range;
244
245
        if (!isset($this->lang[$range])) {
246
            $this->switchLangSet($range);
247
        }
248
249
        // 空参数返回所有定义
250
        if (is_null($name)) {
251
            return $this->lang[$range] ?? [];
252
        }
253
254
        if ($this->config['allow_group'] && str_contains($name, '.')) {
255
            [$name1, $name2] = explode('.', $name, 2);
256
257
            $value = $this->lang[$range][strtolower($name1)][$name2] ?? $name;
258
        } else {
259
            $value = $this->lang[$range][strtolower($name)] ?? $name;
260
        }
261
262
        // 变量解析
263
        if (!empty($vars) && is_array($vars)) {
264
            /**
265
             * Notes:
266
             * 为了检测的方便,数字索引的判断仅仅是参数数组的第一个元素的key为数字0
267
             * 数字索引采用的是系统的 sprintf 函数替换,用法请参考 sprintf 函数
268
             */
269
            if (key($vars) === 0) {
270
                // 数字索引解析
271
                array_unshift($vars, $value);
272
                $value = call_user_func_array('sprintf', $vars);
273
            } else {
274
                // 关联索引解析
275
                $replace = array_keys($vars);
276
                foreach ($replace as &$v) {
277
                    $v = "{:{$v}}";
278
                }
279
                $value = str_replace($replace, $vars, $value);
280
            }
281
        }
282
283
        return $value;
284
    }
285
}
286