Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Translation] Allow default parameters #53425

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 10, 2025
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
Expand Up @@ -967,6 +967,7 @@ private function addTranslatorSection(ArrayNodeDefinition $rootNode, callable $e
->fixXmlConfig('fallback')
->fixXmlConfig('path')
->fixXmlConfig('provider')
->fixXmlConfig('global')
->children()
->arrayNode('fallbacks')
->info('Defaults to the value of "default_locale".')
Expand Down Expand Up @@ -1021,6 +1022,33 @@ private function addTranslatorSection(ArrayNodeDefinition $rootNode, callable $e
->end()
->defaultValue([])
->end()
->arrayNode('globals')
->info('Global parameters.')
->example(['app_version' => 3.14])
->normalizeKeys(false)
->useAttributeAsKey('name')
->arrayPrototype()
->fixXmlConfig('parameter')
->children()
->variableNode('value')->end()
->stringNode('message')->end()
->arrayNode('parameters')
->normalizeKeys(false)
->useAttributeAsKey('name')
->scalarPrototype()->end()
->end()
->stringNode('domain')->end()
->end()
->beforeNormalization()
->ifTrue(static fn ($v) => !\is_array($v))
->then(static fn ($v) => ['value' => $v])
->end()
->validate()
->ifTrue(static fn ($v) => !(isset($v['value']) xor isset($v['message'])))
->thenInvalid('The "globals" parameter should be either a string or an array with a "value" or a "message" key')
->end()
->end()
->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@
use Symfony\Component\Translation\Extractor\PhpAstExtractor;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\PseudoLocalizationTranslator;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Translation\Translator;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\TypeResolver\PhpDocAwareReflectionTypeResolver;
Expand Down Expand Up @@ -1614,6 +1615,10 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
$translator->replaceArgument(4, $options);
}

foreach ($config['globals'] as $name => $global) {
$translator->addMethodCall('addGlobalParameter', [$name, $global['value'] ?? new Definition(TranslatableMessage::class, [$global['message'], $global['parameters'] ?? [], $global['domain'] ?? null])]);
}

if ($config['pseudo_localization']['enabled']) {
$options = $config['pseudo_localization'];
unset($options['enabled']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@
<xsd:element name="path" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="pseudo-localization" type="pseudo_localization" minOccurs="0" maxOccurs="1" />
<xsd:element name="provider" type="translation_provider" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="global" type="translation_global" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="fallback" type="xsd:string" />
Expand Down Expand Up @@ -285,6 +286,24 @@
<xsd:attribute name="dsn" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="translation_global" mixed="true">
<xsd:sequence>
<xsd:element name="parameter" type="translation_global_parameter" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
<xsd:attribute name="value" type="xsd:string" />
<xsd:attribute name="message" type="xsd:string" />
<xsd:attribute name="domain" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="translation_global_parameter">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>

<xsd:complexType name="validation">
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element name="static-method" type="xsd:string" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ protected static function getBundleDefaultConfig()
'localizable_html_attributes' => [],
],
'providers' => [],
'globals' => [],
],
'validation' => [
'enabled' => !class_exists(FullStack::class),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

$container->loadFromExtension('framework', [
'annotations' => false,
'http_method_override' => false,
'handle_all_throwables' => true,
'php_errors' => ['log' => true],
'translator' => [
'globals' => [
'%%app_name%%' => 'My application',
'{app_version}' => '1.2.3',
'{url}' => ['message' => 'url', 'parameters' => ['scheme' => 'https://'], 'domain' => 'global'],
],
],
]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

$container->loadFromExtension('framework', [
'annotations' => false,
'http_method_override' => false,
'handle_all_throwables' => true,
'php_errors' => ['log' => true],
'translator' => ['globals' => []],
]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config secret="s3cr3t" http-method-override="false" handle-all-throwables="true">
<framework:annotations enabled="false" />
<framework:php-errors log="true" />
<framework:translator enabled="true">
<framework:global name="%%app_name%%">My application</framework:global>
<framework:global name="{app_version}" value="1.2.3" />
<framework:global name="{url}" message="url" domain="global">
<framework:parameter name="scheme">https://</framework:parameter>
</framework:global>
</framework:translator>
</framework:config>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config secret="s3cr3t" http-method-override="false" handle-all-throwables="true">
<framework:annotations enabled="false" />
<framework:php-errors log="true" />
<framework:translator enabled="true" />
</framework:config>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
framework:
annotations: false
http_method_override: false
handle_all_throwables: true
php_errors:
log: true
translator:
globals:
'%%app_name%%': 'My application'
'{app_version}': '1.2.3'
'{url}': { message: 'url', parameters: { scheme: 'https://' }, domain: 'global' }
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
framework:
annotations: false
http_method_override: false
handle_all_throwables: true
php_errors:
log: true
translator:
globals: []
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\DependencyInjection\TranslatorPass;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
Expand Down Expand Up @@ -1241,6 +1242,36 @@ public function testTranslatorCacheDirDisabled()
$this->assertNull($options['cache_dir']);
}

public function testTranslatorGlobals()
{
$container = $this->createContainerFromFile('translator_globals');

$calls = $container->getDefinition('translator.default')->getMethodCalls();

$this->assertCount(5, $calls);
$this->assertSame(
['addGlobalParameter', ['%%app_name%%', 'My application']],
$calls[2],
);
$this->assertSame(
['addGlobalParameter', ['{app_version}', '1.2.3']],
$calls[3],
);
$this->assertEquals(
['addGlobalParameter', ['{url}', new Definition(TranslatableMessage::class, ['url', ['scheme' => 'https://'], 'global'])]],
$calls[4],
);
}

public function testTranslatorWithoutGlobals()
{
$container = $this->createContainerFromFile('translator_without_globals');

$calls = $container->getDefinition('translator.default')->getMethodCalls();

$this->assertCount(2, $calls);
}

public function testValidation()
{
$container = $this->createContainerFromFile('full');
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"symfony/serializer": "^7.1",
"symfony/stopwatch": "^6.4|^7.0",
"symfony/string": "^6.4|^7.0",
"symfony/translation": "^6.4.3|^7.0",
"symfony/translation": "^7.3",
"symfony/twig-bundle": "^6.4|^7.0",
"symfony/type-info": "^7.1",
"symfony/validator": "^6.4|^7.0",
Expand Down Expand Up @@ -101,7 +101,7 @@
"symfony/security-core": "<6.4",
"symfony/serializer": "<7.1",
"symfony/stopwatch": "<6.4",
"symfony/translation": "<6.4.3",
"symfony/translation": "<7.3",
"symfony/twig-bridge": "<6.4",
"symfony/twig-bundle": "<6.4",
"symfony/validator": "<6.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,27 @@
{% endblock messages %}
{% endif %}

{% if collector.globalParameters|default([]) %}
<h2>Global parameters</h2>

<table>
<thead>
<tr>
<th>Message ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for id, value in collector.globalParameters %}
<tr>
<td class="font-normal text-small nowrap">{{ id }}</td>
<td class="font-normal text-small nowrap">{{ profiler_dump(value) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}

{% endblock %}

{% macro render_table(messages, is_fallback) %}
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Translation/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.3
---

* Add `Translator::addGlobalParameter()` to allow defining global translation parameters

7.2
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public function collect(Request $request, Response $response, ?\Throwable $excep
{
$this->data['locale'] = $this->translator->getLocale();
$this->data['fallback_locales'] = $this->translator->getFallbackLocales();
$this->data['global_parameters'] = $this->translator->getGlobalParameters();
}

public function reset(): void
Expand Down Expand Up @@ -84,6 +85,14 @@ public function getFallbackLocales(): Data|array
return (isset($this->data['fallback_locales']) && \count($this->data['fallback_locales']) > 0) ? $this->data['fallback_locales'] : [];
}

/**
* @internal
*/
public function getGlobalParameters(): Data|array
{
return $this->data['global_parameters'] ?? [];
}

public function getName(): string
{
return 'translation';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ public function getFallbackLocales(): array
return [];
}

public function getGlobalParameters(): array
{
if ($this->translator instanceof Translator || method_exists($this->translator, 'getGlobalParameters')) {
return $this->translator->getGlobalParameters();
}

return [];
}

public function __call(string $method, array $args): mixed
{
return $this->translator->{$method}(...$args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,20 @@ public function testCollectAndReset()
$translator = $this->getTranslator();
$translator->method('getLocale')->willReturn('fr');
$translator->method('getFallbackLocales')->willReturn(['en']);
$translator->method('getGlobalParameters')->willReturn(['welcome' => 'Welcome {name}!']);

$dataCollector = new TranslationDataCollector($translator);
$dataCollector->collect($this->createMock(Request::class), $this->createMock(Response::class));

$this->assertSame('fr', $dataCollector->getLocale());
$this->assertSame(['en'], $dataCollector->getFallbackLocales());
$this->assertSame(['welcome' => 'Welcome {name}!'], $dataCollector->getGlobalParameters());

$dataCollector->reset();

$this->assertNull($dataCollector->getLocale());
$this->assertSame([], $dataCollector->getFallbackLocales());
$this->assertSame([], $dataCollector->getGlobalParameters());
}

private function getTranslator()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\DataCollectorTranslator;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Translation\Translator;

class DataCollectorTranslatorTest extends TestCase
Expand Down Expand Up @@ -84,6 +85,18 @@ public function testCollectMessages()
$this->assertEquals($expectedMessages, $collector->getCollectedMessages());
}

public function testGetGlobalParameters()
{
$translatable = new TranslatableMessage('url.front');

$translator = new Translator('en');
$translator->addGlobalParameter('app', 'My app');
$translator->addGlobalParameter('url', $translatable);
$collector = new DataCollectorTranslator($translator);

$this->assertEquals(['app' => 'My app', 'url' => $translatable], $collector->getGlobalParameters());
}

private function createCollector()
{
$translator = new Translator('en');
Expand Down
Loading
Loading