73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
namespace app\api\util;
|
||
|
||
use support\Request;
|
||
|
||
/**
|
||
* API 多语言:根据请求头 lang(en=英文,zh=中文)翻译返回文案
|
||
*/
|
||
class ApiLang
|
||
{
|
||
private const LANG_HEADER = 'lang';
|
||
private const LANG_EN = 'en';
|
||
private const LANG_ZH = 'zh';
|
||
|
||
/** @var array<string, string>|null */
|
||
private static ?array $enMap = null;
|
||
|
||
/**
|
||
* 从请求中获取语言:lang 请求头 en=英文,zh=中文,默认 zh
|
||
*/
|
||
public static function getLang(?Request $request = null): string
|
||
{
|
||
$request = $request ?? (function_exists('request') ? request() : null);
|
||
if ($request === null) {
|
||
return self::LANG_ZH;
|
||
}
|
||
$lang = $request->header(self::LANG_HEADER);
|
||
if ($lang !== null && $lang !== '') {
|
||
$lang = strtolower(trim((string) $lang));
|
||
if ($lang === self::LANG_EN) {
|
||
return self::LANG_EN;
|
||
}
|
||
if ($lang === self::LANG_ZH || $lang === 'chs') {
|
||
return self::LANG_ZH;
|
||
}
|
||
}
|
||
return self::LANG_ZH;
|
||
}
|
||
|
||
/**
|
||
* 翻译文案:当前请求语言为 en 时返回英文,否则返回原文(中文)
|
||
* @param string $message 中文或原文
|
||
* @param Request|null $request 当前请求,不传则自动取 request()
|
||
*/
|
||
public static function translate(string $message, ?Request $request = null): string
|
||
{
|
||
$lang = self::getLang($request);
|
||
if ($lang !== self::LANG_EN) {
|
||
return $message;
|
||
}
|
||
if (self::$enMap === null) {
|
||
$path = dirname(__DIR__) . '/lang/en.php';
|
||
self::$enMap = is_file($path) ? (require $path) : [];
|
||
}
|
||
return self::$enMap[$message] ?? $message;
|
||
}
|
||
|
||
/**
|
||
* 带占位符的翻译,如 translateParams('当前玩家余额%s小于%s无法继续游戏', [$coin, $minCoin])
|
||
* 先翻译再替换(en 文案使用 %s 占位)
|
||
*/
|
||
public static function translateParams(string $message, array $params = [], ?Request $request = null): string
|
||
{
|
||
$translated = self::translate($message, $request);
|
||
if ($params !== []) {
|
||
$translated = sprintf($translated, ...$params);
|
||
}
|
||
return $translated;
|
||
}
|
||
}
|