Initialer Laravel Commit für BetiX
This commit is contained in:
48
app/Http/Controllers/LocaleController.php
Normal file
48
app/Http/Controllers/LocaleController.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
|
||||
class LocaleController extends Controller
|
||||
{
|
||||
/** @var array<string> */
|
||||
private array $available = [
|
||||
'en','de','es','pt_BR','tr','pl',
|
||||
'fr','it','ru','uk','vi','id','zh_CN','ja','ko','sv','no','fi','nl',
|
||||
];
|
||||
|
||||
public function set(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'locale' => ['required','string','max:8'],
|
||||
]);
|
||||
$code = $this->normalize($data['locale']);
|
||||
if (!in_array($code, $this->available, true)) {
|
||||
return response()->json(['message' => 'Unsupported locale.'], 422);
|
||||
}
|
||||
|
||||
// Persist to session and cookie (1 year)
|
||||
$request->session()->put('locale', $code);
|
||||
Cookie::queue(cookie('locale', $code, 60 * 24 * 365));
|
||||
|
||||
// Update user preference if logged in (no local DB writes in gateway)
|
||||
if ($user = $request->user()) {
|
||||
if (($user->preferred_locale ?? null) !== $code) {
|
||||
// Defer persistence to external API if needed; here we only keep session/cookie.
|
||||
// Optionally enqueue an event to sync upstream.
|
||||
}
|
||||
}
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
private function normalize(string $code): string
|
||||
{
|
||||
$code = str_replace([' ', '-'], ['','_'], trim($code));
|
||||
if (strtolower($code) === 'pt_br') return 'pt_BR';
|
||||
if (strtolower($code) === 'zh_cn') return 'zh_CN';
|
||||
return strtolower($code);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user