JSON formatter
JSON translation files for eugene-erg/icu-i18n-translator: messages are ICU strings, groups are objects. This covers FormatJS / react-intl, i18next with ICU, vue-i18n, Laravel lang/*.json and any other "key → ICU message" JSON.
composer require eugene-erg/json-formatter-icu-i18n-translatoruse EugeneErg\JsonFormatterIcuI18nTranslator\JsonFormatter;
$translator = new Translator(/* … */, formatters: ['json' => new JsonFormatter(indent: 2)]);
$translator->addFile('json', 'messages', file_get_contents('lang/en.json'), 'en');
file_put_contents('lang/ru.json', $translator->getFile('json', 'messages', 'ru'));Shape
{
"cart": {
"title": "Cart",
"items": "{count, plural, one {# item} other {# items}}"
},
"app.menu.open": "Open",
"days": ["Mon", "Tue"]
}- Nested and flat at once. An object is a group and a string is a message. A dot in a key is not split, so flat files (
"app.menu.open") stay flat. - Order and arrays. Keys keep their order, and a JSON array stays an array.
- Characters. Unicode and slashes are written as they are, not as
\u…or\/. - Rejected values. Numbers, booleans and
nullare not messages: the file is refused with the key named, e.g."a.b": a value is a message (string) or a group, not int. - Indentation. 4 spaces by default;
indent: 2for JavaScript projects. - Message syntax. Messages are ICU by default. Pass another
MessageSyntaxInterfaceto read and write them in their own syntax:new JsonFormatter(new LaravelSyntax())for Laravel's:nameandapple|apples, orTextSyntaxfor plain text where{is just a character. The translator always works with ICU.
One thing JSON keeps and the translator does not: an object with keys "0", "1", … in order is written back as an array, because the translator's tree does not tell the two apart.
Writing over a file
updateFile() (and php artisan i18n:sync of the Laravel package) writes the texts into an existing file: its keys keep their order, missing ones are added at the end of their object, ones the source no longer has are removed, an object stays an object and an array an array, and the file keeps its indentation (spaces or tabs, taken from the file) and its last new line. The result is read back and compared with what was meant before it is returned.
Development
composer check # pint --test, phpstan (level max, strict rules) and phpunit
composer coverageLicense
MIT
From the README.md of EugeneErg/json-formatter-icu-i18n-translator · composer require eugene-erg/json-formatter-icu-i18n-translator