SetLanguage.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\App;
  5. use Illuminate\Support\Facades\Auth;
  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 http client send an accept-language header
  19. // - There is an authenticated user with a possible language set
  20. // - No language is specified at all
  21. //
  22. // Priority to the user preference, then the header request, otherwise the fallback language.
  23. // Note that if a user is authenticated later by the auth guard, the app locale
  24. // will be overriden if the user has set a specific language in its preferences.
  25. $lang = config('app.fallback_locale');
  26. $accepted = str_replace(' ', '', $request->header('Accept-Language'));
  27. if ($accepted && $accepted !== '*') {
  28. $prefLocales = array_reduce(
  29. array_diff(explode(',', $accepted), ['*']),
  30. function ($langs, $langItem) {
  31. [$langLong, $weight] = array_merge(explode(';q=', $langItem), [1]);
  32. $langShort = substr($langLong, 0, 2);
  33. if (array_key_exists($langShort, $langs)) {
  34. if ($langs[$langShort] < $weight) {
  35. $langs[$langShort] = (float) $weight;
  36. }
  37. } else {
  38. $langs[$langShort] = (float) $weight;
  39. }
  40. return $langs;
  41. },
  42. []
  43. );
  44. arsort($prefLocales);
  45. // We take the first accepted language available
  46. foreach ($prefLocales as $locale => $weight) {
  47. if (in_array($locale, config('2fauth.locales'))) {
  48. $lang = $locale;
  49. break;
  50. }
  51. }
  52. }
  53. $user = $request->user();
  54. if (! is_null($user) && $request->user()->preferences['lang'] != 'browser') {
  55. $lang = $request->user()->preferences['lang'];
  56. }
  57. // If the language is not available (or partial), strings will be translated using the fallback language.
  58. App::setLocale($lang);
  59. return $next($request);
  60. }
  61. }