-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathPaginator.php
121 lines (90 loc) · 2.18 KB
/
Paginator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
declare(strict_types=1);
namespace Milo\Github;
/**
* Iterates through the GitHub API responses by Link: header.
*
* @see https://developer.github.com/guides/traversing-with-pagination/
*
* @author Miloslav Hůla (https://github.com/milo)
*/
class Paginator implements \Iterator
{
use Strict;
private Http\Request $firstRequest;
private ?Http\Request $request;
private ?Http\Response $response;
private ?int $limit = null;
private int $counter = 0;
public function __construct(
private Api $api,
Http\Request $request
) {
$this->firstRequest = clone $request;
}
/**
* Limits maximum steps of iteration.
*/
public function limit(?int $limit): static
{
$this->limit = $limit;
return $this;
}
public function rewind(): void
{
$this->request = $this->firstRequest;
$this->response = null;
$this->counter = 0;
}
public function valid(): bool
{
return $this->request !== null && ($this->limit === null || $this->counter < $this->limit);
}
public function current(): Http\Response
{
$this->load();
return $this->response;
}
public function key(): int
{
return static::parsePage($this->request->getUrl());
}
public function next(): void
{
$this->load();
if ($url = static::parseLink((string) $this->response->getHeader('Link'), 'next')) {
$this->request = new Http\Request(
$this->request->getMethod(),
$url,
$this->request->getHeaders(),
$this->request->getContent()
);
} else {
$this->request = null;
}
$this->response = null;
$this->counter++;
}
private function load(): void
{
if ($this->response === null) {
$this->response = $this->api->request($this->request);
}
}
public static function parsePage(string $url): int
{
[, $parametersStr] = explode('?', $url, 2) + ['', ''];
parse_str($parametersStr, $parameters);
return max((int) ($parameters['page'] ?? 1), 1);
}
/**
* @see https://developer.github.com/guides/traversing-with-pagination/#navigating-through-the-pages
*/
public static function parseLink(string $link, string $rel): ?string
{
if (!preg_match('(<([^>]+)>;\s*rel="' . preg_quote($rel) . '")', $link, $match)) {
return null;
}
return $match[1];
}
}