Skip to content

[Translator] Adding support for intl message formatter and decoupling default formatter. #15068

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

Closed
wants to merge 2 commits into from
Closed
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
5 changes: 5 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,13 @@ public function trans($message, array $arguments = array(), $domain = null, $loc
return $this->translator->trans($message, $arguments, $domain, $locale);
}

/**
* @deprecated since version 2.8, to be removed in 3.0. Use the {@link trans} method instead.
*/
public function transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use trans() method instead.', E_USER_DEPRECATED);

return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
}

Expand Down
110 changes: 85 additions & 25 deletions src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader;

class TranslationExtensionTest extends \PHPUnit_Framework_TestCase
Expand All @@ -34,7 +33,7 @@ public function testTrans($template, $expected, array $variables = array())
print $template."\n";
$loader = new \Twig_Loader_Array(array('index' => $template));
$twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
$twig->addExtension(new TranslationExtension(new Translator('en', new MessageSelector())));
$twig->addExtension(new TranslationExtension(new Translator('en')));

echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSource('index'), 'index')))."\n\n";
$this->assertEquals($expected, $this->getTemplate($template)->render($variables));
Expand All @@ -43,6 +42,15 @@ public function testTrans($template, $expected, array $variables = array())
$this->assertEquals($expected, $this->getTemplate($template)->render($variables));
}

/**
* @dataProvider getTranschoiceTests
* @group legacy
*/
public function testTranschoice($template, $expected, array $variables = array())
{
$this->testTrans($template, $expected, $variables);
}

/**
* @expectedException \Twig_Error_Syntax
* @expectedExceptionMessage Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3.
Expand Down Expand Up @@ -85,6 +93,18 @@ public function getTransTests()

array('{% trans into "fr"%}Hello{% endtrans %}', 'Hello'),

// trans filter
array('{{ "Hello"|trans }}', 'Hello'),
array('{{ name|trans }}', 'Symfony', array('name' => 'Symfony')),
array('{{ hello|trans({ \'%name%\': \'Symfony\' }) }}', 'Hello Symfony', array('hello' => 'Hello %name%')),
array('{% set vars = { \'%name%\': \'Symfony\' } %}{{ hello|trans(vars) }}', 'Hello Symfony', array('hello' => 'Hello %name%')),
array('{{ "Hello"|trans({}, "messages", "fr") }}', 'Hello'),
);
}

public function getTranschoiceTests()
{
return array(
// transchoice
array('{% transchoice count from "messages" %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}',
'There is no apples', array('count' => 0),),
Expand All @@ -99,21 +119,14 @@ public function getTransTests()
array('{% transchoice 5 into "fr"%}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}',
'There is 5 apples',),

// trans filter
array('{{ "Hello"|trans }}', 'Hello'),
array('{{ name|trans }}', 'Symfony', array('name' => 'Symfony')),
array('{{ hello|trans({ \'%name%\': \'Symfony\' }) }}', 'Hello Symfony', array('hello' => 'Hello %name%')),
array('{% set vars = { \'%name%\': \'Symfony\' } %}{{ hello|trans(vars) }}', 'Hello Symfony', array('hello' => 'Hello %name%')),
array('{{ "Hello"|trans({}, "messages", "fr") }}', 'Hello'),

// transchoice filter
array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count) }}', 'There is 5 apples', array('count' => 5)),
array('{{ text|transchoice(5, {\'%name%\': \'Symfony\'}) }}', 'There is 5 apples (Symfony)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')),
array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count, {}, "messages", "fr") }}', 'There is 5 apples', array('count' => 5)),
);
}

public function testDefaultTranslationDomain()
public function testTransDefaultTranslationDomain()
{
$templates = array(
'index' => '
Expand All @@ -126,6 +139,31 @@ public function testDefaultTranslationDomain()
{%- trans from "custom" %}foo{% endtrans %}
{{- "foo"|trans }}
{{- "foo"|trans({}, "custom") }}
{% endblock %}
',

'base' => '
{%- block content "" %}
',
);

$template = $this->getTemplate($templates, $this->getTranslator());

$this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render(array())));
}

/**
* @group legacy
*/
public function testTransChoiceDefaultTranslationDomain()
{
$templates = array(
'index' => '
{%- extends "base" %}

{%- trans_default_domain "foo" %}

{%- block content %}
{{- "foo"|transchoice(1) }}
{{- "foo"|transchoice(1, {}, "custom") }}
{% endblock %}
Expand All @@ -136,15 +174,9 @@ public function testDefaultTranslationDomain()
',
);

$translator = new Translator('en', new MessageSelector());
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', array('foo' => 'foo (messages)'), 'en');
$translator->addResource('array', array('foo' => 'foo (custom)'), 'en', 'custom');
$translator->addResource('array', array('foo' => 'foo (foo)'), 'en', 'foo');

$template = $this->getTemplate($templates, $translator);
$template = $this->getTemplate($templates, $this->getTranslator());

$this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render(array())));
$this->assertEquals('foo (foo)foo (custom)', trim($template->render(array())));
}

