1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- namespace App\Http\Middleware;
- use Closure;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\App;
- /**
- * 读取语言环境
- *
- */
- class LoadLocale
- {
- /**
- * 处理传入请求
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle(Request $request, Closure $next)
- {
- // 设置语言
- $request = $this->setLocale($request);
- // 返回结果
- return $next($request);
- }
-
- /**
- * 自动侦测当前语言
- * @param \Illuminate\Http\Request $request
- */
- private function setLocale(Request $request){
- // 默认语言
- $langSet = config('lang.default_lang','en');
- // 多语言自动侦测变量名
- if ($request->get(config('lang.detect_var','lang'))) {
- // url中设置了语言变量
- $langSet = strtolower($request->get(config('lang.detect_var','lang')));
- } elseif ($request->header(config('lang.header_var','lang'))) {
- // Header中设置了语言变量
- $langSet = strtolower($request->header(config('lang.header_var','lang')));
-
- } elseif ($request->cookie(config('lang.cookie_var','lang'))) {
- // Cookie中设置了语言变量
- $langSet = strtolower($request->cookie(config('lang.cookie_var','lang')));
- } elseif ($request->server('HTTP_ACCEPT_LANGUAGE')) {
- // 自动侦测浏览器语言
- $match = preg_match('/^([a-z\d\-]+)/i', $request->server('HTTP_ACCEPT_LANGUAGE'), $matches);
- // 如果有匹配语言,获取第一条语言
- if ($match) $langSet = strtolower($matches[1]);
- }
- // 统一分割符号
- $langSet = str_ireplace('_','-',$langSet);
- // 允许语言列表
- $allow_lang_list = config('lang.allow_lang_list');
- // 如果不在允许语言内,使用默认语言
- if( !empty($allow_lang_list) && !in_array($langSet,$allow_lang_list) ) $langSet = config('lang.default_lang','en');
- // 请求语言设置为最终语言
- $request->lang = $langSet;
- // 设置语言
- App::setLocale($langSet);
- // 返回结果
- return $request;
- }
- }
|