-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubClient.php
More file actions
220 lines (184 loc) · 6.22 KB
/
Copy pathGitHubClient.php
File metadata and controls
220 lines (184 loc) · 6.22 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<?php
declare(strict_types=1);
namespace Light\App\Service;
use CurlHandle;
use Fig\Http\Message\StatusCodeInterface;
use RuntimeException;
use function curl_error;
use function curl_exec;
use function curl_getinfo;
use function curl_init;
use function curl_setopt_array;
use function explode;
use function is_array;
use function json_decode;
use function preg_match;
use function sprintf;
use function str_starts_with;
use function strlen;
use function strtolower;
use function trim;
use const CURLINFO_RESPONSE_CODE;
use const CURLOPT_CONNECTTIMEOUT;
use const CURLOPT_FOLLOWLOCATION;
use const CURLOPT_HEADERFUNCTION;
use const CURLOPT_HTTPHEADER;
use const CURLOPT_MAXREDIRS;
use const CURLOPT_RETURNTRANSFER;
use const CURLOPT_TIMEOUT;
use const CURLOPT_URL;
use const CURLOPT_USERAGENT;
/**
* Minimal cURL-backed GitHub API client.
*
* Deliberately not a general purpose HTTP client: it covers the authenticated GET requests the
* package generator needs and nothing more. Requests degrade to unauthenticated when no token is
* configured, which keeps the generator usable on a machine without credentials.
*
* @phpstan-type ResponseData array{status: int, body: string, links: array<string, non-empty-string>}
*/
class GitHubClient implements GitHubClientInterface
{
private const string API_ROOT = 'https://api.github.com';
private const string API_VERSION = '2022-11-28';
private const string DEFAULT_USER_AGENT = 'dotkernel.com';
/**
* cURL rejects an empty user agent, and GitHub rejects requests without one, so an empty
* configured value falls back to the default rather than failing every request.
*
* @var non-empty-string
*/
private readonly string $userAgent;
public function __construct(
private readonly string $token,
string $userAgent,
private readonly int $timeout,
private readonly int $connectTimeout,
) {
$this->userAgent = $userAgent === '' ? self::DEFAULT_USER_AGENT : $userAgent;
}
/**
* @param non-empty-string $path
*/
public function get(string $path, string $accept = self::ACCEPT_JSON): ?string
{
$response = $this->request($this->absoluteUrl($path), $accept);
if ($response['status'] === StatusCodeInterface::STATUS_NOT_FOUND) {
return null;
}
$this->assertOk($response['status'], $path);
return $response['body'];
}
/**
* @param non-empty-string $path
* @return list<array<string, mixed>>
*/
public function getAllPages(string $path): array
{
$url = $this->absoluteUrl($path);
$items = [];
while ($url !== null) {
$response = $this->request($url, self::ACCEPT_JSON);
$this->assertOk($response['status'], $url);
$decoded = json_decode($response['body'], true);
if (! is_array($decoded)) {
throw new RuntimeException(sprintf('Expected a JSON array from %s.', $url));
}
foreach ($decoded as $item) {
if (is_array($item)) {
$items[] = $item;
}
}
$url = $response['links']['next'] ?? null;
}
return $items;
}
/**
* @param non-empty-string $url
* @return ResponseData
*/
private function request(string $url, string $accept): array
{
$handle = curl_init();
if (! $handle instanceof CurlHandle) {
throw new RuntimeException('Unable to initialise a cURL handle.');
}
$links = [];
curl_setopt_array($handle, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_USERAGENT => $this->userAgent,
CURLOPT_HTTPHEADER => $this->headers($accept),
CURLOPT_HEADERFUNCTION => function (CurlHandle $curlHandle, string $header) use (&$links): int {
$parts = explode(':', $header, 2);
if (isset($parts[1]) && strtolower(trim($parts[0])) === 'link') {
$links = $this->parseLinkHeader(trim($parts[1]));
}
return strlen($header);
},
]);
$body = curl_exec($handle);
$error = curl_error($handle);
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
if ($body === false) {
throw new RuntimeException(sprintf('Request to %s failed: %s', $url, $error));
}
return [
'status' => (int) $status,
'body' => (string) $body,
'links' => $links,
];
}
/**
* Parses `<https://...>; rel="next", <https://...>; rel="last"` into a rel => url map.
*
* @return array<string, non-empty-string>
*/
private function parseLinkHeader(string $value): array
{
$links = [];
foreach (explode(',', $value) as $part) {
if (preg_match('/<([^>]+)>\s*;\s*rel="([^"]+)"/', trim($part), $matches) !== 1) {
continue;
}
$links[$matches[2]] = $matches[1];
}
return $links;
}
/**
* @return list<string>
*/
private function headers(string $accept): array
{
$headers = [
'Accept: ' . $accept,
'X-GitHub-Api-Version: ' . self::API_VERSION,
];
if ($this->token !== '') {
$headers[] = 'Authorization: Bearer ' . $this->token;
}
return $headers;
}
/**
* @param non-empty-string $path
* @return non-empty-string
*/
private function absoluteUrl(string $path): string
{
if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
return $path;
}
return self::API_ROOT . $path;
}
private function assertOk(int $status, string $url): void
{
if ($status === StatusCodeInterface::STATUS_OK) {
return;
}
throw new RuntimeException(sprintf('GitHub returned HTTP %d for %s.', $status, $url));
}
}