-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathAbstractClient.php
102 lines (76 loc) · 2.06 KB
/
AbstractClient.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
<?php
declare(strict_types=1);
namespace Milo\Github\Http;
use Milo\Github;
/**
* Ancestor for HTTP clients. Cares about redirecting and debug events.
*
* @author Miloslav Hůla (https://github.com/milo)
*/
abstract class AbstractClient implements IClient
{
use Github\Strict;
/** @var int[] will follow Location header on these response codes */
public array $redirectCodes = [
Response::S301_MOVED_PERMANENTLY,
Response::S302_FOUND,
Response::S307_TEMPORARY_REDIRECT,
];
/** Maximum redirects per request */
public int $maxRedirects = 5;
/** @var callable|null */
private $onRequest;
/** @var callable|null */
private $onResponse;
/**
* @see https://developer.github.com/v3/#http-redirects
*
* @throws BadResponseException
*/
public function request(Request $request): Response
{
$request = clone $request;
$counter = $this->maxRedirects;
$previous = null;
do {
$this->setupRequest($request);
$this->onRequest && call_user_func($this->onRequest, $request);
$response = $this->process($request);
$this->onResponse && call_user_func($this->onResponse, $response);
$previous = $response->setPrevious($previous);
if ($counter > 0 && in_array($response->getCode(), $this->redirectCodes) && $response->hasHeader('Location')) {
/** @todo Use the same HTTP $method for redirection? Set $content to NULL? */
$request = new Request(
$request->getMethod(),
$response->getHeader('Location'),
$request->getHeaders(),
$request->getContent()
);
$counter--;
continue;
}
break;
} while (true);
return $response;
}
/** @inheritdoc */
public function onRequest(?callable $callback): static
{
$this->onRequest = $callback;
return $this;
}
/** @inheritdoc */
public function onResponse(?callable $callback): static
{
$this->onResponse = $callback;
return $this;
}
protected function setupRequest(Request $request): void
{
$request->addHeader('Expect', '');
}
/**
* @throws BadResponseException
*/
abstract protected function process(Request $request): Response;
}