Skip to content

ICU i18n Translator ​

A PHP library for automatic machine translation of ICU Message Format strings with persistent caching. Feed it plurals, selects, and complex ICU patterns — it translates every variant individually, preserves all formatting variables, and caches results in your database so the API is called only once per unique string.

bash
composer require eugene-erg/icu-i18n-translator

Why this library? ​

Most PHP i18n solutions require you to write translations manually for every language. This library is for a different workflow: you write strings in one language and let machine translation APIs (DeepL, Google Translate, etc.) fill in the rest — automatically, with full ICU format support.

How it differs from alternatives ​

This librarysymfony/translationphp-translation/translatorbermudaphp/polyglot
Auto-translates via API✅ Core feature❌ Manual only⚠️ Basic fallback❌ Manual only
ICU plural/select aware✅ Per-variant❌ Whole string❌ Whole string✅ Formatting only
Preserves ICU variables✅ {count}, {price, number} safeN/A❌ Can corruptN/A
DB caching✅ Built-in❌❌❌
Language auto-detection✅❌❌❌
Multiple API backends✅N/A⚠️ SingleN/A
File import/export✅✅✅✅
FrameworkAgnosticSymfonySymfonyAgnostic

The key difference: when you call translateMessage('{count, plural, one {# item} other {# items}}', ['count' => 5], 'fr'), this library does not send the raw ICU pattern to the translation API. It splits it into {count} item and {count} items, translates each independently, and reassembles a valid French ICU pattern. This prevents the API from corrupting {count, plural, ...} syntax, which virtually all translation APIs do when given raw ICU strings.


Requirements ​

  • PHP 8.2+
  • ext-intl
  • Your own implementations of the repository interfaces (any storage: MySQL, PostgreSQL, Redis, in-memory)
  • Your own implementation of TranslatorInterface (wrapping DeepL, Google, OpenAI, etc.)

Core concept ​

The library manages four tables. You implement how they are stored.

translate          — one translated variant
  pattern          "5 éléments"
  locale           "fr"

group              — one ICU message
  original_pattern "{count, plural, one {# item} other {# items}}"
  pattern          "{count, plural, one {0} other {1}}"   ← selector pattern
  locale           "en"
  context          optional hint for the translator ("e-commerce product list")

group_translates   — which translate belongs to which group variant
  group_id, translate_id, key, source_id

path               — node in a localization file tree
  parent_id, group_id, value, note   ← note: what the file explains about the message

A group never stores translated text directly. It stores the ICU selector and points to translate records through group_translates. This means the string {count} item can be reused across many groups.


Setup ​

1. Implement the repositories (7 interfaces) ​

php
// All interfaces are in EugeneErg\IcuI18nTranslator\Repositories\
// Read and Write are separated — you can use different sources for each.

class DoctrineGroupRepository implements
    ReadGroupRepositoryInterface,
    WriteGroupRepositoryInterface
{
    public function findByPattern(string $originalPattern, ?string $context, ?string $locale = null): ?Group
    {
        // SELECT ... WHERE original_pattern = ? AND context <=> ? AND (locale = ? OR ? IS NULL)
    }

    public function create(string $originalPattern, string $pattern, ?string $context, string $locale): Group
    {
        // INSERT INTO groups ...
        return new Group(new GroupId($id), $originalPattern, $pattern, $locale, $context);
    }

    // ... find(), list(), delete()
}

2. Implement TranslatorInterface ​

php
use EugeneErg\IcuI18nTranslator\TranslatorInterface;
use EugeneErg\IcuI18nTranslator\DataTransferObjects\Variable;
use EugeneErg\IcuI18nTranslator\ValueObjects\Translated;
use DeepL\Translator as DeepLClient;

class DeepLTranslator implements TranslatorInterface
{
    public function __construct(private DeepLClient $client) {}

    /**
     * $pattern is a mixed array of plain strings and Variable objects.
     * Variables represent ICU placeholders like {count} or {price, number, currency}.
     * YOU MUST NOT translate Variable objects — pass them through unchanged.
     */
    public function translate(array $pattern, string $fromLocale, string $toLocale, ?string $context = null): array
    {
        // Encode Variables as XML tags that DeepL will leave untouched
        $text = '';
        foreach ($pattern as $part) {
            $text .= $part instanceof Variable
                ? "<keep id=\"{$part->value}\"/>"
                : $part;
        }

        $result = $this->client->translateText(
            $text,
            $fromLocale,
            $toLocale,
            ['tag_handling' => 'xml', 'ignore_tags' => ['keep'], 'context' => $context]
        );

        // Decode XML tags back to Variable objects
        return $this->decode($result->text, $pattern);
    }

