Disabling the translations for the test environment with Symfony

Published on 2023-01-31 • Modified on 2023-01-31

This snippet shows how to disable the translations for the test environment with Symfony. The goal is to test the translation codes instead of the translated text for a given locale. It makes the test more robust as they won't break if a given translation is modified. You can use the following service that decorates the default translator service. The config is in the yaml property in a HEREDOC block, so you can copy/paste it. It is a simple version: it handles only the translation codes, not the parameters.


<?php

declare(strict_types=1);

namespace App\Translator;

use Symfony\Component\Translation\MessageCatalogueInterface;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Disable translations in the test env.
 *
 * @see https://jolicode.com/blog/how-to-properly-manage-translations-in-symfony
 */
final class NoTranslator implements TranslatorInterface, TranslatorBagInterface, LocaleAwareInterface
{
    public string $yaml;

    /**
     * @param TranslatorInterface&TranslatorBagInterface&LocaleAwareInterface $translator
     */
    public function __construct(
        private readonly TranslatorInterface $translator,
    ) {
        $this->yaml = <<<HEREDOC

when@test:
    services:
        // Disable the translations to test on codes instead of the translated text
        App\Translator\NoTranslator:
            decorates: translator
            arguments:
                - '@App\Translator\NoTranslator.inner'

HEREDOC;
    }

    /**
     * We don't test parameters for now. My advice would be: don't test parameters
     * until you have to fix a related bug reported or if you use them a lot.
     *
     * @param array<mixed> $parameters
     */
    public function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
    {
        // to find EasyAdmin translations codes, uncomment this
        //         if ($domain === 'EasyAdminBundle') {
        //             dump($id);
        //         }

        return $id;
    }

    /**
     * @return array<MessageCatalogueInterface>
     */
    public function getCatalogues(): array
    {
        return $this->translator->getCatalogues();
    }

    public function getCatalogue(?string $locale = null): MessageCatalogueInterface
    {
        return $this->translator->getCatalogue($locale);
    }

    public function setLocale(string $locale): void
    {
        $this->translator->setLocale($locale);
    }

    public function getLocale(): string
    {
        return $this->translator->getLocale();
    }
}

 More on the web  Random snippet

  Work with me!