Localization.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Base\Middleware;
  3. use Closure;
  4. use App\Base\Exceptions\ApiException;
  5. class Localization
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @param \Closure $next
  12. * @param string|null $guard
  13. * @return mixed
  14. * @throws ApiException
  15. */
  16. public function handle($request, Closure $next, $guard = null)
  17. {
  18. //设置多语言
  19. $isOverseas = boolval(config('app.overseas_edition'));
  20. $siteName = 'inside';
  21. if ($isOverseas) {
  22. $siteName = 'overseas';
  23. }
  24. $lang = $request->input('lang');
  25. if(empty($lang)) {
  26. //?lang=en-us
  27. // 使用客户端的语言设置
  28. $lang = $request->header("Language-Set");
  29. if (empty($lang)) {
  30. // 使用cookie语言设置
  31. $globalLocaleCookieKey = $siteName.'_'.config('app.global_locale_cookie_key');
  32. $lang = $request->cookie($globalLocaleCookieKey);
  33. }
  34. }
  35. $translator = app('translator');
  36. $curLang = $translator->getLocale();
  37. $allowSet = false;
  38. if (!empty(config('app.overseas_edition'))) {
  39. // 海外版支持的语言
  40. if (in_array($lang, ['en-us', 'zh-tw'])) {
  41. $allowSet = true;
  42. }
  43. } else {
  44. if ($lang == 'zh-cn') {
  45. $allowSet = true;
  46. }
  47. }
  48. if ($allowSet && $lang && $lang != $curLang) {
  49. $translator->setLocale($lang);
  50. }
  51. $response = $next($request);
  52. return $response;
  53. }
  54. }