Files
dafuweng-buildadmin/dafuweng-webman/app/common/middleware/LoadLangPack.php
2026-03-07 19:42:22 +08:00

50 lines
1.6 KiB
PHP
Raw 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
{
$controllerPath = get_controller_path($request);
if (!$controllerPath) {
return;
}
$langSet = config('lang.default_lang', config('translation.locale', 'zh-cn'));
$langSet = str_replace('_', '-', strtolower($langSet));
$path = trim($request->path(), '/');
$parts = explode('/', $path);
$app = $parts[0] ?? 'api';
$langFile = base_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $app
. DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . $langSet
. DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $controllerPath) . '.php';
if (is_file($langFile) && class_exists(\support\Translation::class)) {
$translator = \support\Translation::instance();
$translator->addResource('phpfile', $langFile, $langSet, $controllerPath);
}
}
}