Skip to content

[FrameworkBundle][Translation] add LocaleSwitcher service #45793

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
Mar 26, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*
* @internal
*/
class ConfigureLocaleSwitcherPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->has('translation.locale_switcher')) {
return;
}

$localeAwareServices = array_map(
fn (string $id) => new Reference($id),
array_keys($container->findTaggedServiceIds('kernel.locale_aware'))
);

if ($container->has('translation.locale_aware_request_context')) {
$localeAwareServices[] = new Reference('translation.locale_aware_request_context');
}

$container->getDefinition('translation.locale_switcher')
->setArgument(1, new IteratorArgument($localeAwareServices))
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,7 @@ 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
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
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 @@ -158,6 +159,7 @@ 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,6 +13,7 @@

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 All @@ -39,6 +40,7 @@
use Symfony\Component\Translation\Loader\QtFileLoader;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\LoggingTranslator;
use Symfony\Component\Translation\Reader\TranslationReader;
use Symfony\Component\Translation\Reader\TranslationReaderInterface;
Expand Down Expand Up @@ -163,4 +165,21 @@
->tag('container.service_subscriber', ['id' => 'translator'])
->tag('kernel.cache_warmer')
;

if (class_exists(LocaleSwitcher::class)) {
$container->services()
->set('translation.locale_switcher', LocaleSwitcher::class)
->args([
param('kernel.default_locale'),
abstract_arg('LocaleAware services'),
])
->alias(LocaleSwitcher::class, 'translation.locale_switcher')

->set('translation.locale_aware_request_context', LocaleAwareRequestContext::class)
->args([
service('router.request_context'),
param('kernel.default_locale'),
])
;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigureLocaleSwitcherPass;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class ConfigureLocaleSwitcherPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$container->register('translation.locale_switcher')->setArgument(0, 'en');
$container->register('locale_aware_service')
->addTag('kernel.locale_aware')
;

$pass = new ConfigureLocaleSwitcherPass();
$pass->process($container);

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

$this->assertInstanceOf(IteratorArgument::class, $switcherDef->getArgument(1));
$this->assertEquals([new Reference('locale_aware_service')], $switcherDef->getArgument(1)->getValues());
}

public function testProcessWithRequestContext()
{
$container = new ContainerBuilder();
$container->register('translation.locale_switcher');
$container->register('locale_aware_service')
->addTag('kernel.locale_aware')
;
$container->register('translation.locale_aware_request_context');

$pass = new ConfigureLocaleSwitcherPass();
$pass->process($container);

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

$this->assertInstanceOf(IteratorArgument::class, $switcherDef->getArgument(1));
$this->assertEquals(
[
new Reference('locale_aware_service'),
new Reference('translation.locale_aware_request_context'),
],
$switcherDef->getArgument(1)->getValues()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
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 @@ -65,6 +66,7 @@
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\DependencyInjection\TranslatorPass;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\Validation;
Expand Down Expand Up @@ -1967,6 +1969,26 @@ public function testIfNotifierTransportsAreKnownByFrameworkExtension()
}
}

public function testLocaleSwitcherServiceRegistered()
{
if (!class_exists(LocaleSwitcher::class)) {
$this->markTestSkipped('LocaleSwitcher not available.');
}

$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));
}

protected function createContainer(array $data = [])
{
return new ContainerBuilder(new EnvPlaceholderParameterBag(array_merge([
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\Translation;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Translation\LocaleAwareRequestContext;
use Symfony\Component\Routing\RequestContext;

class LocaleAwareRequestContextTest extends TestCase
{
public function testCanSwitchLocale()
{
$context = new RequestContext();
$service = new LocaleAwareRequestContext($context, 'en');

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

$service->setLocale('fr');

$this->assertSame('fr', $service->getLocale());
$this->assertSame('fr', $context->getParameter('_locale'));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Translation;

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

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class LocaleAwareRequestContext implements LocaleAwareInterface
{
public function __construct(private RequestContext $requestContext, private string $defaultLocale)
{
}

public function setLocale(string $locale): void
{
$this->requestContext->setParameter('_locale', $locale);
}

public function getLocale(): string
{
return $this->requestContext->getParameter('_locale') ?? $this->defaultLocale;
}
}
58 changes: 58 additions & 0 deletions src/Symfony/Component/Translation/LocaleSwitcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Translation;

use Symfony\Contracts\Translation\LocaleAwareInterface;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class LocaleSwitcher implements LocaleAwareInterface
{
/**
* @param LocaleAwareInterface[] $localeAwareServices
*/
public function __construct(private string $locale, private iterable $localeAwareServices)
{
}

public function setLocale(string $locale): void
{
\Locale::setDefault($this->locale = $locale);

foreach ($this->localeAwareServices as $service) {
$service->setLocale($locale);
}
}

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

/**
* Switch to a new locale, execute a callback, then switch back to the original.
*
* @param callable():void $callback
*/
public function runWithLocale(string $locale, callable $callback): void
{
$original = $this->getLocale();
$this->setLocale($locale);

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