public function testDefaultTranslationDomainWithNamedArguments()
Expand All @@ -155,10 +187,33 @@ public function testDefaultTranslationDomainWithNamedArguments()

{%- block content %}
{{- "foo"|trans(arguments = {}, domain = "custom") }}
{{- "foo"|transchoice(count = 1) }}
{{- "foo"|transchoice(count = 1, arguments = {}, domain = "custom") }}
{{- "foo"|trans({}, domain = "custom") }}
{{- "foo"|trans({}, "custom", locale = "fr") }}
{% endblock %}
',

'base' => '
{%- block content "" %}
',
);

$template = $this->getTemplate($templates, $this->getTranslator());

$this->assertEquals('foo (custom)foo (custom)foo (fr)', trim($template->render(array())));
}

/**
* @group legacy
*/
public function testTransChoiceDefaultTranslationDomainWithNamedArguments()
{
$templates = array(
'index' => '
{%- trans_default_domain "foo" %}

{%- block content %}
{{- "foo"|transchoice(count = 1) }}
{{- "foo"|transchoice(count = 1, arguments = {}, domain = "custom") }}
{{- "foo"|transchoice(1, arguments = {}, domain = "custom") }}
{{- "foo"|transchoice(1, {}, "custom", locale = "fr") }}
{% endblock %}
Expand All @@ -169,22 +224,27 @@ public function testDefaultTranslationDomainWithNamedArguments()
',
);

$translator = new Translator('en', new MessageSelector());
$template = $this->getTemplate($templates, $this->getTranslator());

$this->assertEquals('foo (foo)foo (custom)foo (custom)foo (fr)', trim($template->render(array())));
}

protected function getTranslator()
{
$translator = new Translator('en');
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', array('foo' => 'foo (messages)'), 'en');
$translator->addResource('array', array('foo' => 'foo (custom)'), 'en', 'custom');
$translator->addResource('array', array('foo' => 'foo (foo)'), 'en', 'foo');
$translator->addResource('array', array('foo' => 'foo (fr)'), 'fr', 'custom');

$template = $this->getTemplate($templates, $translator);

$this->assertEquals('foo (custom)foo (foo)foo (custom)foo (custom)foo (fr)foo (custom)foo (fr)', trim($template->render(array())));
return $translator;
}

protected function getTemplate($template, $translator = null)
{
if (null === $translator) {
$translator = new Translator('en', new MessageSelector());
$translator = new Translator('en');
}

if (is_array($template)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,7 @@ private function addTranslatorSection(ArrayNodeDefinition $rootNode)
->defaultValue(array('en'))
->end()
->booleanNode('logging')->defaultValue($this->debug)->end()
->scalarNode('formatter')->defaultValue('translator.formatter.legacy_intl')->end()
->arrayNode('paths')
->prototype('scalar')->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,7 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder

// Use the "real" translator instead of the identity default
$container->setAlias('translator', 'translator.default');
$container->setAlias('translator.formatter', $config['formatter']);
$translator = $container->findDefinition('translator.default');
$translator->addMethodCall('setFallbackLocales', array($config['fallbacks']));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="fallback" type="xsd:string" />
<xsd:attribute name="logging" type="xsd:boolean" />
<xsd:attribute name="formatter" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="validation">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
<services>
<service id="translator.default" class="%translator.class%">
<argument type="service" id="service_container" />
<argument type="service" id="translator.selector" />
<argument type="service" id="translator.formatter" />
<argument type="collection" /> <!-- translation loaders -->
<argument type="collection">
<argument key="cache_dir">%kernel.cache_dir%/translations</argument>
Expand All @@ -54,6 +54,13 @@
</service>

<service id="translator" class="%translator.identity.class%">
<argument type="service" id="translator.formatter" />
</service>

<service id="translator.formatter" alias="translator.formatter.legacy_intl" />
<service id="translator.formatter.intl" class="Symfony\Component\Translation\Formatter\IntlMessageFormatter" public="false" />

<service id="translator.formatter.legacy_intl" class="Symfony\Component\Translation\Formatter\LegacyIntlMessageFormatter" public="false">
<argument type="service" id="translator.selector" />
</service>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ protected static function getBundleDefaultConfig()
),
'translator' => array(
'enabled' => false,
'formatter' => 'translator.formatter.legacy_intl',
'fallbacks' => array('en'),
'logging' => true,
'paths' => array(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Formatter\IntlMessageFormatter;

class TranslatorTest extends \PHPUnit_Framework_TestCase
{
Expand Down Expand Up @@ -50,10 +50,10 @@ public function testTransWithoutCaching()
$this->assertEquals('foo (FR)', $translator->trans('foo'));
$this->assertEquals('bar (EN)', $translator->trans('bar'));
$this->assertEquals('foobar (ES)', $translator->trans('foobar'));
$this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0));
$this->assertEquals('choice 0 (EN)', $translator->trans('choice', array(0)));
$this->assertEquals('no translation', $translator->trans('no translation'));
$this->assertEquals('foobarfoo (PT-PT)', $translator->trans('foobarfoo'));
$this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1));
$this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', array(1)));
$this->assertEquals('foobarbaz (fr.UTF-8)', $translator->trans('foobarbaz'));
$this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax'));
}
Expand All @@ -68,10 +68,10 @@ public function testTransWithCaching()
$this->assertEquals('foo (FR)', $translator->trans('foo'));
$this->assertEquals('bar (EN)', $translator->trans('bar'));
$this->assertEquals('foobar (ES)', $translator->trans('foobar'));
$this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0));
$this->assertEquals('choice 0 (EN)', $translator->trans('choice', array(0)));
$this->assertEquals('no translation', $translator->trans('no translation'));
$this->assertEquals('foobarfoo (PT-PT)', $translator->trans('foobarfoo'));
$this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1));
$this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', array(1)));
$this->assertEquals('foobarbaz (fr.UTF-8)', $translator->trans('foobarbaz'));
$this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax'));

Expand All @@ -86,10 +86,10 @@ public function testTransWithCaching()
$this->assertEquals('foo (FR)', $translator->trans('foo'));
$this->assertEquals('bar (EN)', $translator->trans('bar'));
$this->assertEquals('foobar (ES)', $translator->trans('foobar'));
$this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0));
$this->assertEquals('choice 0 (EN)', $translator->trans('choice', array(0)));
$this->assertEquals('no translation', $translator->trans('no translation'));
$this->assertEquals('foobarfoo (PT-PT)', $translator->trans('foobarfoo'));
$this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1));
$this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', array(1)));
$this->assertEquals('foobarbaz (fr.UTF-8)', $translator->trans('foobarbaz'));
$this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax'));
}
Expand Down Expand Up @@ -157,7 +157,7 @@ public function testGetDefaultLocale()
->will($this->returnValue('en'))
;

$translator = new Translator($container, new MessageSelector());
$translator = new Translator($container, new IntlMessageFormatter());

$this->assertSame('en', $translator->getLocale());
}
Expand Down Expand Up @@ -191,7 +191,7 @@ protected function getLoader()
->will($this->returnValue($this->getCatalogue('en', array(
'foo' => 'foo (EN)',
'bar' => 'bar (EN)',
'choice' => '{0} choice 0 (EN)|{1} choice 1 (EN)|]1,Inf] choice inf (EN)',
'choice' => '{0, plural, =0 {choice 0 (EN)} =1 {choice 1 (EN)} other {# choice inf (EN)}}',
))))
;
$loader
Expand All @@ -212,7 +212,7 @@ protected function getLoader()
->expects($this->at(4))
->method('load')
->will($this->returnValue($this->getCatalogue('pt_BR', array(
'other choice' => '{0} other choice 0 (PT-BR)|{1} other choice 1 (PT-BR)|]1,Inf] other choice inf (PT-BR)',
'other choice' => '{0, plural, =0 {other choice 0 (PT-BR)} =1 {other choice 1 (PT-BR)} other {# other choice inf (PT-BR)}}',
))))
;
$loader
Expand Down Expand Up @@ -290,7 +290,7 @@ private function createTranslator($loader, $options, $translatorClass = '\Symfon
{
return new $translatorClass(
$this->getContainer($loader),
new MessageSelector(),
new IntlMessageFormatter(),
array($loaderFomat => array($loaderFomat)),
$options
);
Expand Down
12 changes: 6 additions & 6 deletions src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ class Translator extends BaseTranslator implements WarmableInterface
* * debug: Whether to enable debugging or not (false by default)
* * resource_files: List of translation resources available grouped by locale.
*
* @param ContainerInterface $container A ContainerInterface instance
* @param MessageSelector $selector The message selector for pluralization
* @param array $loaderIds An array of loader Ids
* @param array $options An array of options
* @param ContainerInterface $container A ContainerInterface instance
* @param MessageFormatterInterface|MessageSelector $formatter The message formatter
* @param array $loaderIds An array of loader Ids
* @param array $options An array of options
*
* @throws \InvalidArgumentException
*/
public function __construct(ContainerInterface $container, MessageSelector $selector, $loaderIds = array(), array $options = array())
public function __construct(ContainerInterface $container, $formatter, $loaderIds = array(), array $options = array())
{
$this->container = $container;
$this->loaderIds = $loaderIds;
Expand All @@ -69,7 +69,7 @@ public function __construct(ContainerInterface $container, MessageSelector $sele
$this->loadResources();
}

parent::__construct($container->getParameter('kernel.default_locale'), $selector, $this->options['cache_dir'], $this->options['debug']);
parent::__construct($container->getParameter('kernel.default_locale'), $formatter, $this->options['cache_dir'], $this->options['debug']);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public function trans($id, array $parameters = array(), $domain = null, $locale
*/
public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Rely on the MessageFormatterInterface and TranslatorInterface::trans() method instead.', E_USER_DEPRECATED);
$trans = $this->translator->transChoice($id, $number, $parameters, $domain, $locale);
$this->collectMessage($locale, $domain, $id, $trans, $parameters, $number);

Expand Down
Loading