8000 [Translation] Improve LocaleSwitcher a bit by nicolas-grekas · Pull Request #46045 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Translation] Improve LocaleSwitcher a bit #46045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@
use Symfony\Component\Translation\Bridge\Loco\LocoProviderFactory;
use Symfony\Component\Translation\Bridge\Lokalise\LokaliseProviderFactory;
use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\PseudoLocalizationTranslator;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Uid\Factory\UuidFactory;
Expand Down Expand Up @@ -1082,7 +1083,6 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co
$container->removeDefinition('console.command.router_debug');
$container->removeDefinition('console.command.router_match');
$container->removeDefinition('messenger.middleware.router_context');
$container->removeDefinition('translation.locale_aware_request_context');

return;
}
Expand Down Expand Up @@ -1295,6 +1295,11 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
}

$loader->load('translation.php');

if (!ContainerBuilder::willBeAvailable('symfony/translation', LocaleSwitcher::class, ['symfony/framework-bundle'])) {
$container->removeDefinition('translation.locale_switcher');
}

$loader->load('translation_providers.php');

// Use the "real" translator instead of the identity default
Expand Down
2 changes: 0 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddDebugLogProcessorPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AssetsContextPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigureLocaleSwitcherPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\DataCollectorTranslatorPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
Expand Down Expand Up @@ -164,7 +163,6 @@ public function build(ContainerBuilder $container)
$container->addCompilerPass(new RegisterReverseContainerPass(true));
$container->addCompilerPass(new RegisterReverseContainerPass(false), PassConfig::TYPE_AFTER_REMOVING);
$container->addCompilerPass(new RemoveUnusedSessionMarshallingHandlerPass());
$container->addCompilerPass(new ConfigureLocaleSwitcherPass());

if ($container->getParameter('kernel.debug')) {
$container->addCompilerPass(new AddDebugLogProcessorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TranslationsCacheWarmer;
use Symfony\Bundle\FrameworkBundle\Translation\LocaleAwareRequestContext;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\Translation\Dumper\CsvFileDumper;
use Symfony\Component\Translation\Dumper\IcuResFileDumper;
Expand Down Expand Up @@ -46,6 +45,7 @@
use Symfony\Component\Translation\Reader\TranslationReaderInterface;
use Symfony\Component\Translation\Writer\TranslationWriter;
use Symfony\Component\Translation\Writer\TranslationWriterInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

return static function (ContainerConfigurator $container) {
Expand Down Expand Up @@ -164,22 +164,15 @@
->args([service(ContainerInterface::class)])
->tag('container.service_subscriber', ['id' => 'translator'])
->tag('kernel.cache_warmer')
;

if (class_exists(LocaleSwitcher::class)) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be careful NOT doing conditional definition in the config files please. This logic is for DI extensions. Config files should remain purely declarative. /cc @symfony/mergers for future reviews.

$container->services()
->set('translation.locale_switcher', LocaleSwitcher::class)
->args([
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed wrong indentation also

param('kernel.default_locale'),
abstract_arg('LocaleAware services'),
])
->alias(LocaleSwitcher::class, 'translation.locale_switcher')

->set('translation.locale_aware_request_context', LocaleAwareRequestContext::class)
->set('translation.locale_switcher', LocaleSwitcher::class)
->args([
service('router.request_context'),
param('kernel.default_locale'),
tagged_iterator('kernel.locale_aware'),
service('router.request_context')->ignoreOnInvalid(),
])
;
}
->tag('kernel.reset', ['method' => 'reset'])
->alias(LocaleAwareInterface::class, 'translation.locale_switcher')
->alias(LocaleSwitcher::class, 'translation.locale_switcher')
;
};

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Symfony\Component\Cache\DependencyInjection\CachePoolPass;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
Expand Down Expand Up @@ -2019,15 +2018,13 @@ public function testLocaleSwitcherServiceRegistered()
$container = $this->createContainerFromFile('full');

$this->assertTrue($container->has('translation.locale_switcher'));
$this->assertTrue($container->has('translation.locale_aware_request_context'));

$switcherDef = $container->getDefinition('translation.locale_switcher');
$localeAwareRequestContextDef = $container->getDefinition('translation.locale_aware_request_context');

$this->assertSame('%kernel.default_locale%', $switcherDef->getArgument(0));
$this->assertInstanceOf(AbstractArgument::class, $switcherDef->getArgument(1));
$this->assertEquals(new Reference('router.request_context'), $localeAwareRequestContextDef->getArgument(0));
$this->assertSame('%kernel.default_locale%', $localeAwareRequestContextDef->getArgument(1));
$this->assertInstanceOf(TaggedIteratorArgument::class, $switcherDef->getArgument(1));
$this->assertSame('kernel.locale_aware', $switcherDef->getArgument(1)->getTag());
$this->assertEquals(new Reference('router.request_context', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE), $switcherDef->getArgument(2));
}

