1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\Json; |
4
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Middleware\Annotation\ThirdLast; |
6
|
|
|
use ApiClients\Foundation\Middleware\ErrorTrait; |
7
|
|
|
use ApiClients\Foundation\Middleware\MiddlewareInterface; |
8
|
|
|
use ApiClients\Foundation\Middleware\PreTrait; |
9
|
|
|
use ApiClients\Tools\Json\JsonDecodeService; |
10
|
|
|
use GuzzleHttp\Psr7\BufferStream; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use React\Promise\CancellablePromiseInterface; |
13
|
|
|
use React\Stream\ReadableStreamInterface; |
14
|
|
|
use function React\Promise\resolve; |
15
|
|
|
|
16
|
|
|
class JsonDecodeMiddleware implements MiddlewareInterface |
17
|
|
|
{ |
18
|
|
|
use PreTrait; |
19
|
|
|
use ErrorTrait; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var JsonDecodeService |
23
|
|
|
*/ |
24
|
|
|
private $jsonDecodeService; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* JsonDecode constructor. |
28
|
|
|
* @param JsonDecodeService $jsonDecodeService |
29
|
|
|
*/ |
30
|
6 |
|
public function __construct(JsonDecodeService $jsonDecodeService) |
31
|
|
|
{ |
32
|
6 |
|
$this->jsonDecodeService = $jsonDecodeService; |
33
|
6 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param ResponseInterface $response |
37
|
|
|
* @param array $options |
38
|
|
|
* @return CancellablePromiseInterface |
39
|
|
|
* |
40
|
|
|
* @ThirdLast() |
41
|
|
|
*/ |
42
|
6 |
|
public function post( |
43
|
|
|
ResponseInterface $response, |
44
|
|
|
string $transactionId, |
45
|
|
|
array $options = [] |
46
|
|
|
): CancellablePromiseInterface { |
47
|
6 |
|
if ($response->getBody() instanceof ReadableStreamInterface) { |
48
|
1 |
|
return resolve($response); |
49
|
|
|
} |
50
|
|
|
|
51
|
5 |
|
if (!isset($options[self::class]) && |
52
|
5 |
|
$response->getHeaderLine('Content-Type') !== 'application/json') { |
53
|
2 |
|
return resolve($response); |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
if (isset($options[self::class][Options::CONTENT_TYPE]) && |
57
|
3 |
|
$response->getHeaderLine('Content-Type') !== $options[self::class][Options::CONTENT_TYPE]) { |
58
|
|
|
return resolve($response); |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
$body = (string)$response->getBody(); |
62
|
3 |
|
if ($body === '') { |
63
|
|
|
$stream = new BufferStream(0); |
64
|
|
|
$stream->write($body); |
65
|
|
|
return resolve($response->withBody($stream)); |
66
|
|
|
} |
67
|
|
|
|
68
|
3 |
|
return $this->jsonDecodeService->decode($body)->then(function ($json) use ($response) { |
69
|
3 |
|
$body = new JsonStream($json); |
70
|
3 |
|
return resolve($response->withBody($body)); |
71
|
3 |
|
}); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|