From 693956586776108847a447e86b4e5e92ee0a20be Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 23 May 2013 18:28:35 +0200 Subject: [PATCH] added support for object instances as the second argument of the constant test (closes #1100) --- CHANGELOG | 1 + doc/tests/constant.rst | 11 +++++++++++ lib/Twig/Node/Expression/Test/Constant.php | 11 +++++++++++ test/Twig/Tests/Fixtures/tests/constant.test | 4 +++- 4 files changed, 26 insertions(+), 1 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index d0dfeb4..1bd4a98 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.13.1 (2013-XX-XX) + * added support for object instances as the second argument of the constant test * fixed the include function when used in an assignment * 1.13.0 (2013-05-10) diff --git a/doc/tests/constant.rst b/doc/tests/constant.rst index 7970933..8d0724a 100644 --- a/doc/tests/constant.rst +++ b/doc/tests/constant.rst @@ -1,6 +1,9 @@ ``constant`` ============ +.. versionadded: 1.13.1 + constant now accepts object instances as the second argument. + ``constant`` checks if a variable has the exact same value as a constant. You can use either global constants or class constants: @@ -9,3 +12,11 @@ can use either global constants or class constants: {% if post.status is constant('Post::PUBLISHED') %} the status attribute is exactly the same as Post::PUBLISHED {% endif %} + +You can test constants from object instances as well: + +.. code-block:: jinja + + {% if post.status is constant('PUBLISHED', post) %} + the status attribute is exactly the same as Post::PUBLISHED + {% endif %} diff --git a/lib/Twig/Node/Expression/Test/Constant.php b/lib/Twig/Node/Expression/Test/Constant.php index 45b1e5d..de55f5f 100644 --- a/lib/Twig/Node/Expression/Test/Constant.php +++ b/lib/Twig/Node/Expression/Test/Constant.php @@ -28,6 +28,17 @@ class Twig_Node_Expression_Test_Constant extends Twig_Node_Expression_Test ->raw('(') ->subcompile($this->getNode('node')) ->raw(' === constant(') + ; + + if ($this->getNode('arguments')->hasNode(1)) { + $compiler + ->raw('get_class(') + ->subcompile($this->getNode('arguments')->getNode(1)) + ->raw(')."::".') + ; + } + + $compiler ->subcompile($this->getNode('arguments')->getNode(0)) ->raw('))') ; diff --git a/test/Twig/Tests/Fixtures/tests/constant.test b/test/Twig/Tests/Fixtures/tests/constant.test index c8adb15..60218ac 100644 --- a/test/Twig/Tests/Fixtures/tests/constant.test +++ b/test/Twig/Tests/Fixtures/tests/constant.test @@ -4,9 +4,11 @@ {{ 8 is constant('E_NOTICE') ? 'ok' : 'no' }} {{ 'bar' is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} {{ value is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} +{{ 2 is constant('ARRAY_AS_PROPS', object) ? 'ok' : 'no' }} --DATA-- -return array('value' => 'bar'); +return array('value' => 'bar', 'object' => new ArrayObject(array('hi'))); --EXPECT-- ok ok +ok ok \ No newline at end of file -- 1.7.2.5