    public function translateWithDetect(array $pattern, string $toLocale, ?string $context = null): Translated
    {
        // Same encoding, but fromLocale is null — API detects it
        $result = $this->client->translateText(..., null, $toLocale, [...]);
        return new Translated(
            locale: strtolower($result->detectedSourceLang),
            pattern: $this->decode($result->text, $pattern),
        );
    }

    public function canTranslate(string $toLocale, ?string $fromLocale = null): bool
    {
        $supported = ['en', 'de', 'fr', 'es', 'it', 'nl', 'pl', 'ru', 'ja', 'zh'];
        return in_array(strtolower($toLocale), $supported, true)
            && ($fromLocale === null || in_array(strtolower($fromLocale), $supported, true));
    }

    private function decode(string $text, array $originalPattern): array
    {
        $variables = array_filter($originalPattern, fn($p) => $p instanceof Variable);
        $parts = preg_split('/(<keep id="\d+"\/> ?)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
        $result = [];
        foreach ($parts as $part) {
            if (preg_match('/<keep id="(\d+)"\/>/', $part, $m)) {
                $result[] = $variables[(int)$m[1]];
            } elseif ($part !== '') {
                $result[] = $part;
            }
        }
        return $result;
    }
}

3. Choose file formats ​

A format is a FormatterInterface: it turns a file into trees of messages, one per language the file holds, and back. Ready ones are packages:

PackageFiles
eugene-erg/json-formatter-icu-i18n-translatorJSON: FormatJS, i18next, vue-i18n, Laravel lang/*.json
eugene-erg/php-array-formatter-icu-i18n-translatorLaravel lang/*/*.php, parsed, never executed
eugene-erg/yaml-formatter-icu-i18n-translatorSymfony translations/*.yaml
eugene-erg/android-resources-formatter-icu-i18n-translatorAndroid strings.xml
eugene-erg/xliff-formatter-icu-i18n-translatorXLIFF 1.2 and 2.0: Symfony, Crowdin, Lokalise, Phrase
eugene-erg/xcstrings-formatter-icu-i18n-translatorApple String Catalogs (.xcstrings)

Writing one:

php
use EugeneErg\IcuI18nTranslator\DataTransferObjects\FilePathContainer;
use EugeneErg\IcuI18nTranslator\DataTransferObjects\Message;
use EugeneErg\IcuI18nTranslator\DataTransferObjects\TranslationFile;
use EugeneErg\IcuI18nTranslator\FileLanguages;
use EugeneErg\IcuI18nTranslator\FormatterInterface;
use EugeneErg\IcuI18nTranslator\Syntax\IcuSyntax;
use EugeneErg\IcuI18nTranslator\Syntax\MessageSyntaxInterface;

final readonly class JsonFormatter implements FormatterInterface
{
    public function __construct(private MessageSyntaxInterface $syntax = new IcuSyntax())
    {
    }

    public function languages(): FileLanguages
    {
        return FileLanguages::One;            // SourceAndTarget for XLIFF/PO, All for a String Catalog
    }

    public function parse(string $content, string $locale): TranslationFile
    {
        $tree = $this->tree(json_decode($content, true, flags: JSON_THROW_ON_ERROR), $locale);

        return TranslationFile::single($locale, $tree);
    }

    public function format(TranslationFile $file): string
    {
        return json_encode($this->data($file->first(), $file->firstLocale()), JSON_THROW_ON_ERROR);
    }

    private function tree(array $data, string $locale): FilePathContainer
    {
        $children = [];
        foreach ($data as $key => $value) {
            $children[$key] = is_array($value) ? $this->tree($value, $locale) : new Message($this->syntax->toIcu($value, $locale));
        }
        return new FilePathContainer($children);
    }

    private function data(FilePathContainer $tree, string $locale): array
    {
        return array_map(
            fn ($child) => $child instanceof FilePathContainer ? $this->data($child, $locale) : $this->syntax->fromIcu($child->types, $locale),
            $tree->children,
        );
    }
}
  • Messages in the tree are Message: the parsed ICU (Types) and, when the file has them, a context that tells apart the same text (gettext msgctxt) and a note for a translator (#., <note>, a catalog comment). The context becomes part of what the translation is stored under ("<file context> / <message context>"); the note is kept with the key, given to providers of whole messages and returned on export, so a format can write it. On export machine says whether a provider made the translation (a form of it included): a format that has a mark for it (PO fuzzy, an XLIFF or String Catalog state) writes it. On import that mark decides over the ImportMode: true keeps the text a machine's, false makes it a person's — an editor that cleared the mark approved it. null, the default, leaves it to the mode.
  • Messages are always ICU. How a file writes them is its MessageSyntaxInterface: IcuSyntax takes ICU as it is, TextSyntax is plain text in which { is a character, and packages add others (Laravel :name and a|b, printf %1$s).
  • A file names its languages in the returned TranslationFile: the source language and a tree for each language. Formats such as XLIFF read them from the file; $locale is what the caller passed.
  • A format whose files hold more than texts (comments, states, other languages) implements MergingFormatterInterface::formatOver(TranslationFile $file, string $base): it writes the texts into the file as it is now and keeps the rest. updateFile() uses it.
  • A format whose texts are XML (XLIFF, Android resources) implements MarkupFormatterInterface::markup(): inline elements and entities stay in the message (Click <g id="1">here</g> &amp; go), and the translator keeps them intact. Providers of texts see only the words — every tag is a placeholder they must give back once, in an order in which the elements still nest (Click {0}here{1} & go); a provider that breaks them is skipped like one that loses an ICU argument. A whole-message answer or an imported translation is stored only with the same tags and codes, well formed; otherwise the message is skipped with the reason. Elements named in Markup::$codes are codes with their content (XLIFF <ph>, Android <xliff:g>). CDATA is words: its tags are text, and a translation gives it back escaped (&lt;b&gt;). A message of such a file must be well-formed XML itself, and is given back so: when the shortest form would share a start tag between plural variants, every variant stands whole. Messages from code (translateMessage()) and setTranslate() are not checked.
  • Testing\InMemoryTranslator runs the whole import and export path in memory. Use it to test a format against the real translator, not only on its own.

4. Wire everything together ​

php
use EugeneErg\IcuI18nTranslator\Translator;
use EugeneErg\ICUMessageFormatParser\Parser;

$translator = new Translator(
    readGroupRepository:           $readGroupRepo,
    writeGroupRepository:          $writeGroupRepo,
    readTranslateRepository:       $readTranslateRepo,
    writeTranslateRepository:      $writeTranslateRepo,
    writeGroupTranslateRepository: $writeGroupTranslateRepo,
    readPathRepository:            $readPathRepo,
    writePathRepository:           $writePathRepo,
    parser:                        new Parser(),
    translators:                   [new DeepLTranslator($deepLClient)],
    formatters:                    ['json' => new JsonFormatter()],
);

Usage ​

Translate plain text ​

php
// Source language known
$result = $translator->translateText('Hello world', toLocale: 'fr', fromLocale: 'en');
// → 'Bonjour monde'

// Source language unknown — detected by the API
$result = $translator->translateText('Hello world', toLocale: 'de');
// → 'Hallo Welt'

// With context (improves translation quality for ambiguous terms)
$result = $translator->translateText('File', toLocale: 'fr', fromLocale: 'en', context: 'computer menu item');
// → 'Fichier'  (not 'Dossier' or 'Déposer')

Translate ICU plural ​

php
$pattern = '{count, plural, one {# item} other {# items}}';

echo $translator->translateMessage($pattern, ['count' => 1], 'fr', 'en');
// → '1 élément'

echo $translator->translateMessage($pattern, ['count' => 5], 'fr', 'en');
// → '5 éléments'

What happens internally:

  1. Parser produces selector {count, plural, one {0} other {1}} and variants {count} item, {count} items
  2. Each variant is translated independently — the {count} variable placeholder is protected from the API
  3. Results are cached in DB — the next call for the same pattern+locale costs zero API calls
  4. The ICU pattern is reconstructed from translated variants and formatted with count = 5
  5. Numbers keep the format of the language: # is stored as {count, number}, so 1000 prints as 1,000 / 1 000
  6. Asking for the language of the message itself ('en' here) only registers the message and formats it — no provider is called

Plural forms of the target language ​

Languages have different plural categories: English has one/other, Russian one/few/many/other, Arabic six of them. The library never invents translations, but it gives every form of the target language its own slot, so a missing form can be filled:

php
$pattern = '{count, plural, one {# post} other {# posts}}';

$translator->translateMessage($pattern, ['count' => 2], 'ru', 'en'); // '2 постов' — `few` uses the `other` variant

$translates = $translator->getTranslates($group->id, 'ru');
// '0'                  => one
// '1'                  => other
// '1@plural:count=few' => Translate(pattern: null, inheritedFrom: '1', needsReview: true)
// '1@plural:count=many'=> Translate(pattern: null, inheritedFrom: '1', needsReview: true)

$translator->setTranslate($group->id, '1@plural:count=few', 'ru', '{count} поста');

$translator->translateMessage($pattern, ['count' => 2], 'ru', 'en'); // '2 поста'
$translator->getFile('json', 'messages', 'ru');
// {count, plural, one {# пост} few {# поста} other {# постов}}
  • The forms come from CLDR rules of the target language (php-intl). Exact options (=0) that cover all numbers of a category make its slot unnecessary.
  • An empty slot uses the translation of the variant it would fall into (other here), so nothing changes until a slot is filled and no extra machine translations are made. This is checked by tests on several languages: with empty slots every number is formatted exactly as before.
  • needsReview marks the slots that still borrow a translation; inheritedFrom says from which key.
  • A key with several plurals looks like 5@plural:n=few@plural:p=many; an empty one falls back to the slot without some of its parts, then to the variant.
  • setTranslate() accepts only keys of the message and of the language (UnknownTranslateKeyException otherwise).
  • No database changes: slot keys are ordinary values of group_translates.key.

Translate ICU select ​

php
$pattern = '{gender, select, male {He sent} female {She sent} other {They sent}} a message';

echo $translator->translateMessage($pattern, ['gender' => 'female'], 'de', 'en');
// → 'Sie hat eine Nachricht gesendet'

Translate a string with formatting variables ​

php
// {price, number, currency} is an ICU variable — the library passes it through untranslated
$pattern = 'Your order of {count, plural, one {# item} other {# items}} totals {total, number, currency}';

echo $translator->translateMessage(
    $pattern,
    ['count' => 3, 'total' => 59.99],
    'fr',
    'en',
);
// → 'Votre commande de 3 articles totalise 59,99 €'

Import a localization file ​

php
$json = file_get_contents('translations/messages.en.json');
// {
//   "auth": {
//     "login": "Log in",
//     "errors": {
//       "invalid": "Invalid email or password"
//     }
//   },
//   "cart": {
//     "items": "{count, plural, one {# item in cart} other {# items in cart}}"
//   }
// }

$translator->addFile('json', 'messages', $json, locale: 'en');
// All strings are now registered in the DB.
// No translations are triggered yet.

Uploading the file again makes the stored file equal to the new content: a changed message points to its new text, removed keys disappear, a key may turn from a message into a nested object and back. Messages are shared: every file (and every translateMessage() call) with the same text uses one group and its translations, so changing one file never loses translations used by another, and groups are never deleted automatically.

Import ready translations ​

A file that is already translated (by people or another tool) can be imported as translations of the stored messages instead of replacing them:

php
$result = $translator->importTranslations('json', 'messages', $russianJson, locale: 'ru');

$result->imported; // ['auth.login', 'cart.items', …]
$result->skipped;  // ['auth.old' => 'the file has no such message', …]
  • Texts are matched by keys; the messages themselves stay unchanged and no provider is called.
  • A plural translation may have more forms than the message: {count, plural, one {…} few {…} many {…} other {…}} for an English one/other message fills the few and many form slots of Russian. A form the translation does not write stays marked needsReview.
  • A select option the translation lacks takes its other text.
  • Skipped, with the reason in $result->skipped: keys the file does not have, a message where the file has an object (and back), translations selecting on other arguments than the message, unknown arguments, and messages that are themselves in that language.
  • A file that holds its source language too (XLIFF, PO from an agency) contributes only its translations.
  • addFile() of such a file stores the source and imports the translations at once; its result lists both.
  • From a file of several languages (a String Catalog) every language is taken, or only those in only:: importTranslations('xcstrings', 'app', $catalog, 'en', only: ['de']).

Export a translated file ​

php
// This triggers translation for any strings not yet in DB for locale 'fr'
$translated = $translator->getFile('json', 'messages', 'fr');
file_put_contents('translations/messages.fr.json', $translated);
// {
//   "auth": {
//     "login": "Se connecter",
//     "errors": {
//       "invalid": "Email ou mot de passe invalide"
//     }
//   },
//   "cart": {
//     "items": "{count, plural, one {# article dans le panier} other {# articles dans le panier}}"
//   }
// }

A format that holds a source and a target (XLIFF, PO) gets the source language from the translator, so it is asked for the target only. A format of all languages takes any number of them: getFile('xcstrings', 'app', 'de', 'ru').

getFile() builds the file from the stored texts alone. A file that holds more — comments, states, notes, languages not asked for, strings that are not translated — is updated instead, from the file as it is in the project:

php
$catalog = file_get_contents('Localizable.xcstrings');

// the languages the catalog holds, translated where missing; comments, other strings and states stay
file_put_contents('Localizable.xcstrings', $translator->updateFile('xcstrings', 'Localizable', $catalog));

// only German, added if the catalog has no German yet; Japanese and the rest stay as they are
file_put_contents('Localizable.xcstrings', $translator->updateFile('xcstrings', 'Localizable', $catalog, 'de'));

updateFile() needs a format implementing MergingFormatterInterface (FormatCannotMergeException otherwise), and a language for a format of one language: updateFile('android', 'strings', $ruXml, 'ru').

Browse and edit translations ​

php
// List registered string groups (paginated)
$groups = $translator->getGroups(pageSize: 50, page: 1);

foreach ($groups as $group) {
    echo $group->originalPattern . ' [' . $group->locale . "]\n";
}

// Inspect all variants of one group with their current translations
$translates = $translator->getTranslates($group->id, locale: 'fr');
// [
//   '0' => Translate(cases: ['plural' => ['count' => 'one']], pattern: '{count} élément'),
//   '1' => Translate(cases: ['plural' => ['count' => ['one']]], pattern: null),  // missing
//   …plural form slots of the language, see "Plural forms of the target language"
// ]

// Fix a missing translation manually
$translator->setTranslate($group->id, key: '1', locale: 'fr', pattern: '{count} éléments');
// {count} of a plural is stored as {count, number} so the number keeps the format of the language

// Remove a translation (e.g., to force re-translation)
$translator->deleteTranslateFromGroup($group->id, key: '0', locale: 'fr');

Multiple translation backends ​

If you have multiple API keys or want a fallback chain, register several translators. They are tried in order among those whose canTranslate() returns true. A provider is skipped and the next one is tried when it throws, when it loses or invents an argument placeholder (the translated {count} must come back exactly), or when it cannot detect the source language. If every suitable provider fails, TranslationFailedException is thrown with the last failure as getPrevious():

php
$translator = new Translator(
    // ...
    translators: [
        new DeepLTranslator($deepLClient),    // preferred
        new GoogleTranslator($googleClient),  // fallback
    ],
);

Machine and manual translations ​

getTranslates() tells who made each translation: machine: true for providers, false for translations written with setTranslate() or imported with importTranslations() (and for the message itself), null when the slot has no own translation. Providers only fill empty slots, so they never overwrite a manual translation.

importTranslations() says who the imported texts are from with mode::

ImportModeImported texts become
Manual (default)manual, all of them: the same text too — importing approves it
Changesmanual where they differ from the stored text; the same text keeps who made it (a file the translator wrote, read back)
Machinemachine translations (another tool's); manual ones stay

A file whose format marks machine translations (Message::$machine) decides by its marks, message by message; the mode applies to the messages it leaves unmarked.

To refresh machine translations — after switching to a better provider, say — remove them; manual ones stay and the removed ones are translated again when requested:

php
$translator->deleteMachineTranslations(null, 'ru');          // every message
$translator->deleteMachineTranslations($group->id, 'ru');    // one message

A person who checked machine translations approves them: they become manual, their texts stay, and refreshing no longer removes them (a corrected text is approved with setTranslate() or an import):

php
$translator->approveMachineTranslations(null, 'ru');                // every message
$translator->approveMachineTranslations($group->id, 'ru');          // one message
$translator->approveMachineTranslations($group->id, 'ru', '1@plural:count=few');   // one form

Batch translation ​

getFile() collects every variant of the file that is missing in the requested language and sends them together: one request per source language and context, each distinct text once. A provider gets the whole batch when it implements BatchTranslatorInterface:

php
final class DeepLTranslator implements BatchTranslatorInterface
{
    public function translateBatch(array $patterns, string $fromLocale, string $toLocale, ?string $context = null): array
    {
        // one API call for all $patterns, results in the same order
    }

    // translate(), translateWithDetect(), canTranslate() as for TranslatorInterface
}

Other providers receive the texts one by one. Failures are handled per text: a text that a provider spoils (lost placeholder, wrong number of results, exception) is asked from the next provider, the rest is kept.

Whole messages ​

A provider that understands ICU — a language model, say — can translate a message whole: every plural form and select branch at once, agreed with the grammar of the target language, including forms the source language lacks (Russian few and many for an English one/other). It implements MessageTranslatorInterface and goes into the same translators list; one object may implement both interfaces:

php
use EugeneErg\IcuI18nTranslator\DataTransferObjects\SourceMessage;

final class LlmTranslator implements MessageTranslatorInterface
{
    /** @param array<string, SourceMessage> $messages */
    public function translateMessages(array $messages, string $fromLocale, string $toLocale): array
    {
        // one request for all $messages ($message->message is ICU, $message->context what it is about);
        // return ICU messages in $toLocale by the same ids, leave out what failed
    }