protected function createContainer(array $data = [])
Expand Down

This file was deleted.

This file was deleted.

29 changes: 23 additions & 6 deletions src/Symfony/Component/Translation/LocaleSwitcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,31 @@

namespace Symfony\Component\Translation;

use Symfony\Component\Routing\RequestContext;
use Symfony\Contracts\Translation\LocaleAwareInterface;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class LocaleSwitcher implements LocaleAwareInterface
class LocaleSwitcher implements LocaleAwareInterface
Copy link
Member Author
@nicolas-grekas nicolas-grekas Apr 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the class is registered as an autowiring alias, it means we're telling ppl they can type-hint for it. Type-hinting for a final class breaks many SOLID principles, so I removed the keyword.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imho, we should register LocaleAwareInterface as an autowiring alias, and not advocate typehinting implementations.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That works for get/setLocale, but runWithLocale isn't in any interfaces, and I'm not sure we want to add one for it.
I'm fine type-hinting with the implem personnaly, but only if it's open for inheritance of course.

{
private string $defaultLocale;

/**
* @param LocaleAwareInterface[] $localeAwareServices
*/
public function __construct(private string $locale, private iterable $localeAwareServices)
{
public function __construct(
private string $locale,
private iterable $localeAwareServices,
private ?RequestContext $requestContext = null,
) {
$this->defaultLocale = $locale;
}

public function setLocale(string $locale): void
{
\Locale::setDefault($this->locale = $locale);
$this->requestContext?->setParameter('_locale', $locale);

foreach ($this->localeAwareServices as $service) {
$service->setLocale($locale);
Expand All @@ -42,17 +50,26 @@ public function getLocale(): string
/**
* Switch to a new locale, execute a callback, then switch back to the original.
*
* @param callable():void $callback
* @template T
*
* @param callable():T $callback
*
* @return T
*/
public function runWithLocale(string $locale, callable $callback): void
public function runWithLocale(string $locale, callable $callback): mixed
{
$original = $this->getLocale();
$this->setLocale($locale);

try {
$callback();
return $callback();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's return the callback's result.

} finally {
$this->setLocale($original);
}
}

public function reset(): void
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Statefull services must at least reset their state.

Although the default locale is already set back in LocaleAwareListener::onKernelFinishRequest(), this doesn't cover eg message handlers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to implement ResetInterface?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not mandatory: ->tag('kernel.reset', ['method' => 'reset'])

{
$this->setLocale($this->defaultLocale);
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Translation/Tests/LocaleSwitcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Translation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Contracts\Translation\LocaleAwareInterface;

Expand Down Expand Up @@ -75,6 +76,24 @@ public function testCanSwitchLocaleForCallback()
$this->assertSame('en', $service->getLocale());
$this->assertSame('en', $switcher->getLocale());
}

public function testWithRequestContext()
{
$context = new RequestContext();
$service = new LocaleSwitcher('en', [], $context);

$this->assertSame('en', $service->getLocale());

$service->setLocale('fr');

$this->assertSame('fr', $service->getLocale());
$this->assertSame('fr', $context->getParameter('_locale'));

$service->reset();

$this->assertSame('en', $service->getLocale());
$this->assertSame('en', $context->getParameter('_locale'));
}
}

class DummyLocaleAware implements LocaleAwareInterface
Expand Down
Loading
0