Download the PHP package tmi/translation-bundle without Composer

On this page you can find all versions of the php package tmi/translation-bundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package translation-bundle

TMI Translation Bundle - Doctrine Entity Translations for Symfony

CI codecov PHPStan Latest Version License PHP 8.4+ Symfony 8.0+ Doctrine ORM 3.5+ Total Downloads GitHub Stars

Stores every locale variant as a row in the entity's own table — one indexed lookup per variant, no joins, no translation tables.

How it works

Why This Bundle

Performance. Every query-cost number this README states is enforced by an exact assertion (assertSame, not a ceiling) in Performance table below. Two headline numbers: finding a translatable entity under the active locale filter costs 1 query; translating into an already-existing variant costs 1 query and 0 inserts. Reading pays no per-row overhead — the bundle registers no lifecycle hook on load. Every cross-locale lookup is a single indexed (tuuid, locale) query, preload() batches import lookups per class instead of per entity, and the translation cache resets itself between jobs in long-running workers (kernel.reset).

Verified quality. 100% line coverage is a CI gate (composer test, tracked by the Codecov badge above), not a one-time snapshot. PHPStan runs at level max with the strict-rules, doctrine, symfony and phpunit extensions installed (composer stan). PHPUnit runs in tests/Documentation/DocumentationReferencesTest.php asserts that every link, anchor and class name in these docs still resolves. Every bug fix in this codebase ships with a negative-proof test — one demonstrably red against the old code before the fix, not merely green after it — the discipline is visible directly in the commit history.

✨ Features

⚠️ Limitations & When Not to Use It

📦 Installation

Register the bundle to your config/bundles.php.

The tuuid Doctrine DBAL type registers itself at compile time — there is nothing to add to config/packages/doctrine.yaml. If your application already declares its own dbal.types entry for tuuid (for any reason), that manual entry still wins over the bundle's own registration.

⚙️ Configuration

Configure your available locales in framework.yaml and, optionally, additional bundle settings:

Each configured locale must be 2-16 characters long and match the language[_SUBTAG...] shape (en, en_US, pt_BR_ROMANIAN) — the bundle validates this at compile time, so a locale the locale column cannot hold fails fast instead of truncating silently or erroring at INSERT.

🚀 Quick Start

Make your entity translatable

Implement Tmi\TranslationBundle\Doctrine\Model\TranslatableInterface and use the trait Tmi\TranslationBundle\Doctrine\Model\TranslatableTrait on an entity you want to make translatable.

Translate your entity

Autowire Tmi\TranslationBundle\Translation\EntityTranslatorInterface and let Symfony wire it — every service this bundle registers is private, so there is no $container->get('tmi_translation....') shortcut outside a test container.

