Completed
Push — master ( ee56eb...1eb78b )
by Juuso
04:46
created

ActiveQueryChunker   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 1
dl 0
loc 58
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B chunk() 0 29 4
A paginateRecords() 0 7 1
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
}