Skip to content

Commit

Permalink
CachingIterator: refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jun 18, 2024
1 parent 47f0b5a commit 99976d6
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 20 deletions.
24 changes: 5 additions & 19 deletions src/Iterators/CachingIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,12 @@ class CachingIterator extends \CachingIterator implements \Countable
private int $counter = 0;


public function __construct($iterator)
public function __construct(iterable|\stdClass $iterable)
{
if (is_array($iterator) || $iterator instanceof \stdClass) {
$iterator = new \ArrayIterator($iterator);

} elseif ($iterator instanceof \IteratorAggregate) {
do {
$iterator = $iterator->getIterator();
} while ($iterator instanceof \IteratorAggregate);

assert($iterator instanceof \Iterator);

} elseif ($iterator instanceof \Iterator) {
} elseif ($iterator instanceof \Traversable) {
$iterator = new \IteratorIterator($iterator);
} else {
throw new Nette\InvalidArgumentException(sprintf('Invalid argument passed to %s; array or Traversable expected, %s given.', self::class, get_debug_type($iterator)));
}

parent::__construct($iterator, 0);
$iterable = $iterable instanceof \stdClass
? new \ArrayIterator($iterable)
: Nette\Utils\Iterables::toIterator($iterable);
parent::__construct($iterable, 0);
}


Expand Down
2 changes: 1 addition & 1 deletion tests/Iterators/CachingIterator.construct.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ test('object', function () {
Assert::exception(function () {
$arr = dir('.');
foreach (new Iterators\CachingIterator($arr) as $k => $v);
}, InvalidArgumentException::class, null);
}, TypeError::class, null);
});


Expand Down

0 comments on commit 99976d6

Please sign in to comment.