From 99976d606c131e1320a27f019f808a4dbc10d95c Mon Sep 17 00:00:00 2001 From: David Grudl Date: Fri, 3 May 2024 13:19:44 +0200 Subject: [PATCH] CachingIterator: refactoring --- src/Iterators/CachingIterator.php | 24 ++++--------------- .../Iterators/CachingIterator.construct.phpt | 2 +- 2 files changed, 6 insertions(+), 20 deletions(-) diff --git a/src/Iterators/CachingIterator.php b/src/Iterators/CachingIterator.php index 18b1397da..02bd74070 100644 --- a/src/Iterators/CachingIterator.php +++ b/src/Iterators/CachingIterator.php @@ -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); } diff --git a/tests/Iterators/CachingIterator.construct.phpt b/tests/Iterators/CachingIterator.construct.phpt index a5948c1f9..615d88d54 100644 --- a/tests/Iterators/CachingIterator.construct.phpt +++ b/tests/Iterators/CachingIterator.construct.phpt @@ -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); });