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