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

327 lines
12 KiB
PHP

<?php
namespace App\Services\UserCopy;
/**
* 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));
}
/** @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
{
$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;
}
$pointer = is_array($current)
&& ($current['schema'] ?? null) === 1
&& is_array($current['locales'] ?? null)
&& 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
{
$locale = str_replace('_', '-', trim($locale));
if (preg_match(
'/\A[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*\z/D',
$locale
) !== 1) {
throw new UserCopyCatalogException('Invalid user copy locale.');
}
$parts = explode('-', $locale);
$parts[0] = strtolower($parts[0]);
for ($index = 1; $index < count($parts); $index++) {
$parts[$index] = strlen($parts[$index]) === 2
? strtoupper($parts[$index]) : $parts[$index];
}
return implode('-', $parts);
}
}