Files
2026-03-18 15:10:40 +08:00

75 lines
2.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;
/**
* 加载控制器语言包中间件Webman 迁移版,等价 ThinkPHP LoadLangPack
* 根据当前路由加载对应控制器的语言包到 Translator
*/
class LoadLangPack implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$path = trim($request->path(), '/');
if (str_starts_with($path, 'api/') || str_starts_with($path, 'admin/')) {
$this->loadLang($request);
}
return $handler($request);
}
protected function loadLang(Request $request): void
{
// 优先从请求头 think-lang 获取前端选择的语言(与前端 axios 发送的 header 对应)
$headerLang = $request->header('think-lang');
$allowLangList = config('lang.allow_lang_list', ['zh-cn', 'en']);
if ($headerLang && in_array(str_replace('_', '-', strtolower($headerLang)), $allowLangList)) {
$langSet = str_replace('_', '-', strtolower($headerLang));
} else {
$langSet = config('lang.default_lang', config('translation.locale', 'zh-cn'));
$langSet = str_replace('_', '-', strtolower($langSet));
}
// 设置当前请求的翻译语言,使 __() 和 trans() 使用正确的语言
if (function_exists('locale')) {
locale($langSet);
}
$path = trim($request->path(), '/');
$parts = explode('/', $path);
$app = $parts[0] ?? 'api';
$appLangDir = base_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $app . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR;
if (!class_exists(\support\Translation::class)) {
return;
}
$translator = \support\Translation::instance();
// 1. 加载根级语言包zh-cn.php / en.php供 common 翻译使用
$rootLangFile = $appLangDir . $langSet . '.php';
if (is_file($rootLangFile)) {
$translator->addResource('phpfile', $rootLangFile, $langSet, 'messages');
}
// 2. 加载控制器专用语言包(如 zh-cn/auth/group.php供 get_route_remark 等使用
$controllerPath = get_controller_path($request);
if ($controllerPath) {
$controllerPathForFile = str_replace('.', '/', $controllerPath);
$controllerPathForFile = implode('/', array_map(function ($p) {
return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $p));
}, explode('/', $controllerPathForFile)));
$controllerLangFile = $appLangDir . $langSet . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $controllerPathForFile) . '.php';
if (is_file($controllerLangFile)) {
$translator->addResource('phpfile', $controllerLangFile, $langSet, $controllerPath);
}
}
}
}