Completed
Push — master ( 8246ca...1e0bdf )
by Sergey
04:14
created

PaginationHelper::reachBatchesLimit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 2
1
<?php
2
3
namespace seregazhuk\PinterestBot\Helpers;
4
5
class PaginationHelper
6
{
7
    /**
8
     * Iterate through results of Api function call. By
9
     * default generator will return all pagination results.
10
     * To limit result batches, set $batchesLimit. Call function
11
     * of object to get data.
12
     *
13
     * @param mixed  $obj
14
     * @param string $function
15
     * @param array  $params
16
     * @param int    $batchesLimit
17
     * @return \Iterator
18
     */
19
    public static function getPaginatedData($obj, $function, $params, $batchesLimit = 0)
20
    {
21
        $batchesNum = 0;
22
        do {
23
            if (self::reachBatchesLimit($batchesLimit, $batchesNum))  break;
24
25
            $items = [];
26
            $res = call_user_func_array([$obj, $function], $params);
27
28
            if (self::_responseHasData($res)) {
29
                if (isset($res['data'][0]['type']) && $res['data'][0]['type'] == 'module') {
30
                    array_shift($res['data']);
31
                }
32
                $items = $res['data'];
33
            }
34
35
            if (isset($res['bookmarks'])) {
36
                $params['bookmarks'] = $res['bookmarks'];
37
            }
38
39
            if (empty($items)) return;
40
41
            $batchesNum++;
42
            yield $items;
43
        } while (self::_responseHasData($res));
44
    }
45
46
    /**
47
     * @param array $res
48
     * @return bool
49
     */
50
    protected static function _responseHasData($res)
51
    {
52
        return isset($res['data']) && ! empty($res['data']);
53
    }
54
55
    /**
56
     * Check if we get batches limit in pagination
57
     * @param int $batchesLimit
58
     * @param int $batchesNum
59
     * @return bool
60
     */
61
    protected static function reachBatchesLimit($batchesLimit, $batchesNum)
62
    {
63
        return $batchesLimit && $batchesNum >= $batchesLimit;
64
    }
65
}
66