webfactory / WebfactoryPolyglotBundle

Symfony bundle simplifying translations in Doctrine.
MIT License
3 stars 3 forks source link

Add support for type-safe `TranslatableInterface` fields (Case 167550) #31

Closed mpdude closed 9 months ago

mpdude commented 10 months ago

This PR adds a translatable DBAL type that allows type-safe declarations of entity fields holding translatable values, even without using union types. The requirement for that is that the underlying values that are are strings and would use either the string or text column types in Doctrine ORM.

Example entity from the README:

<?php

use Doctrine\ORM\Mapping as ORM;
use Webfactory\Bundle\PolyglotBundle\Annotation as Polyglot;
use Webfactory\Bundle\PolyglotBundle\TranslatableInterface;

/**
 * @ORM\Entity
 * @Polyglot\Locale(primary="en_GB")
 */
class Document
{
    // ... fields and collections omitted for brevity

    /**
     * @ORM\Column(type="translatable") 
     * @Polyglot\Translatable
     */
    private TranslatableInterface $text;

    // ...
}

The translatable column type behaves like the string column type, but allows you to type hint for TranslatableInterface only (no TranslatableInterface|string union required). If you want the database column to behave like a text type, you can use @ORM\Column(type="translatable", options={"use_text_column": true}).

Note that it is not necessary to do this in the translations class (DocumentTranslation in the README examples), since that class represents the values of a single locale only and never contains Translatable instances.

mpdude commented 10 months ago

@MalteWunsch I hope this addresses your concerns raised in #29

mpdude commented 10 months ago

Good point, I'll see to get that into the README

mpdude commented 10 months ago

I have updated the README. Let me know what you think.