generated from gocanto/php-template
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHttpClient.php
196 lines (159 loc) · 5.29 KB
/
HttpClient.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
<?php
declare(strict_types=1);
namespace Gocanto\HttpClient;
use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\TransferStats;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class HttpClient extends Client
{
public const VERSION = '1.1.0';
private LoggerInterface $logger;
private array $config;
public function __construct(array $config = [], ?LoggerInterface $logger = null)
{
$this->logger = $logger ?? new NullLogger();
$config['on_stats'] = $config['on_stats'] ?? $this->addStatsListener();
parent::__construct($config);
}
private function addStatsListener(): callable
{
return fn (TransferStats $stats) => $this->logger->info('Request stats summary.', [
'method' => $stats->getRequest()->getMethod(),
'stats' => $stats->getHandlerStats(),
]);
}
public function retry($times = 5, array $options = []): HttpClient
{
$handler = $options['handler'] ?? $this->getConfig('handler');
$handler->push(Middleware::retry($this->decider($times), $this->delay($options)));
$config = $this->getConfig();
$config['handler'] = $handler;
$new = clone $this;
$new->config = empty($config) ? [] : $config;
return $new;
}
public function onRetry(callable $callback, array $options = []): HttpClient
{
$new = clone $this;
$decider = static function (
$retries,
RequestInterface $request,
ResponseInterface $response = null,
ConnectException $exception = null
) use (
$callback,
$new
) {
$bound = Closure::bind($callback, $new, static::class);
return $bound($retries, $request, $response, $exception);
};
$handler = $options['handler'] ?? $this->getConfig('handler');
$handler->push(Middleware::retry($decider, $this->delay($options)));
$config = $this->getConfig();
$config['handler'] = $handler;
$new->config = empty($config) ? [] : $config;
return $new;
}
private function decider(int $retryTotal): callable
{
return function (
$retries,
RequestInterface $request,
ResponseInterface $response = null,
ConnectException $exception = null
) use (
$retryTotal
) {
if ($retries >= $retryTotal) {
return false;
}
$shouldRetry = false;
// Retry connection exceptions
if ($exception instanceof ConnectException) {
$shouldRetry = true;
}
// Retry on server errors
if ($response && $response->getStatusCode() >= 500) {
$shouldRetry = true;
}
if ($shouldRetry === true) {
$this->warning($request, $retries, $retryTotal, $response, $exception);
}
return $shouldRetry;
};
}
private function warning(
RequestInterface $request,
int $retries,
int $retryTotal,
?ResponseInterface $response,
?ConnectException $exception
): void {
$this->getLogger()->warning(
sprintf(
'Retrying %s %s %s/%s, %s',
$request->getMethod(),
$request->getUri(),
$retries + 1,
$retryTotal,
$response ? 'status code: ' . $response->getStatusCode() :
$exception->getMessage()
),
[
'exception' => $exception,
'request' => $request,
'response' => $response,
]
);
}
private function delay(array $options): callable
{
$customDelay = $options['delay'] ?? null;
return static function ($numberOfRetries) use ($customDelay) {
if ($customDelay !== null) {
return (int)$customDelay;
}
return (2 ** ($numberOfRetries - 1)) * 200;
};
}
public function withHeaders(array $headers): self
{
$middleware = static function (callable $handler) use ($headers) {
return static function (
RequestInterface $request,
array $options
) use (
$handler,
$headers
) {
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
return $handler($request, $options);
};
};
/** @var HandlerStack $handler */
$handler = $this->getConfig('handler');
$handler->push($middleware, 'dynamic_headers');
$config = $this->getConfig();
$config['handler'] = $handler;
$new = clone $this;
$new->config = empty($config) ? [] : $config;
return $new;
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
}