SetLanguage.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Facades\Settings;
  4. use Closure;
  5. use Illuminate\Support\Facades\App;
  6. class SetLanguage
  7. {
  8. /**
  9. * Handle an incoming request.
  10. *
  11. * @param \Illuminate\Http\Request $request
  12. * @param \Closure $next
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next)
  16. {
  17. // 3 possible cases here:
  18. // - The user has choosen a specific language among those available in the Setting view of 2FAuth
  19. // - The client send an accept-language header
  20. // - No language is passed from the client
  21. //
  22. // We prioritize the user defined one, then the request header one, and finally the fallback one.
  23. // FI: Settings::get() always returns a fallback value
  24. $lang = Settings::get('lang');
  25. if ($lang === 'browser') {
  26. $lang = config('app.fallback_locale');
  27. $accepted = str_replace(' ', '', $request->header('Accept-Language'));
  28. if ($accepted && $accepted !== '*') {
  29. $prefLocales = array_reduce(
  30. array_diff(explode(',', $accepted), ['*']),
  31. function ($res, $el) {
  32. [$l, $q] = array_merge(explode(';q=', $el), [1]);
  33. $res[$l] = (float) $q;
  34. return $res;
  35. },
  36. []
  37. );
  38. arsort($prefLocales);
  39. // We only keep the primary language passed via the header.
  40. $lang = array_key_first($prefLocales);
  41. }
  42. }
  43. // If the language is not available (or partial), strings will be translated using the fallback language.
  44. App::setLocale($lang);
  45. return $next($request);
  46. }
  47. }