Repository navigation
Expand file tree
/
Copy pathHttpMessageBuilder.php
More file actions
80 lines (65 loc) · 2.43 KB
/
Copy pathHttpMessageBuilder.php
File metadata and controls
80 lines (65 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\RpcMultiplex;
use Hyperf\Codec\Json;
use Hyperf\Context\Context;
use Hyperf\Context\ResponseContext;
use Hyperf\Contract\PackerInterface;
use Hyperf\HttpMessage\Server\Request;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpMessage\Uri\Uri;
use Hyperf\Rpc\Context as RpcContext;
use Hyperf\RpcMultiplex\Contract\HostReaderInterface;
use Hyperf\RpcMultiplex\Contract\HttpMessageBuilderInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
use Swow\Psr7\Message\ResponsePlusInterface;
use Swow\Psr7\Message\ServerRequestPlusInterface;
class HttpMessageBuilder implements HttpMessageBuilderInterface
{
public function __construct(protected PackerInterface $packer, protected RpcContext $context, protected HostReaderInterface $hostReader)
{
}
public function buildRequest(array $data, array $config = []): ServerRequestPlusInterface
{
$extra = $data[Constant::EXTRA] ?? [];
$uri = $this->buildUri(
$data[Constant::PATH] ?? '/',
$data[Constant::HOST] ?? $this->hostReader->read(),
$data[Constant::PORT] ?? $config['port'] ?? 80
);
$parsedData = $data[Constant::DATA] ?? [];
$this->context->setData($data[Constant::CONTEXT] ?? []);
$request = new Request('POST', $uri, ['Content-Type' => 'application/json', ...$extra], new SwooleStream(Json::encode($parsedData)));
return $request->setParsedBody($parsedData);
}
public function buildResponse(ServerRequestInterface $request, array $data): ResponsePlusInterface
{
$packed = $this->packer->pack($data);
return $this->response()->setBody(new SwooleStream($packed));
}
public function persistToContext(ResponsePlusInterface $response): ResponsePlusInterface
{
return ResponseContext::set($response);
}
protected function buildUri($path, $host, $port, $scheme = 'http'): UriInterface
{
$uri = "{$scheme}://{$host}:{$port}/" . ltrim($path, '/');
return new Uri($uri);
}
/**
* Get response instance from context.
*/
protected function response(): ResponsePlusInterface
{
return ResponseContext::get();
}
}