1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\Json; |
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 ApiClients\Tools\Json\JsonDecodeService; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use React\Promise\CancellablePromiseInterface; |
12
|
|
|
use React\Stream\ReadableStreamInterface; |
13
|
|
|
use function React\Promise\resolve; |
14
|
|
|
|
15
|
|
|
class JsonDecodeMiddleware implements MiddlewareInterface |
16
|
|
|
{ |
17
|
|
|
use PreTrait; |
18
|
|
|
use ErrorTrait; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var JsonDecodeService |
22
|
|
|
*/ |
23
|
|
|
private $jsonDecodeService; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* JsonDecode constructor. |
27
|
|
|
* @param JsonDecodeService $jsonDecodeService |
28
|
|
|
*/ |
29
|
3 |
|
public function __construct(JsonDecodeService $jsonDecodeService) |
30
|
|
|
{ |
31
|
3 |
|
$this->jsonDecodeService = $jsonDecodeService; |
32
|
3 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @return int |
36
|
|
|
*/ |
37
|
1 |
|
public function priority(): int |
38
|
|
|
{ |
39
|
1 |
|
return Priority::FIRST; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param ResponseInterface $response |
44
|
|
|
* @param array $options |
45
|
|
|
* @return CancellablePromiseInterface |
46
|
|
|
*/ |
47
|
2 |
|
public function post(ResponseInterface $response, array $options = []): CancellablePromiseInterface |
48
|
|
|
{ |
49
|
2 |
|
if ($response->getBody() instanceof ReadableStreamInterface) { |
50
|
1 |
|
return resolve($response); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
return $this->jsonDecodeService->decode((string)$response->getBody())->then(function ($json) use ($response) { |
54
|
1 |
|
$body = new JsonStream($json); |
55
|
1 |
|
return resolve($response->withBody($body)); |
56
|
1 |
|
}); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|