Skip to content

Commit 80d653a

Browse files
committed
use getArrayCopy() for ArrayIterator
1 parent 67a450c commit 80d653a

File tree

2 files changed

+26
-11
lines changed

2 files changed

+26
-11
lines changed

src/Finder.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace ArrayLookup;
66

7+
use ArrayIterator;
78
use Traversable;
89
use Webmozart\Assert\Assert;
910

@@ -37,6 +38,19 @@ public static function first(iterable $data, callable $filter): mixed
3738
return null;
3839
}
3940

41+
/**
42+
* @param Traversable<mixed, mixed> $traversable
43+
* @return mixed[]
44+
*/
45+
private static function resolveArrayFromTraversable(Traversable $traversable): array
46+
{
47+
if ($traversable instanceof ArrayIterator) {
48+
return $traversable->getArrayCopy();
49+
}
50+
51+
return iterator_to_array($traversable);
52+
}
53+
4054
/**
4155
* @param mixed[]|iterable $data
4256
* @param callable(mixed $datum): bool $filter
@@ -45,7 +59,7 @@ public static function last(iterable $data, callable $filter): mixed
4559
{
4660
// convert to array when data is Traversable instance
4761
if ($data instanceof Traversable) {
48-
$data = iterator_to_array($data);
62+
$data = self::resolveArrayFromTraversable($data);
4963
}
5064

5165
// ensure data is array for end(), key(), current(), prev() usage

tests/FinderTest.php

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace ArrayLookup\Tests;
66

7+
use ArrayIterator;
78
use ArrayLookup\Finder;
89
use ArrayObject;
910
use PHPUnit\Framework\TestCase;
@@ -34,16 +35,6 @@ public function firstDataProvider(): array
3435
static fn($datum): bool => $datum === 1000,
3536
null,
3637
],
37-
[
38-
new ArrayObject([1, 2, 3]),
39-
static fn($datum): bool => $datum === 2,
40-
2,
41-
],
42-
[
43-
new ArrayObject([1, "1", 3]),
44-
static fn($datum): bool => $datum === 1000,
45-
null,
46-
],
4738
];
4839
}
4940

@@ -71,6 +62,16 @@ public function lastDataProvider(): array
7162
static fn($datum): bool => $datum < 5,
7263
null,
7364
],
65+
[
66+
new ArrayIterator([6, 7, 8, 9]),
67+
static fn($datum): bool => $datum > 5,
68+
9,
69+
],
70+
[
71+
new ArrayIterator([6, 7, 8, 9]),
72+
static fn($datum): bool => $datum < 5,
73+
null,
74+
],
7475
[
7576
new ArrayObject([6, 7, 8, 9]),
7677
static fn($datum): bool => $datum > 5,

0 commit comments

Comments
 (0)