Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -7863,10 +7863,10 @@ public function find(string $collection, array $queries = [], string $forPermiss
* @param callable $callback
* @param array<Query> $queries
* @param string $forPermission
* @return void
* @return \Generator
Comment thread
Meldiron marked this conversation as resolved.
* @throws \Utopia\Database\Exception
*/
public function foreach(string $collection, callable $callback, array $queries = [], string $forPermission = Database::PERMISSION_READ): void
public function foreach(string $collection, ?callable $callback = null, array $queries = [], string $forPermission = Database::PERMISSION_READ): \Generator
Comment thread
Meldiron marked this conversation as resolved.
Outdated
{
$grouped = Query::groupByType($queries);
$limitExists = $grouped['limit'] !== null;
Expand Down Expand Up @@ -7906,8 +7906,10 @@ public function foreach(string $collection, callable $callback, array $queries =
$sum = count($results);

foreach ($results as $document) {
if (is_callable($callback)) {
if (!is_null($callback) && is_callable($callback)) {
$callback($document);
} else {
yield $document;
}
}

Expand Down
20 changes: 20 additions & 0 deletions tests/e2e/Adapter/Scopes/DocumentTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -4014,6 +4014,26 @@ public function testForeach(): void
/** @var Database $database */
$database = $this->getDatabase();

/**
* Test, foreach without callback on empty collection
*/
$database->createCollection('moviesEmpty');
$documents = [];
foreach ($database->foreach('moviesEmpty', queries: [Query::limit(2)], ) as $document) {
$documents[] = $document;
}
$this->assertEquals(0, \count($documents));
$this->assertTrue($database->deleteCollection('moviesEmpty'));
Comment thread
Meldiron marked this conversation as resolved.

/**
* Test, foreach without callback
*/
$documents = [];
foreach ($database->foreach('movies', queries: [Query::limit(2)], ) as $document) {
Comment thread
Meldiron marked this conversation as resolved.
Outdated
$documents[] = $document;
}
$this->assertEquals(6, count($documents));

/**
* Test, foreach goes through all the documents
*/
Expand Down
Loading