From 80d653a1b62569274ddae301ed68c8ceec89d653 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Mon, 9 Jan 2023 09:56:49 +0700 Subject: [PATCH] use getArrayCopy() for ArrayIterator --- src/Finder.php | 16 +++++++++++++++- tests/FinderTest.php | 21 +++++++++++---------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/Finder.php b/src/Finder.php index e47d48b..a0ecbf0 100644 --- a/src/Finder.php +++ b/src/Finder.php @@ -4,6 +4,7 @@ namespace ArrayLookup; +use ArrayIterator; use Traversable; use Webmozart\Assert\Assert; @@ -37,6 +38,19 @@ public static function first(iterable $data, callable $filter): mixed return null; } + /** + * @param Traversable $traversable + * @return mixed[] + */ + private static function resolveArrayFromTraversable(Traversable $traversable): array + { + if ($traversable instanceof ArrayIterator) { + return $traversable->getArrayCopy(); + } + + return iterator_to_array($traversable); + } + /** * @param mixed[]|iterable $data * @param callable(mixed $datum): bool $filter @@ -45,7 +59,7 @@ public static function last(iterable $data, callable $filter): mixed { // convert to array when data is Traversable instance if ($data instanceof Traversable) { - $data = iterator_to_array($data); + $data = self::resolveArrayFromTraversable($data); } // ensure data is array for end(), key(), current(), prev() usage diff --git a/tests/FinderTest.php b/tests/FinderTest.php index de40460..1dc0672 100644 --- a/tests/FinderTest.php +++ b/tests/FinderTest.php @@ -4,6 +4,7 @@ namespace ArrayLookup\Tests; +use ArrayIterator; use ArrayLookup\Finder; use ArrayObject; use PHPUnit\Framework\TestCase; @@ -34,16 +35,6 @@ public function firstDataProvider(): array static fn($datum): bool => $datum === 1000, null, ], - [ - new ArrayObject([1, 2, 3]), - static fn($datum): bool => $datum === 2, - 2, - ], - [ - new ArrayObject([1, "1", 3]), - static fn($datum): bool => $datum === 1000, - null, - ], ]; } @@ -71,6 +62,16 @@ public function lastDataProvider(): array static fn($datum): bool => $datum < 5, null, ], + [ + new ArrayIterator([6, 7, 8, 9]), + static fn($datum): bool => $datum > 5, + 9, + ], + [ + new ArrayIterator([6, 7, 8, 9]), + static fn($datum): bool => $datum < 5, + null, + ], [ new ArrayObject([6, 7, 8, 9]), static fn($datum): bool => $datum > 5,