1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ApiClients\Middleware\Json; |
4
|
|
|
|
5
|
|
|
use ApiClients\Foundation\Middleware\Annotation\Third; |
6
|
|
|
use ApiClients\Foundation\Middleware\ErrorTrait; |
7
|
|
|
use ApiClients\Foundation\Middleware\MiddlewareInterface; |
8
|
|
|
use ApiClients\Foundation\Middleware\PostTrait; |
9
|
|
|
use ApiClients\Foundation\Transport\ParsedContentsInterface; |
10
|
|
|
use ApiClients\Tools\Json\JsonEncodeService; |
11
|
|
|
use Psr\Http\Message\RequestInterface; |
12
|
|
|
use React\Promise\CancellablePromiseInterface; |
13
|
|
|
use function React\Promise\resolve; |
14
|
|
|
use RingCentral\Psr7\BufferStream; |
15
|
|
|
|
16
|
|
|
class JsonEncodeMiddleware implements MiddlewareInterface |
17
|
|
|
{ |
18
|
|
|
use PostTrait; |
19
|
|
|
use ErrorTrait; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var JsonEncodeService |
23
|
|
|
*/ |
24
|
|
|
private $jsonEncodeService; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param JsonEncodeService $jsonEncodeService |
28
|
|
|
*/ |
29
|
2 |
|
public function __construct(JsonEncodeService $jsonEncodeService) |
30
|
|
|
{ |
31
|
2 |
|
$this->jsonEncodeService = $jsonEncodeService; |
32
|
2 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param RequestInterface $request |
36
|
|
|
* @param array $options |
37
|
|
|
* @return CancellablePromiseInterface |
38
|
|
|
* |
39
|
|
|
* @Third() |
40
|
|
|
*/ |
41
|
2 |
|
public function pre( |
42
|
|
|
RequestInterface $request, |
43
|
|
|
string $transactionId, |
44
|
|
|
array $options = [] |
45
|
|
|
): CancellablePromiseInterface { |
46
|
2 |
|
$body = $request->getBody(); |
47
|
2 |
|
if (!($body instanceof ParsedContentsInterface)) { |
48
|
1 |
|
return resolve($request); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $this->jsonEncodeService->encode($body->getParsedContents())->then(function ($json) use ($request) { |
52
|
1 |
|
$body = new BufferStream(\strlen($json)); |
53
|
1 |
|
$body->write($json); |
54
|
|
|
|
55
|
1 |
|
return resolve($request->withBody($body)->withAddedHeader('Content-Type', 'application/json')); |
56
|
1 |
|
}); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|