From: Fabien Potencier Date: Wed, 24 Nov 2010 08:47:51 +0000 (+0100) Subject: added a defined test (strict_variables is now useable) X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=5b4c074223d6e9efdd3874b0e7a714c40719b550;p=web%2Fkonrad%2Ftwig.git added a defined test (strict_variables is now useable) --- diff --git a/doc/02-Twig-for-Template-Designers.markdown b/doc/02-Twig-for-Template-Designers.markdown index 5ab7508..37c2359 100644 --- a/doc/02-Twig-for-Template-Designers.markdown +++ b/doc/02-Twig-for-Template-Designers.markdown @@ -1301,7 +1301,7 @@ variable: the foo attribute really is the `false` PHP value {% endif %} -### `constant` (new in Twig 0.9.9) +### `constant` `constant` checks if a variable has the exact same value as a constant. You can use either global constants or class constants: @@ -1311,6 +1311,11 @@ can use either global constants or class constants: the status attribute is exactly the same as Post::PUBLISHED {% endif %} +### `defined` + +`defined` checks if a variable is defined in the current context. This is very +useful if you use the `strict_variables` option. + Extensions ---------- diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index 84b45ff..97db509 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -95,7 +95,7 @@ class Twig_Extension_Core extends Twig_Extension return array( 'even' => new Twig_Test_Function('twig_test_even'), 'odd' => new Twig_Test_Function('twig_test_odd'), - //'defined' => new Twig_Test_Function(), + 'defined' => new Twig_Test_Function('twig_test_defined'), 'sameas' => new Twig_Test_Function('twig_test_sameas'), 'none' => new Twig_Test_Function('twig_test_none'), 'divisibleby' => new Twig_Test_Function('twig_test_divisibleby'), @@ -410,3 +410,8 @@ function twig_test_constant($value, $constant) { return constant($constant) === $value; } + +function twig_test_defined($name, $context) +{ + return array_key_exists($name, $context); +} diff --git a/lib/Twig/Node/Expression/Test.php b/lib/Twig/Node/Expression/Test.php index 1354dc5..50cb293 100644 --- a/lib/Twig/Node/Expression/Test.php +++ b/lib/Twig/Node/Expression/Test.php @@ -22,6 +22,21 @@ class Twig_Node_Expression_Test extends Twig_Node_Expression throw new Twig_Error_Syntax(sprintf('The test "%s" does not exist', $this->getAttribute('name')), $this->getLine()); } + // defined is a special case + if ('defined' === $this->getAttribute('name')) { + if (!$this->getNode('node') instanceof Twig_Node_Expression_Name){ + throw new Twig_Error_Syntax('The "defined" test only works with simple variables', $this->getLine()); + } + + $compiler + ->raw($testMap[$this->getAttribute('name')]->compile().'(') + ->repr($this->getNode('node')->getAttribute('name')) + ->raw(', $context)') + ; + + return; + } + $compiler ->raw($testMap[$this->getAttribute('name')]->compile().'(') ->subcompile($this->getNode('node'))