TR
games/rob-revisited / tests / RevisitedI18nTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\I18n\Extractor;use App\Revisited\I18n\Translator;use App\Revisited\Land\Game;use App\Revisited\Land\Npc;use App\Revisited\Land\Talk;use App\Revisited\Sim\Crafting;use App\Revisited\Sim\Items;use PHPUnit\Framework\TestCase;/** The English of Rob revisited (src/Revisited/I18n, assets/revisited/lang/en.php, docs/i18n-plan.md). */final class RevisitedI18nTest extends TestCase{    private const ROOT = __DIR__ . '/..';    protected function setUp(): void    {        Translator::load();        Translator::setLang('en');    }    protected function tearDown(): void    {        Translator::setLang('fr');    }    /** @return array<string, string> */    private static function dict(): array    {        return require self::ROOT . '/assets/revisited/lang/en.php';    }    /** @return array<string, string> key => file:line */    private static function extracted(): array    {        $keys = [];        foreach (Extractor::sourceFiles(self::ROOT) as $file) {            foreach (Extractor::extract((string) file_get_contents($file)) as [$key, $line]) {                $keys[$key] ??= basename($file) . ':' . $line;            }        }        return $keys;    }    public function testEveryExtractedTextHasAnEnglishValueWithTheSamePlaceholders(): void    {        $dict = self::dict();        $missing = [];        $badTokens = [];        foreach (self::extracted() as $fr => $where) {            $en = $dict[$fr] ?? '';            if ($en === '') {                $missing[] = "$where  $fr";                continue;            }            preg_match_all('/\{(\w+)\}/', $fr, $a);            preg_match_all('/\{(\w+)\}/', $en, $b);            if (array_diff($b[1], $a[1])) {                $badTokens[] = "$where  $fr  =>  $en";            }        }        self::assertSame([], $missing, "untranslated (run tools/reborn/i18n_extract.php, then translate):\n" . implode("\n", $missing));        self::assertSame([], $badTokens, "English placeholders that the French does not have:\n" . implode("\n", $badTokens));    }    /**     * Independent of the extractor's heuristics: every literal of the sources with a French accent (a sure sign of a     * French text) must be part of a key. Reports the missed ones; at least 95 %.     */    public function testTheExtractorFindsAtLeast95PercentOfTheFrenchLiterals(): void    {        $keys = implode("\n", array_keys(self::extracted()));        $seen = 0;        $missed = [];        foreach (Extractor::sourceFiles(self::ROOT) as $file) {            foreach (token_get_all((string) file_get_contents($file)) as $t) {                if (!is_array($t) || !in_array($t[0], [T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE], true)) {                    continue;                }                $s = $t[0] === T_ENCAPSED_AND_WHITESPACE ? $t[1]                    : ($t[1][0] === "'" ? str_replace(['\\\\', "\\'"], ['\\', "'"], substr($t[1], 1, -1)) : stripcslashes(substr($t[1], 1, -1)));                if (!preg_match('/[àâçéèêëîïôûùœ]/u', $s) || !preg_match('/\p{L}{3}/u', $s) || preg_match('/^[a-z_:]+$|^[a-z]+:\S/u', $s)) {                    continue;                }                $seen++;                if (!str_contains($keys, Extractor::printfToTokens($s))) {                    $missed[] = basename($file) . ':' . $t[2] . '  ' . $s;                }            }        }        $ratio = 1 - count($missed) / max(1, $seen);        fwrite(STDERR, sprintf("\n[i18n] literal coverage %.1f %% (%d / %d)%s\n", $ratio * 100, $seen - count($missed), $seen,            $missed ? "\n  missed: " . implode("\n  missed: ", array_slice($missed, 0, 30)) : ''));        self::assertGreaterThanOrEqual(0.95, $ratio);    }    /** What the game really shows: items, recipes, every dialogue node reachable from 'root'. At least 95 % known. */    public function testTheTextsTheGameProducesAreTranslated(): void    {        $texts = [];        foreach (Items::all() as $id) {            $it = Items::get($id);            $texts[] = (string) $it['name'];            $texts[] = (string) $it['desc'];        }        foreach (Crafting::recipes() as $r) {            $texts[] = (string) $r['name'];        }        $g = Game::newGame(7);        foreach (['maeva', 'oko', 'sela', 'koru', 'aika', 'tamu', 'nadje', 'vask', 'grell', 'mira', 'orsolo', 'kessa', 'jonas'] as $key) {            $npc = new Npc(1, ucfirst($key), 'haldi', 0, 0, 0);            $npc->data['key'] = $key;            $todo = ['root'];            $done = [];            while ($todo && count($done) < 60) {                $node = array_shift($todo);                if (isset($done[$node])) {                    continue;                }                $done[$node] = true;                $r = Talk::node($g, $npc, $node, null);                $texts[] = $r['text'];                foreach ($r['choices'] as $c) {                    $texts[] = $c[0];                    if (str_starts_with($c[1], 'node:')) {                        $todo[] = substr($c[1], 5);                    }                }            }        }        $texts = array_values(array_unique(array_filter($texts, static fn ($t) => preg_match('/\p{L}{2}/u', $t) === 1)));        $unknown = array_values(array_filter($texts, static fn ($t) => !Translator::knows($t)));        $ratio = 1 - count($unknown) / max(1, count($texts));        fwrite(STDERR, sprintf("\n[i18n] runtime texts known %.1f %% (%d)%s\n", $ratio * 100, count($texts),            $unknown ? "\n  unknown: " . implode("\n  unknown: ", array_slice($unknown, 0, 30)) : ''));        self::assertGreaterThanOrEqual(0.95, $ratio);    }    public function testTemplatesGiveTheNumbersAndNamesBack(): void    {        self::assertSame('Day 12 on Ysor', Translator::t('Jour 12 sur Ysor'));        self::assertSame('Day 3, 07:05', Translator::t('Jour 3, 07:05'));        self::assertSame('Severity 42 %', Translator::t('Gravité 42 %'));        self::assertSame('Graphics quality lowered to Low to keep the game smooth (24 fps).',            Translator::t('Qualité graphique abaissée à Basse pour garder le jeu fluide (24 i/s).'));        // a captured French part is translated in turn        self::assertSame('You need the tool: Stone axe.', Translator::t('Il te faut l\'outil : Hache de pierre.'));        self::assertSame('Search: crate', Translator::t('Fouiller : caisse'));        // fragments, '{0}{1}' and capitals        self::assertSame('Fell the dead tree (you need an axe)', Translator::t('Abattre l\'arbre mort (il faut une hache)'));        self::assertSame('IN HAND', Translator::t('EN MAIN'));        self::assertSame('ON RIGHT ARM', Translator::t('SUR BRAS DROIT'));        // the same text round trip through f() (code that builds its own text)        self::assertSame('Day 5 on Ysor', Translator::f('Jour {0} sur Ysor', [5]));        // unknown: the French stays        self::assertSame('Texte inconnu 123', Translator::t('Texte inconnu 123'));    }    public function testFrenchIsUntouchedAndTheLanguageFollowsThePageThenTheSavedChoice(): void    {        Translator::setLang('fr');        self::assertSame('Jour 12 sur Ysor', Translator::t('Jour 12 sur Ysor'));        self::assertSame('fr', Translator::detect(null, 'fr-CA'));        self::assertSame('fr', Translator::detect(null, 'fr_FR.UTF-8'));        self::assertSame('en', Translator::detect(null, 'de'));        self::assertSame('en', Translator::detect('en', 'fr'));        self::assertSame('fr', Translator::detect('fr', 'en'));        self::assertSame('en', Translator::detect('xx', 'en'));        Translator::setLang('en');        self::assertSame('Resume', Translator::t('Reprendre'));        self::assertSame('fr', Translator::next());    }    public function testATranslatedTextCostsLessThan5MicrosecondsOnceWarm(): void    {        $texts = ['Reprendre', 'Jour 12 sur Ysor', 'Gravité 42 %', 'EN MAIN', 'Il te faut l\'outil : Hache de pierre.', 'Texte inconnu 123'];        foreach ($texts as $t) {            Translator::t($t);        }        $n = 20000;        $t0 = hrtime(true);        for ($i = 0; $i < $n; $i++) {            Translator::t($texts[$i % 6]);        }        $us = (hrtime(true) - $t0) / 1000 / $n;        // a cold template (a new number each time, the worst case of a frame): measured, reported        $t0 = hrtime(true);        for ($i = 0; $i < 500; $i++) {            Translator::t('Jour ' . (1000 + $i) . ' sur Ysor');        }        $cold = (hrtime(true) - $t0) / 1000 / 500;        fwrite(STDERR, sprintf("\n[i18n] t(): %.2f µs warm, %.1f µs cold template, %d keys\n", $us, $cold, Translator::size()));        self::assertLessThan(5.0, $us);        self::assertLessThan(200.0, $cold);    }    // the text-overflow walk (every screen, both languages, desktop and phone): tests/RevisitedOverflowTest.php}