Skip to content
Open
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,63 @@
<?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\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* @internal
*/
class EnabledLocalesPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$enabledLocales = $container->resolveEnvPlaceholders($container->getParameter('kernel.enabled_locales'), true);
$container->setParameter('kernel.enabled_locales', $enabledLocales);

if ($container->hasDefinition('translator.default')) {
$translator = $container->findDefinition('translator.default');
$translator->setArgument(5, $enabledLocales);
}
if ($container->hasDefinition('routing.loader')) {
$routing = $container->findDefinition('routing.loader');
if ($enabledLocales) {
$routingEnabledLocales = implode('|', array_map('preg_quote', $enabledLocales));

Check failure on line 34 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/EnabledLocalesPass.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedInterfaceMethod

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/EnabledLocalesPass.php:34:79: UndefinedInterfaceMethod: Method UnitEnum::offsetGet does not exist (see https://psalm.dev/181)

Check failure on line 34 in src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/EnabledLocalesPass.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedInterfaceMethod

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/EnabledLocalesPass.php:34:79: UndefinedInterfaceMethod: Method UnitEnum::offsetGet does not exist (see https://psalm.dev/181)
$routing->replaceArgument(2, ['_locale' => $routingEnabledLocales]);
}
}

$providerDefinitions = [
'translation.provider_collection_factory' => 1,
'console.command.translation_pull' => 5,
'console.command.translation_push' => 3,
];

$locales = $enabledLocales;

foreach ($providerDefinitions as $definitionId => $argumentIndex) {
if ($container->hasDefinition($definitionId)) {
$definition = $container->getDefinition($definitionId);
$locales = array_merge($locales, $definition->getArgument($argumentIndex));
break;
}
}

foreach ($providerDefinitions as $definitionId => $argumentIndex) {
if (!$container->hasDefinition($definitionId)) {
continue;
}
$definition = $container->getDefinition($definitionId);
$definition->replaceArgument($argumentIndex, $locales);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -447,10 +447,10 @@ public function load(array $configs, ContainerBuilder $container): void
$this->registerEsiConfiguration($config['esi'], $container, $loader);
$this->registerSsiConfiguration($config['ssi'], $container, $loader);
$this->registerFragmentsConfiguration($config['fragments'], $container, $loader);
$this->registerTranslatorConfiguration($config['translator'], $container, $loader, $config['default_locale'], $config['enabled_locales']);
$this->registerTranslatorConfiguration($config['translator'], $container, $loader, $config['default_locale']);
$this->registerWorkflowConfiguration($config['workflows'], $container, $loader);
$this->registerDebugConfiguration($config['php_errors'], $container, $loader);
$this->registerRouterConfiguration($config['router'], $container, $loader, $config['enabled_locales']);
$this->registerRouterConfiguration($config['router'], $container, $loader);
$this->registerPropertyAccessConfiguration($config['property_access'], $container, $loader);
$this->registerSecretsConfiguration($config['secrets'], $container, $loader, $config['secret'] ?? null);

Expand Down Expand Up @@ -1347,7 +1347,7 @@ private function registerDebugConfiguration(array $config, ContainerBuilder $con
}
}

private function registerRouterConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader, array $enabledLocales = []): void
private function registerRouterConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
Copy link
Member

Choose a reason for hiding this comment

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

Accepting environment variables in the router isn't possible. The values are dumped in the routing cache, in a big regex for the url matcher.

The expression language is the only way we have currently to match parts of the request with env var.

{
if (!$this->readConfigEnabled('router', $container, $config)) {
$container->removeDefinition('console.command.router_debug');
Expand All @@ -1374,11 +1374,6 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co
$container->getDefinition('routing.loader')->replaceArgument(1, ['utf8' => true]);
}

if ($enabledLocales) {
$enabledLocales = implode('|', array_map('preg_quote', $enabledLocales));
$container->getDefinition('routing.loader')->replaceArgument(2, ['_locale' => $enabledLocales]);
}

if (!ContainerBuilder::willBeAvailable('symfony/expression-language', ExpressionLanguage::class, ['symfony/framework-bundle', 'symfony/routing'])) {
$container->removeDefinition('router.expression_language_provider');
}
Expand Down Expand Up @@ -1636,7 +1631,7 @@ private function createVersion(ContainerBuilder $container, ?string $version, ?s
return new Reference('assets.empty_version_strategy');
}

private function registerTranslatorConfiguration(array $config, ContainerBuilder $container, LoaderInterface $loader, string $defaultLocale, array $enabledLocales): void
private function registerTranslatorConfiguration(array $config, ContainerBuilder $container, LoaderInterface $loader, string $defaultLocale): void
Copy link
Member

Choose a reason for hiding this comment

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

For the translator, there is only this type to modify to accept a parameter. The default.translator service car receive an %env(...)% value that is resolved by the DIC at runtime.

Suggested change
private function registerTranslatorConfiguration(array $config, ContainerBuilder $container, LoaderInterface $loader, string $defaultLocale): void
private function registerTranslatorConfiguration(array $config, ContainerBuilder $container, LoaderInterface $loader, string $defaultLocale, array|string $enabledLocales): void

But it needs a bit of refactoring to merge the lists from enabled locales and providers at runtime in the commands.

{
if (!$this->readConfigEnabled('translator', $container, $config)) {
$container->removeDefinition('console.command.translation_debug');
Expand Down Expand Up @@ -1672,7 +1667,6 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
$defaultOptions = $translator->getArgument(4);
$defaultOptions['cache_dir'] = $config['cache_dir'];
$translator->setArgument(4, $defaultOptions);
$translator->setArgument(5, $enabledLocales);

$container->setParameter('translator.logging', $config['logging']);
$container->setParameter('translator.default_path', $config['default_path']);
Expand Down Expand Up @@ -1806,11 +1800,11 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
return;
}

$locales = $enabledLocales;
$locales = [];

foreach ($config['providers'] as $provider) {
if ($provider['locales']) {
$locales += $provider['locales'];
$locales = array_merge($locales, $provider['locales']);
}
}

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\AssetsContextPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ContainerBuilderDebugDumpPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\EnabledLocalesPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ErrorLoggerCompilerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RemoveUnusedSessionMarshallingHandlerPass;
Expand Down Expand Up @@ -167,6 +168,7 @@ public function build(ContainerBuilder $container): void
$container->addCompilerPass(new TranslationLintCommandPass(), PassConfig::TYPE_BEFORE_REMOVING, 10);
// must be registered as late as possible to get access to all Twig paths registered in
// twig.template_iterator definition
$container->addCompilerPass(new EnabledLocalesPass());
$this->addCompilerPassIfExists($container, TranslatorPass::class, PassConfig::TYPE_BEFORE_OPTIMIZATION, -32);
$this->addCompilerPassIfExists($container, TranslatorPathsPass::class, PassConfig::TYPE_AFTER_REMOVING);
$this->addCompilerPassIfExists($container, LoggingTranslatorPass::class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LogLevel;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\EnabledLocalesPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator\DefinitionValidator;
Expand Down Expand Up @@ -2879,7 +2880,7 @@ protected function createContainerFromFile(string $file, array $data = [], bool
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);
}
$container->getCompilerPassConfig()->setBeforeOptimizationPasses([new LoggerPass()]);
$container->getCompilerPassConfig()->setBeforeOptimizationPasses([new LoggerPass(), new EnabledLocalesPass()]);
$container->getCompilerPassConfig()->setBeforeRemovingPasses([new AddConstraintValidatorsPass(), new TranslatorPass()]);

if (!$compile) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;

use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\EnabledLocalesPass;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -425,6 +426,101 @@ public static function emailValidationModeProvider()
}
yield ['loose'];
}

#[DataProvider('enabledLocalesDataProvider')]
/**
* @dataProvider enabledLocalesDataProvider
*/
public function testEnabledLocales(mixed $enabledLocalesValue, array $envVars, array $expectedLocales)
{
$container = $this->createContainerFromClosure(function ($container) use ($enabledLocalesValue, $envVars) {
foreach ($envVars as $name => $value) {
$container->setParameter('env('.$name.')', $value);
}
$container->addCompilerPass(new EnabledLocalesPass());

$container->loadFromExtension('framework', [
'enabled_locales' => $enabledLocalesValue,
'translator' => [
'enabled' => true,
'fallbacks' => ['en'],
'providers' => [
'loco' => [
'dsn' => '%env(DSN)%',
'domains' => ['messages'],
'locales' => ['uk']
],
'crowdin' => [
'dsn' => '%env(DSN)%',
'domains' => ['messages'],
'locales' => ['sk']
],
'lokalise' => [
'dsn' => '%env(DSN)%',
'domains' => ['messages'],
'locales' => ['cz']
],
'phrase' => [
'dsn' => '%env(DSN)%',
'domains' => ['messages'],
'locales' => ['pl']
]
]
],
'router' => [
'resource' => '%kernel.project_dir%/config/routes.yaml',
'type' => 'yaml',
],
]);
});

$this->assertEquals($expectedLocales, $container->getParameter('kernel.enabled_locales'));

$routerLoaderDef = $container->getDefinition('routing.loader');
$this->assertSame(['_locale' => implode('|', $expectedLocales)], $routerLoaderDef->getArgument(2));

$translatorDef = $container->getDefinition('translator.default');
$this->assertSame($expectedLocales, $translatorDef->getArgument(5));

$providerDefinitions = [
'translation.provider_collection_factory' => 1,
'console.command.translation_pull' => 5,
'console.command.translation_push' => 3,
];

foreach ($providerDefinitions as $definitionId => $argumentIndex) {
$this->assertEquals(
array_merge(
$expectedLocales,
['uk', 'sk', 'cz', 'pl']
),
$container->getDefinition($definitionId)->getArgument($argumentIndex)
);
}
}

public static function enabledLocalesDataProvider(): \Generator
{
yield [
'enabledLocalesValue' => ['fr', 'de'],
'envVars' => [],
'expectedLocales' => ['fr', 'de']];
yield [
'enabledLocalesValue' => ['%env(LOCALE)%'],
'envVars' => ['LOCALE' => 'de'],
'expectedLocales' => ['de']
];
yield [
'enabledLocalesValue' => '%env(json:AVAILABLE_LOCALES)%',
'envVars' => ['AVAILABLE_LOCALES' => '["en", "fr", "de"]'],
'expectedLocales' => ['en', 'fr', 'de']
];
yield [
'enabledLocalesValue' => '%env(json:resolve::AVAILABLE_LOCALES)%',
'envVars' => ['LOCALE' => 'de', 'AVAILABLE_LOCALES' => '["en", "fr", "%env(LOCALE)%"]'],
'expectedLocales' => ['en', 'fr', 'de']
];
}
}

class WorkflowValidatorWithConstructor implements DefinitionValidatorInterface
Expand Down
Loading