mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-14 03:16:34 +00:00
Be able to count on iterator
This commit is contained in:
committed by
Patrick Landolt
parent
b36e3eb452
commit
be2c32cc1c
@@ -14,6 +14,8 @@ return value of the ``count()`` method.
|
||||
For objects that implement the ``__toString()`` magic method (and not ``Countable``),
|
||||
it will return the length of the string provided by that method.
|
||||
|
||||
For objects that implement the ``IteratorAggregate`` interface, ``length`` will use the return value of the ``iterator_count()`` method.
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% if users|length > 10 %}
|
||||
|
||||
@@ -1270,6 +1270,10 @@ if (function_exists('mb_get_info')) {
|
||||
if ($thing instanceof \Countable || is_array($thing)) {
|
||||
return count($thing);
|
||||
}
|
||||
|
||||
if ($thing instanceof \IteratorAggregate) {
|
||||
return iterator_count($thing);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
@@ -1369,6 +1373,10 @@ else {
|
||||
if ($thing instanceof \Countable || is_array($thing)) {
|
||||
return count($thing);
|
||||
}
|
||||
|
||||
if ($thing instanceof \IteratorAggregate) {
|
||||
return iterator_count($thing);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
{{ number|length }}
|
||||
{{ to_string_able|length }}
|
||||
{{ countable|length }}
|
||||
{{ iterator_aggregate|length }}
|
||||
{{ null|length }}
|
||||
{{ magic|length }}
|
||||
{{ non_countable|length }}
|
||||
@@ -16,6 +17,7 @@ return array(
|
||||
'number' => 1000,
|
||||
'to_string_able' => new ToStringStub('foobar'),
|
||||
'countable' => new CountableStub(42), /* also asserts we do *not* call __toString() */
|
||||
'iterator_aggregate' => new IteratorAggregateStub(array('a', 'b', 'c')), /* also asserts we do *not* call __toString() */
|
||||
'null' => null,
|
||||
'magic' => new MagicCallStub(), /* used to assert we do *not* call __call */
|
||||
'non_countable' => new \StdClass(),
|
||||
@@ -26,6 +28,7 @@ return array(
|
||||
4
|
||||
6
|
||||
42
|
||||
3
|
||||
0
|
||||
1
|
||||
1
|
||||
|
||||
@@ -307,3 +307,21 @@ class CountableStub implements \Countable
|
||||
throw new Exception('__toString shall not be called on \Countables');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is used in tests for the length filter
|
||||
*/
|
||||
class IteratorAggregateStub implements \IteratorAggregate
|
||||
{
|
||||
private $data;
|
||||
|
||||
public function __construct(array $data)
|
||||
{
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
public function getIterator()
|
||||
{
|
||||
return new ArrayIterator($this->data);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user