Search by

lsr / translations

Heroyt

Framework-neutral gettext localization runtime (native gettext or compiled PHP catalogs) with optional Laravel integration.

0.2.0 2026-12-01 09:19 UTC

This package is auto-updated.

Last update: 2026-12-01 09:21:09 UTC


README

lsr/translations is a framework-neutral gettext runtime: supported-language resolution, locale application, and contextual/plural message translation with sprintf or %{name} interpolation. It ships two drivers, native gettext and compiled PHP catalogs, behind one MessageTranslator interface. Namespace: Lsr\Translations\.

It is the translation engine of lsr/core (0.7+) and of the optional TextTranslator of lsr/text-catalog, and it ships an optional Laravel 12+ service provider.

Installation

composer require lsr/translations

The package is available from Packagist and from the LSR Satis repository (https://packages.laserliga.cz).

Requirements

  • PHP >=8.4 and gettext/languages ^2.10.
  • native driver: ext-gettext. On glibc, also installed OS locales for every supported language (locale -a); a missing OS locale silently leaves messages untranslated. On Alpine/musl no OS locales are needed.
  • php driver: no extension and no OS locales.
  • Optional: gettext/gettext ^5.7 to write PHP catalogs and for the commands, symfony/console ^7.4 || ^8.0 for the commands, laravel/framework ^12.0 || ^13.0 for the service provider. Older Laravel versions conflict.

Drivers

native php
Reads <locale>/LC_MESSAGES/<domain>.mo <locale>/LC_MESSAGES/<domain>.php
Locale lives in the process (setlocale, environment, domain bindings) a PhpCatalogEnvironment object
Environment / translator GettextEnvironment / GettextTranslator Php\PhpCatalogEnvironment / Php\PhpTranslator
Threaded runtimes one locale per process at a time safe: one environment per request

Both drivers produce the same output for the same catalog: the package's tests run one fixture set through both. The driver is configured, never auto-detected, so an image that loses ext-gettext fails instead of switching drivers.

use Lsr\Translations\GettextEnvironment;
use Lsr\Translations\GettextTranslator;
use Lsr\Translations\Localization;
use Lsr\Translations\Php\PhpCatalogEnvironment;
use Lsr\Translations\Php\PhpTranslator;
use Lsr\Translations\SupportedLanguages;

$languages = new SupportedLanguages(['cs_CZ', 'en_US']);

// native
$environment = new GettextEnvironment('messages', __DIR__ . '/languages', ['results' => __DIR__ . '/languages']);
$localization = new Localization($languages, $environment, defaultLanguage: 'cs_CZ'); // applied immediately
$translator = new GettextTranslator('messages');

// php
$environment = new PhpCatalogEnvironment('messages', __DIR__ . '/languages', ['results' => __DIR__ . '/languages']);
$localization = new Localization($languages, $environment, defaultLanguage: 'cs_CZ');
$translator = new PhpTranslator($environment, 'messages');

$localization->setLocale('en');                     // resolves to en_US and applies it
echo $translator->translate('Hello %{name}', format: ['name' => 'Ada']);
echo $translator->translate('%d player', '%d players', 3, format: [3]);
echo $translator->translate('Open', context: 'menu', domain: 'results');
echo $localization->withLocale('cs', fn () => $translator->translate('Open')); // then back to en_US
  • SupportedLanguages accepts a list of language_COUNTRY codes or a language => COUNTRY map; each language maps to one country. resolve('cs') and resolve('cs_CZ') both return the cs_CZ Locale. Unknown or unsupported languages throw InvalidLanguageException.
  • Localization applies its locale to a LocaleEnvironment. setLocale() applies only when the resolved locale changes; a rejected locale keeps the active one. withLocale() runs a callback in another locale and restores the previous one, also when the callback throws.
  • GettextEnvironment::apply() sets LANGUAGE, LANG, LC_ALL, setlocale(LC_ALL/LC_MESSAGES), binds every domain with UTF-8 and re-selects the default domain, which also invalidates GNU gettext's translation cache.
  • MessageTranslator::translate() uses the gettext context (msgctxt), selects the plural form whenever a plural is given, and strips the context from untranslated messages; untranslated plurals fall back to the msgid for n == 1 and to the plural otherwise. Integer format keys use sprintf; string keys replace %{name} placeholders (vue-gettext compatible). Mixed key kinds and non-scalar values are rejected.
  • Output is unescaped data: render it through the consumer's normal escaping.

Process-global state (native)

Native gettext state belongs to the PHP process and, in ZTS builds, to every thread. Apply locales sequentially. Long-running workers (RoadRunner, Octane, queue workers) must apply the locale of each request or job; concurrent requests in one process, such as threaded FrankenPHP workers, need the php driver.

PHP catalogs

<directory>/<locale>/LC_MESSAGES/<domain>.php returns an array: formatVersion (1), locale, pluralCount, plural (a closure) and messages, keyed like MO (context\x04msgid or msgid; plural entries list every form). The catalogs are trusted build output, loaded with require (opcached) and memoized per process like MO files.

The plural rule is emitted as PHP code from the CLDR formula of gettext/languages when the catalog is written, never from the catalog's Plural-Forms header, so nothing is evaluated at runtime and translator-supplied text never becomes code. A catalog whose header declares another number of plural forms than CLDR is refused.

  • Php\PhpCatalogWriter::write($translations, 'cs_CZ', $path) writes a catalog from gettext/gettext translations (loaded from PO or MO). Like msgfmt, obsolete, fuzzy and untranslated entries are left out.
  • CatalogCompiler::compile($directory, 'cs_CZ', 'messages') compiles <domain>.po into <domain>.mo and <domain>.php; a domain that only has an MO file gets its PHP catalog from the MO.
  • The translations:compile console command (--domain to limit it) does that for every configured domain and supported language.
  • lsr/text-catalog 0.4+ writes the PHP catalog of its own domain itself.

Laravel

The service provider is auto-discovered. Publish the configuration when the defaults do not fit:

php artisan vendor:publish --tag=lsr-translations-config
// config/lsr-translations.php
return [
    'driver' => env('TRANSLATIONS_DRIVER', 'native'), // native | php
    'directory' => lang_path('gettext'),      // kept apart from Laravel's PHP/JSON translations
    'default_domain' => 'messages',
    'domains' => ['results' => null],         // null uses `directory`
    'default_language' => 'en_US',            // used for unsupported Laravel locales
    'supported_languages' => ['en_US', 'cs_CZ'],
    'laravel' => [                            // Laravel's framework messages through gettext, see below
        'enabled' => false,
        'domain' => 'laravel',
        'groups' => ['validation', 'auth', 'passwords', 'pagination'],
        'source_locale' => 'en',
    ],
];

An unknown driver, or native without ext-gettext, fails at boot with an error that names lsr-translations.driver.

Laravel owns locale selection. The provider mirrors App::getLocale() into the driver when the localization is first resolved, on every LocaleUpdated event, and on Octane's RequestReceived. Laravel locales such as cs resolve to cs_CZ; unsupported locales select default_language. Localization, LocaleEnvironment and MessageTranslator are scoped bindings, so every Octane request and queue job starts with fresh state; do not keep them in singletons of your own.

Inject Lsr\Translations\MessageTranslator (bound to the driver's translator) or use the Blade directive, which escapes its output:

@gettext('Hello %{name}', format: ['name' => $user->name])
@gettext('%d player', '%d players', $count, format: [$count])

Laravel's own __(), trans() and @lang keep working with Laravel's PHP/JSON translations.

Framework messages through gettext

With laravel.enabled, Laravel's translation loader is decorated so that the configured groups (validation, auth, password reset and pagination messages) come from the laravel gettext domain, through the configured driver:

  • every string in the source_locale files of a group is a gettext message: the context is the dotted Laravel key (validation.required, validation.between.numeric, validation.custom.email.required), the msgid its English text;
  • translations are laid over Laravel's files of the requested locale. A key missing from the domain, or whose English text changed after a Laravel upgrade, keeps Laravel's file value; an entry translated to its English text counts as missing;
  • :attribute placeholders and {0}|[1,*] choices pass through: Laravel replaces them after loading;
  • JSON translations, other groups, package (namespaced) groups, the source locale and unsupported locales are Laravel's.
php artisan translations:laravel:extract cs   # lang/gettext/laravel.pot and cs_CZ/LC_MESSAGES/laravel.po
php artisan translations:compile              # laravel.mo and laravel.php for every supported language

translations:laravel:extract writes the POT from the source-locale files (Laravel's own plus lang/en) and merges it into the PO of each given locale: existing translations are kept, a changed English text marks its translation fuzzy, removed keys become obsolete, and untranslated entries are seeded from Laravel's own files of that locale, for example lang/cs/*.php from laravel-lang/lang. A locale that is not supported yet is given as de_DE.

Development and verification

composer install
composer validate --strict --no-check-publish
composer phpstan
composer test
composer cs

Native tests need ext-gettext and, on glibc, the cs_CZ, de_DE and en_US OS locales; without them they are skipped and the php driver tests still run. CI runs PHP 8.4 and 8.5 against Laravel 12 and 13 (Testbench 10 and 11).

Upgrading from 0.1

  • ext-gettext is suggested instead of required. Applications on the native driver must require it themselves (lsr/core does).
  • Localization::$environment is typed LocaleEnvironment; GettextEnvironment implements it, so existing construction is unchanged.
  • Laravel: the driver defaults to native, so existing applications behave as before. Localization and MessageTranslator are now scoped instead of singletons, and MessageTranslator is no longer an alias of GettextTranslator.

License

MIT, copyright (c) 2026 Tomáš Vojík.