https://github.com/bpolaszek/rewindable-generator
Uncaught Exception: Cannot traverse an already closed generator => NOT ANYMORE.
https://github.com/bpolaszek/rewindable-generator
Last synced: 3 months ago
JSON representation
Uncaught Exception: Cannot traverse an already closed generator => NOT ANYMORE.
- Host: GitHub
- URL: https://github.com/bpolaszek/rewindable-generator
- Owner: bpolaszek
- License: mit
- Created: 2018-04-26T14:44:28.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-12-23T15:49:13.000Z (about 2 years ago)
- Last Synced: 2025-02-01T05:12:45.948Z (11 months ago)
- Language: PHP
- Size: 10.7 KB
- Stars: 4
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://packagist.org/packages/bentools/rewindable-generator)
[](https://packagist.org/packages/bentools/rewindable-generator)
[](https://github.com/bpolaszek/rewindable-generator/actions/workflows/ci.yml)
[](https://codecov.io/gh/bpolaszek/rewindable-generator)
[](https://packagist.org/packages/bentools/rewindable-generator)
Rewindable generator
==============
```php
$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:
```php
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