83 lines
2.7 KiB
PHP
83 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace app\common\library\docs;
|
|
|
|
use Webman\Http\Request;
|
|
|
|
/**
|
|
* 按请求语言读取 docs 目录下的 Markdown 文件(英文缺失时回退中文)。
|
|
*/
|
|
final class MarkdownDocReader
|
|
{
|
|
/**
|
|
* @param array{relative:string,filename:string,ascii_fallback?:string} $zh
|
|
* @param array{relative:string,filename:string,ascii_fallback?:string} $en
|
|
* @return array{path:string,filename:string,ascii_fallback:string,lang:string}
|
|
*/
|
|
public static function resolve(Request $request, array $zh, array $en): array
|
|
{
|
|
$lang = self::resolveLang($request);
|
|
$useEn = $lang === 'en';
|
|
$spec = $useEn ? $en : $zh;
|
|
$base = rtrim(base_path(), DIRECTORY_SEPARATOR . '/');
|
|
$path = $base . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $spec['relative']);
|
|
if ($useEn && !is_file($path)) {
|
|
$spec = $zh;
|
|
$path = $base . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $zh['relative']);
|
|
$lang = 'zh-cn';
|
|
}
|
|
$filename = strval($spec['filename'] ?? 'document.md');
|
|
$asciiFallback = strval($spec['ascii_fallback'] ?? $filename);
|
|
|
|
return [
|
|
'path' => $path,
|
|
'filename' => $filename,
|
|
'ascii_fallback' => $asciiFallback,
|
|
'lang' => $lang,
|
|
];
|
|
}
|
|
|
|
public static function resolveLang(Request $request): string
|
|
{
|
|
$thinkRaw = $request->header('think-lang', '');
|
|
$thinkLang = is_string($thinkRaw) ? trim($thinkRaw) : '';
|
|
if ($thinkLang === '' && is_array($thinkRaw) && isset($thinkRaw[0]) && is_string($thinkRaw[0])) {
|
|
$thinkLang = trim($thinkRaw[0]);
|
|
}
|
|
|
|
$queryRaw = $request->get('lang');
|
|
if ($queryRaw === null || $queryRaw === '') {
|
|
$queryRaw = $request->post('lang');
|
|
}
|
|
$queryLang = is_string($queryRaw) ? trim($queryRaw) : (is_scalar($queryRaw) ? trim(strval($queryRaw)) : '');
|
|
|
|
$headerRaw = $request->header('lang', '');
|
|
$headerLang = is_string($headerRaw) ? trim($headerRaw) : '';
|
|
|
|
$normalize = static function (string $raw): string {
|
|
$s = str_replace('_', '-', strtolower(trim($raw)));
|
|
if ($s === 'zh') {
|
|
return 'zh-cn';
|
|
}
|
|
return $s;
|
|
};
|
|
|
|
foreach ([$thinkLang, $headerLang, $queryLang] as $candidate) {
|
|
if ($candidate === '') {
|
|
continue;
|
|
}
|
|
$normalized = $normalize($candidate);
|
|
if ($normalized === 'en') {
|
|
return 'en';
|
|
}
|
|
if ($normalized === 'zh-cn') {
|
|
return 'zh-cn';
|
|
}
|
|
}
|
|
|
|
return 'zh-cn';
|
|
}
|
|
}
|