Skip to content

[BC] Filter method trans of Twig Bridge should allow null values for $message parameter again #37931

@Flinsch

Description

@Flinsch

Symfony version(s) affected: 5.*

Description
Upgrading Symfony from 4.4 to 5.* has led to BC breaks in our projects since filter method trans of class Symfony\Bridge\Twig\Extension\TranslationExtension does not allow null values for $message anymore. In our projects, we tried to overcome this problem by using the null coalescing operator with an empty string where it was required, but this change turned out to be too time-consuming, so we just provided our own Twig implementation for trans hiding/overriding that from the Symfony Twig Bridge. Yes, this is pretty dirty and we feel bad about it, so we hope for a "correction" of the BC break.

How to reproduce
To reproduce the problem just call trans on a null value in one of your Twig templates, for example:

{{ null|trans }}

Possible Solution
I suggest allowing null values for the $message parameter of filter method trans in Symfony\Bridge\Twig\Extension\TranslationExtension again:

public function trans(?string $message, array $arguments = [], string $domain = null, string $locale = null, int $count = null): string
{
    if (empty($message)) {
        return ''; // Early out, but not really necessary.
    }

    if (null !== $count) {
        $arguments['%count%'] = $count;
    }

    return $this->getTranslator()->trans($message, $arguments, $domain, $locale);
}

Additional context
All implementations of Symfony\Contracts\Translation\TranslatorInterface in fact do allow null values as well, so there is no need to restrict the parameter to be not null. On the contrary, it is even inconsistent to forbid null values.

One might think it's nonsense to write something like {{ null|trans }}. Yes, but this was just a simple example for reproducing the problem. When the possible to-be-translated string comes from some kind of user-configured object, for example, then it makes perfect sense:

{{ form_row(form.shop_contact_url, { attr: { placeholder: tenant.findContactDetailByType('TYPE_WEBSITE') } }) }}

(The value of placeholder gets translated by calling trans filter automatically.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions