Skip to content

Commit 7c899dc

Browse files
committed
Add chunkArray() method
1 parent 658e1a5 commit 7c899dc

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

system/BaseModel.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,21 @@ abstract public function countAllResults(bool $reset = true, bool $test = false)
585585
*/
586586
abstract public function chunk(int $size, Closure $userFunc);
587587

588+
/**
589+
* Loops over records in batches, allowing you to operate on each chunk at a time.
590+
* This method works only with DB calls.
591+
*
592+
* This method calls the `$userFunc` with the chunk, instead of a single record as in `chunk()`.
593+
* This allows you to operate on multiple records at once, which can be more efficient for certain operations.
594+
*
595+
* @param Closure(array<array<string, string>>|array<object>): mixed $userFunc
596+
*
597+
* @return void
598+
*
599+
* @throws DataException
600+
*/
601+
abstract public function chunkArray(int $size, Closure $userFunc);
602+
588603
/**
589604
* Fetches the row of database.
590605
*

system/Model.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,40 @@ public function chunk(int $size, Closure $userFunc)
560560
}
561561
}
562562

563+
/**
564+
* {@inheritDoc}
565+
*
566+
* Works with `$this->builder` to get the Compiled select to
567+
* determine the rows to operate on.
568+
* This method works only with dbCalls.
569+
*/
570+
public function chunkArray(int $size, Closure $userFunc)
571+
{
572+
$total = $this->builder()->countAllResults(false);
573+
$offset = 0;
574+
575+
while ($offset <= $total) {
576+
$builder = clone $this->builder();
577+
$rows = $builder->get($size, $offset);
578+
579+
if (! $rows) {
580+
throw DataException::forEmptyDataset('chunk');
581+
}
582+
583+
$rows = $rows->getResult($this->tempReturnType);
584+
585+
$offset += $size;
586+
587+
if ($rows === []) {
588+
continue;
589+
}
590+
591+
if ($userFunc($rows) === false) {
592+
return;
593+
}
594+
}
595+
}
596+
563597
/**
564598
* Provides a shared instance of the Query Builder.
565599
*

0 commit comments

Comments
 (0)