390 lines
24 KiB
PHP
390 lines
24 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\Translations\AiTranslator;
|
|
use JumPHP\Ide\Translations\Catalogs;
|
|
use JumPHP\Ide\Translations\JsonCatalog;
|
|
use JumPHP\Ide\Translations\PhpCatalog;
|
|
use JumPHP\Ide\Translations\Placeholders;
|
|
use JumPHP\Ide\Translations\TranslationCommands;
|
|
use JumPHP\Ide\Translations\Usages;
|
|
use JumPHP\Ide\Translations\XliffCatalog;
|
|
use JumPHP\Ide\Translations\YamlCatalog;
|
|
use JumPHP\Ide\Workspace\MemoryWorkspace;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
final class TranslationsTest extends TestCase
|
|
{
|
|
private const YAML = <<<'YAML'
|
|
# the site's texts
|
|
app:
|
|
title: My shop # shown in the header
|
|
menu:
|
|
home: Home
|
|
cart: 'Your cart'
|
|
flash.saved: "Saved!"
|
|
long: |
|
|
First line
|
|
Second line
|
|
|
|
footer:
|
|
copyright: © 2026
|
|
YAML;
|
|
|
|
// ------------------------------------------------------------------------------------------- YAML
|
|
|
|
public function testANestedYamlCatalogueIsReadWithDottedKeys(): void
|
|
{
|
|
$values = YamlCatalog::read(self::YAML);
|
|
self::assertSame(['app.title' => 'My shop', 'app.menu.home' => 'Home', 'app.menu.cart' => 'Your cart', 'flash.saved' => 'Saved!',
|
|
'long' => "First line\nSecond line\n", 'footer.copyright' => '© 2026'], $values);
|
|
}
|
|
|
|
public function testAYamlEditWithNothingToDoLeavesTheFileByteForByte(): void
|
|
{
|
|
self::assertSame(self::YAML, YamlCatalog::edit(self::YAML, []));
|
|
self::assertSame(self::YAML, YamlCatalog::set(self::YAML, [], true, 'app.title', 'My shop'));
|
|
}
|
|
|
|
public function testAValueChangesOnItsLineOnlyKeepingItsComment(): void
|
|
{
|
|
$after = YamlCatalog::set(self::YAML, [], true, 'app.title', 'Ma boutique');
|
|
self::assertSame(str_replace('title: My shop # shown', 'title: Ma boutique # shown', self::YAML), $after);
|
|
self::assertSame('Ma boutique', YamlCatalog::read($after)['app.title']);
|
|
}
|
|
|
|
public function testANewNestedKeyGoesUnderItsParentAtItsBrothersIndentation(): void
|
|
{
|
|
$after = YamlCatalog::set(self::YAML, [], true, 'app.menu.account', 'Account');
|
|
self::assertStringContainsString(" cart: 'Your cart'\n account: Account\n", $after);
|
|
$after = YamlCatalog::set($after, [], true, 'app.errors.not_found', 'Not found');
|
|
self::assertStringContainsString(" account: Account\n errors:\n not_found: Not found\n", $after);
|
|
$values = YamlCatalog::read($after);
|
|
self::assertSame('Not found', $values['app.errors.not_found']);
|
|
self::assertSame('My shop', $values['app.title']);
|
|
self::assertStringStartsWith("# the site's texts\n", $after);
|
|
}
|
|
|
|
public function testAKeyIsDeletedWithItsEmptyParents(): void
|
|
{
|
|
$text = "app:\n menu:\n home: Home\n title: Shop\nother: x\n";
|
|
$after = YamlCatalog::delete($text, [], true, 'app.menu.home');
|
|
self::assertSame("app:\n title: Shop\nother: x\n", $after);
|
|
self::assertSame("app:\n menu:\n home: Home\n title: Shop\n", YamlCatalog::delete($text, [], true, 'other'));
|
|
self::assertSame("app:\n menu:\n home: Home\n title: Shop\nother: x\n", YamlCatalog::delete($text, [], true, 'nothing'));
|
|
}
|
|
|
|
public function testABlockScalarIsReplacedWhole(): void
|
|
{
|
|
$after = YamlCatalog::set(self::YAML, [], true, 'long', "Une\nDeux");
|
|
self::assertSame("Une\nDeux", YamlCatalog::read($after)['long']);
|
|
self::assertStringContainsString("long: |-\n Une\n Deux\n\nfooter:", $after);
|
|
}
|
|
|
|
public function testARenameInTheSameParentKeepsTheLine(): void
|
|
{
|
|
$after = YamlCatalog::rename(self::YAML, [], true, 'app.title', 'app.name');
|
|
self::assertSame(str_replace(' title: My shop', ' name: My shop', self::YAML), $after);
|
|
$moved = YamlCatalog::rename(self::YAML, [], true, 'flash.saved', 'app.flash.saved');
|
|
self::assertSame('Saved!', YamlCatalog::read($moved)['app.flash.saved']);
|
|
self::assertArrayNotHasKey('flash.saved', YamlCatalog::read($moved));
|
|
}
|
|
|
|
public function testAFlatKeyUnderAParentThatIsATextStaysFlat(): void
|
|
{
|
|
$after = YamlCatalog::set("flash.saved: Saved\n", [], true, 'flash.saved.more', 'More');
|
|
self::assertSame(['flash.saved' => 'Saved', 'flash.saved.more' => 'More'], YamlCatalog::read($after));
|
|
}
|
|
|
|
public function testAFlowMapFallsBackToADumpWithTheSameValues(): void
|
|
{
|
|
$after = YamlCatalog::set("app: {title: Shop}\n", [], true, 'app.name', 'X');
|
|
self::assertSame(['app.title' => 'Shop', 'app.name' => 'X'], YamlCatalog::read($after));
|
|
}
|
|
|
|
public function testJumphpLangYamlIsEditedPerLanguage(): void
|
|
{
|
|
$text = "fr:\n PLAY: JOUER\n QUIT: QUITTER\nes:\n PLAY: JUGAR\n";
|
|
self::assertSame(['fr', 'es'], YamlCatalog::topKeys($text));
|
|
self::assertSame(['PLAY' => 'JUGAR'], YamlCatalog::read($text, ['es'], false));
|
|
$after = YamlCatalog::set($text, ['es'], false, 'QUIT', 'SALIR');
|
|
self::assertSame("fr:\n PLAY: JOUER\n QUIT: QUITTER\nes:\n PLAY: JUGAR\n QUIT: SALIR\n", $after);
|
|
$after = YamlCatalog::set($after, ['fr'], false, 'A.B C', 'x');
|
|
self::assertSame('x', YamlCatalog::read($after, ['fr'], false)['A.B C']);
|
|
self::assertSame("fr:\n PLAY: JOUER\n QUIT: QUITTER\nes:\n PLAY: JUGAR\nde:\n PLAY: ''\n", YamlCatalog::addTop($text, 'de', ['PLAY' => '']));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- XLIFF
|
|
|
|
private const XLF12 = <<<'XML'
|
|
<?xml version="1.0" encoding="utf-8"?>
|
|
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
|
|
<file source-language="en" target-language="fr" datatype="plaintext" original="file.ext">
|
|
<body>
|
|
<trans-unit id="a1" resname="app.title">
|
|
<source>app.title</source>
|
|
<target>Ma boutique</target>
|
|
<note>The header</note>
|
|
</trans-unit>
|
|
<trans-unit id="b2">
|
|
<source>Delete & close</source>
|
|
<target state="needs-translation"></target>
|
|
</trans-unit>
|
|
</body>
|
|
</file>
|
|
</xliff>
|
|
|
|
XML;
|
|
|
|
public function testXliff12IsReadAndEditedInPlace(): void
|
|
{
|
|
self::assertSame(['app.title' => 'Ma boutique', 'Delete & close' => ''], XliffCatalog::read(self::XLF12, $meta));
|
|
self::assertSame(['id' => 'a1', 'notes' => ['The header']], $meta['app.title']);
|
|
self::assertSame(self::XLF12, XliffCatalog::edit(self::XLF12, []));
|
|
$after = XliffCatalog::set(self::XLF12, 'Delete & close', 'Supprimer & fermer');
|
|
self::assertSame(str_replace('<target state="needs-translation"></target>', '<target state="needs-translation">Supprimer & fermer</target>', self::XLF12), $after);
|
|
$added = XliffCatalog::set(self::XLF12, 'app.cart', 'Panier <b>');
|
|
self::assertSame('Panier <b>', XliffCatalog::read($added)['app.cart']);
|
|
self::assertStringContainsString(" </trans-unit>\n <trans-unit id=\"", $added);
|
|
self::assertStringContainsString("resname=\"app.cart\">\n <source>app.cart</source>\n <target>Panier <b></target>\n </trans-unit>\n </body>", $added);
|
|
self::assertSame(self::XLF12, XliffCatalog::delete($added, 'app.cart'));
|
|
$renamed = XliffCatalog::rename(self::XLF12, 'app.title', 'app.name');
|
|
self::assertStringContainsString('<trans-unit id="a1" resname="app.name">', $renamed);
|
|
self::assertStringContainsString('<source>app.name</source>', $renamed);
|
|
self::assertStringContainsString('<note>The header</note>', $renamed);
|
|
}
|
|
|
|
public function testXliff20IsReadAndEdited(): void
|
|
{
|
|
$text = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\" srcLang=\"en\" trgLang=\"de\">\n <file id=\"messages.de\">\n <unit id=\"1\" name=\"hello\">\n <segment>\n <source>hello</source>\n <target>Hallo</target>\n </segment>\n </unit>\n </file>\n</xliff>\n";
|
|
self::assertSame('2.0', XliffCatalog::version($text));
|
|
self::assertSame('de', XliffCatalog::locale($text));
|
|
self::assertSame(['hello' => 'Hallo'], XliffCatalog::read($text));
|
|
$after = XliffCatalog::set($text, 'bye', 'Tschüss');
|
|
self::assertSame(['hello' => 'Hallo', 'bye' => 'Tschüss'], XliffCatalog::read($after));
|
|
self::assertStringContainsString(" <unit id=\"2\" name=\"bye\">\n <segment>\n <source>bye</source>", $after);
|
|
self::assertSame($text, XliffCatalog::delete($after, 'bye'));
|
|
self::assertSame(['a' => 'x', 'b' => 'y'], XliffCatalog::read(XliffCatalog::build(['a' => 'x', 'b' => 'y'], 'en', 'de', '2.0')));
|
|
self::assertSame(['a' => 'x'], XliffCatalog::read(XliffCatalog::build(['a' => 'x'], 'en', 'de')));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- JSON, PHP
|
|
|
|
public function testJsonKeepsItsStyle(): void
|
|
{
|
|
$text = "{\n \"app\": {\n \"title\": \"Shop\"\n },\n \"bye\": \"Bye\"\n}\n";
|
|
self::assertSame(['app.title' => 'Shop', 'bye' => 'Bye'], JsonCatalog::read($text));
|
|
self::assertSame($text, JsonCatalog::edit($text, []));
|
|
$after = JsonCatalog::edit($text, [['op' => 'set', 'key' => 'app.cart', 'value' => 'Cart é/']]);
|
|
self::assertSame("{\n \"app\": {\n \"title\": \"Shop\",\n \"cart\": \"Cart é/\"\n },\n \"bye\": \"Bye\"\n}\n", $after);
|
|
self::assertSame($text, JsonCatalog::edit($after, [['op' => 'delete', 'key' => 'app.cart']]));
|
|
$laravel = "{\n \"Log in\": \"Connexion\"\n}\n";
|
|
self::assertSame(['Log in' => 'Connexion', 'a.b' => 'c'], JsonCatalog::read(JsonCatalog::edit($laravel, [['op' => 'set', 'key' => 'a.b', 'value' => 'c']], false), false));
|
|
}
|
|
|
|
public function testPhpArraysAreEditedWithoutRunningThem(): void
|
|
{
|
|
$text = "<?php\n\n// auth texts\nreturn [\n 'failed' => 'These credentials do not match.',\n 'nested' => [\n 'a' => 'A', // first\n ],\n 'dynamic' => strtoupper('x'),\n];\n";
|
|
self::assertSame(['failed' => 'These credentials do not match.', 'nested.a' => 'A'], PhpCatalog::read($text));
|
|
self::assertSame($text, PhpCatalog::edit($text, []));
|
|
$after = PhpCatalog::set($text, 'failed', "Identifiants invalides, l'accès");
|
|
self::assertSame(str_replace("'These credentials do not match.'", "'Identifiants invalides, l\\'accès'", $text), $after);
|
|
$added = PhpCatalog::set($text, 'nested.b', 'B');
|
|
self::assertStringContainsString(" 'a' => 'A', // first\n 'b' => 'B',\n ],", $added);
|
|
$deep = PhpCatalog::set($text, 'new.deep', 'D');
|
|
self::assertSame('D', PhpCatalog::read($deep)['new.deep']);
|
|
self::assertSame($text, PhpCatalog::delete($added, 'nested.b'));
|
|
self::assertStringContainsString("'b' => 'A', // first", PhpCatalog::rename($text, 'nested.a', 'nested.b'));
|
|
self::assertSame(['x' => '1', 'g.y' => '2'], PhpCatalog::read(PhpCatalog::build(['x' => '1', 'g.y' => '2'])));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- checks
|
|
|
|
public function testPlaceholdersAndIcuAreChecked(): void
|
|
{
|
|
self::assertSame(['%count%', '{name}'], Placeholders::of('Hello {name}, %count% items'));
|
|
self::assertSame([], Placeholders::of('{0} none|{1} one|]1,Inf[ many'));
|
|
self::assertSame(['{{ limit }}'], Placeholders::of('At most {{ limit }} chars'));
|
|
self::assertSame([':name'], Placeholders::of('Hi :name at 10:30', 'laravel'));
|
|
self::assertSame([], Placeholders::compare('Hello %name%', 'Bonjour %name%'));
|
|
self::assertSame(['missing placeholder %name%', 'unknown placeholder %nom%'], Placeholders::compare('Hello %name%', 'Bonjour %nom%'));
|
|
self::assertSame(['HTML tags differ'], Placeholders::compare('<b>Hi</b>', 'Salut'));
|
|
self::assertSame(['plural forms: 2 instead of 3'], Placeholders::compare('{0} none|{1} one|]1,Inf[ many', '{0} aucun|]0,Inf[ plusieurs'));
|
|
$icu = '{count, plural, one {# item} other {# items}}';
|
|
self::assertSame(['{count}'], Placeholders::of($icu));
|
|
self::assertSame([], Placeholders::compare($icu, '{count, plural, one {# article} many {# articles} other {# articles}}', 'symfony', true));
|
|
self::assertSame(['ICU: count has no "other" case'], Placeholders::icuErrors('{count, plural, one {# item}}'));
|
|
self::assertSame(['ICU: "several" is not a plural category (zero, one, two, few, many, other, =N)'], Placeholders::icuErrors('{count, plural, =0 {none} several {#} other {#}}'));
|
|
self::assertSame(['ICU: a "{" is not closed'], Placeholders::icuErrors('{count, plural, one {# item} other {# items}'));
|
|
self::assertSame([], Placeholders::icuErrors("It's '{literal}' {g, select, male {he} other {they}}"));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- the project
|
|
|
|
private function project(): MemoryWorkspace
|
|
{
|
|
return new MemoryWorkspace([
|
|
'config/packages/translation.yaml' => "framework:\n default_locale: en\n",
|
|
'translations/messages.en.yaml' => "app:\n title: Shop\n hello: Hello %name%\nunused.key: Old\n",
|
|
'translations/messages.fr.yaml' => "app:\n title: Shop\n hello: Bonjour %nom%\n",
|
|
'translations/validators.en.xlf' => XliffCatalog::build(['blank' => 'Must not be blank'], 'en', 'en'),
|
|
'templates/base.html.twig' => "<h1>{{ 'app.title'|trans }}</h1>{{ 'app.hello'|trans({'%name%': user}) }} {{ 'app.missing'|trans({}, 'messages') }}\n{% trans %}app.title{% endtrans %}\n",
|
|
'src/Controller/HomeController.php' => "<?php\nclass HomeController {\n public function x(\$t) { return \$t->trans('app.hello', [], 'messages') . \$t->trans('flash.done'); }\n}\n",
|
|
'games/demo/config/lang.yaml' => "fr:\n PLAY: JOUER\n QUIT: QUITTER\nes:\n PLAY: JUGAR\n",
|
|
'games/demo/src/Scene/TitleScene.php' => "<?php\n\$items = [['PLAY', null], ['QUIT', null]];\n",
|
|
]);
|
|
}
|
|
|
|
public function testTheProjectsCataloguesAreGroupedByDomainWithEveryLanguage(): void
|
|
{
|
|
$groups = (new Catalogs($this->project()))->groups();
|
|
$ids = array_column($groups, 'id');
|
|
self::assertSame(['jumphp:games/demo/config:lang', 'symfony:translations:messages', 'symfony:translations:validators'], $ids);
|
|
$messages = $groups[1];
|
|
self::assertSame('en', $messages['source']);
|
|
self::assertSame(['en', 'fr'], $messages['locales']);
|
|
self::assertSame(['app.title', 'app.hello', 'unused.key'], $messages['keys']);
|
|
self::assertSame(['en' => 'Old', 'fr' => null], $messages['values']['unused.key']);
|
|
// validators has no French file: the column is there, its file made when written
|
|
self::assertSame(['en' => 'translations/validators.en.xlf', 'fr' => null], $groups[2]['files']);
|
|
$checks = Catalogs::check($messages);
|
|
self::assertSame(['identical'], $checks['app.title']['fr']);
|
|
self::assertSame(['missing placeholder %name%', 'unknown placeholder %nom%'], $checks['app.hello']['fr']);
|
|
self::assertSame(['missing'], $checks['unused.key']['fr']);
|
|
$lang = $groups[0];
|
|
self::assertSame(['fr', 'es'], $lang['locales']);
|
|
self::assertSame(['missing'], Catalogs::check($lang)['QUIT']['es']);
|
|
}
|
|
|
|
public function testANewKeyGoesIntoEveryLanguageFileAndMakesTheMissingOnes(): void
|
|
{
|
|
$ws = $this->project();
|
|
$catalogs = new Catalogs($ws);
|
|
$changes = $catalogs->changes('symfony:translations:validators', [['op' => 'add', 'key' => 'too.long', 'values' => ['en' => 'Too long', 'fr' => 'Trop long']]]);
|
|
self::assertSame(['translations/validators.en.xlf', 'translations/validators.fr.xlf'], array_column($changes, 'path'));
|
|
self::assertTrue($changes[1]['create']);
|
|
$catalogs->apply($changes);
|
|
self::assertSame(['too.long' => 'Trop long'], XliffCatalog::read($ws->read('translations/validators.fr.xlf')));
|
|
self::assertSame('fr', XliffCatalog::locale($ws->read('translations/validators.fr.xlf')));
|
|
$changes = (new Catalogs($ws))->changes('symfony:translations:messages', [['op' => 'add', 'key' => 'app.cart', 'values' => ['fr' => 'Panier']]]);
|
|
self::assertSame("app:\n title: Shop\n hello: Hello %name%\n cart: ''\nunused.key: Old\n", $changes[0]['after']);
|
|
self::assertSame("app:\n title: Shop\n hello: Bonjour %nom%\n cart: Panier\n", $changes[1]['after']);
|
|
}
|
|
|
|
public function testRenameAndDeleteGoThroughEveryCatalogue(): void
|
|
{
|
|
$ws = $this->project();
|
|
$c = new Catalogs($ws);
|
|
$c->apply($c->changes('symfony:translations:messages', [['op' => 'rename', 'key' => 'app.title', 'to' => 'app.name']]));
|
|
self::assertSame("app:\n name: Shop\n hello: Bonjour %nom%\n", $ws->read('translations/messages.fr.yaml'));
|
|
$c = new Catalogs($ws);
|
|
$c->apply($c->changes('symfony:translations:messages', [['op' => 'delete', 'key' => 'app.hello']]));
|
|
self::assertSame("app:\n name: Shop\n", $ws->read('translations/messages.fr.yaml'));
|
|
self::assertSame("app:\n name: Shop\nunused.key: Old\n", $ws->read('translations/messages.en.yaml'));
|
|
// the file changed since the preview: refused
|
|
$c = new Catalogs($ws);
|
|
$changes = $c->changes('symfony:translations:messages', [['op' => 'set', 'key' => 'app.name', 'locale' => 'fr', 'value' => 'Boutique']]);
|
|
$ws->write('translations/messages.fr.yaml', "app:\n name: Changed\n");
|
|
$this->expectException(\RuntimeException::class);
|
|
$c->apply($changes);
|
|
}
|
|
|
|
public function testALanguageAddedMakesAllItsFiles(): void
|
|
{
|
|
$ws = $this->project();
|
|
$changes = (new Catalogs($ws))->addLanguage(['de', 'it'], 'source');
|
|
$paths = array_column($changes, 'path');
|
|
sort($paths);
|
|
self::assertSame(['games/demo/config/lang.yaml', 'translations/messages.de.yaml', 'translations/messages.it.yaml', 'translations/validators.de.xlf', 'translations/validators.it.xlf'], $paths);
|
|
(new Catalogs($ws))->apply($changes);
|
|
self::assertSame(['app.title' => 'Shop', 'app.hello' => 'Hello %name%', 'unused.key' => 'Old'], YamlCatalog::read($ws->read('translations/messages.de.yaml')));
|
|
self::assertSame(['fr', 'es', 'de', 'it'], YamlCatalog::topKeys($ws->read('games/demo/config/lang.yaml')));
|
|
self::assertSame(['PLAY' => 'PLAY', 'QUIT' => 'QUIT'], YamlCatalog::read($ws->read('games/demo/config/lang.yaml'), ['it'], false));
|
|
}
|
|
|
|
public function testTheCodeScanFindsUsedUnusedAndMissingKeys(): void
|
|
{
|
|
$ws = $this->project();
|
|
$u = (new Usages($ws))->scan();
|
|
self::assertSame('used', $u->status('app.title'));
|
|
self::assertSame('used', $u->status('app.hello'));
|
|
self::assertSame('unused', $u->status('unused.key'));
|
|
self::assertSame('maybe', $u->status('PLAY'));
|
|
$missing = $u->missing((new Catalogs($ws))->groups());
|
|
self::assertSame(['app.missing', 'flash.done'], array_column($missing, 'key'));
|
|
self::assertSame('messages', $missing[0]['domain']);
|
|
self::assertSame([['path' => 'templates/base.html.twig', 'line' => 1]], $missing[0]['places']);
|
|
}
|
|
|
|
public function testARenameReachesTheTemplatesAndTheCode(): void
|
|
{
|
|
$ws = $this->project();
|
|
$changes = (new Usages($ws))->scan()->renameChanges('app.title', 'app.name');
|
|
self::assertSame(['templates/base.html.twig'], array_column($changes, 'path'));
|
|
self::assertSame("<h1>{{ 'app.name'|trans }}</h1>{{ 'app.hello'|trans({'%name%': user}) }} {{ 'app.missing'|trans({}, 'messages') }}\n{% trans %}app.name{% endtrans %}\n", $changes[0]['after']);
|
|
$php = (new Usages($ws))->scan()->renameChanges('app.hello', 'app.hi');
|
|
self::assertSame(['src/Controller/HomeController.php', 'templates/base.html.twig'], array_column($php, 'path'));
|
|
self::assertStringContainsString("->trans('app.hi', [], 'messages')", $php[0]['after']);
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- AI
|
|
|
|
public function testTheAiRequestIsBatchedWithTheGlossaryAndItsAnswerChecked(): void
|
|
{
|
|
$items = array_map(fn ($i) => ['key' => "k$i", 'source' => "Text $i of the Shop"], range(1, 45));
|
|
$batches = AiTranslator::batches($items);
|
|
self::assertSame([40, 5], array_map('count', $batches));
|
|
$prompt = AiTranslator::prompt([['key' => 'app.hello', 'source' => 'Hello %name%, welcome to the Shop', 'others' => ['de' => 'Hallo %name%']]], 'en', 'fr',
|
|
[['term' => 'Shop', 'translations' => ['fr' => 'Boutique']], ['term' => 'JumPHP', 'keep' => true]]);
|
|
self::assertStringContainsString('from "en" to "fr"', $prompt);
|
|
self::assertStringContainsString('- "Shop" => "Boutique"', $prompt);
|
|
self::assertStringNotContainsString('JumPHP', $prompt); // a term the texts do not have costs nothing
|
|
self::assertStringContainsString('"other_languages": {', $prompt);
|
|
$parsed = AiTranslator::parse("Here you go:\n```json\n{\"translations\": [{\"key\": \"app.hello\", \"text\": \"Bonjour %nom%\"}, {\"key\": \"other\", \"text\": \"x\"}]}\n```",
|
|
[['key' => 'app.hello', 'source' => 'Hello %name%']]);
|
|
self::assertSame([['key' => 'app.hello', 'text' => 'Bonjour %nom%', 'issues' => ['missing placeholder %name%', 'unknown placeholder %nom%']]], $parsed);
|
|
self::assertSame([['key' => 'a', 'text' => 'b', 'issues' => []]], AiTranslator::parse(['a' => 'b'], [['key' => 'a', 'source' => 'c']]));
|
|
}
|
|
|
|
public function testTheFakeAiTranslatesOnlyWhatIsAskedThroughTheCommand(): void
|
|
{
|
|
$ws = $this->project();
|
|
$commands = [];
|
|
$run = function (array $command) use (&$commands): Deferred {
|
|
$commands[] = $command;
|
|
$prompt = $command[2];
|
|
preg_match('/Texts:\n(.*)$/s', $prompt, $m);
|
|
$entries = json_decode($m[1], true);
|
|
$out = ['translations' => array_map(fn ($e) => ['key' => $e['key'], 'text' => 'FR ' . $e['source']], $entries)];
|
|
// claude answers its JSON envelope, OpenCode the text of the model
|
|
return Deferred::resolved(['code' => 0, 'stdout' => json_encode($command[0] === 'claude' ? ['structured_output' => $out] : $out), 'stderr' => '']);
|
|
};
|
|
$handlers = [];
|
|
TranslationCommands::register(function (string $name, callable $h) use (&$handlers) {
|
|
$handlers[$name] = $h;
|
|
}, $ws, $run);
|
|
$r = $handlers['translations.ai'](['group' => 'symfony:translations:messages', 'to' => 'fr', 'keys' => ['unused.key'], 'provider' => 'claude']);
|
|
self::assertTrue($r->isDone());
|
|
self::assertSame([['key' => 'unused.key', 'text' => 'FR Old', 'issues' => []]], $r->result()['results']);
|
|
self::assertSame(['claude', '-p'], array_slice($commands[0], 0, 2));
|
|
self::assertContains('--json-schema', $commands[0]);
|
|
// JumPHP: English is the key itself
|
|
$r = $handlers['translations.ai'](['group' => 'jumphp:games/demo/config:lang', 'to' => 'es', 'keys' => ['QUIT'], 'provider' => 'opencode']);
|
|
self::assertSame('opencode', $commands[1][0]);
|
|
self::assertNull($r->error());
|
|
self::assertSame([['key' => 'QUIT', 'text' => 'FR QUIT', 'issues' => []]], $r->result()['results']);
|
|
// nothing was written
|
|
self::assertSame("app:\n title: Shop\n hello: Bonjour %nom%\n", $ws->read('translations/messages.fr.yaml'));
|
|
$list = $handlers['translations.list'](['usages' => true]);
|
|
self::assertSame('unused', $list['groups'][1]['usage']['unused.key']);
|
|
self::assertSame(['app.missing', 'flash.done'], array_column($list['missing'], 'key'));
|
|
}
|
|
|
|
public function testDebugTranslationsTableIsRead(): void
|
|
{
|
|
$out = " ---------- ---------- ------------- -----------\n State Domain Id Message Preview (fr)\n ---------- ---------- ------------- -----------\n | missing | messages | app.cart | app.cart |\n | unused | messages | old | Vieux |\n";
|
|
self::assertSame([['domain' => 'messages', 'key' => 'app.cart']], TranslationCommands::parseDebug($out));
|
|
}
|
|
}
|