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 $batchesLimit. Call function |
||
28 | * of object to get data. |
||
29 | * |
||
30 | * @param string $method |
||
31 | * @param array $params |
||
32 | * @param int $batchesLimit |
||
33 | * @return \Iterator |
||
34 | */ |
||
35 | public function paginate($method, $params, $batchesLimit = 0) |
||
36 | { |
||
37 | $batchesNum = 0; |
||
38 | do { |
||
39 | $results = $this->callProviderRequest($method, $params); |
||
40 | if (empty($results) || $this->checkEndBookMarks()) { |
||
41 | return; |
||
42 | } |
||
43 | |||
44 | $batchesNum++; |
||
45 | foreach ($results as $result) { |
||
46 | yield $result; |
||
47 | } |
||
48 | |||
49 | } while (!$this->reachBatchesLimit($batchesLimit, $batchesNum)); |
||
50 | } |
||
51 | |||
52 | protected function callProviderRequest($method, array $params) |
||
65 | |||
66 | protected function getDataFromPaginatedResponse($response) |
||
76 | |||
77 | /** |
||
78 | * @param array $response |
||
79 | * |
||
80 | * @return bool |
||
81 | */ |
||
82 | protected function responseHasData($response) |
||
86 | |||
87 | /** |
||
88 | * Check if we get batches limit in pagination. |
||
89 | * |
||
90 | * @param int $batchesLimit |
||
91 | * @param int $batchesNum |
||
92 | * |
||
93 | * @return bool |
||
94 | */ |
||
95 | protected function reachBatchesLimit($batchesLimit, $batchesNum) |
||
99 | |||
100 | /** |
||
101 | * Remove 'module' data from response. |
||
102 | * |
||
103 | * @param array $response |
||
104 | * |
||
105 | * @return array mixed |
||
106 | */ |
||
107 | protected function clearResponseFromMetaData($response) |
||
115 | |||
116 | /** |
||
117 | * @param $response |
||
118 | * |
||
119 | * @return array |
||
120 | */ |
||
121 | protected function getBookMarks($response) |
||
127 | |||
128 | protected function checkEndBookMarks() |
||
132 | } |
||
133 |