-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApi.php
323 lines (253 loc) · 9.03 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
<?php
namespace ProgrammatorDev\Api;
use Http\Client\Common\Plugin\AuthenticationPlugin;
use Http\Client\Common\Plugin\CachePlugin;
use Http\Client\Common\Plugin\ContentLengthPlugin;
use Http\Client\Common\Plugin\ContentTypePlugin;
use Http\Client\Common\Plugin\LoggerPlugin;
use Http\Message\Authentication;
use ProgrammatorDev\Api\Builder\CacheBuilder;
use ProgrammatorDev\Api\Builder\ClientBuilder;
use ProgrammatorDev\Api\Builder\Listener\CacheLoggerListener;
use ProgrammatorDev\Api\Builder\LoggerBuilder;
use ProgrammatorDev\Api\Event\PostRequestEvent;
use ProgrammatorDev\Api\Event\PreRequestEvent;
use ProgrammatorDev\Api\Event\ResponseContentsEvent;
use ProgrammatorDev\Api\Exception\ConfigException;
use ProgrammatorDev\Api\Helper\StringHelperTrait;
use Psr\Http\Client\ClientExceptionInterface as ClientException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Api
{
use StringHelperTrait;
private ?string $baseUrl = null;
private array $queryDefaults = [];
private array $headerDefaults = [];
private ClientBuilder $clientBuilder;
private ?CacheBuilder $cacheBuilder = null;
private ?LoggerBuilder $loggerBuilder = null;
private ?Authentication $authentication = null;
private EventDispatcher $eventDispatcher;
protected OptionsResolver $optionsResolver;
public function __construct()
{
$this->clientBuilder ??= new ClientBuilder();
$this->eventDispatcher = new EventDispatcher();
$this->optionsResolver = new OptionsResolver();
}
/**
* @throws ConfigException If a base URL has not been set.
* @throws ClientException
*/
public function request(
string $method,
string $path,
array $query = [],
array $headers = [],
string|StreamInterface $body = null
): mixed
{
if (!$this->baseUrl) {
throw new ConfigException('A base URL must be set.');
}
$this->configurePlugins();
if (!empty($this->queryDefaults)) {
$query = \array_merge($this->queryDefaults, $query);
}
if (!empty($this->headerDefaults)) {
$headers = \array_merge($this->headerDefaults, $headers);
}
$uri = $this->buildUri($path, $query);
$request = $this->createRequest($method, $uri, $headers, $body);
// pre request listener
$request = $this->eventDispatcher->dispatch(new PreRequestEvent($request))->getRequest();
// request
$response = $this->clientBuilder->getClient()->sendRequest($request);
// post request listener
$response = $this->eventDispatcher->dispatch(new PostRequestEvent($request, $response))->getResponse();
// always rewind the body contents in case it was used in the PostRequestEvent
// otherwise it would return an empty string
$response->getBody()->rewind();
$contents = $response->getBody()->getContents();
// response contents listener
return $this->eventDispatcher->dispatch(new ResponseContentsEvent($contents))->getContents();
}
private function configurePlugins(): void
{
// https://docs.php-http.org/en/latest/plugins/content-type.html
$this->clientBuilder->addPlugin(
plugin: new ContentTypePlugin(),
priority: 40
);
// https://docs.php-http.org/en/latest/plugins/content-length.html
$this->clientBuilder->addPlugin(
plugin: new ContentLengthPlugin(),
priority: 32
);
// https://docs.php-http.org/en/latest/message/authentication.html
if ($this->authentication) {
$this->clientBuilder->addPlugin(
plugin: new AuthenticationPlugin($this->authentication),
priority: 24
);
}
// https://docs.php-http.org/en/latest/plugins/cache.html
if ($this->cacheBuilder) {
$cacheOptions = [
'default_ttl' => $this->cacheBuilder->getTtl(),
'methods' => $this->cacheBuilder->getMethods(),
'respect_response_cache_directives' => $this->cacheBuilder->getResponseCacheDirectives(),
'cache_listeners' => []
];
if ($this->loggerBuilder) {
$cacheOptions['cache_listeners'][] = new CacheLoggerListener($this->loggerBuilder);
}
$this->clientBuilder->addPlugin(
plugin: new CachePlugin(
$this->cacheBuilder->getPool(),
$this->clientBuilder->getStreamFactory(),
$cacheOptions
),
priority: 16
);
}
// https://docs.php-http.org/en/latest/plugins/logger.html
if ($this->loggerBuilder) {
$this->clientBuilder->addPlugin(
plugin: new LoggerPlugin(
$this->loggerBuilder->getLogger(),
$this->loggerBuilder->getFormatter()
),
priority: 8
);
}
}
public function getBaseUrl(): ?string
{
return $this->baseUrl;
}
public function setBaseUrl(string $baseUrl): self
{
$this->baseUrl = $baseUrl;
return $this;
}
public function getQueryDefault(string $name): mixed
{
return $this->queryDefaults[$name] ?? null;
}
public function addQueryDefault(string $name, mixed $value): self
{
$this->queryDefaults[$name] = $value;
return $this;
}
public function removeQueryDefault(string $name): self
{
unset($this->queryDefaults[$name]);
return $this;
}
public function getHeaderDefault(string $name): mixed
{
return $this->headerDefaults[$name] ?? null;
}
public function addHeaderDefault(string $name, mixed $value): self
{
$this->headerDefaults[$name] = $value;
return $this;
}
public function removeHeaderDefault(string $name): self
{
unset($this->headerDefaults[$name]);
return $this;
}
public function getClientBuilder(): ?ClientBuilder
{
return $this->clientBuilder;
}
public function setClientBuilder(ClientBuilder $clientBuilder): self
{
$this->clientBuilder = $clientBuilder;
return $this;
}
public function getCacheBuilder(): ?CacheBuilder
{
return $this->cacheBuilder;
}
public function setCacheBuilder(?CacheBuilder $cacheBuilder): self
{
$this->cacheBuilder = $cacheBuilder;
return $this;
}
public function getLoggerBuilder(): ?LoggerBuilder
{
return $this->loggerBuilder;
}
public function setLoggerBuilder(?LoggerBuilder $loggerBuilder): self
{
$this->loggerBuilder = $loggerBuilder;
return $this;
}
public function getAuthentication(): ?Authentication
{
return $this->authentication;
}
public function setAuthentication(?Authentication $authentication): self
{
$this->authentication = $authentication;
return $this;
}
public function addPreRequestListener(callable $listener, int $priority = 0): self
{
$this->eventDispatcher->addListener(PreRequestEvent::class, $listener, $priority);
return $this;
}
public function addPostRequestListener(callable $listener, int $priority = 0): self
{
$this->eventDispatcher->addListener(PostRequestEvent::class, $listener, $priority);
return $this;
}
public function addResponseContentsListener(callable $listener, int $priority = 0): self
{
$this->eventDispatcher->addListener(ResponseContentsEvent::class, $listener, $priority);
return $this;
}
public function buildPath(string $path, array $parameters): string
{
foreach ($parameters as $parameter => $value) {
$path = \str_replace(
\sprintf('{%s}', $parameter),
$value,
$path
);
}
return $path;
}
private function buildUri(string $path, array $query = []): string
{
$uri = $this->reduceDuplicateSlashes($this->baseUrl . $path);
if (!empty($query)) {
$uri = \sprintf('%s?%s', $uri, \http_build_query($query));
}
return $uri;
}
private function createRequest(
string $method,
string $uri,
array $headers = [],
string|StreamInterface $body = null
): RequestInterface
{
$request = $this->clientBuilder->getRequestFactory()->createRequest($method, $uri);
foreach ($headers as $key => $value) {
$request = $request->withHeader($key, $value);
}
if ($body !== null && $body !== '') {
$request = $request->withBody(
\is_string($body) ? $this->clientBuilder->getStreamFactory()->createStream($body) : $body
);
}
return $request;
}
}