interface Yielder
{
public function getData(): iterable;
}
class ClassicYielder implements Yielder
{
public function getData(): iterable
{
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
}
class LimitedYielder implements Yielder
{
private $wrapped;
private $total = 3;
private $count = 0;
public function __construct(Yielder $wrapped)
{
$this->wrapped = $wrapped;
}
public function getData(): iterable
{
if ($this->count < $this->total) {
$this->count++;
yield from $this->wrapped->getData();
}
// how to stop here?
}
}
$x = new ClassicYielder();
$y = new LimitedYielder($x);
foreach ($y->getData() as $data) {
echo $data;
}
===
Will print: 1 2 3 4 5
I have a Yielder interface with a single method that returns a iterable via yield. I want to wrap my classic yielder in a limited one, that only yields values as long as a condition passes. As you can see, the code above will yield all the values of my classic yielder, without keeping track of my counter.
What am I doing wrong here? Is there any way I can get this to work?