1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace seregazhuk\PinterestBot\Helpers\Providers; |
4
|
|
|
|
5
|
|
|
trait 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 callable $callback |
14
|
|
|
* @param array $params |
15
|
|
|
* @param int $batchesLimit |
16
|
|
|
* @return \Iterator |
17
|
|
|
*/ |
18
|
|
|
public function getPaginatedData($callback, $params, $batchesLimit = 0) |
19
|
|
|
{ |
20
|
|
|
$batchesNum = 0; |
21
|
|
|
do { |
22
|
|
|
if (self::reachBatchesLimit($batchesLimit, $batchesNum)) break; |
23
|
|
|
|
24
|
|
|
$items = []; |
25
|
|
|
$res = call_user_func_array($callback, $params); |
26
|
|
|
|
27
|
|
|
if (self::_responseHasData($res)) { |
28
|
|
|
$res = self::_clearResponseFromMetaData($res); |
29
|
|
|
$items = $res['data']; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (empty($items)) return; |
33
|
|
|
|
34
|
|
|
if (isset($res['bookmarks'])) { |
35
|
|
|
$params['bookmarks'] = $res['bookmarks']; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$batchesNum++; |
39
|
|
|
yield $items; |
40
|
|
|
} while (self::_responseHasData($res)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param array $res |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
|
|
protected function _responseHasData($res) |
48
|
|
|
{ |
49
|
|
|
return isset($res['data']) && ! empty($res['data']); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Check if we get batches limit in pagination |
54
|
|
|
* @param int $batchesLimit |
55
|
|
|
* @param int $batchesNum |
56
|
|
|
* @return bool |
57
|
|
|
*/ |
58
|
|
|
protected function reachBatchesLimit($batchesLimit, $batchesNum) |
59
|
|
|
{ |
60
|
|
|
return $batchesLimit && $batchesNum >= $batchesLimit; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Remove 'module' data from response |
65
|
|
|
* @param array $res |
66
|
|
|
* @return array mixed |
67
|
|
|
*/ |
68
|
|
|
protected function _clearResponseFromMetaData($res) |
69
|
|
|
{ |
70
|
|
|
if (isset($res['data'][0]['type']) && $res['data'][0]['type'] == 'module') { |
71
|
|
|
array_shift($res['data']); |
72
|
|
|
return $res; |
73
|
|
|
} |
74
|
|
|
return $res; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|