Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[FrameworkBundle][Translation] addLocaleSwitcher 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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fabpot merged 1 commit intosymfony:6.1fromkbond:locale-switcher
Mar 26, 2022
Merged
Show file tree
Hide file tree
Changes fromall 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 numberDiff line numberDiff 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))
;
}
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionssrc/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddDebugLogProcessorPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AssetsContextPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ConfigureLocaleSwitcherPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\DataCollectorTranslatorPass;
useSymfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
Expand DownExpand Up@@ -158,6 +159,7 @@ public function build(ContainerBuilder $container)
$container->addCompilerPass(newRegisterReverseContainerPass(true));
$container->addCompilerPass(newRegisterReverseContainerPass(false), PassConfig::TYPE_AFTER_REMOVING);
$container->addCompilerPass(newRemoveUnusedSessionMarshallingHandlerPass());
$container->addCompilerPass(newConfigureLocaleSwitcherPass());

if ($container->getParameter('kernel.debug')) {
$container->addCompilerPass(newAddDebugLogProcessorPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION,2);
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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()
);
}
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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.
*/

namespaceSymfony\Bundle\FrameworkBundle\Tests\Translation;

usePHPUnit\Framework\TestCase;
useSymfony\Bundle\FrameworkBundle\Translation\LocaleAwareRequestContext;
useSymfony\Component\Routing\RequestContext;

class LocaleAwareRequestContextTestextends TestCase
{
publicfunctiontestCanSwitchLocale()
{
$context =newRequestContext();
$service =newLocaleAwareRequestContext($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'));
}
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionssrc/Symfony/Component/Translation/LocaleSwitcher.php
View file
Open in desktop
Original file line numberDiff line numberDiff 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.
*/

namespaceSymfony\Component\Translation;

useSymfony\Contracts\Translation\LocaleAwareInterface;

/**
* @author Kevin Bond <kevinbond@gmail.com>
*/
finalclass LocaleSwitcherimplements LocaleAwareInterface
{
/**
* @param LocaleAwareInterface[] $localeAwareServices
*/
publicfunction__construct(privatestring$locale,privateiterable$localeAwareServices)
{
}

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

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

publicfunctiongetLocale():string
{
return$this->locale;
}

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

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

[8]ページ先頭

©2009-2025 Movatter.jp