    public function canTranslate(string $toLocale, ?string $fromLocale = null): bool { /* ... */ }
}

getFile(), updateFile() and translateMessage() ask these providers first, for the messages that miss variants in the language. Every answer is checked like an imported translation: the same arguments, the same selectors, plural forms of the target language. An answer that fails the check, is left out or comes from a provider that throws goes to the next provider of messages, and in the end to the TranslatorInterface providers variant by variant. Answers are stored as machine translations; manual translations of the message stay. translateText() does not use them: plain text has no forms to agree.

Locales ​

Locales are normalized with php-intl before use, so EN, en, en-us, en_US and EN-us are one language (en / en_US, the ICU spelling; zh-hant-tw becomes zh_Hant_TW). An empty or malformed locale throws InvalidLocaleException. Data stored before this version under other spellings (en-US) has to be updated to the ICU spelling once, e.g. UPDATE … SET locale = 'en_US' WHERE locale = 'en-US'.


Upgrading to 4.x ​

4.0 lets a file say more about its messages than their text.

  • Leaves of FilePathContainer are DataTransferObjects\Message (types, context, note) instead of Types: formats wrap what they parse in new Message($types) and read $message->types on export.
  • Path has note, and WritePathRepositoryInterface::create() takes ?string $note: add a nullable text column note to the table of paths.
  • A message whose file gives a context is stored under "<file context> / <message context>". PO entries with msgctxt shared one translation per text before; after the upgrade they are translated apart, once.
  • SourceMessage has note: providers of whole messages get what the files explain (several notes of one message joined by new lines).

