Skip to content

Instantly share code, notes, and snippets.

@jenkoian
Created July 24, 2017 13:35
Show Gist options
  • Save jenkoian/2f3e32a6945085884e71c2a78d8464d1 to your computer and use it in GitHub Desktop.
Save jenkoian/2f3e32a6945085884e71c2a78d8464d1 to your computer and use it in GitHub Desktop.
Generators are non rewindable by default, you can wrap them in this to make them rewindable.
<?php
namespace Jenko;
/**
* Usage:
* $rewindableGenerator = new RewindableGenerator(function() {
* reset($this->cursor);
* while ($row = $this->fetch()) {
* yield $row;
* }
*});
*/
class RewindableGenerator implements \IteratorAggregate
{
private $generator;
/**
* @param callable $generator
*/
public function __construct(callable $generator)
{
$this->generator = $generator;
}
public function getIterator()
{
return ($this->generator)();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment