Skip to content

Commit

Permalink
use getArrayCopy() for ArrayIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonasik committed Jan 9, 2023
1 parent 67a450c commit 80d653a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
16 changes: 15 additions & 1 deletion src/Finder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace ArrayLookup;

use ArrayIterator;
use Traversable;
use Webmozart\Assert\Assert;

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

/**
* @param Traversable<mixed, mixed> $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
Expand All @@ -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
Expand Down
21 changes: 11 additions & 10 deletions tests/FinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace ArrayLookup\Tests;

use ArrayIterator;
use ArrayLookup\Finder;
use ArrayObject;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -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,
],
];
}

Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit 80d653a

Please sign in to comment.