|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\HeaderCollector; |
|
4
|
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Middleware\ErrorTrait; |
|
6
|
|
|
use ApiClients\Foundation\Middleware\MiddlewareInterface; |
|
7
|
|
|
use ApiClients\Foundation\Middleware\PreTrait; |
|
8
|
|
|
use ApiClients\Foundation\Middleware\Priority; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
use React\Promise\CancellablePromiseInterface; |
|
11
|
|
|
use function React\Promise\resolve; |
|
12
|
|
|
|
|
13
|
|
|
final class HeaderCollectorMiddleware implements MiddlewareInterface |
|
14
|
|
|
{ |
|
15
|
|
|
use ErrorTrait; |
|
16
|
|
|
use PreTrait; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var Headers |
|
20
|
|
|
*/ |
|
21
|
|
|
private $headers; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param Headers $headers |
|
25
|
|
|
*/ |
|
26
|
1 |
|
public function __construct(Headers $headers) |
|
27
|
|
|
{ |
|
28
|
1 |
|
$this->headers = $headers; |
|
29
|
1 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param ResponseInterface $response |
|
33
|
|
|
* @param array $options |
|
34
|
|
|
* @return CancellablePromiseInterface |
|
35
|
|
|
*/ |
|
36
|
1 |
|
public function post(ResponseInterface $response, array $options = []): CancellablePromiseInterface |
|
37
|
|
|
{ |
|
38
|
1 |
|
if (isset($options[self::class]) && |
|
39
|
1 |
|
isset($options[self::class][Options::HEADERS]) && |
|
40
|
1 |
|
is_array($options[self::class][Options::HEADERS]) |
|
41
|
|
|
) { |
|
42
|
1 |
|
$this->extractHeaders($response, $options[self::class][Options::HEADERS]); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
1 |
|
return resolve($response); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @return int |
|
50
|
|
|
*/ |
|
51
|
|
|
public function priority(): int |
|
52
|
|
|
{ |
|
53
|
|
|
return Priority::LAST; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param ResponseInterface $response |
|
58
|
|
|
* @param array $headers |
|
59
|
|
|
*/ |
|
60
|
1 |
|
private function extractHeaders(ResponseInterface $response, array $headers) |
|
61
|
|
|
{ |
|
62
|
1 |
|
$set = []; |
|
63
|
|
|
|
|
64
|
1 |
|
foreach ($headers as $header) { |
|
65
|
1 |
|
if (!$response->hasHeader($header)) { |
|
66
|
|
|
continue; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
1 |
|
$set[$header] = $response->getHeaderLine($header); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
1 |
|
if (count($set) === 0) { |
|
73
|
|
|
return; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
$this->headers->onNext($set); |
|
77
|
1 |
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|