diff --git a/CHANGELOG b/CHANGELOG index 6e1784974..ff4e92f8e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.42.3 (2019-XX-XX) + * fixed the "empty" test on Traversable instances * fixed cache when opcache is installed but disabled * 1.42.2 (2019-06-18) diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index 9d8214768..5f3cc24a1 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -1507,6 +1507,10 @@ function twig_test_empty($value) return 0 == \count($value); } + if ($value instanceof \Traversable) { + return !iterator_count($value); + } + if (\is_object($value) && method_exists($value, '__toString')) { return '' === (string) $value; } diff --git a/tests/Fixtures/tests/empty.test b/tests/Fixtures/tests/empty.test index f3862c083..ffcd51870 100644 --- a/tests/Fixtures/tests/empty.test +++ b/tests/Fixtures/tests/empty.test @@ -15,6 +15,10 @@ {{ tostring_not_empty is empty ? 'ko' : 'ok' }} {{ markup_empty is empty ? 'ok' : 'ko' }} {{ markup_not_empty is empty ? 'ko' : 'ok' }} +{{ iterator is empty ? 'ko' : 'ok' }} +{{ empty_iterator is empty ? 'ok' : 'ko' }} +{{ callback_iterator is empty ? 'ko' : 'ok' }} +{{ empty_callback_iterator is empty ? 'ok' : 'ko' }} --DATA-- return [ 'string_empty' => '', 'string_zero' => '0', @@ -24,6 +28,10 @@ return [ 'countable_empty' => new \Twig\Tests\CountableStub([]), 'countable_not_empty' => new \Twig\Tests\CountableStub([1, 2]), 'tostring_empty' => new \Twig\Tests\ToStringStub(''), 'tostring_not_empty' => new \Twig\Tests\ToStringStub('0' /* edge case of using "0" as the string */), 'markup_empty' => new \Twig\Markup('', 'UTF-8'), 'markup_not_empty' => new \Twig\Markup('test', 'UTF-8'), + 'iterator' => $iter = new \ArrayIterator(['bar', 'foo']), + 'empty_iterator' => new \ArrayIterator(), + 'callback_iterator' => new \CallbackFilterIterator($iter, function ($el) { return true; }), + 'empty_callback_iterator' => new \CallbackFilterIterator($iter, function ($el) { return false; }), ] --EXPECT-- ok @@ -40,3 +48,7 @@ ok ok ok ok +ok +ok +ok +ok