Parcourir la source

[TwigBundle] added tests for trans tag and filter

Fabien Potencier il y a 14 ans
Parent
commit
47bc809dc3

+ 19 - 11
src/Symfony/Bundle/TwigBundle/Node/TransNode.php

@@ -32,11 +32,11 @@ class TransNode extends \Twig_Node
     {
         $compiler->addDebugInfo($this);
 
+        $defaults = null;
         if ($this->getAttribute('is_simple')) {
-            list($msg, $vars) = $this->compileString($this->getNode('body'));
+            list($msg, $defaults) = $this->compileString($this->getNode('body'));
         } else {
             $msg = $this->getNode('body');
-            $vars = $this->getNode('vars');
         }
 
         $method = null === $this->getNode('count') ? 'trans' : 'transChoice';
@@ -55,25 +55,33 @@ class TransNode extends \Twig_Node
             ;
         }
 
-        $compiler->raw('array(');
+        $compiler->raw('array_merge(');
 
-        if (is_array($vars)) {
-            foreach ($vars as $var) {
+        if (null === $defaults) {
+            $compiler->raw('array()');
+        } else {
+            $compiler->raw('array(');
+            foreach ($defaults as $default) {
                 $compiler
-                    ->string('{{ '.$var['name'].' }}')
+                    ->string('{{ '.$default->getAttribute('name').' }}')
                     ->raw(' => ')
-                    ->subcompile($var)
+                    ->subcompile($default)
                     ->raw(', ')
                 ;
             }
-        } elseif (null !== $vars) {
-            $compiler->subcompile($vars);
-        } else {
+            $compiler->raw(')');
+        }
+
+        $compiler->raw(', ');
+
+        if (null === $this->getNode('vars')) {
             $compiler->raw('array()');
+        } else {
+            $compiler->subcompile($this->getNode('vars'));
         }
 
         $compiler
-            ->raw("), ")
+            ->raw('), ')
             ->subcompile($this->getNode('domain'))
             ->raw(");\n")
         ;

+ 86 - 0
src/Symfony/Bundle/TwigBundle/Tests/TransTest.php

@@ -0,0 +1,86 @@
+<?php
+
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Symfony\Bundle\TwigBundle\Tests;
+
+use Symfony\Bundle\TwigBundle\Tests\TestCase;
+use Symfony\Bundle\TwigBundle\Extension\TransExtension;
+use Symfony\Component\Translation\Translator;
+use Symfony\Component\Translation\MessageSelector;
+
+class TransTest extends TestCase
+{
+    /**
+     * @dataProvider getTransTests
+     */
+    public function testTrans($template, $expected, array $variables = array())
+    {
+
+        if ($expected != $this->getTemplate($template)->render($variables)) {
+            print $template."\n";
+            $loader = new \Twig_Loader_Array(array('index' => $template));
+            $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
+            $twig->addExtension(new TransExtension(new Translator('en', new MessageSelector())));
+
+            echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSource('index'), 'index')))."\n\n";
+            $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
+            exit();
+        }
+
+        $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
+    }
+
+    public function getTransTests()
+    {
+        return array(
+            // trans tag
+            array('{% trans "Hello" %}', 'Hello'),
+            array('{% trans name %}', 'Symfony2', array('name' => 'Symfony2')),
+            array('{% trans hello with [\'{{ name }}\': \'Symfony2\'] %}', 'Hello Symfony2', array('hello' => 'Hello {{ name }}')),
+            array('{% set vars = [\'{{ name }}\': \'Symfony2\'] %}{% trans hello with vars %}', 'Hello Symfony2', array('hello' => 'Hello {{ name }}')),
+
+            array('{% trans %}Hello{% endtrans %}', 'Hello'),
+            array('{% trans %}{{ name }}{% endtrans %}', 'Symfony2', array('name' => 'Symfony2')),
+
+            array('{% trans "Hello" from elsewhere %}', 'Hello'),
+            array('{% trans from elsewhere %}Hello{% endtrans %}', 'Hello'),
+
+            array('{% trans %}Hello {{ name }}{% endtrans %}', 'Hello Symfony2', array('name' => 'Symfony2')),
+            array('{% trans with [\'{{ name }}\': \'Symfony2\'] %}Hello {{ name }}{% endtrans %}', 'Hello Symfony2'),
+            array('{% set vars = [\'{{ name }}\': \'Symfony2\'] %}{% trans with vars %}Hello {{ name }}{% endtrans %}', 'Hello Symfony2'),
+
+            // 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)),
+            array('{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples{% endtranschoice %}',
+                'There is 5 apples', array('count' => 5)),
+            array('{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples ({{ name }}){% endtranschoice %}',
+                'There is 5 apples (Symfony2)', array('count' => 5, 'name' => 'Symfony2')),
+            array('{% transchoice count with [\'{{ name }}\': \'Symfony2\'] %}{0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples ({{ name }}){% endtranschoice %}',
+                'There is 5 apples (Symfony2)', array('count' => 5)),
+
+            // trans filter
+            array('{{ "Hello"|trans }}', 'Hello'),
+            array('{{ name|trans }}', 'Symfony2', array('name' => 'Symfony2')),
+            array('{{ hello|trans([\'{{ name }}\': \'Symfony2\']) }}', 'Hello Symfony2', array('hello' => 'Hello {{ name }}')),
+            array('{% set vars = [\'{{ name }}\': \'Symfony2\'] %}{{ hello|trans(vars) }}', 'Hello Symfony2', array('hello' => 'Hello {{ name }}')),
+        );
+    }
+
+    protected function getTemplate($template)
+    {
+        $loader = new \Twig_Loader_Array(array('index' => $template));
+        $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
+        $twig->addExtension(new TransExtension(new Translator('en', new MessageSelector())));
+
+        return $twig->loadTemplate('index');
+    }
+}

