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/tests/UserCopyAdminServiceTest.php

582 lines
23 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyAdminException;
use App\Services\UserCopy\UserCopyAdminService;
use App\Services\UserCopy\UserCopyAuthoringProjection;
use App\Services\UserCopy\UserCopyManifestSynchronizer;
use App\Services\UserCopy\UserCopyPublicationStore;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$reject = static function (
callable $callback,
int $status,
string $message
) use ($assert): void {
try {
$callback();
} catch (UserCopyAdminException $exception) {
$assert($exception->httpStatus === $status,
$message . ' Wrong status: ' . $exception->httpStatus);
return;
}
throw new RuntimeException($message);
};
$removeTree = static function (string $directory): void {
if (!is_dir($directory)) {
return;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$directory,
FilesystemIterator::SKIP_DOTS
),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $item) {
$item->isDir()
? rmdir($item->getPathname())
: unlink($item->getPathname());
}
rmdir($directory);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$database = $capsule->getConnection('default');
$schema = $database->getSchemaBuilder();
$schema->create('ui_copy_locales', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('locale', 32)->unique();
$table->string('display_name', 128);
$table->boolean('enabled')->default(false);
$table->unsignedTinyInteger('source_claim')->nullable()->unique();
$table->unsignedBigInteger('created_by')->default(0);
$table->unsignedBigInteger('updated_by')->default(0);
$table->unsignedBigInteger('created_at')->default(0);
$table->unsignedBigInteger('updated_at')->default(0);
});
$schema->create('ui_copy_entries', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('copy_key', 191)->unique();
$table->string('scope', 64);
$table->string('page_key', 96);
$table->string('location', 191);
$table->string('kind', 32);
$table->string('format', 24);
$table->string('criticality', 16);
$table->boolean('required');
$table->boolean('allow_hide');
$table->unsignedInteger('max_length');
$table->longText('source_text_zh');
$table->string('source_hash_zh', 64);
$table->text('placeholder_contract_json');
$table->string('placeholder_hash', 64);
$table->unsignedBigInteger('manifest_revision');
$table->string('state', 16);
$table->unsignedBigInteger('first_seen_at');
$table->unsignedBigInteger('last_seen_at');
$table->unsignedBigInteger('created_by');
$table->unsignedBigInteger('updated_by');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('ui_copy_drafts', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('entry_id');
$table->unsignedBigInteger('locale_id');
$table->longText('draft_text');
$table->string('draft_hash', 64);
$table->string('visibility', 16);
$table->string('translated_source_hash_zh', 64);
$table->string('translated_placeholder_hash', 64);
$table->unsignedBigInteger('draft_version');
$table->string('validation_state', 16);
$table->text('validation_errors_json');
$table->unsignedBigInteger('created_by');
$table->unsignedBigInteger('updated_by');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unique(['entry_id', 'locale_id']);
});
$schema->create('ui_copy_publications', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('publication_key', 32)->unique();
$table->unsignedBigInteger('locale_id');
$table->unsignedBigInteger('revision');
$table->string('catalog_generation', 66);
$table->unsignedBigInteger('previous_publication_id')->nullable();
$table->unsignedBigInteger('manifest_revision');
$table->string('manifest_hash', 64);
$table->string('catalog_hash', 64)->default('');
$table->string('artifact_path', 512)->default('');
$table->unsignedInteger('entry_count')->default(0);
$table->string('state', 16);
$table->string('request_idempotency_key', 64);
$table->string('request_fingerprint', 64);
$table->unsignedBigInteger('requested_by');
$table->unsignedBigInteger('published_by')->nullable();
$table->unsignedBigInteger('prepared_at');
$table->unsignedBigInteger('published_at');
$table->string('error_code', 128)->default('');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unique(['locale_id', 'revision']);
$table->unique(['locale_id', 'catalog_generation']);
$table->unique(['requested_by', 'request_idempotency_key']);
});
$schema->create('ui_copy_revision_items', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('publication_id');
$table->unsignedBigInteger('entry_id');
$table->string('copy_key', 191);
$table->longText('source_text_zh');
$table->longText('published_text');
$table->string('visibility', 16);
$table->string('source_hash_zh', 64);
$table->text('placeholder_contract_json');
$table->string('placeholder_hash', 64);
$table->string('published_hash', 64);
$table->unsignedBigInteger('manifest_revision');
$table->unsignedBigInteger('draft_version')->nullable();
$table->unsignedBigInteger('created_at');
$table->unique(['publication_id', 'entry_id']);
$table->unique(['publication_id', 'copy_key']);
});
$manifest = [
'version' => 1,
'pages' => [
'test.page' => ['label' => '测试页面', 'scopes' => ['test']],
],
'entries' => [
[
'key' => 'test.count', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'description',
'source' => '{count, plural, =0 {暂无项目} other {# 个项目}}',
'format' => 'icu', 'parameters' => ['count' => 'integer'],
'criticality' => 'required', 'allow_hide' => false,
'toast_tone' => null,
'editor_surface' => 'page', 'editor_group' => 'test.page',
],
[
'key' => 'test.help', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'help',
'source' => '可选说明', 'format' => 'plain_text',
'parameters' => [], 'criticality' => 'normal',
'allow_hide' => true, 'toast_tone' => null,
'editor_surface' => 'page', 'editor_group' => 'test.page',
],
[
'key' => 'test.title', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'title',
'source' => '中文标题', 'format' => 'plain_text',
'parameters' => [], 'criticality' => 'required',
'allow_hide' => false, 'toast_tone' => null,
'editor_surface' => 'page', 'editor_group' => 'test.page',
],
[
'key' => 'test.warning', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'warning',
'source' => '高风险操作提醒', 'format' => 'plain_text',
'parameters' => [], 'criticality' => 'critical',
'allow_hide' => false, 'toast_tone' => null,
'editor_surface' => 'feedback', 'editor_group' => 'test.advanced',
],
[
'key' => 'test.shared', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'button',
'source' => '公共操作', 'format' => 'plain_text',
'parameters' => [], 'criticality' => 'required',
'allow_hide' => false, 'toast_tone' => null,
'editor_surface' => 'shared', 'editor_group' => 'common.shared',
],
],
];
$root = sys_get_temp_dir() . '/virt-user-copy-admin-'
. bin2hex(random_bytes(8));
mkdir($root, 0750, true);
$super = [
'user_id' => 9,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
];
try {
$sync = new UserCopyManifestSynchronizer($database, $manifest);
$syncResult = $sync->synchronize((int) $super['user_id']);
$assert($syncResult['active'] === 5
&& $syncResult['created'] === 5
&& $database->table('ui_copy_entries')->where('state', 'active')->count() === 5,
'Manifest synchronization did not create the active source projection.');
$sourceLocale = $database->table('ui_copy_locales')
->where('locale', 'zh-CN')->first();
$assert($sourceLocale !== null
&& (int) $sourceLocale->source_claim === 1
&& (int) $sourceLocale->enabled === 1,
'Manifest synchronization did not claim the Chinese source locale.');
$countEntry = $database->table('ui_copy_entries')
->where('copy_key', 'test.count')->first();
$assert($countEntry !== null
&& json_decode((string) $countEntry->placeholder_contract_json, true)
=== ['count' => 'integer'],
'Placeholder type contract was not projected into the ledger.');
$store = new UserCopyPublicationStore($root);
$service = new UserCopyAdminService($database, $manifest, $store);
$resynchronized = $service->synchronize($super);
$assert($resynchronized['active'] === 5
&& $resynchronized['created'] === 0,
'Administrator service could not idempotently synchronize the Manifest.');
$locale = $service->saveLocale($super, 'en', '目标语言', true);
$assert($locale['locale'] === 'en' && $locale['enabled'] === true,
'Target locale registry was not saved.');
$reject(
static fn () => $service->saveLocale($super, 'zh-CN', '错误', true),
409,
'Source locale was editable through the target-locale registry.'
);
$warning = $service->saveDraft(
$super, 'test.warning', 'en', '目标语言高风险提醒', 'visible', 0
);
$assert($warning['validation_state'] === 'valid'
&& $warning['version'] === 1,
'Valid safety copy was not saved as a validated draft.');
$reject(
static fn () => $service->saveDraft(
$super, 'test.warning', 'en', '', 'hidden', 1
),
422,
'Critical copy was allowed to become hidden.'
);
$assert((int) $database->table('ui_copy_drafts')
->where('id', $warning['id'])->value('draft_version') === 1,
'Rejected critical-copy hiding mutated its optimistic version.');
$invalid = $service->saveDraft(
$super,
'test.count',
'en',
'{total, plural, =0 {暂无项目} other {# 个项目}}',
'visible',
0
);
$assert($invalid['validation_state'] === 'invalid'
&& $invalid['validation_errors'] !== [],
'Placeholder mismatch was not retained as an invalid draft.');
$reject(
static fn () => $service->publish($super, 'en', str_repeat('a', 64)),
422,
'An invalid draft was published.'
);
$validCount = $service->saveDraft(
$super,
'test.count',
'en',
'{count, plural, =0 {目标语言暂无项目} other {目标语言 # 个项目}}',
'visible',
1
);
$assert($validCount['validation_state'] === 'valid'
&& $validCount['version'] === 2,
'Corrected ICU draft did not become valid.');
$titleOne = $service->saveDraft(
$super, 'test.title', 'en', '目标语言标题一', 'visible', 0
);
$service->saveDraft($super, 'test.help', 'en', '', 'hidden', 0);
$reject(
static fn () => $service->saveDraft(
$super, 'test.title', 'en', '陈旧覆盖', 'visible', 0
),
409,
'A stale optimistic draft update was accepted.'
);
$first = $service->publish($super, 'en', str_repeat('b', 64));
$assert($first['state'] === 'ready'
&& $first['entry_count'] === 5
&& is_file($root . '/current.json')
&& $database->table('ui_copy_revision_items')
->where('publication_id', $first['id'])->count() === 5,
'First publication did not freeze all revision items and switch current.json.');
$hiddenItem = $database->table('ui_copy_revision_items')
->where('publication_id', $first['id'])
->where('copy_key', 'test.help')->first();
$assert($hiddenItem !== null
&& $hiddenItem->visibility === 'hidden'
&& $hiddenItem->published_text === '',
'Allowed hidden copy was not frozen in the publication ledger.');
$fallbackItem = $database->table('ui_copy_revision_items')
->where('publication_id', $first['id'])
->where('copy_key', 'test.warning')->first();
$assert($fallbackItem !== null
&& $fallbackItem->published_text === '目标语言高风险提醒',
'Validated safety translation was not frozen.');
$workspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
]);
$assert($workspace['schema'] === 1
&& $workspace['selected'] === [
'page' => 'test.page',
'locale' => 'en',
]
&& $workspace['authoring'] === [
'channel' => 'legacy',
'group' => '',
]
&& $workspace['groups'] === [
[
'id' => 'common.shared',
'label' => '公共框架',
],
[
'id' => 'test.advanced',
'label' => 'test.advanced',
],
[
'id' => 'test.page',
'label' => '测试页面',
],
]
&& $workspace['coverage']['published'] === 4
&& $workspace['coverage']['missing'] === 1
&& count($workspace['entries']) === 5
&& $workspace['write_ready'] === true
&& $workspace['current_generation'] === $first['generation'],
'Administrator workspace omitted selection, coverage or current generation.');
$pageWorkspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'page',
]);
$assert($pageWorkspace['authoring']['channel'] === 'page'
&& $pageWorkspace['coverage']['total'] === 3
&& $pageWorkspace['coverage']['published'] === 3
&& array_column($pageWorkspace['entries'], 'key') === [
'test.count', 'test.help', 'test.title',
],
'Page editing channel did not isolate visible page copy.');
$directPageProjection = (new UserCopyAuthoringProjection($manifest))
->project(
[
'page' => 'test.page',
'locale' => 'en',
'channel' => 'page',
],
$database->table('ui_copy_entries')
->where('state', 'active')
->orderBy('copy_key')
->get()
->all()
);
$assert(
array_map(
static fn (object $row): string => (string) $row->copy_key,
$directPageProjection['entry_rows']
) === array_column($pageWorkspace['entries'], 'key')
&& $directPageProjection['pages'] === $pageWorkspace['pages']
&& $directPageProjection['groups'] === $pageWorkspace['groups']
&& $directPageProjection['selected_page']
=== $pageWorkspace['selected']['page']
&& $directPageProjection['channel']
=== $pageWorkspace['authoring']['channel']
&& $directPageProjection['selected_group']
=== $pageWorkspace['authoring']['group'],
'Administrator service drifted from the pure authoring projection.'
);
$advancedWorkspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'advanced',
'group' => 'test.advanced',
]);
$assert($advancedWorkspace['authoring'] === [
'channel' => 'advanced',
'group' => 'test.advanced',
]
&& $advancedWorkspace['coverage']['total'] === 1
&& $advancedWorkspace['coverage']['published'] === 1
&& count($advancedWorkspace['entries']) === 1
&& $advancedWorkspace['entries'][0]['key'] === 'test.warning'
&& $advancedWorkspace['entries'][0]['editor_surface'] === 'feedback'
&& $advancedWorkspace['entries'][0]['editor_group'] === 'test.advanced',
'Advanced editing channel did not isolate non-page copy.');
$emptyPageWorkspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'page',
'group' => 'test.advanced',
]);
$assert($emptyPageWorkspace['entries'] === []
&& $emptyPageWorkspace['coverage']['total'] === 0
&& $emptyPageWorkspace['current_generation'] === $first['generation']
&& $emptyPageWorkspace['write_ready'] === true,
'Empty authoring projection lost the locale publication state.');
$sharedWorkspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'shared',
]);
$assert($sharedWorkspace['authoring']['channel'] === 'shared'
&& $sharedWorkspace['coverage']['total'] === 1
&& $sharedWorkspace['coverage']['missing'] === 1
&& array_column($sharedWorkspace['entries'], 'key') === [
'test.shared',
],
'Shared editing channel did not isolate reusable copy.');
$allWorkspace = $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'all',
]);
$assert($allWorkspace['coverage']['total'] === 5
&& count($allWorkspace['entries']) === 5,
'All-copy authoring channel did not return the complete projection.');
$reject(
static fn () => $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'invalid',
]),
422,
'Unknown authoring channel was accepted.'
);
$reject(
static fn () => $service->workspace([
'page' => 'test.page',
'locale' => 'en',
'channel' => 'advanced',
'group' => 'missing.group',
]),
422,
'Unknown authoring group was accepted.'
);
$titleTwo = $service->saveDraft(
$super,
'test.title',
'en',
'目标语言标题二',
'visible',
(int) $titleOne['version']
);
$second = $service->publish($super, 'en', str_repeat('c', 64));
$assert($second['revision'] === 2
&& $second['generation'] !== $first['generation'],
'Changed drafts did not create a second immutable publication.');
$database->table('ui_copy_publications')
->where('id', $second['id'])
->update([
'state' => 'preparing',
'catalog_hash' => '',
'artifact_path' => '',
'published_by' => null,
'published_at' => 0,
]);
$resumed = $service->publish($super, 'en', str_repeat('c', 64));
$assert($resumed['id'] === $second['id']
&& $resumed['state'] === 'ready'
&& $resumed['generation'] === $second['generation'],
'An exact preparing publication could not be reconciled and finalized.');
$service->saveDraft(
$super,
'test.title',
'en',
'目标语言标题一',
'visible',
(int) $titleTwo['version']
);
$retryFirst = $service->publish($super, 'en', str_repeat('b', 64));
$activeAfterOldRetry = $store->current();
$assert($retryFirst['id'] === $first['id']
&& $activeAfterOldRetry['locales']['en']['generation']
=== $second['generation'],
'Retrying an older ready request changed the active generation.');
$localeHistory = $service->history('en');
$entryHistory = $service->history('test.title', 'en');
$assert(count($localeHistory['revisions']) === 2
&& $localeHistory['revisions'][0]['version'] === 2
&& count($entryHistory['revisions']) === 2
&& $entryHistory['revisions'][0]['text'] === '目标语言标题二',
'Locale or focused entry publication history is incomplete.');
$rolledBack = $service->rollback(
$super, 'en', (string) $first['publication_key']
);
$current = json_decode(
(string) file_get_contents($root . '/current.json'),
true,
32,
JSON_THROW_ON_ERROR
);
$assert($rolledBack['generation'] === $first['generation']
&& $current['locales']['en']['generation'] === $first['generation']
&& $database->table('ui_copy_publications')->count() === 2,
'Rollback did not switch the sole runtime pointer to a retained generation.');
$changedManifest = $manifest;
$changedManifest['entries'] = array_values(array_filter(
$changedManifest['entries'],
static fn (array $entry): bool => $entry['key'] !== 'test.help'
));
foreach ($changedManifest['entries'] as &$entry) {
if ($entry['key'] === 'test.title') {
$entry['source'] = '更新后的中文标题';
}
}
unset($entry);
$changedManifest['entries'][] = [
'key' => 'test.status', 'scope' => 'test',
'page' => 'test.page', 'kind' => 'status',
'source' => '新状态', 'format' => 'plain_text',
'parameters' => [], 'criticality' => 'normal',
'allow_hide' => true, 'toast_tone' => null,
'editor_surface' => 'feedback', 'editor_group' => 'test.page',
];
$changedSync = new UserCopyManifestSynchronizer($database, $changedManifest);
$changed = $changedSync->synchronize((int) $super['user_id']);
$titleDraftState = (string) $database->table('ui_copy_drafts')
->where('id', $titleOne['id'])->value('validation_state');
$assert($changed['active'] === 5
&& $changed['created'] === 1
&& $changed['orphaned'] === 1
&& $titleDraftState === 'stale'
&& $database->table('ui_copy_entries')
->where('copy_key', 'test.help')->value('state') === 'orphaned'
&& $database->table('ui_copy_entries')
->where('copy_key', 'test.status')->value('state') === 'active',
'Manifest change did not project active/orphaned state or stale drafts.');
$assert($database->table('ui_copy_locales')->where('locale', 'en')->count() === 1,
'Manifest resynchronization removed the administrator locale registry.');
$newService = new UserCopyAdminService($database, $changedManifest, $store);
$reject(
static fn () => $newService->rollback(
$super, 'en', (string) $first['publication_key']
),
409,
'A generation from an incompatible source Manifest was reactivated.'
);
} finally {
$removeTree($root);
}
echo "User copy Manifest synchronization and administrator service tests passed.\n";