- Added standard Laravel directory structure and configuration. - Included Svelte and Tailwind configuration for the admin interface. - Added core PHPUnit and testing scripts.
76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Services\TranslationManager;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class SetLocaleMiddleware
|
|
{
|
|
protected TranslationManager $translationManager;
|
|
|
|
public function __construct(TranslationManager $translationManager)
|
|
{
|
|
$this->translationManager = $translationManager;
|
|
}
|
|
|
|
/**
|
|
* Handle an incoming request.
|
|
*
|
|
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$settingService = app(\App\Services\SettingService::class);
|
|
$locale = $this->determineLocale($request, $settingService);
|
|
|
|
app()->setLocale($locale);
|
|
$this->translationManager->setLocale($locale);
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
protected function determineLocale(Request $request, \App\Services\SettingService $settingService): string
|
|
{
|
|
// 1. User Preference (Authenticated)
|
|
if (Auth::check() && Auth::user()->preferred_locale) {
|
|
return Auth::user()->preferred_locale;
|
|
}
|
|
|
|
// 2. URL Prefix (e.g., /en/about-us)
|
|
$segments = $request->segments();
|
|
$availableLocales = $settingService->getSupportedLocales();
|
|
|
|
// In test or some scenarios, segments might be different
|
|
if (count($segments) > 0 && in_array($segments[0], $availableLocales)) {
|
|
return $segments[0];
|
|
}
|
|
|
|
// Handle case where it might be in route parameters directly
|
|
$routeLocale = $request->route('locale');
|
|
if ($routeLocale && in_array($routeLocale, $availableLocales)) {
|
|
return $routeLocale;
|
|
}
|
|
|
|
// 3. Session
|
|
if (session()->has('locale')) {
|
|
return session()->get('locale');
|
|
}
|
|
|
|
// 4. Request Header
|
|
$acceptLanguage = $request->server('HTTP_ACCEPT_LANGUAGE');
|
|
if ($acceptLanguage) {
|
|
$headerLocale = substr($acceptLanguage, 0, 2);
|
|
if (in_array($headerLocale, $availableLocales)) {
|
|
return $headerLocale;
|
|
}
|
|
}
|
|
|
|
// 5. Global Default
|
|
return $settingService->get('default_locale', config('app.locale'));
|
|
}
|
|
}
|