1 | <?php |
||
7 | class Pagination |
||
8 | { |
||
9 | /** |
||
10 | * @var Provider |
||
11 | */ |
||
12 | private $provider; |
||
13 | |||
14 | /** |
||
15 | * @var array |
||
16 | */ |
||
17 | protected $bookmarks = []; |
||
18 | |||
19 | public function __construct(Provider $provider) |
||
23 | |||
24 | /** |
||
25 | * Iterate through results of Api function call. By |
||
26 | * default generator will return all pagination results. |
||
27 | * To limit result batches, set $limit. Call function |
||
28 | * of object to get data. |
||
29 | * |
||
30 | * @param string $method |
||
31 | * @param array $params |
||
32 | * @param int $limit |
||
33 | * @return \Iterator |
||
34 | */ |
||
35 | public function paginateOver($method, $params, $limit = 0) |
||
36 | { |
||
37 | $resultsNum = 0; |
||
38 | while (true) { |
||
39 | |||
40 | $results = $this->callProviderRequest($method, $params); |
||
41 | if (empty($results) || $this->checkEndBookMarks()) { |
||
42 | return; |
||
43 | } |
||
44 | |||
45 | foreach ($results as $result) { |
||
46 | $resultsNum++; |
||
47 | yield $result; |
||
48 | |||
49 | if ($this->reachesLimit($limit, $resultsNum)) { |
||
50 | return; |
||
51 | } |
||
52 | } |
||
53 | } |
||
54 | } |
||
55 | |||
56 | protected function callProviderRequest($method, array $params) |
||
69 | |||
70 | protected function getDataFromPaginatedResponse($response) |
||
80 | |||
81 | /** |
||
82 | * @param array $response |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | protected function responseHasData($response) |
||
90 | |||
91 | /** |
||
92 | * Check if we get batches limit in pagination. |
||
93 | * |
||
94 | * @param int $limit |
||
95 | * @param int $resultsNum |
||
96 | * |
||
97 | * @return bool |
||
98 | */ |
||
99 | protected function reachesLimit($limit, $resultsNum) |
||
103 | |||
104 | /** |
||
105 | * Remove 'module' data from response. |
||
106 | * |
||
107 | * @param array $response |
||
108 | * |
||
109 | * @return array mixed |
||
110 | */ |
||
111 | protected function clearResponseFromMetaData($response) |
||
119 | |||
120 | /** |
||
121 | * @param $response |
||
122 | * |
||
123 | * @return array |
||
124 | */ |
||
125 | protected function getBookMarks($response) |
||
131 | |||
132 | protected function checkEndBookMarks() |
||
136 | } |
||
137 |