69 lines
2.3 KiB
PHP
69 lines
2.3 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Middleware;
|
||
|
||
use Closure;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Support\Facades\App;
|
||
use Illuminate\Support\Facades\Session;
|
||
use Illuminate\Support\Str;
|
||
use Illuminate\Validation\ValidationException;
|
||
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
|
||
|
||
class ForceLocale
|
||
{
|
||
/**
|
||
* This middleware forces the locale:
|
||
* - when it is changed from the back office
|
||
* - and when the form submitted in the request belongs to a different locale
|
||
*
|
||
* The issue occurred when two browser tabs were open in different locales:
|
||
* the data being saved could end up using the other tab’s locale.
|
||
*
|
||
* @param \Illuminate\Http\Request $request
|
||
* @param Closure $next
|
||
* @return mixed
|
||
* @throws ValidationException Not supported locale.
|
||
*/
|
||
public function handle(Request $request, Closure $next): mixed
|
||
{
|
||
$routeName = $request->route()?->getName();
|
||
if (! $routeName || ! Str::startsWith($routeName, 'back.')) {
|
||
return $next($request);
|
||
}
|
||
|
||
$locale = (Session::has('lang')) ? Session::get('lang') : config('app.fallback_locale');
|
||
App::setLocale($locale);
|
||
|
||
// 1. Is Post method or Inertia request ?
|
||
if (
|
||
in_array($request->method(), ['POST', 'PUT', 'PATCH'], true) and
|
||
($request->headers->has('X-Inertia') && $request->headers->get('X-Inertia') === 'true')
|
||
) {
|
||
// 1. Request Locale
|
||
$requestLocale = $request->locale ?? config('app.fallback_locale');
|
||
// 2. If prefix is not in supportedLocales
|
||
if (!in_array($requestLocale, LaravelLocalization::getSupportedLanguagesKeys(), true)) {
|
||
throw ValidationException::withMessages(["Langue" => "Not supported locale."]);
|
||
}
|
||
// 3. Set new locale if locale and prefix are not the same
|
||
if ($requestLocale !== app()->getLocale()) {
|
||
$this->changeLang($requestLocale);
|
||
}
|
||
}
|
||
|
||
return $next($request);
|
||
}
|
||
|
||
/**
|
||
* Change lang function
|
||
*
|
||
* @param string $lang
|
||
* @return void
|
||
*/
|
||
private function changeLang(string $lang): void
|
||
{
|
||
Session::put('lang', $lang);
|
||
app()->setLocale($lang);
|
||
}
|
||
}
|