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

422 lines
15 KiB
PHTML

<?php
namespace App\Services\UserCopy;
use App\Services\LocaleCode;
/**
* Read-only runtime Adapter. It reads only current.json and immutable files;
* persistence services are deliberately absent from this dependency graph.
*/
final class UserCopyRuntimeReader
{
private readonly string $root;
/** @var array<string,array<string,mixed>|null> */
private array $scopeCache = [];
public function __construct(
string $rootDirectory,
private readonly UserCopySourceCatalog $source
) {
$this->root = rtrim($rootDirectory, DIRECTORY_SEPARATOR);
if ($this->root === '') {
throw new UserCopyCatalogException(
'User copy runtime directory cannot be empty.'
);
}
}
/**
* @param list<string> $scopes
* @return array{locale:string,generation:?string,messages:array<string,string>,metadata:array<string,array<string,mixed>>,fallback_scopes:list<string>}
*/
public function read(string $locale, array $scopes): array
{
$locale = $this->normalizeLocale($locale);
$scopes = $this->normalizeScopes($scopes);
$fallback = $this->sourceSnapshot($locale, $scopes);
$active = $this->activeGeneration($locale);
if ($active === null) {
return $fallback;
}
$generation = $active['generation'];
$manifest = $active['manifest'];
$messages = [];
$metadata = [];
$fallbackScopes = [];
foreach ($scopes as $scope) {
$sourcePayload = $this->sourceScope($locale, $scope);
$publishedPayload = $this->readScope(
$locale,
$generation,
$scope,
$manifest
);
if ($publishedPayload === null) {
$fallbackScopes[] = $scope;
$publishedPayload = ['messages' => [], 'metadata' => []];
}
$scopeFallback = false;
foreach ($sourcePayload['messages'] as $key => $sourceMessage) {
$sourceMetadata = $sourcePayload['metadata'][$key];
$publishedMetadata = $publishedPayload['metadata'][$key] ?? null;
$compatible = is_array($publishedMetadata)
&& array_key_exists($key, $publishedPayload['messages'])
&& is_string($publishedMetadata['source_hash'] ?? null)
&& is_string($publishedMetadata['placeholder_hash'] ?? null)
&& hash_equals(
(string) $sourceMetadata['source_hash'],
(string) $publishedMetadata['source_hash']
)
&& hash_equals(
(string) $sourceMetadata['placeholder_hash'],
(string) $publishedMetadata['placeholder_hash']
);
if ($compatible) {
$messages[$key] = $publishedPayload['messages'][$key];
$metadata[$key] = $publishedMetadata;
continue;
}
$messages[$key] = $sourceMessage;
$metadata[$key] = $sourceMetadata;
$scopeFallback = true;
}
if ($scopeFallback && !in_array($scope, $fallbackScopes, true)) {
$fallbackScopes[] = $scope;
}
}
ksort($messages, SORT_STRING);
ksort($metadata, SORT_STRING);
return [
'locale' => $locale,
'generation' => $generation,
'messages' => $messages,
'metadata' => $metadata,
'fallback_scopes' => $fallbackScopes,
];
}
/**
* @return array{locale:string,generation:?string,messages:array<string,string>,metadata:array<string,array<string,mixed>>,fallback_scopes:list<string>}
*/
public function readPage(string $locale, string $page): array
{
return $this->read($locale, $this->scopesForPage($page));
}
/**
* Runtime-visible languages. The source locale is always available;
* targets require both an enabled directory entry and a valid immutable
* publication. An old English pointer without directory metadata remains
* readable during a clean rolling upgrade.
*
* @return list<array{locale:string,display_name:string,source:bool}>
*/
public function availableLocales(): array
{
$source = [[
'locale' => 'zh-CN',
'display_name' => '简体中文',
'source' => true,
]];
$current = $this->currentPointer();
if ($current === null) {
return $source;
}
$rawDirectory = $current['locale_directory'] ?? [];
if (is_array($rawDirectory)
&& is_array($rawDirectory['locales'] ?? null)) {
$rawDirectory = $rawDirectory['locales'];
}
$targets = [];
$directoryLocales = [];
if (is_array($rawDirectory)) {
foreach ($rawDirectory as $key => $descriptor) {
if (!is_array($descriptor)) {
continue;
}
$locale = is_string($descriptor['locale'] ?? null)
? $descriptor['locale']
: (is_string($key) ? $key : '');
try {
$locale = $this->normalizeLocale($locale);
} catch (UserCopyCatalogException) {
continue;
}
$directoryLocales[$locale] = true;
if ($locale === 'zh-CN'
|| !(($descriptor['enabled'] ?? false) === true
|| ($descriptor['enabled'] ?? null) === 1)
|| $this->activeGenerationFromCurrent(
$locale,
$current
) === null) {
continue;
}
$displayName = is_string(
$descriptor['display_name'] ?? null
) ? trim($descriptor['display_name']) : '';
if ($displayName === ''
|| !mb_check_encoding($displayName, 'UTF-8')
|| mb_strlen($displayName, 'UTF-8') > 128
|| preg_match('/[\x00-\x1F\x7F]/u', $displayName) === 1) {
$displayName = $locale;
}
$targets[$locale] = [
'locale' => $locale,
'display_name' => $displayName,
'source' => false,
];
}
}
if (!isset($directoryLocales['en'])
&& $this->activeGenerationFromCurrent('en', $current) !== null) {
$targets['en'] = [
'locale' => 'en',
'display_name' => 'English',
'source' => false,
];
}
ksort($targets, SORT_STRING);
return array_merge($source, array_values($targets));
}
/** @return list<string> */
public function scopesForPage(string $page): array
{
$pages = $this->source->pageScopes();
if (!isset($pages[$page])) {
throw new UserCopyCatalogException(
'Unknown user copy page: ' . $page
);
}
return $pages[$page];
}
/** @return array{generation:string,manifest:array<string,mixed>}|null */
private function activeGeneration(string $locale): ?array
{
$current = $this->currentPointer();
return $current === null
? null
: $this->activeGenerationFromCurrent($locale, $current);
}
/** @return array<string,mixed>|null */
private function currentPointer(): ?array
{
$path = $this->root . '/current.json';
$raw = is_file($path) ? file_get_contents($path) : false;
if (!is_string($raw)) {
return null;
}
try {
$current = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return null;
}
return is_array($current)
&& ($current['schema'] ?? null) === 1
&& is_array($current['locales'] ?? null)
? $current : null;
}
/**
* @param array<string,mixed> $current
* @return array{generation:string,manifest:array<string,mixed>}|null
*/
private function activeGenerationFromCurrent(
string $locale,
array $current
): ?array {
$pointer = is_array($current['locales'][$locale] ?? null)
? $current['locales'][$locale] : null;
if ($pointer === null) {
return null;
}
$generation = $pointer['generation'] ?? null;
if (!is_string($generation)
|| preg_match('/\Ag-[a-f0-9]{64}\z/D', $generation) !== 1
|| preg_match(
'/\A[a-f0-9]{64}\z/D',
(string) ($pointer['manifest_sha256'] ?? '')
) !== 1) {
return null;
}
$manifestPath = $this->root . '/generations/' . $generation
. '/manifest.json';
$manifestRaw = is_file($manifestPath)
? file_get_contents($manifestPath) : false;
if (!is_string($manifestRaw)
|| !hash_equals($pointer['manifest_sha256'], hash('sha256', $manifestRaw))) {
return null;
}
try {
$manifest = json_decode(
$manifestRaw,
true,
512,
JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
return null;
}
if (!is_array($manifest)
|| ($manifest['schema'] ?? null) !== 1
|| ($manifest['locale'] ?? null) !== $locale
|| ($manifest['generation'] ?? null) !== $generation
|| preg_match(
'/\A[a-f0-9]{64}\z/D',
(string) ($manifest['source_manifest_sha256'] ?? '')
) !== 1
|| ($manifest['catalog_sha256'] ?? null)
!== ($pointer['catalog_sha256'] ?? null)
|| !is_array($manifest['scopes'] ?? null)) {
return null;
}
return [
'generation' => $generation,
'manifest' => $manifest,
];
}
/** @param array<string,mixed> $manifest @return array<string,mixed>|null */
private function readScope(
string $locale,
string $generation,
string $scope,
array $manifest
): ?array {
$descriptor = $manifest['scopes'][$scope] ?? null;
if (!is_array($descriptor)
|| ($descriptor['php'] ?? null) !== $locale . '/' . $scope . '.php'
|| preg_match(
'/\A[a-f0-9]{64}\z/D',
(string) ($descriptor['payload_sha256'] ?? '')
) !== 1) {
return null;
}
$cacheKey = $generation . '|' . $locale . '|' . $scope;
if (array_key_exists($cacheKey, $this->scopeCache)) {
return $this->scopeCache[$cacheKey];
}
$path = $this->root . '/generations/' . $generation
. '/' . $locale . '/' . $scope . '.php';
if (!is_file($path)) {
return $this->scopeCache[$cacheKey] = null;
}
try {
$payload = require $path;
} catch (\Throwable) {
return $this->scopeCache[$cacheKey] = null;
}
if (!is_array($payload)
|| ($payload['schema'] ?? null) !== 1
|| ($payload['locale'] ?? null) !== $locale
|| ($payload['scope'] ?? null) !== $scope
|| !is_array($payload['messages'] ?? null)
|| !is_array($payload['metadata'] ?? null)) {
return $this->scopeCache[$cacheKey] = null;
}
$hash = hash(
'sha256',
UserCopySourceCatalog::canonicalJson($payload)
);
if (!hash_equals($descriptor['payload_sha256'], $hash)) {
return $this->scopeCache[$cacheKey] = null;
}
return $this->scopeCache[$cacheKey] = $payload;
}
/**
* @param list<string> $scopes
* @return array{locale:string,generation:null,messages:array<string,string>,metadata:array<string,array<string,mixed>>,fallback_scopes:list<string>}
*/
private function sourceSnapshot(string $locale, array $scopes): array
{
$messages = [];
$metadata = [];
foreach ($scopes as $scope) {
$payload = $this->sourceScope($locale, $scope);
$messages += $payload['messages'];
$metadata += $payload['metadata'];
}
ksort($messages, SORT_STRING);
ksort($metadata, SORT_STRING);
return [
'locale' => $locale,
'generation' => null,
'messages' => $messages,
'metadata' => $metadata,
'fallback_scopes' => $scopes,
];
}
/** @return array{messages:array<string,string>,metadata:array<string,array<string,mixed>>} */
private function sourceScope(string $locale, string $scope): array
{
$messages = [];
$metadata = [];
foreach ($this->source->entriesForScopes([$scope]) as $key => $entry) {
$messages[$key] = $entry['source'];
$metadata[$key] = [
'kind' => $entry['kind'],
'criticality' => $entry['criticality'],
'severity' => $entry['severity'],
'format' => $entry['format'],
'required' => $entry['required'],
'allow_hide' => $entry['allow_hide'],
'hidden' => false,
'translated' => false,
'parameters' => $entry['parameters'],
'source_hash' => $entry['source_hash'],
'placeholder_hash' => $entry['placeholder_hash'],
];
}
return [
'schema' => 1,
'locale' => $locale,
'scope' => $scope,
'messages' => $messages,
'metadata' => $metadata,
];
}
/** @param list<string> $scopes @return list<string> */
private function normalizeScopes(array $scopes): array
{
$known = array_fill_keys($this->source->scopes(), true);
foreach ($this->source->pageScopes() as $pageScopes) {
foreach ($pageScopes as $scope) {
$known[$scope] = true;
}
}
$normalized = ['common' => true];
foreach ($scopes as $scope) {
if (!is_string($scope) || !isset($known[$scope])) {
throw new UserCopyCatalogException(
'Unknown user copy scope.'
);
}
$normalized[$scope] = true;
}
return array_keys($normalized);
}
private function normalizeLocale(string $locale): string
{
$normalized = LocaleCode::canonicalize($locale);
if ($normalized === null) {
throw new UserCopyCatalogException('Invalid user copy locale.');
}
return $normalized;
}
}