+ 9 - 15
src/Symfony/Bundle/TwigBundle/TokenParser/TransTokenParser.php

@@ -33,10 +33,11 @@ class TransTokenParser extends \Twig_TokenParser
         $stream = $this->parser->getStream();
 
         $vars = null;
+        $body = null;
+        $isSimple = false;
         $domain = new \Twig_Node_Expression_Constant('messages', $lineno);
         if (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
-            $body = null;
-            if (!$stream->test('from')) {
+            if (!$stream->test('from') && !$stream->test('with')) {
                 // {% trans "message" %}
                 // {% trans message %}
                 $body = $this->parser->getExpressionParser()->parseExpression();
@@ -52,24 +53,21 @@ class TransTokenParser extends \Twig_TokenParser
                 // {% trans "message" from "messages" %}
                 $stream->next();
                 $domain = $this->parser->getExpressionParser()->parseExpression();
-
-                // {% trans from "messages" %}message{% endtrans %}
-                if (null === $body) {
-                    $stream->expect(\Twig_Token::BLOCK_END_TYPE);
-                    $body = $this->parser->subparse(array($this, 'decideTransFork'), true);
-                }
             } elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
                 throw new \Twig_SyntaxError(sprintf('Unexpected token. Twig was looking for the "from" keyword line %s)', $lineno), -1);
             }
-        } else {
+        }
+
+        if (null === $body) {
             // {% trans %}message{% endtrans %}
             $stream->expect(\Twig_Token::BLOCK_END_TYPE);
             $body = $this->parser->subparse(array($this, 'decideTransFork'), true);
+            $isSimple = $this->isSimpleString($body);
         }
 
         $stream->expect(\Twig_Token::BLOCK_END_TYPE);
 
-        return new TransNode($body, $domain, null, $vars, $this->isSimpleString($body), $lineno, $this->getTag());
+        return new TransNode($body, $domain, null, $vars, $isSimple, $lineno, $this->getTag());
     }
 
     public function decideTransFork($token)
@@ -79,15 +77,11 @@ class TransTokenParser extends \Twig_TokenParser
 
     protected function isSimpleString(\Twig_NodeInterface $body)
     {
-        if (0 === count($body)) {
-            return false;
-        }
-
         foreach ($body as $i => $node) {
             if (
                 $node instanceof \Twig_Node_Text
                 ||
-                ($node instanceof \Twig_Node_Print && $node->expr instanceof \Twig_Node_Expression_Name)
+                ($node instanceof \Twig_Node_Print && $node->getNode('expr') instanceof \Twig_Node_Expression_Name)
             ) {
                 continue;
             }