|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace leinonen\Yii2Algolia\ActiveRecord; |
|
4
|
|
|
|
|
5
|
|
|
use yii\db\ActiveQueryInterface; |
|
6
|
|
|
|
|
7
|
|
|
class ActiveQueryChunker |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Chunk the results of an ActiveQuery. |
|
11
|
|
|
* |
|
12
|
|
|
* @param ActiveQueryInterface $query |
|
13
|
|
|
* @param int $size The size of chunk retrieved from the query. |
|
14
|
|
|
* @param callable $callback |
|
15
|
|
|
* |
|
16
|
|
|
* @return array |
|
17
|
|
|
*/ |
|
18
|
6 |
|
public function chunk(ActiveQueryInterface $query, $size, callable $callback) |
|
19
|
|
|
{ |
|
20
|
6 |
|
$pageNumber = 1; |
|
21
|
6 |
|
$records = $this->paginateRecords($query, $pageNumber, $size)->all(); |
|
22
|
6 |
|
$results = []; |
|
23
|
|
|
|
|
24
|
6 |
|
while (count($records) > 0) { |
|
25
|
|
|
// On each chunk, pass the records to the callback and then let the |
|
26
|
|
|
// developer take care of everything within the callback. This allows to |
|
27
|
|
|
// keep the memory low when looping through large result sets. |
|
28
|
6 |
|
$callableResults = $callback($records); |
|
29
|
|
|
|
|
30
|
6 |
|
if ($callableResults === false) { |
|
31
|
1 |
|
break; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
// If the results of the given callable function were an array |
|
35
|
|
|
// merge them into the result array which is returned at the end of the chunking. |
|
36
|
5 |
|
if (\is_array($callableResults)) { |
|
37
|
4 |
|
$results = \array_merge($results, $callableResults); |
|
38
|
4 |
|
} |
|
39
|
|
|
|
|
40
|
5 |
|
$pageNumber++; |
|
41
|
5 |
|
$records = $this->paginateRecords($query, $pageNumber, $size)->all(); |
|
42
|
5 |
|
} |
|
43
|
|
|
|
|
44
|
6 |
|
return $results; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Paginate the results of the query. |
|
49
|
|
|
* |
|
50
|
|
|
* @param ActiveQueryInterface $query |
|
51
|
|
|
* @param int $pageNumber |
|
52
|
|
|
* @param int $count |
|
53
|
|
|
* |
|
54
|
|
|
* @return ActiveQueryInterface |
|
55
|
|
|
*/ |
|
56
|
6 |
|
private function paginateRecords(ActiveQueryInterface $query, $pageNumber, $count) |
|
57
|
|
|
{ |
|
58
|
6 |
|
$offset = ($pageNumber - 1) * $count; |
|
59
|
6 |
|
$limit = $count; |
|
60
|
|
|
|
|
61
|
6 |
|
return $query->offset($offset)->limit($limit); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|