Description
Description
I've encountered inconsistent behaviour in the handling of empty generators with AppendIterator. Please can you confirm whether this is a bug or some weird expected behaviour.
Scenario 1
When iterating over a generator that yields nothing, foreach
has no items to iterate over so var_dump
isn't called, as expected.
<?php
function yieldEmpty()
{
yield from [];
}
foreach (yieldEmpty() as $item) {
var_dump($item);
}
Scenario 2
When attaching a generator yielding items and a generator yielding nothing and attaching both to an AppendIterator, foreach
iterates over the items from the former and the three values are output, as expected.
<?php
function yieldRows()
{
yield from ['one', 'two', 'three'];
}
function yieldEmpty()
{
yield from [];
}
$iterator = new AppendIterator();
$iterator->append(yieldRows());
$iterator->append(yieldEmpty());
foreach ($iterator as $item) {
var_dump($item);
}
Outputs (as expected):
string(3) "one"
string(3) "two"
string(5) "three"
Scenario 3
When attaching ONLY a generator yielding nothing and attaching it to an AppendIterator, foreach
unexpectedly fails with an exception.
<?php
function yieldEmpty()
{
yield from [];
}
$iterator = new AppendIterator();
$iterator->append(yieldEmpty());
foreach ($iterator as $item) {
var_dump($item);
}
Expected output (following on from scenario 1 and 2):
string(3) "one"
string(3) "two"
string(5) "three"
Actual output:
PHP Fatal error: Uncaught Exception: Cannot traverse an already closed generator in /Users/richard.coupland/test3.php:11
Stack trace:
#0 /Users/richard.coupland/test3.php(11): AppendIterator->rewind()
#1 {main}
thrown in /Users/richard.coupland/test3.php on line 11
Fatal error: Uncaught Exception: Cannot traverse an already closed generator in /Users/richard.coupland/test3.php:11
Stack trace:
#0 /Users/richard.coupland/test3.php(11): AppendIterator->rewind()
#1 {main}
thrown in /Users/richard.coupland/test3.php on line 11
PHP Version
8.2.7
Operating System
No response