Every attribute of the source entity will be cloned into a new entity, unless specified otherwise with the EmptyOnTranslate attribute. Generated IDs (properties with #[ORM\Id] + #[ORM\GeneratedValue]) are automatically reset to null on cloned translations.

translate() is idempotent get-or-create, not a live sync. If a locale variant for the source's Tuuid and the target locale already exists, all three methods above return that existing row as-is — the handler chain does not re-run over it, so edits made to the source entity after the variant was created are not copied into it. This is deliberate: persist/update hooks call translate() on every flush, and re-cloning on every call would mint duplicate locale variants instead of returning the one already on record. Propagating a changed value into existing siblings is #[SharedAmongstTranslations]'s job, not translate()'s — it happens inside the editing flush(), or retroactively through tmi:translation:sync-shared — see below.

🔧 Advanced Usage

Usually, you don't wan't to get all fields of your entity to be cloned. Some should be shared throughout all translations, others should be emptied in a new translation. Two special attributes are provided in order to solve this.

SharedAmongstTranslations

This attribute copies the field's value from the source entity when a new translation is created, and marks the field for retroactive reconciliation via tmi:translation:sync-shared. On a relation to a non-translatable entity, that "copy" is the identical instance — object identity is preserved by translate(), by sync-shared and by the flush-time propagation below. A relation whose target is itself translatable cannot be shared at all — see the note further down.

Two modes. By default (propagate_shared_on_flush: true) the attribute is a flush-time invariant: a change to a shared property on any locale variant — whichever row a form, an import or a command happened to edit — is copied onto every other variant of the same Tuuid inside the same flush(), field by field (an unshared edit touches no sibling, and no sibling is even looked up). Two variants flushed at once with different new values for the same shared property throw SharedValueConflictException before anything is written — never last-wins. A variant created with translate() earlier in the same request receives the update too, so the new row is inserted from the updated source.

Switch it off and the copy happens once, at translate() time: updating the field on one locale variant after the translations exist does not propagate to the siblings — the value diverges silently. That is the right mode for an application that legitimately varies such a value per locale (publishing one language at a time). Gate CI with tmi:translation:sync-shared --check (exits non-zero on drift) and repair with tmi:translation:sync-shared.

Turning it back on for an existing database is a two-step move, not a config edit: get tmi:translation:sync-shared --check to zero drift first, and remove the attribute from every property the application diverges per locale on purpose. With the flag on, such a property is no longer a dormant inconsistency — the next edit on any locale repairs it back to the source value, undoing the divergence on purpose.

The copy itself is the public SharedValueSynchronizer service (Tmi\TranslationBundle\Doctrine\SharedValueSynchronizer, alias tmi_translation.doctrine.shared_value_synchronizer): syncFrom($editedRow) copies the shared values onto every sibling with the edited row as source and returns the siblings that changed — managed, not flushed, so the caller's flush() writes them in the same transaction. That is the fan-out an application needs with the flag off, and siblingsOf() is the per-row loop it may still need with the flag on (a per-locale status field, say). sync() and compare() work on one sibling and report the changed and the readonly-but-drifted property paths; sharedProperties() exposes the discovery. Its read-only counterpart over a whole table is SharedDriftScanner::scan($class) (alias tmi_translation.doctrine.shared_drift_scanner): one SharedDrift per drifted sibling row and property path — entity class, Tuuid, path, source locale, drifted locale, readonly flag — streamed with bounded memory, for an application's own scheduled drift watch instead of parsing sync-shared --check output.

Class-level form. #[SharedAmongstTranslations] on a class is honoured on embeddables only (every inner property shared unless it overrides with #[EmptyOnTranslate]). On an entity class it is inert — translate(), sync-shared and the flush-time propagation all read the attribute per property; mark the properties.

Note: this attribute cannot be used on any association whose target is itself a translatable entity — OneToMany, ManyToMany (either direction), a bidirectional ManyToOne/OneToOne (inversedBy/mappedBy set), or a unidirectional ManyToOne/OneToOne (neither set) all reject it: every handler that can reach one throws a RuntimeException. Share the related entity's own columns instead. This does not apply to a relation whose target is not translatable — the Media example below is that case, and sharing it keeps working exactly as shown.

⚠️ Ordering caveat. Shared values propagate to translations created after the value is set. If you set a shared field in one locale and translate the entity to other locales later, those earlier siblings keep their stale value. To back-fill existing data, run:

--tuuid restricts a run to one record — every locale variant of that Tuuid, found in any translatable class or only in --entity — and --source-locale names the row to copy from instead of the default-locale row. That is the targeted repair for a record edited in a non-default locale, where the whole-table write mode would overwrite the edited row with the stale default-locale values; --source-locale is only accepted together with --tuuid, because which row is right is a per-record decision. --dry-run and --check apply as usual.

The command propagates #[SharedAmongstTranslations] values from the default-locale row to every sibling — mapped columns, embedded fields and single-valued associations to a non-translatable target (the same discovery the flush-time propagation uses; a shared collection, or an association to a translatable target, is rejected at translate time and is never synced). Every run prints a table naming each drifted property, how many Tuuid groups and rows it touched, and whether it was writable — nothing to enable, it always runs after the count line.

Embedded fields are covered in all three places sharing can be declared: on the entity property (the whole embeddable is copied), on the embeddable class (every inner property except those overridden with #[EmptyOnTranslate]), or on an individual inner property. This mirrors how EmbeddedHandler resolves sharing at translate time.

A readonly shared property cannot be written after hydration. The command reports such rows instead of crashing, syncs everything else, and exits non-zero — correct those values manually or at the database level.

EmptyOnTranslate

This attribute will empty the field when creating a new translation. ATTENTION: the field must be able to hold an empty value. A nullable property becomes null; a Doctrine\Common\Collections\Collection becomes a fresh empty collection; a non-nullable scalar gets a type-safe default (string → '', int → 0, float → 0.0, bool → false, array → []) and therefore does not have to be nullable. A nullable value object — DateTimeImmutable, an enum, a uid, any object Doctrine has no mapping for — is emptied to null like any nullable field (the same goes for copy_source: false). A non-nullable object, enum, intersection type or iterable/callable has no safe empty value: the container fails to compile (EmptyOnTranslateTypeException) naming the property. Make those nullable, or use #[SharedAmongstTranslations] instead.

Seeding new variants — what copy_source: false leaves behind

With copy_source: false (the default), a freshly created variant starts empty: nullable columns are null, non-nullable scalars get type-safe defaults ('', 0, 0.0, false). That includes fields your application treats as mandatory — a name, a slug. Two consequences you must handle:

Do not clone the source's slug as a workaround. Use the supported seeding hook instead: listen for PostTranslateEvent and mint locale-correct placeholder values the moment the variant is constructed — the event fires before anything is persisted:

Before publication, assert the variant carries real content rather than placeholders — the per-locale completeness API (LocaleCompletenessResolver, see below) reports a variant whose required content is still missing as Incomplete.

Translate events

You can alter the entities before and after a variant is constructed by listening for Tmi\TranslationBundle\Event\PreTranslateEvent and Tmi\TranslationBundle\Event\PostTranslateEvent — both extend the shared TranslateEvent base and are dispatched by class, never by a string event name.

Subscribe with #[AsEventListener(event: PreTranslateEvent::class)] / #[AsEventListener(event: PostTranslateEvent::class)], or $dispatcher->addListener(PostTranslateEvent::class, ...).

Both events also fire for translatable entities reached through associations, so check the entity class in your listener.

Filtering your contents

To fetch your contents out of your database in the current locale, you'd usually do something like $repository->findByLocale($request->getLocale()).

Alternatively, you can use the provided filter that will automatically filter any Translatable entity by the current locale, every time you query the ORM. This way, you can simply do $repository->findAll() instead of the previous example.

Add this to your config/packages/doctrine.yaml:

The filter locale is set on every kernel.request, including sub-requests (fragments rendered with render(controller(...)), ESI, forwards), so a fragment queries in its own locale. On kernel.finish_request the parent request's locale is re-applied, mirroring Symfony's LocaleAwareListener — the shared EntityManager filter never keeps a fragment's locale for the rest of the parent request.

(Optional) Disable the filter for a specific firewall

Usually you'll need to administrate your contents. For doing so, you can disable the filter by configuring the disabled_firewalls option in your configuration:

Quick Fix for unique fields

If you need a translatable slug (or UUID), adjust your database schema to make the slug unique per locale, instead of globally. The locale column already belongs to TranslatableTrait — don't redeclare it, just reference it in the constraint:

Querying Locale Variants

Always use these helpers for cross-locale lookups. Hand-rolled WHERE tuuid = ... queries get the tmi_translation_locale_filter wrong and silently return only the current-locale row.

The quickest way is to extend the ready-made TranslatableEntityRepository base class:

If your repository must extend something else, use TranslatableRepositoryTrait directly:

Both methods temporarily disable the tmi_translation_locale_filter (if enabled) to query across all locales.

TranslatableRepositoryTrait offers exactly the two methods above and nothing else — a thin wrapper around Tmi\TranslationBundle\Doctrine\LocaleVariantFinder. The finder itself carries two more, single-locale lookups that have no trait equivalent: findLocaleVariant(class, tuuid, locale) and findLocaleVariantsBatch(class, tuuids, locale). Inject LocaleVariantFinder directly wherever a repository isn't the natural fit (a service, a console command) or you need those two methods.

Removing a translatable entity

Plain $em->remove($entity) removes exactly the row you pass it — nothing links a translatable entity's sibling locale variants for Doctrine to cascade through on its own, so a naive delete leaves every other locale's copy of the same content online.

Inject Tmi\TranslationBundle\Doctrine\TranslatableRemover to remove correctly:

Every variant goes through EntityManager::remove() individually — never a bulk DQL DELETE — so ORM cascades, orphanRemoval and lifecycle callbacks fire exactly as they would removing one entity at a time.

(Optional) Cascade it automatically

Set cascade_remove_locale_variants: true and a plain $em->remove($entity) on any translatable entity removes its sibling locale variants too, via a preRemove listener:

With the flag on, TranslatableRemover::removeSingleLocaleVariant() becomes the escape hatch for the rarer case — deleting one variant while its siblings stay online.

Per-Locale Completeness

LocaleCompletenessResolver answers, per enabled locale, whether a Tuuid has a variant and whether that variant's translatable content is complete — the building block for admin views showing per-language translation status:

Completeness is relative to a baseline variant — the default-locale row, or the first variant when no default-locale row exists: a variant is complete when every translatable property that is filled on the baseline is filled on it too. Optional fields left empty on the baseline never count against the translations. Identifiers, system columns, shared properties and associations are not inspected; embedded fields contribute their non-shared inner properties; "filled" means not null and, for strings, not blank.

The tuuid column is automatically indexed: the bundle injects a composite (tuuid, locale) index into every translatable entity at mapping time, so locale-variant lookups never hit an unindexed scan. Set unique_locale_variants: true to promote it to a UNIQUE constraint — do this only once existing data is free of duplicate locale rows (see tmi:translation:doctor).

Translation roots

A translatable entity is one row per locale sharing a tuuid. Data that belongs to the object rather than to a language — children, foreign keys, shared scalars — has nowhere to hang: it either sits on one locale row or is keyed by the bare tuuid string with no foreign key. A translation root fixes that: one non-translatable row per object, owning the tuuid, that every locale variant references with a real ManyToOne. Doctrine then cascades natively.

A property is a root reference structurally — a ManyToOne whose declared type implements TranslationRootInterface — with or without the #[TranslationRoot] marker. translate() then hands every clone the identical root instance, tmi:translation:sync-shared --check compares it by identity (and never re-points it), and the compile-time validation refuses the shapes that cannot work: two root references on one class, a root type that is also translatable, #[ORM\Id] or #[EmptyOnTranslate] on the reference, a unique join column, a marker on a non-root property. Once the reference is non-nullable, the constructor must require the root — that is the switch that says "this class has finished migrating".

Existing rows predate their roots. tmi:translation:adopt-root creates them, one per tuuid group, through an adopter you register for each translatable hierarchy:

The command classifies every group before writing anything — new, complete, partial, drift (a row whose tuuid differs from its root's), ambiguous (two roots in one group), mismatched (rows disagree on root class or coherence key) — and refuses to write while any group is drifted, ambiguous or mismatched. Otherwise it adopts in batches of whole groups: a new group gets a root that adopts the group's tuuid, a partial group is healed onto its existing root. --check writes nothing and fails on anything but complete, on roots without rows (counted generically with NOT EXISTS), and on any tmi_translation.tuuid_orphan_counter service above zero — your own count of rows in tables the bundle does not know that reference a tuuid no row carries. Every counter is printed, at 0 too.

Roll out in two phases without a configuration key: first a nullable reference (adopt-root fills it, --check to zero), then make it non-nullable and add the constructor parameter.

Diagnostics

Every locale variant of an entity shares one Tuuid. Translations created through EntityTranslator::translate() inherit it automatically. If application code instead does new Entity() + setLocale('de_DE') and persists it without a shared Tuuid, the result is a standalone entity linked to no other locale — a silent data bug.

The bundle guards against this:

⚡ Performance

Every number in this table is enforced by an exact assertion (assertSame, not a ceiling) in tests/Performance/QueryBudgetTest.php — a query counter wired into the test kernel behind DBAL's own logging middleware, one count per executed statement.

Operation Queries
find() a translatable entity under the active locale filter 1
translate() into an already-existing variant 1 (0 inserts)
translate() a parent with K already-translated association children 2
translate() a child already cloned through its parent's collection 0
LocaleCompletenessResolver::resolveBatch() for 100 Tuuids 1
LocaleVariantFinder::findAllLocaleVariantsBatch() 1
tmi:translation:doctor (per root class scanned, or with --entity) 2
Import of N new entities via preload() + getOrTranslate() + flush() 1 + N
tmi:translation:sync-shared --dry-run / --check (per class, any number of groups) 1
tmi:translation:sync-shared write mode (per class, D drifted sibling rows) 1 + D
tmi:translation:adopt-root --dry-run / --check (per hierarchy, any number of groups) 2
tmi:translation:adopt-root write mode (K new groups holding R rows) 3 + K + R

Why the association-children row is 2, not 1 + K. BidirectionalOneToManyHandler, BidirectionalManyToManyHandler and UnidirectionalManyToManyHandler each hand their whole collection to preload() once, before looping — one batched LocaleVariantFinder query per child class, whether it finds K hits, K misses, or a mix — instead of leaving each child's own translate() call to query for itself. The parent's own preload() lookup (a miss, since it is what triggered the translation) is the other query. A collection mixing several child classes costs one query per class, not per child; a non-translatable item mixed into a ManyToMany collection is skipped by preload() and never queried at all.

Why the child row is 0. Every translation a handler produces is cached under its own (tuuid, locale) — a child cloned while its parent was translated included, whether or not its back-reference is #[SharedAmongstTranslations]. Translating that child on its own afterwards is a cache hit. A removed row's entry is evicted on postRemove, so the hit is never a dead instance.

Why the import row is 1 + N, not 1 + 3N. The upfront preload() remembers every Tuuid its one batched query looked up and found nothing for, so each entity's own internal preload() call — and the handler chain reached once that (already-known) miss falls through to it — never asks the database the same question again; only the N INSERTs on flush() are left. The one caveat: a variant for a remembered Tuuid created by anything other than this translator (a manual persist(), another process) stays invisible to it until this translator creates one for that pair or the service is reset — EntityTranslator is tagged kernel.reset for exactly this (see preload()'s docblock).

Why the command rows do not grow with the table. Both commands walk a table through one streamed query grouped by Tuuid, compare in memory and detach each settled group. sync-shared adds exactly one UPDATE per drifted sibling row on its batch flush. adopt-root fetch-joins the root reference into that stream: a translation root is usually an inheritance hierarchy, and Doctrine cannot proxy a to-one target that has subclasses — it would find() it once per row. The second query is the NOT EXISTS count of roots without rows; write mode streams once more for pass 2 and pays one INSERT per new root and one UPDATE per attached row.

Reflection is cached, not repeated. AttributeHelper and ReflectionHelper::getHierarchyProperties() memoize per (proxy-unwrapped) class — the hot path inside translate() never re-walks a class's attributes and property hierarchy per property, per call.

The (tuuid, locale) index doesn't cover a bare locale = ? predicate (locale is not its leftmost column) — a dedicated locale-only index is not worth adding regardless, since a query planner facing 2-10 distinct locale values would usually ignore one anyway.

Imports and long-running workers. Call preload($batch, $locale) once before looping getOrTranslate() over a batch (see the import row above) — and if your process outlives one request or job (a queue consumer, a long-running import), both InMemoryTranslationCache and EntityTranslator itself are tagged kernel.reset, so they clear themselves between units of work instead of handing the next one an entity the last one cached (possibly one since detached) or a stale "Tuuid not found" answer from preload()'s own miss memory.

🤖 AI-Assisted Development

This bundle includes AI skills that help you implement translations correctly. These skills work with Claude Code and other AI coding assistants.

Available Skills

Skill Purpose When to Use
Entity Translation Setup Guides you through making any Doctrine entity translatable "Make my Product entity translatable"
Translation Debugger Diagnoses and fixes translation configuration issues "Translation not working", "Why isn't my entity translating?"
Custom Handler Creator Helps create custom handlers for specialized field types "Create a handler for encrypted fields"

Using with Claude Code

If you're using Claude Code, the skills are automatically available when working in this project. Simply describe what you need:

Claude Code will automatically invoke the appropriate skill and guide you through the process.

Using with Other AI Assistants

The skills are defined in .agents/skills/ and follow a standard markdown format. Point your AI assistant to:

For comprehensive documentation optimized for AI assistants, see:

📖 Upgrading

5.0.0 is the current release and the only supported one. Anything below it receives no fixes — upgrade rather than reporting an issue against an older tag.

CHANGELOG.md is the single source for what changed in each release; UPGRADING.md carries the migration steps, newest path first, with the unsupported paths kept below an archive divider as a historical reference only.

🤝 Contributing

We welcome contributions!

📄 License

This bundle is licensed under the MIT License.

🙏 Acknowledgments

Based on the original work by umanit/translation-bundle, now completely modernized for current PHP and Symfony ecosystems.


⭐ If this bundle helps you, please give it a star on GitHub!


All versions of translation-bundle with dependencies

PHP Build Version
Package Version
Requires php Version >=8.4
ext-json Version *
doctrine/collections Version ^2.2 || ^3.0
doctrine/dbal Version ^4.2
doctrine/doctrine-bundle Version ^2.18 || ^3.0
doctrine/orm Version ^3.5.8
doctrine/persistence Version ^4.0
psr/log Version ^3.0
symfony/config Version ^8.0
symfony/console Version ^8.0
symfony/dependency-injection Version ^8.0
symfony/event-dispatcher Version ^8.0
symfony/framework-bundle Version ^8.0
symfony/http-kernel Version ^8.0
symfony/property-access Version ^8.0
symfony/security-bundle Version ^8.0
symfony/service-contracts Version ^3.6
symfony/uid Version ^8.0
symfony/yaml Version ^8.0
twig/twig Version ^3.22.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package tmi/translation-bundle contains the following files

Loading the files please wait ...