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

358 lines
12 KiB
PHP

<?php
namespace App\Services\UserCopy;
/**
* Normalized, immutable view of the source-owned copy manifest.
*
* The catalog accepts either an iterable of entries or a future manifest
* object exposing entries() and pageScopes(). Runtime and publication code do
* not need to know which source-manifest implementation owns those entries.
*/
final class UserCopySourceCatalog
{
/** @var array<string,array<string,mixed>> */
private array $entries;
/** @var array<string,list<string>> */
private array $pageScopes;
/**
* @param iterable<int|string,array<string,mixed>>|object $manifest
*/
public function __construct(iterable|object $manifest)
{
[$entries, $pageScopes] = $this->readManifest($manifest);
$this->entries = $this->normalizeEntries($entries);
$this->pageScopes = $this->normalizePageScopes($pageScopes);
}
/** @return array<string,array<string,mixed>> */
public function entries(): array
{
return $this->entries;
}
/** @return array<string,list<string>> */
public function pageScopes(): array
{
return $this->pageScopes;
}
/** @return list<string> */
public function scopes(): array
{
$scopes = [];
foreach ($this->entries as $entry) {
$scopes[$entry['scope']] = true;
}
if (isset($this->pageScopes)) {
foreach ($this->pageScopes as $pageScopes) {
foreach ($pageScopes as $scope) {
$scopes[$scope] = true;
}
}
}
$result = array_keys($scopes);
sort($result, SORT_STRING);
return $result;
}
/** @return array<string,array<string,mixed>> */
public function entriesForScopes(array $scopes): array
{
$wanted = array_fill_keys($scopes, true);
return array_filter(
$this->entries,
static fn (array $entry): bool => isset($wanted[$entry['scope']])
);
}
public function sourceHash(): string
{
return hash('sha256', self::canonicalJson([
'entries' => $this->entries,
'page_scopes' => $this->pageScopes,
]));
}
/**
* @param iterable<int|string,array<string,mixed>>|object $manifest
* @return array{0:iterable<int|string,array<string,mixed>>,1:array<mixed>}
*/
private function readManifest(iterable|object $manifest): array
{
if (is_object($manifest) && method_exists($manifest, 'entries')) {
$entries = $manifest->entries();
if (!is_iterable($entries)) {
throw new UserCopyCatalogException(
'User copy manifest entries must be iterable.'
);
}
$pageScopes = method_exists($manifest, 'pageScopes')
? $manifest->pageScopes() : [];
if (!is_array($pageScopes)) {
throw new UserCopyCatalogException(
'User copy manifest page scopes must be an array.'
);
}
return [$entries, $pageScopes];
}
if (is_array($manifest)
&& isset($manifest['entries'])
&& is_array($manifest['entries'])) {
$pageScopes = [];
foreach (($manifest['pages'] ?? []) as $page => $definition) {
if (is_string($page) && is_array($definition)
&& is_array($definition['scopes'] ?? null)) {
$pageScopes[$page] = $definition['scopes'];
}
}
return [$manifest['entries'], $pageScopes];
}
if (is_iterable($manifest)) {
return [$manifest, []];
}
throw new UserCopyCatalogException(
'User copy manifest must be iterable or expose entries().'
);
}
/**
* @param iterable<int|string,array<string,mixed>> $entries
* @return array<string,array<string,mixed>>
*/
private function normalizeEntries(iterable $entries): array
{
$normalized = [];
foreach ($entries as $index => $entry) {
if (!is_array($entry)) {
throw new UserCopyCatalogException(
'Every user copy manifest entry must be an array.'
);
}
$key = $this->requiredString(
$entry,
['key', 'copy_key'],
is_string($index) ? $index : null
);
if (preg_match('/\A[a-z0-9][a-z0-9._-]{1,190}\z/D', $key) !== 1) {
throw new UserCopyCatalogException(
'Invalid user copy key: ' . $key
);
}
if (isset($normalized[$key])) {
throw new UserCopyCatalogException(
'Duplicate user copy key: ' . $key
);
}
$scope = $this->requiredString($entry, ['scope']);
if (preg_match('/\A[a-z0-9][a-z0-9._-]{0,63}\z/D', $scope) !== 1) {
throw new UserCopyCatalogException(
'Invalid user copy scope for ' . $key . '.'
);
}
$source = $this->requiredString(
$entry,
['source', 'source_text', 'default_zh']
);
$kind = $this->optionalString($entry, ['kind'], 'text');
$criticality = $this->optionalString(
$entry,
['criticality'],
'normal'
);
$format = $this->optionalString(
$entry,
['format'],
'plain_text'
);
if (!in_array($format, ['plain_text', 'icu'], true)) {
throw new UserCopyCatalogException(
'Unsupported user copy format: ' . $key
);
}
$declaredParameters = $entry['parameters']
?? $entry['placeholders']
?? $entry['placeholder_contract']
?? [];
if (is_array($declaredParameters)
&& !array_is_list($declaredParameters)) {
$declaredParameters = array_keys($declaredParameters);
}
if (!is_array($declaredParameters)) {
throw new UserCopyCatalogException(
'User copy placeholders must be an array: ' . $key
);
}
$parameters = [];
foreach ($declaredParameters as $parameter) {
if (!is_string($parameter)
|| preg_match(
'/\A[A-Za-z_][A-Za-z0-9_.-]*\z/D',
$parameter
) !== 1) {
throw new UserCopyCatalogException(
'Invalid user copy placeholder for ' . $key . '.'
);
}
$parameters[$parameter] = true;
}
$parameters = array_keys($parameters);
sort($parameters, SORT_STRING);
$maxLength = $entry['max_length'] ?? 4000;
if (!is_int($maxLength) || $maxLength < 1 || $maxLength > 20000) {
throw new UserCopyCatalogException(
'Invalid user copy maximum length for ' . $key . '.'
);
}
$severity = 'info';
if (is_string($entry['severity'] ?? null)
&& trim($entry['severity']) !== '') {
$severity = $entry['severity'];
} elseif (is_string($entry['toast_tone'] ?? null)
&& trim($entry['toast_tone']) !== '') {
$severity = $entry['toast_tone'];
}
$normalized[$key] = [
'key' => $key,
'scope' => $scope,
'source' => $source,
'kind' => $kind,
'criticality' => $criticality,
'severity' => $severity,
'format' => $format,
'required' => (bool) ($entry['required']
?? ($criticality !== 'normal')),
'allow_hide' => (bool) ($entry['allow_hide'] ?? false),
'max_length' => $maxLength,
'parameters' => $parameters,
'source_hash' => hash('sha256', $source),
'placeholder_hash' => hash(
'sha256',
self::canonicalJson($parameters)
),
];
}
ksort($normalized, SORT_STRING);
return $normalized;
}
/** @param array<mixed> $pageScopes @return array<string,list<string>> */
private function normalizePageScopes(array $pageScopes): array
{
$normalized = [];
foreach ($pageScopes as $page => $scopes) {
if (!is_string($page)
|| preg_match('/\A[a-z0-9][a-z0-9._-]{0,95}\z/D', $page) !== 1
|| !is_array($scopes)) {
throw new UserCopyCatalogException(
'Invalid user copy page scope declaration.'
);
}
$clean = [];
foreach ($scopes as $scope) {
if (!is_string($scope)
|| preg_match(
'/\A[a-z0-9][a-z0-9._-]{0,63}\z/D',
$scope
) !== 1) {
throw new UserCopyCatalogException(
'Invalid user copy scope on page ' . $page . '.'
);
}
$clean[$scope] = true;
}
$list = array_keys($clean);
sort($list, SORT_STRING);
$normalized[$page] = $list;
}
ksort($normalized, SORT_STRING);
return $normalized;
}
/** @param array<string,mixed> $entry @param list<string> $aliases */
private function requiredString(
array $entry,
array $aliases,
?string $fallback = null
): string {
foreach ($aliases as $alias) {
if (array_key_exists($alias, $entry)) {
$value = $entry[$alias];
if (is_string($value) && trim($value) !== '') {
return $value;
}
break;
}
}
if ($fallback !== null && trim($fallback) !== '') {
return $fallback;
}
throw new UserCopyCatalogException(
'User copy manifest is missing ' . implode('/', $aliases) . '.'
);
}
/** @param array<string,mixed> $entry @param list<string> $aliases */
private function optionalString(
array $entry,
array $aliases,
string $fallback
): string {
foreach ($aliases as $alias) {
if (array_key_exists($alias, $entry)) {
$value = $entry[$alias];
if (is_string($value) && trim($value) !== '') {
return $value;
}
throw new UserCopyCatalogException(
'User copy manifest field ' . $alias
. ' must be a non-empty string.'
);
}
}
return $fallback;
}
/** @param mixed $value */
public static function canonicalJson($value): string
{
$encoded = json_encode(
self::canonicalize($value),
JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
| JSON_THROW_ON_ERROR
);
return $encoded;
}
/** @param mixed $value @return mixed */
private static function canonicalize($value)
{
if (!is_array($value)) {
return $value;
}
if (array_is_list($value)) {
return array_map([self::class, 'canonicalize'], $value);
}
ksort($value, SORT_STRING);
foreach ($value as $key => $child) {
$value[$key] = self::canonicalize($child);
}
return $value;
}
}