added an optimization for the set tag when used to capture a large chunk of static...
authorFabien Potencier <fabien.potencier@gmail.com>
Tue, 26 Jul 2011 21:22:49 +0000 (23:22 +0200)
committerFabien Potencier <fabien.potencier@gmail.com>
Sun, 7 Aug 2011 17:08:15 +0000 (19:08 +0200)
CHANGELOG
lib/Twig/Node/Set.php
test/Twig/Tests/Node/SetTest.php

index 742eb4b..43083f8 100644 (file)
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,6 @@
 * 1.2.0
 
+ * added an optimization for the set tag when used to capture a large chunk of static text
  * changed name regex to match PHP one "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" (works for blocks, tags, functions, filters, and macros)
  * removed the possibility to use the "extends" tag from a block
  * added "if" modifier support to "for" loops
index 8a46eec..e466ad9 100644 (file)
@@ -29,6 +29,19 @@ class Twig_Node_Set extends Twig_Node
      */
     public function compile(Twig_Compiler $compiler)
     {
+        /*
+         * Optimizes the node when capture is used for a large block of text.
+         *
+         * {% set foo %}foo{% endset %} is compiled to $context['foo'] = new Twig_Markup("foo");
+         */
+        $safe = false;
+        $values = $this->getNode('values');
+        if ($this->getAttribute('capture') && $values instanceof Twig_Node_Text) {
+            $this->setNode('values', new Twig_Node_Expression_Constant($values->getAttribute('data'), $values->getLine()));
+            $this->setAttribute('capture', false);
+            $safe = true;
+        }
+
         $compiler->addDebugInfo($this);
 
         if (count($this->getNode('names')) > 1) {
@@ -70,7 +83,15 @@ class Twig_Node_Set extends Twig_Node
                 }
                 $compiler->raw(')');
             } else {
-                $compiler->subcompile($this->getNode('values'));
+                if ($safe) {
+                    $compiler
+                        ->raw("new Twig_Markup(")
+                        ->subcompile($this->getNode('values'))
+                        ->raw(")")
+                    ;
+                } else {
+                    $compiler->subcompile($this->getNode('values'));
+                }
             }
         }
 
index 169ea40..8d03a60 100644 (file)
@@ -55,6 +55,11 @@ echo "foo";
 EOF
         );
 
+        $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 0)), array(), 0);
+        $values = new Twig_Node_Text('foo', 0);
+        $node = new Twig_Node_Set(true, $names, $values, 0);
+        $tests[] = array($node, '$context[\'foo\'] = new Twig_Markup("foo");');
+
         $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 0), new Twig_Node_Expression_AssignName('bar', 0)), array(), 0);
         $values = new Twig_Node(array(new Twig_Node_Expression_Constant('foo', 0), new Twig_Node_Expression_Name('bar', 0)), array(), 0);
         $node = new Twig_Node_Set(false, $names, $values, 0);