|
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 function React\Promise\resolve; |
|
14
|
|
|
use React\Stream\ReadableStreamInterface; |
|
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
|
7 |
|
public function __construct(JsonDecodeService $jsonDecodeService) |
|
31
|
|
|
{ |
|
32
|
7 |
|
$this->jsonDecodeService = $jsonDecodeService; |
|
33
|
7 |
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param ResponseInterface $response |
|
37
|
|
|
* @param array $options |
|
38
|
|
|
* @return CancellablePromiseInterface |
|
39
|
|
|
* |
|
40
|
|
|
* @ThirdLast() |
|
41
|
|
|
*/ |
|
42
|
7 |
|
public function post( |
|
43
|
|
|
ResponseInterface $response, |
|
44
|
|
|
string $transactionId, |
|
45
|
|
|
array $options = [] |
|
46
|
|
|
): CancellablePromiseInterface { |
|
47
|
7 |
|
if ($response->getBody() instanceof ReadableStreamInterface) { |
|
48
|
1 |
|
return resolve($response); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
6 |
|
if (!isset($options[self::class]) && |
|
52
|
6 |
|
\strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) { |
|
53
|
2 |
|
return resolve($response); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
4 |
|
if (isset($options[self::class][Options::CONTENT_TYPE]) && |
|
57
|
4 |
|
$response->getHeaderLine('Content-Type') !== $options[self::class][Options::CONTENT_TYPE]) { |
|
58
|
|
|
return resolve($response); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
4 |
|
$body = (string)$response->getBody(); |
|
62
|
4 |
|
if ($body === '') { |
|
63
|
|
|
$stream = new BufferStream(0); |
|
64
|
|
|
$stream->write($body); |
|
65
|
|
|
|
|
66
|
|
|
return resolve($response->withBody($stream)); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $this->jsonDecodeService->decode($body)->then(function ($json) use ($response) { |
|
70
|
4 |
|
$body = new JsonStream($json); |
|
71
|
|
|
|
|
72
|
4 |
|
return resolve($response->withBody($body)); |
|
73
|
4 |
|
}); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|