bentools/rewindable-generator

Now your generators become rewindable.

1.0.1 2018-04-26 14:51 UTC

README

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Rewindable generator

$generator = (function () {
    yield 'foo';
    yield 'bar';
})();

var_dump(iterator_to_array($generator)); // ['foo', 'bar']
var_dump(iterator_to_array($generator)); // Boom

PHP Fatal error: Uncaught Exception: Cannot traverse an already closed generator

Yes, I know. That's annoying. But here's a tiny class which will leverage a CachingIterator to make your generator rewindable.

Simple as:

use BenTools\RewindableGenerator;

$generator = (function () {
    yield 'foo';
    yield 'bar';
})();

$iterator = new RewindableGenerator($generator);

var_dump(iterator_to_array($iterator)); // ['foo', 'bar']
var_dump(iterator_to_array($iterator)); // ['foo', 'bar']

Warning: An exception will be thrown if you intend to rewind a generator which has not reached the end (i.e you breakthe loop), since the CachingIterator won't have all items in cache.

Installation

composer require bentools/rewindable-generator

Tests

./vendor/bin/phpunit