Upgrading to 3.x ​

3.0 changes how file formats work, so that a file can hold several languages (XLIFF, PO, String Catalogs) and a message syntax (Laravel, printf) is separate from the file structure.

  • FormatterInterface: languages(): FileLanguages, parse(string $content, string $locale): TranslationFile, format(TranslationFile $file): string. A format of one language uses TranslationFile::single($locale, $tree), $file->first() and $file->firstLocale().
  • Messages in FilePathContainer are always Types. A string leaf was taken as plain text, which made formats that returned ICU strings store {0} as text; now the type does not allow it. Parse messages with a MessageSyntaxInterface (IcuSyntax for ICU, TextSyntax for plain text).
  • addFile(..., asTranslation: true) is importTranslations($format, $name, $content, $locale).
  • getFile($format, $name, ...$locales): one locale as before; formats of all languages take several.
  • The in-memory repositories used by the tests are public in EugeneErg\IcuI18nTranslator\Testing, with InMemoryTranslator that wires them.
  • Requires eugene-erg/icu-message-format-parser ^2.0.2 (apostrophes as in ICU: Don't is plain text).

Exceptions ​

All exceptions implement TranslatorExceptionInterface:

ExceptionWhen
FormatNotFoundExceptionUnknown file format key passed to addFile()/getFile()
FormatCannotMergeExceptionupdateFile() for a format that only writes files from scratch
FileNotFoundExceptionFile not found in DB when calling getFile()
GroupNotFoundExceptionGroup not found when calling getTranslates() or setTranslate()
UnknownTranslateKeyExceptionsetTranslate() called with a key that is neither a variant nor a plural form slot of the language
IncorrectTransferPatternExceptionInvalid ICU pattern or argument values, or setTranslate() called with a multi-variant pattern
UnexpectedTranslateDirectionExceptionNo registered translator supports the requested locale pair
TranslationFailedExceptionEvery translator supporting the locale pair failed (last error in getPrevious())
LostPlaceholderExceptionA translator dropped or invented an argument placeholder (reported as the cause of TranslationFailedException)
MalformedMarkupExceptionA translator repeated a tag or broke the nesting of the markup (the cause of TranslationFailedException); a subclass of IncorrectTransferPatternException
InvalidLocaleExceptionAn empty or malformed locale
InvalidPaginationExceptiongetGroups()/getFiles() called with a page or page size below 1
UnsupportedLanguagesExceptiongetFile() asked for more languages than the format holds, or for none
SourceLanguageMissingExceptionaddFile() of a file without its source language (a translation: use importTranslations())
php
use EugeneErg\IcuI18nTranslator\Exceptions\TranslatorExceptionInterface;

try {
    $result = $translator->translateText('Hello', toLocale: 'klingon', fromLocale: 'en');
} catch (TranslatorExceptionInterface $e) {
    // handle
}

Architecture ​

Translator                          facade, public API (constructor and methods unchanged)
├── Services\MessageService         translateText() / translateMessage()
├── Services\FileService            addFile() / getFile() / file tree
├── Services\CatalogService         getGroups() / getTranslates() / setTranslate() / delete…()
│
├── Translation\TranslationMemory   stored translations of variants: reuse or translate and store
├── Translation\VariantTranslator   one variant → providers, ICU arguments and tags as checked placeholders
├── Markup\MarkedText               XML markup of messages: words and tags, the same tags in a translation
├── Translation\ProviderChain       TranslatorInterface[] in order, with fallback, batches (BatchTranslatorInterface)
├── Translation\MessageChain        MessageTranslatorInterface[]: whole messages, checked, before the variants
├── Plural\LocaleVariator           plural form slots of the target language (PluralRules, SlotKey)
├── Services\IcuMessages            parsing/formatting with translator exceptions
├── Services\LocaleNormalizer       one spelling per locale
│
├── FormatterInterface[]            file formats: structure (JSON, YAML, XLIFF…) + MessageSyntaxInterface
│                                   (+ MarkupFormatterInterface for XML texts)
├── TranslatorInterface[]           external API adapters (DeepL, Google, OpenAI, …)
├── MessageTranslatorInterface[]    providers of whole ICU messages (language models)
└── 7 repository interfaces         your storage layer

Read and Write repositories are separate interfaces. This lets you point reads at a read replica and writes at a primary, or use a cache layer for reads only.

Repository contracts worth knowing:

  • WriteTranslateRepositoryInterface::delete() also removes the group links of the translate and clears it as a source (a cascade / "set null" foreign key does this).
  • ReadTranslateRepositoryInterface::groupLinksByKey() returns the group links in a locale; a link with source_id is a machine translation (no schema change: the column already exists).
  • WriteGroupRepositoryInterface::delete() is never called by the library: groups are shared translation memory.

The services are @internal: use them through Translator.


Static analysis & tests ​

bash
composer check      # pint --test + phpstan (level max, strict rules) + phpunit
composer fix        # apply code style (Laravel Pint, rules in pint.json)
composer coverage   # coverage report (needs pcov or xdebug)

Besides unit tests with mocks, tests/PluralSlotsTest.php runs the translator end to end on in-memory repositories (tests/Support) and checks the output with php-intl (EquivalenceChecker of the parser).


License ​

MIT


From the README.md of EugeneErg/icu-i18n-translator · composer require eugene-erg/icu-i18n-translator