|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Common\Http; |
|
6
|
|
|
|
|
7
|
|
|
use GuzzleHttp; |
|
8
|
|
|
use Psr\Container\ContainerInterface; |
|
9
|
|
|
use Shlinkio\Shlink\Common\Http\Exception\InvalidHttpMiddlewareException; |
|
10
|
|
|
|
|
11
|
|
|
use function is_callable; |
|
12
|
|
|
use function is_string; |
|
13
|
|
|
|
|
14
|
|
|
class HttpClientFactory |
|
15
|
|
|
{ |
|
16
|
17 |
|
public function __invoke(ContainerInterface $container): GuzzleHttp\Client |
|
17
|
|
|
{ |
|
18
|
17 |
|
$handler = GuzzleHttp\HandlerStack::create(); |
|
19
|
17 |
|
[$requestMiddlewares, $responseMiddlewares] = $this->getRegisteredMiddlewares($container); |
|
20
|
|
|
|
|
21
|
17 |
|
foreach ($requestMiddlewares as $middleware) { |
|
22
|
8 |
|
$middlewareInstance = $this->resolveMiddleware($middleware, $container); |
|
23
|
4 |
|
$handler->push(GuzzleHttp\Middleware::mapRequest($middlewareInstance)); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
13 |
|
foreach ($responseMiddlewares as $middleware) { |
|
27
|
8 |
|
$middlewareInstance = $this->resolveMiddleware($middleware, $container); |
|
28
|
4 |
|
$handler->push(GuzzleHttp\Middleware::mapResponse($middlewareInstance)); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
9 |
|
return new GuzzleHttp\Client(['handler' => $handler]); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
17 |
|
private function getRegisteredMiddlewares(ContainerInterface $container): array |
|
35
|
|
|
{ |
|
36
|
17 |
|
$config = $container->get('config')['http_client'] ?? []; |
|
37
|
|
|
return [ |
|
38
|
17 |
|
$config['request_middlewares'] ?? [], |
|
39
|
17 |
|
$config['response_middlewares'] ?? [], |
|
40
|
|
|
]; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param mixed $middleware |
|
45
|
|
|
*/ |
|
46
|
13 |
|
private function resolveMiddleware($middleware, ContainerInterface $container): callable |
|
47
|
|
|
{ |
|
48
|
13 |
|
$middlewareInstance = is_string($middleware) ? $container->get($middleware) : $middleware; |
|
49
|
13 |
|
if (! is_callable($middlewareInstance)) { |
|
50
|
8 |
|
throw InvalidHttpMiddlewareException::fromMiddleware($middlewareInstance); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
5 |
|
return $middlewareInstance; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|