You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserCopy/UserCopyManifest.php

358 lines
13 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\UserCopy;
use InvalidArgumentException;
/**
* Loads and validates the source-language contract for user-visible copy.
*
* The manifest contains stable semantic keys and a Chinese safety baseline.
* It must never contain target-locale translations; those belong to the
* administrator-managed publication ledger introduced by later stages.
*/
final class UserCopyManifest
{
private const KEY_PATTERN = '/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/D';
private const GENERATED_KEY_PATTERN = '/(?:^|\.)dynamic\.h[0-9a-f]{6,}(?:\.|$)/D';
private const NAME_PATTERN = '/^[a-z][a-z0-9_]*$/D';
private const PAGE_PATTERN = '/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/D';
private const KINDS = [
'title', 'navigation', 'label', 'button', 'placeholder', 'help',
'description', 'status', 'empty_state', 'notice', 'warning',
'confirmation', 'toast_title', 'toast_body', 'aria_label',
'tooltip',
];
private const CRITICALITIES = ['normal', 'required', 'critical'];
private const FORMATS = ['plain_text', 'icu'];
private const PARAMETER_TYPES = [
'string', 'integer', 'number', 'date', 'time', 'datetime',
'currency', 'bytes', 'boolean',
];
private const TOAST_TONES = ['success', 'info', 'warning', 'error'];
private const EDITOR_SURFACES = [
'page', 'dialog', 'feedback', 'task', 'accessibility',
];
private const ENTRY_FIELDS = [
'key', 'scope', 'page', 'kind', 'source', 'format', 'parameters',
'criticality', 'allow_hide', 'toast_tone', 'editor_surface',
'editor_group',
];
public static function load(?string $path = null): array
{
$path = $path ?? dirname(__DIR__, 3)
. '/resources/user-copy/manifest.php';
if (!is_file($path)) {
throw new InvalidArgumentException(
'用户界面文案 Manifest 不存在:' . $path
);
}
$manifest = require $path;
if (!is_array($manifest)) {
throw new InvalidArgumentException(
'用户界面文案 Manifest 必须返回数组。'
);
}
return self::validate($manifest);
}
public static function validate(array $manifest): array
{
self::assertExactFields($manifest, ['version', 'pages', 'entries'],
'Manifest');
if (($manifest['version'] ?? null) !== 1) {
throw new InvalidArgumentException('不支持的文案 Manifest 版本。');
}
if (!is_array($manifest['pages']) || $manifest['pages'] === []) {
throw new InvalidArgumentException('文案页面目录不能为空。');
}
if (!is_array($manifest['entries'])
|| !array_is_list($manifest['entries'])) {
throw new InvalidArgumentException(
'文案词条目录必须是列表,词条键应写入 key 字段。'
);
}
$pages = [];
foreach ($manifest['pages'] as $pageKey => $page) {
if (!is_string($pageKey)
|| preg_match(self::PAGE_PATTERN, $pageKey) !== 1) {
throw new InvalidArgumentException(
'文案页面键格式无效:' . (string) $pageKey
);
}
if (!is_array($page)) {
throw new InvalidArgumentException(
'文案页面定义必须是数组:' . $pageKey
);
}
self::assertExactFields($page, ['label', 'scopes'],
'页面 ' . $pageKey);
$label = self::requiredText($page['label'] ?? null,
'页面标签 ' . $pageKey, 128);
if (!is_array($page['scopes']) || $page['scopes'] === []) {
throw new InvalidArgumentException(
'页面必须声明至少一个 scope:' . $pageKey
);
}
$scopes = [];
foreach ($page['scopes'] as $scope) {
if (!is_string($scope)
|| preg_match(self::NAME_PATTERN, $scope) !== 1) {
throw new InvalidArgumentException(
'页面 scope 格式无效:' . $pageKey
);
}
$scopes[$scope] = true;
}
$pages[$pageKey] = [
'label' => $label,
'scopes' => array_keys($scopes),
];
}
$entries = [];
foreach ($manifest['entries'] as $position => $entry) {
if (!is_array($entry)) {
throw new InvalidArgumentException(
'文案词条定义必须是数组:#' . $position
);
}
self::assertExactFields($entry, self::ENTRY_FIELDS,
'词条 #' . $position);
$copyKey = $entry['key'] ?? null;
if (!is_string($copyKey)
|| preg_match(self::KEY_PATTERN, $copyKey) !== 1
|| preg_match(self::GENERATED_KEY_PATTERN, $copyKey) === 1) {
throw new InvalidArgumentException(
'文案词条键必须是静态语义键:' . (string) $copyKey
);
}
if (array_key_exists($copyKey, $entries)) {
throw new InvalidArgumentException(
'文案词条键重复:' . $copyKey
);
}
$scope = self::name($entry['scope'] ?? null,
'词条 scope ' . $copyKey);
$page = (string) ($entry['page'] ?? '');
if (!isset($pages[$page])) {
throw new InvalidArgumentException(
'词条引用了未声明页面:' . $copyKey
);
}
if (!in_array($scope, $pages[$page]['scopes'], true)) {
throw new InvalidArgumentException(
'词条 scope 不属于声明页面:' . $copyKey
);
}
$kind = (string) ($entry['kind'] ?? '');
if (!in_array($kind, self::KINDS, true)) {
throw new InvalidArgumentException(
'词条类型无效:' . $copyKey
);
}
$source = self::requiredText($entry['source'] ?? null,
'词条中文基线 ' . $copyKey, 4000);
$format = (string) ($entry['format'] ?? 'plain_text');
if (!in_array($format, self::FORMATS, true)) {
throw new InvalidArgumentException(
'词条格式无效:' . $copyKey
);
}
$parameters = self::parameters(
$entry['parameters'] ?? [], $copyKey
);
self::assertSourceParameters($source, $parameters, $copyKey);
if ($parameters !== [] && $format !== 'icu') {
throw new InvalidArgumentException(
'带参数词条必须使用 ICU 格式:' . $copyKey
);
}
$criticality = (string) ($entry['criticality'] ?? 'normal');
if (!in_array($criticality, self::CRITICALITIES, true)) {
throw new InvalidArgumentException(
'词条安全等级无效:' . $copyKey
);
}
if (!is_bool($entry['allow_hide'] ?? null)) {
throw new InvalidArgumentException(
'词条 allow_hide 必须是布尔值:' . $copyKey
);
}
$allowHide = $entry['allow_hide'];
if ($allowHide && $criticality !== 'normal') {
throw new InvalidArgumentException(
'必需或高风险词条不能隐藏:' . $copyKey
);
}
$toastTone = $entry['toast_tone'] ?? null;
$isToast = str_starts_with($kind, 'toast_');
if ($isToast) {
if (!is_string($toastTone)
|| !in_array($toastTone, self::TOAST_TONES, true)) {
throw new InvalidArgumentException(
'Toast 词条必须声明有效 tone:' . $copyKey
);
}
} elseif ($toastTone !== null) {
throw new InvalidArgumentException(
'非 Toast 词条不能声明 tone:' . $copyKey
);
}
$editorSurface = (string) ($entry['editor_surface'] ?? '');
if (!in_array($editorSurface, self::EDITOR_SURFACES, true)) {
throw new InvalidArgumentException(
'词条编辑表面无效:' . $copyKey
);
}
$editorGroup = (string) ($entry['editor_group'] ?? '');
if (preg_match(self::PAGE_PATTERN, $editorGroup) !== 1) {
throw new InvalidArgumentException(
'词条编辑分组无效:' . $copyKey
);
}
$entries[$copyKey] = [
'key' => $copyKey,
'scope' => $scope,
'page' => $page,
'kind' => $kind,
'source' => $source,
'format' => $format,
'parameters' => $parameters,
'criticality' => $criticality,
'allow_hide' => $allowHide,
'toast_tone' => $toastTone,
'editor_surface' => $editorSurface,
'editor_group' => $editorGroup,
];
}
ksort($pages, SORT_STRING);
ksort($entries, SORT_STRING);
return [
'version' => 1,
'pages' => $pages,
'entries' => array_values($entries),
];
}
public static function digest(array $manifest): string
{
$validated = self::validate($manifest);
$json = json_encode($validated,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (!is_string($json)) {
throw new InvalidArgumentException('无法编码文案 Manifest。');
}
return hash('sha256', $json);
}
private static function parameters($value, string $copyKey): array
{
if (!is_array($value)) {
throw new InvalidArgumentException(
'词条参数合同必须是数组:' . $copyKey
);
}
$parameters = [];
foreach ($value as $name => $type) {
if (!is_string($name)
|| preg_match(self::NAME_PATTERN, $name) !== 1
|| !is_string($type)
|| !in_array($type, self::PARAMETER_TYPES, true)) {
throw new InvalidArgumentException(
'词条参数合同无效:' . $copyKey
);
}
if (isset($parameters[$name])) {
throw new InvalidArgumentException(
'词条参数重复:' . $copyKey . ':' . $name
);
}
$parameters[$name] = $type;
}
ksort($parameters, SORT_STRING);
return $parameters;
}
private static function assertSourceParameters(
string $source,
array $parameters,
string $copyKey
): void {
preg_match_all('/\{([a-z][a-z0-9_]*)\s*(?:[,}])/D', $source,
$matches);
$used = array_values(array_unique($matches[1] ?? []));
sort($used, SORT_STRING);
$declared = array_keys($parameters);
sort($declared, SORT_STRING);
if ($used !== $declared) {
throw new InvalidArgumentException(
'词条参数与中文基线不一致:' . $copyKey
);
}
}
private static function requiredText(
$value,
string $label,
int $maximumLength
): string {
if (!is_string($value) || trim($value) === '') {
throw new InvalidArgumentException($label . '不能为空。');
}
if (mb_strlen($value) > $maximumLength
|| preg_match(
'/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x{202A}-\x{202E}\x{2066}-\x{2069}]/u',
$value
)) {
throw new InvalidArgumentException($label . '包含非法内容。');
}
return $value;
}
private static function name($value, string $label): string
{
if (!is_string($value)
|| preg_match(self::NAME_PATTERN, $value) !== 1) {
throw new InvalidArgumentException($label . '格式无效。');
}
return $value;
}
private static function assertExactFields(
array $value,
array $allowed,
string $label
): void {
$unknown = array_values(array_diff(array_keys($value), $allowed));
$missing = array_values(array_diff($allowed, array_keys($value)));
if ($unknown !== []) {
throw new InvalidArgumentException(
$label . ' 包含未声明字段:' . implode(', ', $unknown)
);
}
if ($missing !== []) {
throw new InvalidArgumentException(
$label . ' 缺少字段:' . implode(', ', $missing)
);
}
}
}