diff --git a/CHANGELOG b/CHANGELOG index 50ec829f9..469d6c1c9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 2.11.3 (2019-XX-XX) + * fixed the filter filter (allow the result to be used several times) * fixed macro auto-import when a template contains only macros * 2.11.2 (2019-06-05) diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index eda048727..07360c0a2 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -1522,11 +1522,12 @@ function twig_array_column($array, $name): array function twig_array_filter($array, $arrow) { - foreach ($array as $k => $v) { - if ($arrow($v, $k)) { - yield $k => $v; - } + if (\is_array($array)) { + return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH); } + + // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator + return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow); } function twig_array_map($array, $arrow) diff --git a/test/Twig/Tests/Fixtures/filters/filter.test b/test/Twig/Tests/Fixtures/filters/filter.test index 3d3fdcc68..97b946968 100644 --- a/test/Twig/Tests/Fixtures/filters/filter.test +++ b/test/Twig/Tests/Fixtures/filters/filter.test @@ -35,6 +35,11 @@ {% for k, v in xml|filter(x => true) %} {{ k }}/{{ v }} {% endfor %} + +{% set coll = ['a', 'b']|filter(v => v is same as('a')) %} +{% if coll|length > 0 %} + {{- coll|join(', ') }} +{% endif %} --DATA-- return [ 'it' => new \ArrayIterator(['a' => 1, 'b' => 2, 'c' => 5, 'd' => 8]), @@ -68,3 +73,5 @@ elem/baz elem/foo elem/bar elem/baz + +a