2020-02-27 12:18:46 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
|
|
|
use Closure;
|
2021-12-03 22:50:28 +01:00
|
|
|
use Illuminate\Support\Facades\App;
|
2022-07-30 17:51:02 +02:00
|
|
|
use App\Facades\Settings;
|
2020-02-27 12:18:46 +01:00
|
|
|
|
|
|
|
class SetLanguage
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Handle an incoming request.
|
|
|
|
*
|
|
|
|
* @param \Illuminate\Http\Request $request
|
|
|
|
* @param \Closure $next
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function handle($request, Closure $next)
|
|
|
|
{
|
2021-12-03 22:50:28 +01:00
|
|
|
// 3 possible cases here:
|
|
|
|
// - The user has choosen a specific language among those available in the Setting view of 2FAuth
|
|
|
|
// - The client send an accept-language header
|
|
|
|
// - No language is passed from the client
|
|
|
|
//
|
|
|
|
// We prioritize the user defined one, then the request header one, and finally the fallback one.
|
2022-07-30 17:51:02 +02:00
|
|
|
// FI: Settings::get() always returns a fallback value
|
|
|
|
$lang = Settings::get('lang');
|
2021-12-03 22:50:28 +01:00
|
|
|
|
|
|
|
if($lang === 'browser') {
|
2022-03-31 08:38:35 +02:00
|
|
|
$lang = config('app.fallback_locale');
|
2022-11-17 16:46:29 +01:00
|
|
|
$accepted = str_replace(' ', '', $request->header("Accept-Language"));
|
2022-09-07 17:56:42 +02:00
|
|
|
|
2022-11-17 16:46:29 +01:00
|
|
|
if ($accepted && $accepted !== '*') {
|
2022-09-07 17:56:42 +02:00
|
|
|
$prefLocales = array_reduce(
|
2022-11-17 16:46:29 +01:00
|
|
|
array_diff(explode(',', $accepted), ['*']),
|
2022-09-07 17:56:42 +02:00
|
|
|
function ($res, $el) {
|
|
|
|
list($l, $q) = array_merge(explode(';q=', $el), [1]);
|
|
|
|
$res[$l] = (float) $q;
|
|
|
|
return $res;
|
|
|
|
},
|
|
|
|
[]
|
|
|
|
);
|
|
|
|
arsort($prefLocales);
|
|
|
|
|
2021-12-03 22:50:28 +01:00
|
|
|
// We only keep the primary language passed via the header.
|
2022-09-07 17:56:42 +02:00
|
|
|
$lang = array_key_first($prefLocales);
|
2021-12-03 22:50:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the language is not available (or partial), strings will be translated using the fallback language.
|
|
|
|
App::setLocale($lang);
|
2020-02-27 12:18:46 +01:00
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
}
|