added Twig_Environment::mergeGlobals()

This commit is contained in:
Fabien Potencier
2012-04-03 19:13:43 +02:00
parent 3398b38cf0
commit f2f1f32b41
6 changed files with 38 additions and 16 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.7.0 (2012-XX-XX)
* added Twig_Environment::mergeGlobals()
* fixed a regression when a template only extends another one without defining any blocks
* added compilation checks to avoid misuses of the sandbox tag
* fixed filesystem loader freshness logic for high traffic websites
+20
View File
@@ -972,6 +972,26 @@ class Twig_Environment
return $this->globals;
}
/**
* Merges a context with the defined globals.
*
* @param array $context An array representing the context
*
* @return array The context merged with the globals
*/
public function mergeGlobals(array $context)
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->getGlobals() as $key => $value) {
if (!array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
}
/**
* Gets the registered unary Operators.
*
+1 -1
View File
@@ -44,7 +44,7 @@ class Twig_Node_Macro extends Twig_Node
$compiler->write("\$context = \$this->env->getGlobals();\n\n");
} else {
$compiler
->write("\$context = \$this->mergeContextWithGlobals(array(\n")
->write("\$context = \$this->env->mergeGlobals(array(\n")
->indent()
;
+1 -14
View File
@@ -236,7 +236,7 @@ abstract class Twig_Template implements Twig_TemplateInterface
*/
public function display(array $context, array $blocks = array())
{
$this->displayWithErrorHandling($this->mergeContextWithGlobals($context), $blocks);
$this->displayWithErrorHandling($this->env->mergeGlobals($context), $blocks);
}
/**
@@ -259,19 +259,6 @@ abstract class Twig_Template implements Twig_TemplateInterface
return ob_get_clean();
}
protected function mergeContextWithGlobals(array $context)
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->env->getGlobals() as $key => $value) {
if (!array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
}
protected function displayWithErrorHandling(array $context, array $blocks = array())
{
try {
@@ -0,0 +1,14 @@
--TEST--
"macro" tag
--TEMPLATE--
{% from 'forms.twig' import foo %}
{{ foo('foo') }}
{{ foo() }}
--TEMPLATE(forms.twig)--
{% macro foo(name) %}{{ name|default('foo') }}{{ global }}{% endmacro %}
--DATA--
return array()
--EXPECT--
fooglobal
fooglobal
+1 -1
View File
@@ -46,7 +46,7 @@ class Twig_Tests_Node_MacroTest extends Twig_Tests_Node_TestCase
array($node, <<<EOF
public function getfoo(\$foo = null)
{
\$context = \$this->mergeContextWithGlobals(array(
\$context = \$this->env->mergeGlobals(array(
"foo" => \$foo,
));