bentools/rewindable-generator

Now your generators become rewindable.

1.2 2023-12-23 15:48 UTC

This package is auto-updated.

Last update: 2024-10-23 17:29:19 UTC


README

Latest Stable Version License CI Workflow Coverage 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