-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathApi.php
337 lines (278 loc) · 7.7 KB
/
Api.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php
namespace Milo\Github;
/**
* Github API client library. Read readme.md in repository {@link http://github.com/milo/github-api}
*
* @see https://developer.github.com/v3/
*
* @author Miloslav Hůla (https://github.com/milo)
*/
class Api extends Sanity
{
/** @var string */
private $url = 'https://api.github.com';
/** @var string */
private $defaultAccept = 'application/vnd.github.v3+json';
/** @var array|NULL */
private $defaultParameters = [];
/** @var Http\IClient */
private $client;
/** @var OAuth\Token|NULL */
private $token;
public function __construct(Http\IClient $client = NULL)
{
$this->client = $client ?: Helpers::createDefaultClient();
}
/**
* @return self
*/
public function setToken(OAuth\Token $token = NULL)
{
$this->token = $token;
return $this;
}
/**
* @return OAuth\Token|NULL
*/
public function getToken()
{
return $this->token;
}
/**
* @param array
* @return self
*/
public function setDefaultParameters(array $defaults = NULL)
{
$this->defaultParameters = $defaults ?: [];
return $this;
}
/**
* @return array
*/
public function getDefaultParameters()
{
return $this->defaultParameters;
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @return Http\Response
*
* @throws MissingParameterException
*/
public function delete($urlPath, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::DELETE, $urlPath, $parameters, $headers)
);
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @return Http\Response
*
* @throws MissingParameterException
*/
public function get($urlPath, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::GET, $urlPath, $parameters, $headers)
);
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @return Http\Response
*
* @throws MissingParameterException
*/
public function head($urlPath, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::HEAD, $urlPath, $parameters, $headers)
);
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @param mixed
* @return Http\Response
*
* @throws MissingParameterException
* @throws JsonException
*/
public function patch($urlPath, $content, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::PATCH, $urlPath, $parameters, $headers, $content)
);
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @param mixed
* @return Http\Response
*
* @throws MissingParameterException
* @throws JsonException
*/
public function post($urlPath, $content, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::POST, $urlPath, $parameters, $headers, $content)
);
}
/**
* @see createRequest()
* @see request()
*
* @param string
* @param mixed
* @return Http\Response
*
* @throws MissingParameterException
* @throws JsonException
*/
public function put($urlPath, $content = NULL, array $parameters = [], array $headers = [])
{
return $this->request(
$this->createRequest(Http\Request::PUT, $urlPath, $parameters, $headers, $content)
);
}
/**
* @return Http\Response
*
* @throws Http\BadResponseException
*/
public function request(Http\Request $request)
{
$request = clone $request;
$request->addHeader('Accept', $this->defaultAccept);
$request->addHeader('Time-Zone', date_default_timezone_get());
$request->addHeader('User-Agent', 'milo/github-api');
if ($this->token) {
/** @todo Distinguish token type? */
$request->addHeader('Authorization', "token {$this->token->getValue()}");
}
return $this->client->request($request);
}
/**
* @param string Http\Request::GET|POST|...
* @param string path like '/users/:user/repos' where ':user' is substitution
* @param array[name => value] replaces substitutions in $urlPath, the rest is appended as query string to URL
* @param array[name => value] name is case-insensitive
* @param mixed|NULL arrays and objects are encoded to JSON and Content-Type is set
* @return Http\Request
*
* @throws MissingParameterException when substitution is used in URL but parameter is missing
* @throws JsonException when encoding to JSON fails
*/
public function createRequest($method, $urlPath, array $parameters = [], array $headers = [], $content = NULL)
{
$parameters += $this->defaultParameters;
$this->substituteUrlParameters($urlPath, $parameters);
$url = rtrim($this->url, '/') . '/' . trim($urlPath, '/');
if (count($parameters)) {
$url .= '?' . http_build_query($parameters);
}
if ($content !== NULL && (is_array($content) || is_object($content))) {
$headers['Content-Type'] = 'application/json; charset=utf-8';
$content = Helpers::jsonEncode($content);
}
return new Http\Request($method, $url, $headers, $content);
}
/**
* @param Http\Response
* @param array|NULL these codes are treated as success; code < 300 if NULL
* @return mixed
*
* @throws ApiException
*/
public function decode(Http\Response $response, array $okCodes = NULL)
{
$content = $response->getContent();
if (preg_match('~application/json~i', $response->getHeader('Content-Type', ''))) {
try {
$content = Helpers::jsonDecode($response->getContent());
} catch (JsonException $e) {
throw new InvalidResponseException('JSON decoding failed.', 0, $e, $response);
}
if (!is_array($content) && !is_object($content)) {
throw new InvalidResponseException('Decoded JSON is not an array or object.', 0, NULL, $response);
}
}
$code = $response->getCode();
if (($okCodes === NULL && $code >= 300) || (is_array($okCodes) && !in_array($code, $okCodes))) {
/** @var $content \stdClass */
switch ($code) {
case Http\Response::S400_BAD_REQUEST:
throw new BadRequestException($content->message, $code, NULL, $response);
case Http\Response::S401_UNAUTHORIZED:
throw new UnauthorizedException($content->message, $code, NULL, $response);
case Http\Response::S403_FORBIDDEN:
throw new ForbiddenException($content->message, $code, NULL, $response);
case Http\Response::S404_NOT_FOUND:
throw new NotFoundException('Resource not found or not authorized to access.', $code, NULL, $response);
case Http\Response::S422_UNPROCESSABLE_ENTITY:
$message = $content->message . implode(', ', array_map(function($error) {
return '[' . implode(':', (array) $error) . ']';
}, $content->errors));
throw new UnprocessableEntityException($message, $code, NULL, $response);
}
$message = $okCodes === NULL ? '< 300' : implode(' or ', $okCodes);
throw new UnexpectedResponseException("Expected response with code $message.", $code, NULL, $response);
}
return $content;
}
/**
* @return Http\IClient
*/
public function getClient()
{
return $this->client;
}
/**
* @param string
* @return self
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string
* @param array
*
* @throws MissingParameterException
*/
protected function substituteUrlParameters(& $url, array & $parameters)
{
$url = preg_replace_callback('#(^|/):([^/]+)#', function($m) use ($url, & $parameters) {
if (!isset($parameters[$m[2]])) {
throw new MissingParameterException("Missing parameter '$m[2]' for URL path '$url'.");
}
$parameter = $parameters[$m[2]];
unset($parameters[$m[2]]);
return $m[1] . $parameter;
}, $url);
}
}