From 7b5e5969a2c960b9e50060349250582f05034c3e Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 26 Jul 2011 23:22:49 +0200 Subject: [PATCH] added an optimization for the set tag when used to capture a large chunk of static text --- CHANGELOG | 1 + lib/Twig/Node/Set.php | 23 ++++++++++++++++++++++- test/Twig/Tests/Node/SetTest.php | 5 +++++ 3 files changed, 28 insertions(+), 1 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 742eb4b..43083f8 100644 --- 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 diff --git a/lib/Twig/Node/Set.php b/lib/Twig/Node/Set.php index 8a46eec..e466ad9 100644 --- a/lib/Twig/Node/Set.php +++ b/lib/Twig/Node/Set.php @@ -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')); + } } } diff --git a/test/Twig/Tests/Node/SetTest.php b/test/Twig/Tests/Node/SetTest.php index 169ea40..8d03a60 100644 --- a/test/Twig/Tests/Node/SetTest.php +++ b/test/Twig/Tests/Node/SetTest.php @@ -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); -- 1.7.2.5