php-gettext / Gettext

PHP library to collect and manipulate gettext (.po, .mo, .php, .json, etc)
MIT License
687 stars 134 forks source link

Finding out, if translation does not exist #169

Closed wbswbs closed 6 years ago

wbswbs commented 6 years ago

First of all, thanks for your maintanance, I have a question:

In Translator.php there is the following function to translate a key:

    /**
     * @see TranslatorInterface
     *
     * {@inheritdoc}
     */
    public function dpgettext($domain, $context, $original)
    {
        $translation = $this->getTranslation($domain, $context, $original);

        if (isset($translation[0]) && $translation[0] !== '') {
            return $translation[0];
        }

        return $original;
    }

I would like to use the library to create a new Key - Value Pair in my Translation Database, when a key does not exist. But how can I find it out ? Just when the translated Value is the same as the key. But what if the Value should be like the key ? I have no possibility to distinguish..

I would like the Translator to have a default return Value (maybe null) to be returned, when the key does not exist. Of course there should be a way to still return the original key.

Do you think its possible to integrate that in the library ?

oscarotero commented 6 years ago

I think this can be archieve creating a custom Translator class, either extending this class or creating a new whole class implementing the Gettext\TranslatorInterface. So, your custom class could insert the untranslated values directly to de database if they does not exist. For example:

    /**
     * @see TranslatorInterface
     *
     * {@inheritdoc}
     */
    public function dpgettext($domain, $context, $original)
    {
        $translation = $this->getTranslation($domain, $context, $original);

        if (isset($translation[0]) && $translation[0] !== '') {
            return $translation[0];
        }

        $this->createNewTranslation($domain, $context, $original);

        return $original;
    }

In fact, extending this class and simply overriding the getTranslation method to create the new translation automatically in case of returning false should be enought.

wbswbs commented 6 years ago

Thanks, I will do that ...