diff --git a/CHANGELOG b/CHANGELOG index 38532c765..ccd2765a1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.23.4 (2016-XX-XX) + * fixed the defined test when used on a constant, a map, or a sequence * undeprecated _self (should only be used to get the template name, not the template instance) * fixed parsing on PHP7 diff --git a/lib/Twig/Node/Expression/Test/Defined.php b/lib/Twig/Node/Expression/Test/Defined.php index 4b4a48a2b..3dc6ff592 100644 --- a/lib/Twig/Node/Expression/Test/Defined.php +++ b/lib/Twig/Node/Expression/Test/Defined.php @@ -25,17 +25,19 @@ class Twig_Node_Expression_Test_Defined extends Twig_Node_Expression_Test { public function __construct(Twig_NodeInterface $node, $name, Twig_NodeInterface $arguments = null, $lineno) { - parent::__construct($node, $name, $arguments, $lineno); - if ($node instanceof Twig_Node_Expression_Name) { $node->setAttribute('is_defined_test', true); } elseif ($node instanceof Twig_Node_Expression_GetAttr) { $node->setAttribute('is_defined_test', true); $this->changeIgnoreStrictCheck($node); + } elseif ($node instanceof Twig_Node_Expression_Constant || $node instanceof Twig_Node_Expression_Array) { + $node = new Twig_Node_Expression_Constant(true, $node->getLine()); } else { throw new Twig_Error_Syntax('The "defined" test only works with simple variables.', $this->getLine()); } + + parent::__construct($node, $name, $arguments, $lineno); } protected function changeIgnoreStrictCheck(Twig_Node_Expression_GetAttr $node) diff --git a/test/Twig/Tests/Fixtures/tests/defined.test b/test/Twig/Tests/Fixtures/tests/defined.test index cbfe03de5..d4e204efa 100644 --- a/test/Twig/Tests/Fixtures/tests/defined.test +++ b/test/Twig/Tests/Fixtures/tests/defined.test @@ -26,6 +26,13 @@ {{ object.self.foo is defined ? 'ok' : 'ko' }} {{ object.self.undefinedMethod is defined ? 'ko' : 'ok' }} {{ object.undefinedMethod.self is defined ? 'ko' : 'ok' }} +{{ 0 is defined ? 'ok' : 'ko' }} +{{ "foo" is defined ? 'ok' : 'ko' }} +{{ true is defined ? 'ok' : 'ko' }} +{{ false is defined ? 'ok' : 'ko' }} +{{ null is defined ? 'ok' : 'ko' }} +{{ [1, 2] is defined ? 'ok' : 'ko' }} +{{ { foo: "bar" } is defined ? 'ok' : 'ko' }} --DATA-- return array( 'definedVar' => 'defined', @@ -65,6 +72,13 @@ ok ok ok ok +ok +ok +ok +ok +ok +ok +ok --DATA-- return array( 'definedVar' => 'defined', @@ -106,3 +120,10 @@ ok ok ok ok +ok +ok +ok +ok +ok +ok +ok