Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get the default local from the Laravel config file before the browser #70

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 41 additions & 39 deletions src/Http/Middleware/SwitchLanguageLocale.php
Original file line number Diff line number Diff line change
@@ -1,40 +1,42 @@
<?php

namespace BezhanSalleh\FilamentLanguageSwitch\Http\Middleware;

use BezhanSalleh\FilamentLanguageSwitch\LanguageSwitch;
use Closure;
use Illuminate\Http\Request;

class SwitchLanguageLocale
{
public function handle(Request $request, Closure $next): \Illuminate\Http\Response | \Illuminate\Http\RedirectResponse
{
$locale = session()->get('locale')
?? $request->get('locale')
?? $request->cookie('filament_language_switch_locale')
?? $this->getBrowserLocale($request)
?? config('app.locale', 'en');

if (in_array($locale, LanguageSwitch::make()->getLocales())) {
app()->setLocale($locale);
}

return $next($request);
}

private function getBrowserLocale(Request $request): ?string
{
$appLocales = LanguageSwitch::make()->getLocales();

$userLocales = preg_split('/[,;]/', $request->server('HTTP_ACCEPT_LANGUAGE'));

foreach ($userLocales as $locale) {
if (in_array($locale, $appLocales)) {
return $locale;
}
}

return null;
}
}

namespace BezhanSalleh\FilamentLanguageSwitch\Http\Middleware;

use BezhanSalleh\FilamentLanguageSwitch\LanguageSwitch;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class SwitchLanguageLocale
{
public function handle(Request $request , Closure $next): Response|RedirectResponse
{
$locale = session()->get('locale')
?? $request->get('locale')
?? $request->cookie('filament_language_switch_locale')
?? config('app.locale' , 'en')
?? $this->getBrowserLocale($request);

if (in_array($locale , LanguageSwitch::make()->getLocales())) {
app()->setLocale($locale);
}

return $next($request);
}

private function getBrowserLocale(Request $request): ?string
{
$appLocales = LanguageSwitch::make()->getLocales();

$userLocales = preg_split('/[,;]/' , $request->server('HTTP_ACCEPT_LANGUAGE'));

foreach ($userLocales as $locale) {
if (in_array($locale , $appLocales)) {
return $locale;
}
}

return null;
}
}