bentools / rewindable-generator
Now your generators become rewindable.
1.2
2023-12-23 15:48 UTC
Requires
- php: >=8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.35
- pestphp/pest: ^2.24
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.4
- squizlabs/php_codesniffer: ^3.7
- symfony/var-dumper: @stable
This package is auto-updated.
Last update: 2024-10-23 17:29:19 UTC
README
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 break
the loop), since the CachingIterator
won't have all items in cache.
Installation
composer require bentools/rewindable-generator
Tests
./vendor/bin/phpunit