PHP code example of tmi / translation-bundle

1. Go to this page and download the library: Download tmi/translation-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tmi / translation-bundle example snippets


return [
// ...
Tmi\TranslationBundle\TmiTranslationBundle::class => ['all' => true],
];



namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Tmi\TranslationBundle\Doctrine\Model\TranslatableInterface;
use Tmi\TranslationBundle\Doctrine\Model\TranslatableTrait;

#[ORM\Entity]
class Product implements TranslatableInterface
{
    use TranslatableTrait;
    
    #[ORM\Column]
    private string $name;
    
    // ... your other fields
}

public function __construct(private EntityTranslatorInterface $entityTranslator)
{
}

// Translate only (caller must persist)
$translatedEntity = $this->entityTranslator->translate($entity, 'de_DE');

// Translate and persist in one call
$translatedEntity = $this->entityTranslator->translateAndPersist($entity, 'de_DE');

// Find existing translation or create + persist a new one
$translatedEntity = $this->entityTranslator->getOrTranslate($entity, 'de_DE');

#[ORM\ManyToOne(targetEntity: Media::class)]
#[SharedAmongstTranslations]
private Media $video; // Shared across all translations -- Media is not itself translatable


#[ORM\ManyToOne(targetEntity: Owner::class, cascade: ['persist'], inversedBy: 'product')]
#[ORM\JoinColumn(name: 'owner_id', referencedColumnName: 'id', nullable: true)]
#[EmptyOnTranslate]
private Owner|null $owner = null

#[ORM\Column(type: 'string', nullable: true)]
#[EmptyOnTranslate]
private string|null $title = null;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Tmi\TranslationBundle\Event\PostTranslateEvent;

#[AsEventListener(event: PostTranslateEvent::class)]
final class ListingVariantSeeder
{
    public function __invoke(PostTranslateEvent $event): void
    {
        $variant = $event->getTranslatedEntity();

        if (!$variant instanceof Listing || null !== $variant->getSlug()) {
            return;
        }

        // Unique per variant, obviously non-public, easy to assert on later.
        $variant->setSlug(sprintf('draft-%s-%s', $event->getLocale(), $variant->getTuuid()));
    }
}

#[ORM\Entity]
#[ORM\Table(name: 'product')]
#[ORM\UniqueConstraint(
    name: 'uniq_slug_locale',
    columns: ['slug', 'locale']
)]
class Product implements TranslatableInterface
{
    use TranslatableTrait; // already provides the NOT NULL, length-16 $locale column

    #[ORM\Column(length: 255)]
    private string $slug;
}

use Tmi\TranslationBundle\Doctrine\Repository\TranslatableEntityRepository;

/** @extends TranslatableEntityRepository<Product> */
class ProductRepository extends TranslatableEntityRepository
{
}

use Doctrine\ORM\EntityRepository;
use Tmi\TranslationBundle\Doctrine\Repository\TranslatableRepositoryTrait;

class ProductRepository extends EntityRepository
{
    use TranslatableRepositoryTrait;
}

// All locale variants for a single Tuuid, keyed by locale
$variants = $repository->findAllLocaleVariants($product->getTuuid());
// ['en_US' => Product, 'de_DE' => Product, ...]

// Batch lookup for multiple Tuuids
$batch = $repository->findAllLocaleVariantsBatch([$tuuid1, $tuuid2]);
// ['<tuuid1>' => ['en_US' => Product, ...], '<tuuid2>' => [...]]

use Doctrine\ORM\EntityManagerInterface;
use Tmi\TranslationBundle\Doctrine\TranslatableRemover;

public function __construct(
    private TranslatableRemover $remover,
    private EntityManagerInterface $entityManager,
) {
}

// Schedules every locale variant sharing $product's Tuuid for removal, $product
// 

use Tmi\TranslationBundle\Translation\LocaleCompletenessResolver;
use Tmi\TranslationBundle\ValueObject\TranslationStatus;

public function __construct(private LocaleCompletenessResolver $completeness) {}

$status = $this->completeness->resolveForEntity($product);

$status->statusOf('de_DE');    // TranslationStatus::Missing | Incomplete | Complete
$status->missingLocales();     // ['it_IT']
$status->isFullyTranslated();  // false

// Admin lists: hundreds of rows, one query
$byTuuid = $this->completeness->resolveBatch(Product::class, $tuuids);
$byTuuid[(string) $product->getTuuid()]->statuses(); // ['en_US' => Complete, ...]

use Tmi\TranslationBundle\Doctrine\Model\TranslationRootInterface;
use Tmi\TranslationBundle\Doctrine\Model\TranslationRootTrait;

#[ORM\Entity]
class Listing implements TranslationRootInterface   // NOT translatable: no locale, no listeners
{
    use TranslationRootTrait;                        // unique `tuuid` column; mintTuuid() / adoptTuuid() / getTuuid()

    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;
}

#[ORM\Entity]
class Property implements TranslatableInterface
{
    use TranslatableTrait;

    #[ORM\ManyToOne(targetEntity: Listing::class)]
    #[ORM\JoinColumn(nullable: false)]
    #[TranslationRoot]                               // optional marker -- the TYPE makes it a root reference
    private Listing $listing;

    public function __construct(Listing $listing)
    {
        $this->listing = $listing;
        $this->setTuuid($listing->getTuuid());       // copy the identity, never mint one
    }
}

$listing = new Listing();
$listing->mintTuuid();                               // the one place an identity is born
$row = new Property($listing);

final class PropertyRootAdopter implements RootAdopterInterface
{
    public function getTranslatableClass(): string { return Property::class; }
    public function getRoot(TranslatableInterface $row): ?TranslationRootInterface { /* $row->getListing() */ }
    public function createRootFor(array $group): TranslationRootInterface { return new Listing(); }   // WITHOUT a tuuid
    public function attach(TranslatableInterface $row, TranslationRootInterface $root): void { /* setter or reflection */ }
    public function rootClassFor(TranslatableInterface $row): string { return Listing::class; }        // STI: from the discriminator
    public function coherenceKey(TranslatableInterface $row): string { return ''; }                     // what else must agree inside a group
}

  php bin/console tmi:translation:doctor
  php bin/console tmi:translation:doctor --entity="App\Entity\Product"