2FAuth/app/Http/Middleware/SetLanguage.php

73 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
2023-02-25 21:12:10 +01:00
use Illuminate\Support\Facades\Auth;
class SetLanguage
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function handle($request, Closure $next)
{
// 3 possible cases here:
// - The http client send an accept-language header
// - There is an authenticated user with a possible language set
// - No language is specified at all
//
// Priority to the user preference, then the header request, otherwise the fallback language.
2023-02-25 21:12:10 +01:00
// Note that if a user is authenticated later by the auth guard, the app locale
// will be overriden if the user has set a specific language in its preferences.
$lang = config('app.fallback_locale');
$accepted = str_replace(' ', '', $request->header('Accept-Language'));
if ($accepted && $accepted !== '*') {
$prefLocales = array_reduce(
array_diff(explode(',', $accepted), ['*']),
function ($langs, $langItem) {
[$langLong, $weight] = array_merge(explode(';q=', $langItem), [1]);
2023-02-25 21:12:10 +01:00
$langShort = substr($langLong, 0, 2);
if (array_key_exists($langShort, $langs)) {
if ($langs[$langShort] < $weight) {
$langs[$langShort] = (float) $weight;
}
2023-02-25 21:12:10 +01:00
} else {
$langs[$langShort] = (float) $weight;
}
return $langs;
},
[]
);
arsort($prefLocales);
// We take the first accepted language available
2024-07-05 16:34:25 +02:00
$availableLocales = config('2fauth.locales');
foreach ($prefLocales as $locale => $weight) {
2024-07-05 16:34:25 +02:00
if (in_array($locale, $availableLocales)) {
$lang = $locale;
break;
}
}
}
$user = $request->user();
2024-07-05 16:34:25 +02:00
if (! is_null($user) && $user->preferences['lang'] != 'browser') {
$lang = $user->preferences['lang'];
}
// If the language is not available (or partial), strings will be translated using the fallback language.
App::setLocale($lang);
return $next($request);
}
}