Add traversable test

This commit is contained in:
Jordi Boggiano
2012-04-13 13:05:17 +02:00
parent 5fd2f98720
commit d78ed667ad
3 changed files with 50 additions and 0 deletions
+11
View File
@@ -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 %}
+20
View File
@@ -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.
*
* <pre>
* {# evaluates to true if the foo variable is an array or a traversable object #}
* {% if foo is traversable %}
* {# ... #}
* {% endif %}
* </pre>
*
* @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);
}
@@ -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