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

1169 lines
44 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 Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\ConnectionInterface;
/**
* Administrator editing and publication Module for user-interface copy.
*
* The database is an authoring and audit ledger. Runtime activation happens
* only through UserCopyPublicationStore's atomic current.json switch.
*/
final class UserCopyAdminService
{
/** @var array<string,mixed> */
private readonly array $manifest;
private readonly UserCopySourceCatalog $source;
private readonly UserCopyCatalogCompiler $compiler;
public function __construct(
private readonly ConnectionInterface $database,
array $manifest,
private readonly UserCopyPublicationStore $store
) {
$this->manifest = UserCopyManifest::validate($manifest);
$this->source = new UserCopySourceCatalog($this->manifest);
$this->compiler = new UserCopyCatalogCompiler($this->source);
}
public static function fromApplication(): self
{
$webRoot = dirname(__DIR__, 3);
$manifest = UserCopyManifest::load();
return new self(
DB::connection('default'),
$manifest,
new UserCopyPublicationStore(
$webRoot . '/storage/framework/user-copy'
)
);
}
/** Backward-compatible factory name for command-side callers. */
public static function makeDefault(): self
{
return self::fromApplication();
}
/** @return array<string,mixed> */
public function synchronize(array $actor): array
{
$actorId = $this->authorize($actor);
return (new UserCopyManifestSynchronizer(
$this->database,
$this->manifest
))->synchronize($actorId);
}
/**
* Read model for the administrator workspace.
*
* @param array<string,mixed> $query
* @return array<string,mixed>
*/
public function workspace(array $query = []): array
{
$manifestByKey = [];
foreach ($this->manifest['entries'] as $manifestEntry) {
$manifestByKey[$manifestEntry['key']] = $manifestEntry;
}
$pages = [];
$pageLabels = [];
foreach ($this->manifest['pages'] as $pageKey => $definition) {
$pageLabels[$pageKey] = (string) $definition['label'];
$pages[] = [
'id' => $pageKey,
'label' => (string) $definition['label'],
];
}
$groupIds = [];
foreach ($this->manifest['entries'] as $manifestEntry) {
$groupIds[(string) $manifestEntry['editor_group']] = true;
}
ksort($groupIds, SORT_STRING);
$groups = [];
foreach (array_keys($groupIds) as $groupId) {
$groups[] = [
'id' => $groupId,
'label' => $pageLabels[$groupId]
?? ($groupId === 'common.shared'
? '公共框架' : $groupId),
];
}
$selectedPage = isset($query['page']) && is_string($query['page'])
? trim($query['page']) : '';
if ($selectedPage === '') {
$selectedPage = (string) ($pages[0]['id'] ?? '');
}
if (!isset($this->manifest['pages'][$selectedPage])) {
throw new UserCopyCatalogException('Unknown user copy page.');
}
$channel = 'legacy';
if (array_key_exists('channel', $query)) {
if (!is_string($query['channel'])) {
throw new UserCopyAdminException('文案编辑通道无效。');
}
$candidate = trim($query['channel']);
if ($candidate !== '') {
$channel = $candidate;
}
}
if (!in_array($channel, ['legacy', 'page', 'advanced', 'all'], true)) {
throw new UserCopyAdminException('文案编辑通道无效。');
}
$selectedGroup = '';
if (array_key_exists('group', $query)) {
if (!is_string($query['group'])) {
throw new UserCopyAdminException('文案编辑分组无效。');
}
$selectedGroup = trim($query['group']);
if ($selectedGroup !== '' && !isset($groupIds[$selectedGroup])) {
throw new UserCopyAdminException('文案编辑分组无效。');
}
}
$localeRows = $this->database->table('ui_copy_locales')
->whereNull('source_claim')
->orderByDesc('enabled')
->orderBy('locale')
->get()
->all();
$locales = array_map(
fn ($row): array => $this->localeDto($row),
$localeRows
);
$selectedLocale = isset($query['locale'])
&& is_string($query['locale'])
&& trim($query['locale']) !== ''
? $this->normalizeLocale($query['locale'])
: (string) ($locales[0]['locale'] ?? '');
$selectedLocaleRow = null;
foreach ($localeRows as $row) {
if ((string) $row->locale === $selectedLocale) {
$selectedLocaleRow = $row;
break;
}
}
$allEntryRows = $this->database->table('ui_copy_entries')
->where('state', 'active')
->orderBy('copy_key')
->get()
->all();
$allEntries = [];
foreach ($allEntryRows as $entry) {
$allEntries[(string) $entry->copy_key] = $entry;
}
$projectionReady = true;
try {
$this->assertManifestProjection($allEntries);
} catch (UserCopyAdminException) {
$projectionReady = false;
}
$selectedScopes = array_fill_keys(
$this->manifest['pages'][$selectedPage]['scopes'],
true
);
$entryRows = [];
foreach ($allEntryRows as $entry) {
$copyKey = (string) $entry->copy_key;
$manifestEntry = $manifestByKey[$copyKey] ?? null;
$inSelectedPage = isset($selectedScopes[(string) $entry->scope]);
$matchesChannel = match ($channel) {
'legacy' => $inSelectedPage,
'page' => $inSelectedPage
&& is_array($manifestEntry)
&& $manifestEntry['editor_surface'] === 'page',
'advanced' => is_array($manifestEntry)
&& $manifestEntry['editor_surface'] !== 'page',
'all' => is_array($manifestEntry),
};
if (!$matchesChannel) {
continue;
}
if ($selectedGroup !== ''
&& (!is_array($manifestEntry)
|| $manifestEntry['editor_group'] !== $selectedGroup)) {
continue;
}
$entryRows[] = $entry;
}
$entriesByKey = [];
foreach ($entryRows as $entry) {
$entriesByKey[(string) $entry->copy_key] = $entry;
}
$drafts = [];
$publishedItems = [];
$currentGeneration = null;
$entryIds = array_map(
static fn ($entry): int => (int) $entry->id,
$entryRows
);
if ($selectedLocaleRow !== null) {
if ($entryIds !== []) {
foreach ($this->database->table('ui_copy_drafts')
->where('locale_id', (int) $selectedLocaleRow->id)
->whereIn('entry_id', $entryIds)
->get()->all() as $draft) {
$drafts[(int) $draft->entry_id] = $draft;
}
}
$current = $this->store->current();
$candidate = $current['locales'][$selectedLocale]['generation']
?? null;
if (is_string($candidate)) {
$currentGeneration = $candidate;
$publication = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $selectedLocaleRow->id)
->where('catalog_generation', $candidate)
->where('state', 'ready')
->first();
if ($publication !== null && $entryIds !== []) {
foreach ($this->database->table('ui_copy_revision_items')
->where('publication_id', (int) $publication->id)
->whereIn('entry_id', $entryIds)
->get()->all() as $item) {
$publishedItems[(int) $item->entry_id] = [
'text' => (string) $item->published_text,
'visibility' => (string) $item->visibility,
'version' => (int) $publication->revision,
'publication_key' =>
(string) $publication->publication_key,
'translated' => $item->draft_version !== null,
];
}
}
}
}
$entries = [];
$coverage = [
'total' => count($entryRows),
'published' => 0,
'draft' => 0,
'missing' => 0,
'percent' => 0,
];
$term = isset($query['q']) && is_string($query['q'])
? mb_strtolower(trim($query['q'])) : '';
foreach ($entriesByKey as $copyKey => $entry) {
$draft = $drafts[(int) $entry->id] ?? null;
$published = $publishedItems[(int) $entry->id] ?? null;
$isPublished = is_array($published)
&& ($published['translated'] ?? false) === true;
$state = $isPublished ? 'published'
: ($draft !== null ? 'draft' : 'untranslated');
$coverage[$state === 'untranslated' ? 'missing' : $state]++;
if ($term !== ''
&& !str_contains(mb_strtolower($copyKey), $term)
&& !str_contains(
mb_strtolower((string) $entry->source_text_zh),
$term
)) {
continue;
}
$contract = json_decode(
(string) $entry->placeholder_contract_json,
true
);
$draftDto = $draft === null ? null : $this->draftDto($draft);
$manifestEntry = $manifestByKey[$copyKey] ?? [];
$hidden = $draft !== null
? (string) $draft->visibility === 'hidden'
: (($published['visibility'] ?? 'visible') === 'hidden');
$entries[] = [
'key' => $copyKey,
'scope' => (string) $entry->scope,
'page' => (string) $entry->page_key,
'kind' => (string) $entry->kind,
'format' => (string) $entry->format,
'criticality' => (string) $entry->criticality,
'required' => (bool) $entry->required,
'allow_hide' => (bool) $entry->allow_hide,
'max_length' => (int) $entry->max_length,
'source' => (string) $entry->source_text_zh,
'parameters' => is_array($contract)
? array_keys($contract) : [],
'severity' => is_string($manifestEntry['toast_tone'] ?? null)
? $manifestEntry['toast_tone'] : 'info',
'editor_surface' => is_string(
$manifestEntry['editor_surface'] ?? null
) ? $manifestEntry['editor_surface'] : null,
'editor_group' => is_string(
$manifestEntry['editor_group'] ?? null
) ? $manifestEntry['editor_group'] : null,
'state' => $state,
'hidden' => $hidden,
'draft_version' => $draftDto['version'] ?? 0,
'draft' => $draftDto,
'published' => $published,
];
}
if ($coverage['total'] > 0) {
$coverage['percent'] = round(
($coverage['published'] / $coverage['total']) * 100,
2
);
}
$writeReady = $projectionReady
&& $selectedLocaleRow !== null
&& (int) $selectedLocaleRow->enabled === 1;
$writeBlockReason = '';
if (!$projectionReady) {
$writeBlockReason = 'Manifest 尚未同步,当前仅可查看。';
} elseif ($selectedLocaleRow === null) {
$writeBlockReason = '目标语言尚未登记。';
} elseif ((int) $selectedLocaleRow->enabled !== 1) {
$writeBlockReason = '目标语言已停用。';
}
return [
'schema' => 1,
'pages' => $pages,
'groups' => $groups,
'locales' => array_map(static fn (array $locale): array => [
'id' => $locale['locale'],
'label' => $locale['display_name'],
'enabled' => $locale['enabled'],
], $locales),
'selected' => [
'page' => $selectedPage,
'locale' => $selectedLocale,
],
'authoring' => [
'channel' => $channel,
'group' => $selectedGroup,
],
'coverage' => $coverage,
'entries' => $entries,
'current_generation' => $currentGeneration,
'write_ready' => $writeReady,
'write_block_reason' => $writeBlockReason,
];
}
/** @return array<string,mixed> */
public function history(
string $localeOrCopyKey,
?string $legacyLocale = null
): array
{
$copyKey = $legacyLocale === null ? null : $localeOrCopyKey;
$locale = $legacyLocale ?? $localeOrCopyKey;
$locale = $this->normalizeLocale($locale);
$localeRow = $this->database->table('ui_copy_locales')
->where('locale', $locale)
->whereNull('source_claim')
->first();
if ($localeRow === null) {
return [
'locale' => $locale,
'revisions' => [],
];
}
if ($copyKey === null) {
$rows = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('state', 'ready')
->orderByDesc('revision')
->get()->all();
$revisions = array_map(static fn ($row): array => [
'id' => (string) $row->publication_key,
'publication_key' => (string) $row->publication_key,
'version' => (int) $row->revision,
'generation' => (string) $row->catalog_generation,
'entry_count' => (int) $row->entry_count,
'published_at' => (int) $row->published_at > 0
? gmdate('c', (int) $row->published_at) : null,
], $rows);
return [
'locale' => $locale,
'revisions' => $revisions,
];
}
$entry = $this->database->table('ui_copy_entries')
->where('copy_key', $copyKey)
->first();
if ($entry === null) {
return [
'key' => $copyKey,
'locale' => $locale,
'revisions' => [],
];
}
$rows = $this->database->table('ui_copy_revision_items as item')
->join('ui_copy_publications as publication',
'publication.id', '=', 'item.publication_id')
->where('item.entry_id', (int) $entry->id)
->where('publication.locale_id', (int) $localeRow->id)
->where('publication.state', 'ready')
->orderByDesc('publication.revision')
->get([
'publication.publication_key',
'publication.revision',
'publication.published_at',
'item.published_text',
'item.visibility',
'item.draft_version',
])->all();
$revisions = array_map(static fn ($row): array => [
'id' => (string) $row->publication_key,
'publication_key' => (string) $row->publication_key,
'version' => (int) $row->revision,
'published_at' => (int) $row->published_at > 0
? gmdate('c', (int) $row->published_at) : null,
'text' => (string) $row->published_text,
'hidden' => (string) $row->visibility === 'hidden',
'draft_version' => $row->draft_version === null
? null : (int) $row->draft_version,
], $rows);
return [
'key' => $copyKey,
'locale' => $locale,
'revisions' => $revisions,
];
}
/** @return array<string,mixed> */
public function saveLocale(
array $actor,
string $locale,
string $displayName,
bool $enabled = true
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
if ($locale === 'zh-CN') {
throw new UserCopyAdminException(
'中文源语言由 Manifest 管理,不能在翻译后台修改。',
409
);
}
$displayName = $this->displayName($displayName);
return $this->database->transaction(function () use (
$actorId,
$locale,
$displayName,
$enabled
): array {
$now = time();
$row = $this->database->table('ui_copy_locales')
->where('locale', $locale)
->lockForUpdate()
->first();
$values = [
'display_name' => $displayName,
'enabled' => $enabled ? 1 : 0,
'source_claim' => null,
'updated_by' => $actorId,
'updated_at' => $now,
];
if ($row === null) {
$id = (int) $this->database->table('ui_copy_locales')
->insertGetId($values + [
'locale' => $locale,
'created_by' => $actorId,
'created_at' => $now,
]);
} else {
if ($row->source_claim !== null) {
throw new UserCopyAdminException(
'源语言登记不能改为目标语言。',
409
);
}
$id = (int) $row->id;
$this->database->table('ui_copy_locales')
->where('id', $id)
->update($values);
}
return $this->localeDto(
$this->database->table('ui_copy_locales')->where('id', $id)->first()
);
});
}
/** @return array<string,mixed> */
public function saveDraft(
array $actor,
string $copyKey,
string $locale,
string $text,
string $visibility,
int $expectedVersion
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if ($expectedVersion < 0) {
throw new UserCopyAdminException('草稿版本无效。', 400);
}
if (!in_array($visibility, ['visible', 'hidden'], true)) {
throw new UserCopyAdminException('草稿可见性无效。', 400);
}
if (!mb_check_encoding($text, 'UTF-8')) {
throw new UserCopyAdminException('草稿必须是有效的 UTF-8 文本。', 422);
}
return $this->database->transaction(function () use (
$actorId,
$copyKey,
$locale,
$text,
$visibility,
$expectedVersion
): array {
$localeRow = $this->targetLocale($locale, true);
$entry = $this->database->table('ui_copy_entries')
->where('copy_key', $copyKey)
->where('state', 'active')
->lockForUpdate()
->first();
if ($entry === null) {
throw new UserCopyAdminException(
'词条不存在、已孤立或尚未同步。',
404
);
}
if ($visibility === 'hidden'
&& ((int) $entry->allow_hide !== 1
|| (int) $entry->required === 1
|| (string) $entry->criticality !== 'normal')) {
throw new UserCopyAdminException(
'必需或高风险词条不能隐藏。',
422
);
}
$draft = $this->database->table('ui_copy_drafts')
->where('entry_id', (int) $entry->id)
->where('locale_id', (int) $localeRow->id)
->lockForUpdate()
->first();
$actualVersion = $draft === null
? 0 : (int) $draft->draft_version;
if ($actualVersion !== $expectedVersion) {
throw new UserCopyAdminException(
'草稿已被其他管理员修改,请重新加载。',
409
);
}
$errors = $this->validateDraft(
$copyKey,
$locale,
$text,
$visibility
);
$now = time();
$values = [
'draft_text' => $text,
'draft_hash' => hash('sha256', $text),
'visibility' => $visibility,
'translated_source_hash_zh' => (string) $entry->source_hash_zh,
'translated_placeholder_hash' => (string) $entry->placeholder_hash,
'draft_version' => $actualVersion + 1,
'validation_state' => $errors === [] ? 'valid' : 'invalid',
'validation_errors_json' => UserCopySourceCatalog::canonicalJson(
$errors
),
'updated_by' => $actorId,
'updated_at' => $now,
];
if ($draft === null) {
$id = (int) $this->database->table('ui_copy_drafts')
->insertGetId($values + [
'entry_id' => (int) $entry->id,
'locale_id' => (int) $localeRow->id,
'created_by' => $actorId,
'created_at' => $now,
]);
} else {
$id = (int) $draft->id;
$this->database->table('ui_copy_drafts')
->where('id', $id)
->update($values);
}
return $this->draftDto(
$this->database->table('ui_copy_drafts')->where('id', $id)->first()
);
});
}
/** @return array<string,mixed> */
public function publish(
array $actor,
string $locale,
string $requestIdempotencyKey
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if (preg_match('/\A[a-f0-9]{64}\z/D', $requestIdempotencyKey) !== 1) {
throw new UserCopyAdminException('发布幂等标识无效。', 400);
}
$prepared = $this->database->transaction(function () use (
$actorId,
$locale,
$requestIdempotencyKey
): array {
$localeRow = $this->targetLocale($locale, true);
$existingRequest = $this->database->table('ui_copy_publications')
->where('requested_by', $actorId)
->where('request_idempotency_key', $requestIdempotencyKey)
->lockForUpdate()
->first();
[$entries, $translations, $draftVersions] =
$this->publicationInputs((int) $localeRow->id);
$compiled = $this->compiler->compile($locale, $translations);
$fingerprint = hash(
'sha256',
UserCopySourceCatalog::canonicalJson([
'locale' => $locale,
'generation' => $compiled->generation,
])
);
if ($existingRequest !== null) {
if (!hash_equals(
(string) $existingRequest->request_fingerprint,
$fingerprint
)) {
throw new UserCopyAdminException(
'发布幂等标识已用于其他内容。',
409
);
}
if ((string) $existingRequest->state === 'ready') {
return [
'existing' => true,
'publication' => $existingRequest,
'compiled' => $compiled,
];
}
if (!in_array(
(string) $existingRequest->state,
['preparing', 'failed'],
true
)) {
throw new UserCopyAdminException(
'原发布请求尚未成功完成,请核对后再操作。',
409
);
}
if ((string) $existingRequest->state === 'failed') {
$this->database->table('ui_copy_publications')
->where('id', (int) $existingRequest->id)
->where('state', 'failed')
->update([
'state' => 'preparing',
'error_code' => '',
'updated_at' => time(),
]);
}
return [
'existing' => false,
'publication_id' => (int) $existingRequest->id,
'compiled' => $compiled,
];
}
$sameGeneration = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('catalog_generation', $compiled->generation)
->where('state', 'ready')
->lockForUpdate()
->first();
if ($sameGeneration !== null) {
return [
'existing' => true,
'publication' => $sameGeneration,
'compiled' => $compiled,
];
}
$preparing = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('state', 'preparing')
->lockForUpdate()
->first();
if ($preparing !== null) {
throw new UserCopyAdminException(
'该语言已有发布正在准备,请稍后核对。',
409
);
}
$current = $this->store->current();
$currentGeneration = $current['locales'][$locale]['generation']
?? null;
$previous = is_string($currentGeneration)
? $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('catalog_generation', $currentGeneration)
->where('state', 'ready')
->first()
: null;
$revision = (int) $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->lockForUpdate()
->max('revision') + 1;
$now = time();
$publicationKey = bin2hex(random_bytes(16));
$publicationId = (int) $this->database
->table('ui_copy_publications')->insertGetId([
'publication_key' => $publicationKey,
'locale_id' => (int) $localeRow->id,
'revision' => $revision,
'catalog_generation' => $compiled->generation,
'previous_publication_id' => $previous === null
? null : (int) $previous->id,
'manifest_revision' => (int) $this->manifest['version'],
'manifest_hash' => $this->source->sourceHash(),
'catalog_hash' => '',
'artifact_path' => '',
'entry_count' => count($entries),
'state' => 'preparing',
'request_idempotency_key' => $requestIdempotencyKey,
'request_fingerprint' => $fingerprint,
'requested_by' => $actorId,
'published_by' => null,
'prepared_at' => $now,
'published_at' => 0,
'error_code' => '',
'created_at' => $now,
'updated_at' => $now,
]);
foreach ($entries as $copyKey => $entry) {
$scope = (string) $entry->scope;
$payload = $compiled->scopes[$scope] ?? null;
if (!is_array($payload)
|| !array_key_exists($copyKey, $payload['messages'] ?? [])) {
throw new UserCopyAdminException(
'编译结果缺少词条:' . $copyKey,
500
);
}
$publishedText = (string) $payload['messages'][$copyKey];
$hidden = (bool) ($payload['metadata'][$copyKey]['hidden'] ?? false);
$this->database->table('ui_copy_revision_items')->insert([
'publication_id' => $publicationId,
'entry_id' => (int) $entry->id,
'copy_key' => $copyKey,
'source_text_zh' => (string) $entry->source_text_zh,
'published_text' => $publishedText,
'visibility' => $hidden ? 'hidden' : 'visible',
'source_hash_zh' => (string) $entry->source_hash_zh,
'placeholder_contract_json' =>
(string) $entry->placeholder_contract_json,
'placeholder_hash' => (string) $entry->placeholder_hash,
'published_hash' => hash('sha256', $publishedText),
'manifest_revision' => (int) $entry->manifest_revision,
'draft_version' => $draftVersions[$copyKey] ?? null,
'created_at' => $now,
]);
}
return [
'existing' => false,
'publication_id' => $publicationId,
'compiled' => $compiled,
];
});
/** @var UserCopyCompiledCatalog $compiled */
$compiled = $prepared['compiled'];
if (($prepared['existing'] ?? false) === true) {
$current = $this->store->current();
$pointer = $current['locales'][$locale] ?? [];
return $this->publicationDto(
$prepared['publication'],
is_array($pointer) ? $pointer : []
);
}
$publicationId = (int) $prepared['publication_id'];
try {
$pointer = $this->store->publish($compiled);
} catch (\Throwable $exception) {
try {
$current = $this->store->current();
$active = $current['locales'][$locale] ?? null;
if (!is_array($active)
|| ($active['generation'] ?? null) !== $compiled->generation) {
$this->database->table('ui_copy_publications')
->where('id', $publicationId)
->where('state', 'preparing')
->update([
'state' => 'failed',
'error_code' => 'publication_store_failed',
'updated_at' => time(),
]);
throw new UserCopyAdminException(
'编译目录发布失败,原运行版本保持不变。',
503,
$exception
);
}
$this->store->validateGeneration($compiled->generation);
$pointer = $active;
} catch (UserCopyAdminException $known) {
throw $known;
} catch (\Throwable $reconciliationFailure) {
throw new UserCopyAdminException(
'发布结果无法确认,请保留原幂等标识核对,切勿创建新发布请求。',
503,
$reconciliationFailure
);
}
}
$publishedAt = time();
$updated = $this->database->table('ui_copy_publications')
->where('id', $publicationId)
->where('state', 'preparing')
->update([
'catalog_hash' => (string) $compiled->manifest['catalog_sha256'],
'artifact_path' => 'generations/' . $compiled->generation,
'state' => 'ready',
'published_by' => $actorId,
'published_at' => $publishedAt,
'updated_at' => $publishedAt,
]);
if ($updated !== 1) {
throw new UserCopyAdminException(
'运行版本已切换,但发布账本最终化失败,请人工核对。',
503
);
}
$publication = $this->database->table('ui_copy_publications')
->where('id', $publicationId)
->first();
return $this->publicationDto($publication, $pointer);
}
/** @return array<string,mixed> */
public function rollback(
array $actor,
string $locale,
string $publicationKey
): array {
$this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if (preg_match('/\A[a-f0-9]{32}\z/D', $publicationKey) !== 1) {
throw new UserCopyAdminException('回滚版本标识无效。', 400);
}
$publication = $this->database->transaction(function () use (
$locale,
$publicationKey
) {
$localeRow = $this->targetLocale($locale, true);
$row = $this->database->table('ui_copy_publications')
->where('publication_key', $publicationKey)
->where('locale_id', (int) $localeRow->id)
->where('state', 'ready')
->lockForUpdate()
->first();
if ($row === null) {
throw new UserCopyAdminException('可回滚版本不存在。', 404);
}
if (!hash_equals(
(string) $row->manifest_hash,
$this->source->sourceHash()
)) {
throw new UserCopyAdminException(
'该版本属于旧 Manifest,不能恢复为当前运行版本。',
409
);
}
return $row;
});
$pointer = $this->store->rollback(
$locale,
(string) $publication->catalog_generation
);
return $this->publicationDto($publication, $pointer);
}
/**
* @return array{0:array<string,object>,1:array<string,string|array<string,mixed>>,2:array<string,int>}
*/
private function publicationInputs(int $localeId): array
{
$databaseEntries = $this->database->table('ui_copy_entries')
->where('state', 'active')
->orderBy('copy_key')
->lockForUpdate()
->get()
->all();
$entries = [];
foreach ($databaseEntries as $entry) {
$entries[(string) $entry->copy_key] = $entry;
}
$this->assertManifestProjection($entries);
$drafts = $this->database->table('ui_copy_drafts')
->where('locale_id', $localeId)
->whereIn('entry_id', array_map(
static fn ($entry): int => (int) $entry->id,
$databaseEntries
))
->lockForUpdate()
->get()
->all();
$draftsByEntry = [];
foreach ($drafts as $draft) {
$draftsByEntry[(int) $draft->entry_id] = $draft;
}
$translations = [];
$draftVersions = [];
foreach ($entries as $copyKey => $entry) {
$draft = $draftsByEntry[(int) $entry->id] ?? null;
if ($draft === null) {
continue;
}
$currentContract = hash_equals(
(string) $draft->translated_source_hash_zh,
(string) $entry->source_hash_zh
) && hash_equals(
(string) $draft->translated_placeholder_hash,
(string) $entry->placeholder_hash
);
if (!$currentContract || (string) $draft->validation_state !== 'valid') {
if (!$currentContract) {
$this->database->table('ui_copy_drafts')
->where('id', (int) $draft->id)
->update([
'validation_state' => 'stale',
'validation_errors_json' =>
UserCopySourceCatalog::canonicalJson([
'source_contract_changed',
]),
'updated_at' => time(),
]);
}
throw new UserCopyAdminException(
'存在无效或过期草稿,不能发布:' . $copyKey,
422
);
}
$translations[$copyKey] = (string) $draft->visibility === 'hidden'
? ['hidden' => true]
: (string) $draft->draft_text;
$draftVersions[$copyKey] = (int) $draft->draft_version;
}
return [$entries, $translations, $draftVersions];
}
/** @param array<string,object> $databaseEntries */
private function assertManifestProjection(array $databaseEntries): void
{
$sourceEntries = $this->source->entries();
if (array_keys($databaseEntries) !== array_keys($sourceEntries)) {
throw new UserCopyAdminException(
'Manifest 尚未同步,不能发布。',
409
);
}
$manifestByKey = [];
foreach ($this->manifest['entries'] as $entry) {
$manifestByKey[$entry['key']] = $entry;
}
foreach ($sourceEntries as $copyKey => $sourceEntry) {
$databaseEntry = $databaseEntries[$copyKey];
$placeholderHash = hash(
'sha256',
UserCopySourceCatalog::canonicalJson(
$manifestByKey[$copyKey]['parameters']
)
);
if (!hash_equals(
(string) $databaseEntry->source_hash_zh,
hash('sha256', $sourceEntry['source'])
) || !hash_equals(
(string) $databaseEntry->placeholder_hash,
$placeholderHash
) || (int) $databaseEntry->manifest_revision
!== (int) $this->manifest['version']) {
throw new UserCopyAdminException(
'Manifest 词条合同尚未同步:' . $copyKey,
409
);
}
}
}
/** @return list<string> */
private function validateDraft(
string $copyKey,
string $locale,
string $text,
string $visibility
): array {
try {
$this->compiler->compile($locale, [
$copyKey => $visibility === 'hidden'
? ['hidden' => true]
: $text,
]);
return [];
} catch (UserCopyCatalogException $exception) {
return [$exception->getMessage()];
}
}
private function targetLocale(string $locale, bool $lock): object
{
$query = $this->database->table('ui_copy_locales')
->where('locale', $locale);
if ($lock) {
$query->lockForUpdate();
}
$row = $query->first();
if ($row === null || (int) $row->enabled !== 1) {
throw new UserCopyAdminException('目标语言未启用。', 409);
}
if ($row->source_claim !== null) {
throw new UserCopyAdminException('源语言不能保存翻译草稿。', 409);
}
return $row;
}
private function assertTargetLocale(string $locale): void
{
if ($locale === 'zh-CN') {
throw new UserCopyAdminException('中文基线不能作为翻译草稿。', 409);
}
}
private function authorize(array $actor): int
{
$actorId = (int) ($actor['user_id'] ?? 0);
if ($actorId < 1) {
throw new UserCopyAdminException('请先登录。', 401);
}
if (!($actor['is_admin'] ?? false)) {
throw new UserCopyAdminException('只有管理员可以管理界面文案。', 403);
}
if (!($actor['is_super_admin'] ?? false)
|| !($actor['can_manage'] ?? false)) {
throw new UserCopyAdminException(
'只有超级管理员可以修改或发布界面文案。',
403
);
}
return $actorId;
}
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 UserCopyAdminException('语言代码无效。', 400);
}
$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);
}
private function displayName(string $displayName): string
{
$displayName = trim($displayName);
if ($displayName === '' || mb_strlen($displayName) > 128
|| preg_match('/[\x00-\x1F\x7F]/u', $displayName) === 1) {
throw new UserCopyAdminException('语言显示名称无效。', 422);
}
return $displayName;
}
/** @return array<string,mixed> */
private function localeDto(?object $row): array
{
if ($row === null) {
throw new UserCopyAdminException('语言保存结果不存在。', 500);
}
return [
'id' => (int) $row->id,
'locale' => (string) $row->locale,
'display_name' => (string) $row->display_name,
'enabled' => (bool) $row->enabled,
'source' => $row->source_claim !== null,
];
}
/** @return array<string,mixed> */
private function draftDto(?object $row): array
{
if ($row === null) {
throw new UserCopyAdminException('草稿保存结果不存在。', 500);
}
try {
$errors = json_decode(
(string) $row->validation_errors_json,
true,
32,
JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
$errors = ['validation_result_corrupt'];
}
return [
'id' => (int) $row->id,
'entry_id' => (int) $row->entry_id,
'locale_id' => (int) $row->locale_id,
'text' => (string) $row->draft_text,
'visibility' => (string) $row->visibility,
'version' => (int) $row->draft_version,
'validation_state' => (string) $row->validation_state,
'validation_errors' => is_array($errors) ? $errors : [],
];
}
/** @return array<string,mixed> */
private function publicationDto(?object $row, array $pointer): array
{
if ($row === null) {
throw new UserCopyAdminException('发布结果不存在。', 500);
}
return [
'id' => (int) $row->id,
'publication_key' => (string) $row->publication_key,
'revision' => (int) $row->revision,
'generation' => (string) $row->catalog_generation,
'state' => (string) $row->state,
'entry_count' => (int) $row->entry_count,
'current' => $pointer,
];
}
}