Skip to content

Commit 7193560

Browse files
committed
Support generator for foreEach
1 parent aa80f86 commit 7193560

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

src/Database/Database.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7863,10 +7863,10 @@ public function find(string $collection, array $queries = [], string $forPermiss
78637863
* @param callable $callback
78647864
* @param array<Query> $queries
78657865
* @param string $forPermission
7866-
* @return void
7866+
* @return \Generator
78677867
* @throws \Utopia\Database\Exception
78687868
*/
7869-
public function foreach(string $collection, callable $callback, array $queries = [], string $forPermission = Database::PERMISSION_READ): void
7869+
public function foreach(string $collection, ?callable $callback = null, array $queries = [], string $forPermission = Database::PERMISSION_READ): \Generator
78707870
{
78717871
$grouped = Query::groupByType($queries);
78727872
$limitExists = $grouped['limit'] !== null;
@@ -7906,8 +7906,10 @@ public function foreach(string $collection, callable $callback, array $queries =
79067906
$sum = count($results);
79077907

79087908
foreach ($results as $document) {
7909-
if (is_callable($callback)) {
7909+
if (!is_null($callback) && is_callable($callback)) {
79107910
$callback($document);
7911+
} else {
7912+
yield $document;
79117913
}
79127914
}
79137915

tests/e2e/Adapter/Scopes/DocumentTests.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4014,6 +4014,26 @@ public function testForeach(): void
40144014
/** @var Database $database */
40154015
$database = $this->getDatabase();
40164016

4017+
/**
4018+
* Test, foreach without callback on empty collection
4019+
*/
4020+
$database->createCollection('moviesEmpty');
4021+
$documents = [];
4022+
foreach ($database->foreach('movies', queries: [Query::limit(2)], ) as $document) {
4023+
$documents[] = $document;
4024+
}
4025+
$this->assertEquals(0, \count($documents));
4026+
$this->assertTrue($database->deleteCollection('moviesEmpty'));
4027+
4028+
/**
4029+
* Test, foreach without callback
4030+
*/
4031+
$documents = [];
4032+
foreach ($database->foreach('movies', queries: [Query::limit(2)], ) as $document) {
4033+
$documents[] = $document;
4034+
}
4035+
$this->assertEquals(6, count($documents));
4036+
40174037
/**
40184038
* Test, foreach goes through all the documents
40194039
*/

0 commit comments

Comments
 (0)