Repository navigation
Expand file tree
/
Copy pathDataFormatter.php
More file actions
93 lines (81 loc) · 2.72 KB
/
Copy pathDataFormatter.php
File metadata and controls
93 lines (81 loc) · 2.72 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
81
82
83
84
85
86
87
88
89
90
91
92
93
<?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\Rpc\Context;
use Hyperf\Rpc\Contract\DataFormatterInterface;
use Hyperf\Rpc\ErrorResponse;
use Hyperf\Rpc\Request;
use Hyperf\Rpc\Response;
use Hyperf\RpcClient\Exception\RequestException;
use Hyperf\RpcMultiplex\Contract\DataFetcherInterface;
use Throwable;
class DataFormatter implements DataFormatterInterface, DataFetcherInterface
{
protected Context $context;
public function __construct(Context $context)
{
$this->context = $context;
}
public function formatRequest(Request $request): array
{
return [
Constant::ID => $request->getId(),
Constant::PATH => $request->getPath(),
Constant::DATA => $request->getParams(),
Constant::EXTRA => $request->getExtra(),
Constant::CONTEXT => $this->context->getData(),
];
}
public function formatResponse(Response $response): array
{
return [
Constant::ID => $response->getId(),
Constant::RESULT => $response->getResult(),
Constant::CONTEXT => $this->context->getData(),
];
}
public function formatErrorResponse(ErrorResponse $response): array
{
$exception = $response->getException();
if ($exception instanceof Throwable) {
$exception = [
'class' => get_class($exception),
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
];
}
return [
Constant::ID => $response->getId(),
Constant::ERROR => [
Constant::CODE => $response->getCode(),
Constant::MESSAGE => $response->getMessage(),
Constant::DATA => $exception,
],
Constant::CONTEXT => $this->context->getData(),
];
}
public function fetch(array $data): mixed
{
if (array_key_exists(Constant::RESULT, $data)) {
$this->context->setData($data[Constant::CONTEXT] ?? []);
return $data[Constant::RESULT];
}
if (array_key_exists(Constant::ERROR, $data)) {
throw new RequestException(
$data[Constant::ERROR][Constant::MESSAGE] ?? 'Invalid error message',
$data[Constant::ERROR][Constant::CODE] ?? 0,
$data[Constant::ERROR][Constant::DATA],
);
}
throw new RequestException('Unknown data ' . Json::encode($data), 0);
}
}