Skip to content

Commit 9cc3cd9

Browse files
committed
[Finder] Add optional pass limit to Finder::rows() to allow only gather maximum until provided limit
1 parent f86a0e1 commit 9cc3cd9

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Finder.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
use function key;
1717
use function prev;
1818

19+
use const PHP_INT_MAX;
20+
1921
final class Finder
2022
{
2123
/**
@@ -123,10 +125,11 @@ public static function last(
123125
* @param callable(mixed $datum, int|string|null $key=): bool $filter
124126
* @return mixed[]
125127
*/
126-
public static function rows(iterable $data, callable $filter, bool $preserveKey = false): array
128+
public static function rows(iterable $data, callable $filter, bool $preserveKey = false, int $limit = PHP_INT_MAX): array
127129
{
128130
$rows = [];
129131
$newKey = 0;
132+
$total = 0;
130133

131134
foreach ($data as $key => $datum) {
132135
$isFound = $filter($datum, $key);
@@ -146,6 +149,11 @@ public static function rows(iterable $data, callable $filter, bool $preserveKey
146149
}
147150

148151
$rows[$rowKey] = $datum;
152+
153+
++$total;
154+
if ($total === $limit) {
155+
break;
156+
}
149157
}
150158

151159
return $rows;

tests/FinderTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,4 +323,17 @@ public static function rowsDataProviderPreserveKey(): array
323323
],
324324
];
325325
}
326+
327+
public function testRowsWithLimit(): void
328+
{
329+
$data = [1, 2];
330+
$filter = static fn ($datum): bool => $datum >= 0;
331+
332+
$this->assertSame(
333+
[
334+
1,
335+
],
336+
Finder::rows($data, $filter, limit: 1)
337+
);
338+
}
326339
}

0 commit comments

Comments
 (0)