From: Jordi Boggiano Date: Fri, 13 Apr 2012 11:05:17 +0000 (+0200) Subject: Add traversable test X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=d78ed667ad3f42d8712a7836fb0a27db7e0671ce;p=web%2Fkonrad%2Ftwig.git Add 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