From d78ed667ad3f42d8712a7836fb0a27db7e0671ce Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Fri, 13 Apr 2012 13:05:17 +0200 Subject: [PATCH] Add traversable test --- doc/tests/traversable.rst | 11 +++++++++++ lib/Twig/Extension/Core.php | 20 ++++++++++++++++++++ test/Twig/Tests/Fixtures/tests/traversable.test | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+), 0 deletions(-) create mode 100644 doc/tests/traversable.rst create mode 100644 test/Twig/Tests/Fixtures/tests/traversable.test diff --git a/doc/tests/traversable.rst b/doc/tests/traversable.rst new file mode 100644 index 0000000..1809755 --- /dev/null +++ b/doc/tests/traversable.rst @@ -0,0 +1,11 @@ +``traversable`` +========= + +``traversable`` checks if a variable is an array or a traversable object: + +.. code-block:: jinja + + {# evaluates to true if the foo variable is traversable #} + {% if foo is traversable %} + ... + {% endif %} diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index bdd2d00..14fbca7 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -203,6 +203,7 @@ class Twig_Extension_Core extends Twig_Extension 'constant' => new Twig_Test_Node('Twig_Node_Expression_Test_Constant'), 'empty' => new Twig_Test_Function('twig_test_empty'), 'array' => new Twig_Test_Function('is_array'), + 'traversable' => new Twig_Test_Function('twig_test_traversable'), ); } @@ -1014,3 +1015,22 @@ function twig_test_empty($value) return false === $value || (empty($value) && '0' != $value); } + +/** + * Checks if a variable is traversable. + * + *
+ * {# evaluates to true if the foo variable is an array or a traversable object #}
+ * {% if foo is traversable %}
+ *     {# ... #}
+ * {% endif %}
+ * 
+ * + * @param mixed $value A variable + * + * @return Boolean true if the value is traversable + */ +function twig_test_traversable($value) +{ + return is_array($value) || (is_object($value) && $value instanceof Traversable); +} diff --git a/test/Twig/Tests/Fixtures/tests/traversable.test b/test/Twig/Tests/Fixtures/tests/traversable.test new file mode 100644 index 0000000..de406cd --- /dev/null +++ b/test/Twig/Tests/Fixtures/tests/traversable.test @@ -0,0 +1,19 @@ +--TEST-- +"traversable" test +--TEMPLATE-- +{{ foo is traversable ? 'ok' : 'ko' }} +{{ traversable is traversable ? 'ok' : 'ko' }} +{{ obj is traversable ? 'ok' : 'ko' }} +{{ val is traversable ? 'ok' : 'ko' }} +--DATA-- +return array( + 'foo' => array(), + 'traversable' => new ArrayIterator(array()), + 'obj' => new stdClass(), + 'val' => 'test', +); +--EXPECT-- +ok +ok +ko +ko \ No newline at end of file -- 1.7.2.5