refactor: 重构语言协商中间件,简化语言解析逻辑并增强异常处理,更新相关配置以支持多环境开发
This commit is contained in:
52
app/Support/LotteryLocale.php
Normal file
52
app/Support/LotteryLocale.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 与 NegotiateLotteryLocale 相同的协商规则;供异常 render 等非中间件链路使用。
|
||||
*/
|
||||
final class LotteryLocale
|
||||
{
|
||||
public static function resolve(Request $request): string
|
||||
{
|
||||
/** @var list<string> $supported */
|
||||
$supported = array_values(array_unique(config('lottery.locales.supported', ['en', 'zh', 'ne'])));
|
||||
$fallback = (string) config('lottery.locales.fallback', 'en');
|
||||
|
||||
$header = strtolower(trim((string) $request->header('X-Locale', '')));
|
||||
if ($header !== '' && in_array($header, $supported, true)) {
|
||||
return $header;
|
||||
}
|
||||
|
||||
return self::fromAcceptLanguage((string) $request->header('Accept-Language', ''), $supported, $fallback);
|
||||
}
|
||||
|
||||
/** @param list<string> $supported */
|
||||
private static function fromAcceptLanguage(string $header, array $supported, string $fallback): string
|
||||
{
|
||||
if ($header === '') {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
foreach (explode(',', $header) as $part) {
|
||||
$code = strtolower(trim(explode(';', trim($part), 2)[0] ?? ''));
|
||||
if ($code === '') {
|
||||
continue;
|
||||
}
|
||||
$primary = explode('-', $code, 2)[0] ?? $code;
|
||||
if ($primary === 'zh' && in_array('zh', $supported, true)) {
|
||||
return 'zh';
|
||||
}
|
||||
if ($primary === 'ne' && in_array('ne', $supported, true)) {
|
||||
return 'ne';
|
||||
}
|
||||
if ($primary === 'en' && in_array('en', $supported, true)) {
|
||||
return 'en';
|
||||
}
|
||||
}
|
||||
|
||||
return $fallback;
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ final class LotteryMessage
|
||||
public static function sso(Request $request, int $code): string
|
||||
{
|
||||
$fallback = (string) config('lottery.locales.fallback', 'en');
|
||||
$locale = (string) ($request->attributes->get('lottery_locale') ?? $fallback);
|
||||
$locale = (string) ($request->attributes->get('lottery_locale') ?? LotteryLocale::resolve($request));
|
||||
$key = 'sso.'.$code; // 对应 lang/{locale}/sso.php 内键名,如 '8001'
|
||||
|
||||
$msg = trans($key, [], $locale);
|
||||
|
||||
Reference in New Issue
Block a user