lsr / translations
Framework-neutral gettext localization runtime (native gettext or compiled PHP catalogs) with optional Laravel integration.
Requires
- php: >=8.4
- gettext/languages: ^2.10
Requires (Dev)
- ext-gettext: *
- friendsofphp/php-cs-fixer: ^3.95
- gettext/gettext: ^5.7
- orchestra/testbench: ^10.0 || ^11.0
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^12.0 || ^13.0
- symfony/console: ^7.4 || ^8.0
Suggests
- ext-gettext: for the native driver (the default); the php driver needs no extension.
- gettext/gettext: ^5.7 to write PHP catalogs (PhpCatalogWriter, CatalogCompiler) and for the translations commands.
- laravel/framework: ^12.0 || ^13.0 for the optional Laravel service provider.
- symfony/console: ^7.4 || ^8.0 for the translations:compile and translations:laravel:extract commands.
Provides
None
Conflicts
- laravel/framework: <12.0
Replaces
None
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.4andgettext/languages ^2.10. nativedriver: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.phpdriver: no extension and no OS locales.- Optional:
gettext/gettext ^5.7to write PHP catalogs and for the commands,symfony/console ^7.4 || ^8.0for the commands,laravel/framework ^12.0 || ^13.0for 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
SupportedLanguagesaccepts a list oflanguage_COUNTRYcodes or alanguage => COUNTRYmap; each language maps to one country.resolve('cs')andresolve('cs_CZ')both return thecs_CZLocale. Unknown or unsupported languages throwInvalidLanguageException.Localizationapplies its locale to aLocaleEnvironment.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()setsLANGUAGE,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 forn == 1and to the plural otherwise. Integerformatkeys usesprintf; 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 fromgettext/gettexttranslations (loaded from PO or MO). Likemsgfmt, obsolete, fuzzy and untranslated entries are left out.CatalogCompiler::compile($directory, 'cs_CZ', 'messages')compiles<domain>.pointo<domain>.moand<domain>.php; a domain that only has an MO file gets its PHP catalog from the MO.- The
translations:compileconsole command (--domainto limit it) does that for every configured domain and supported language. lsr/text-catalog0.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_localefiles 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;
:attributeplaceholders 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-gettextis suggested instead of required. Applications on the native driver must require it themselves (lsr/coredoes).Localization::$environmentis typedLocaleEnvironment;GettextEnvironmentimplements it, so existing construction is unchanged.- Laravel: the driver defaults to
native, so existing applications behave as before.LocalizationandMessageTranslatorare now scoped instead of singletons, andMessageTranslatoris no longer an alias ofGettextTranslator.
License
MIT, copyright (c) 2026 Tomáš Vojík.