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/UserCopyCatalogCompiler.php

243 lines
7.7 KiB
PHP

<?php
namespace App\Services\UserCopy;
use App\Services\LocaleCode;
use MessageFormatter;
/**
* Compiles source-owned entries and administrator-owned translations into one
* deterministic, immutable locale generation.
*/
final class UserCopyCatalogCompiler
{
public function __construct(private readonly UserCopySourceCatalog $source)
{
}
/**
* @param array<string,string|array<string,mixed>> $translations
*/
public function compile(
string $locale,
array $translations = []
): UserCopyCompiledCatalog {
$locale = $this->normalizeLocale($locale);
$entries = $this->source->entries();
foreach (array_keys($translations) as $key) {
if (!is_string($key) || !isset($entries[$key])) {
throw new UserCopyCatalogException(
'Translation references an unknown user copy key.'
);
}
}
$scopes = [];
foreach ($this->source->scopes() as $scope) {
$scopes[$scope] = [
'schema' => 1,
'locale' => $locale,
'scope' => $scope,
'messages' => [],
'metadata' => [],
];
}
foreach ($entries as $key => $entry) {
$this->validateMessage($key, $entry, $entry['source'], 'zh-CN');
[$message, $hidden, $translated] = $this->translationFor(
$key,
$entry,
$translations[$key] ?? null
);
if (!$hidden) {
$this->validateMessage($key, $entry, $message, $locale);
}
$scope = $entry['scope'];
$scopes[$scope]['messages'][$key] = $message;
$scopes[$scope]['metadata'][$key] = [
'kind' => $entry['kind'],
'criticality' => $entry['criticality'],
'severity' => $entry['severity'],
'format' => $entry['format'],
'required' => $entry['required'],
'allow_hide' => $entry['allow_hide'],
'hidden' => $hidden,
'translated' => $translated,
'parameters' => $entry['parameters'],
'source_hash' => $entry['source_hash'],
'placeholder_hash' => $entry['placeholder_hash'],
];
}
ksort($scopes, SORT_STRING);
foreach ($scopes as &$payload) {
ksort($payload['messages'], SORT_STRING);
ksort($payload['metadata'], SORT_STRING);
}
unset($payload);
$scopeManifest = [];
foreach ($scopes as $scope => $payload) {
$scopeManifest[$scope] = [
'php' => $locale . '/' . $scope . '.php',
'json' => $locale . '/' . $scope . '.json',
'payload_sha256' => hash(
'sha256',
UserCopySourceCatalog::canonicalJson($payload)
),
'entry_count' => count($payload['messages']),
];
}
$catalogHash = hash('sha256', UserCopySourceCatalog::canonicalJson(
array_map(
static fn (array $scope): string => $scope['payload_sha256'],
$scopeManifest
)
));
$manifest = [
'schema' => 1,
'locale' => $locale,
'catalog_sha256' => $catalogHash,
'source_manifest_sha256' => $this->source->sourceHash(),
'page_scopes' => $this->source->pageScopes(),
'scopes' => $scopeManifest,
];
$generation = 'g-' . hash(
'sha256',
UserCopySourceCatalog::canonicalJson($manifest)
);
$manifest['generation'] = $generation;
return new UserCopyCompiledCatalog(
$locale,
$generation,
$manifest,
$scopes
);
}
/**
* @param array<string,mixed> $entry
* @param string|array<string,mixed>|null $translation
* @return array{0:string,1:bool,2:bool}
*/
private function translationFor(
string $key,
array $entry,
string|array|null $translation
): array {
if ($translation === null) {
return [$entry['source'], false, false];
}
$hidden = false;
if (is_array($translation)) {
$hidden = ($translation['hidden'] ?? false) === true;
$translation = $translation['text']
?? $translation['translation']
?? null;
if ($hidden && $translation === null) {
$translation = '';
}
}
if (!is_string($translation)) {
throw new UserCopyCatalogException(
'Translation must contain text for ' . $key . '.'
);
}
if ($hidden) {
if (!$entry['allow_hide']
|| $entry['criticality'] !== 'normal'
|| $entry['required']) {
throw new UserCopyCatalogException(
'Required or safety copy cannot be hidden: ' . $key
);
}
return ['', true, true];
}
return [$translation, false, true];
}
/** @param array<string,mixed> $entry */
private function validateMessage(
string $key,
array $entry,
string $message,
string $locale
): void {
if (trim($message) === '') {
throw new UserCopyCatalogException(
'User copy text cannot be empty: ' . $key
);
}
if (mb_strlen($message) > $entry['max_length']) {
throw new UserCopyCatalogException(
'User copy text exceeds its length limit: ' . $key
);
}
if (preg_match(
'/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u',
$message
) === 1 || preg_match(
'/[\x{061C}\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}]/u',
$message
) === 1) {
throw new UserCopyCatalogException(
'User copy text contains forbidden control characters: ' . $key
);
}
if (preg_match('/<\s*\/?\s*[A-Za-z][^>]*>/u', $message) === 1) {
throw new UserCopyCatalogException(
'User copy text must not contain HTML: ' . $key
);
}
$used = $this->extractParameters($message);
$declared = $entry['parameters'];
sort($used, SORT_STRING);
sort($declared, SORT_STRING);
if ($used !== $declared) {
throw new UserCopyCatalogException(
'User copy placeholders do not match the manifest: ' . $key
);
}
if ($entry['format'] === 'icu') {
$formatter = MessageFormatter::create($locale, $message);
if (!$formatter instanceof MessageFormatter) {
throw new UserCopyCatalogException(
'Invalid ICU user copy pattern for ' . $key . ': '
. intl_get_error_message()
);
}
}
}
/** @return list<string> */
private function extractParameters(string $message): array
{
preg_match_all(
'/\{\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*(?:[,}])/u',
$message,
$matches
);
$parameters = array_values(array_unique($matches[1] ?? []));
sort($parameters, SORT_STRING);
return $parameters;
}
private function normalizeLocale(string $locale): string
{
$normalized = LocaleCode::canonicalize($locale);
if ($normalized === null) {
throw new UserCopyCatalogException('Invalid user copy locale.');
}
return $normalized;
}
}