* * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ class JsonRpcResponse { /** * JsonRpc版本。 */ private string $jsonRpcVersion = '2.0'; private mixed $id; private mixed $result; private mixed $error; protected LoggerInterface $logger; public function __construct(LoggerFactory $loggerFactory, $id = null, $result = null, $error = null) { $this->id = $id; $this->result = $result; $this->error = $error; $this->logger = $loggerFactory->get('jsonrpc'); } public function withId($id): static { $this->id = $id; return $this; } public function withResult($result): static { $this->result = $result; $this->logger->info(json_encode(['RPC result' => $result], JSON_UNESCAPED_UNICODE)); return $this; } public function withError($code, $message, $data = null): static { $this->error = [ 'code' => $code, 'message' => $message, 'data' => $data, ]; $this->logger->error(json_encode(['RPC error' => $message], JSON_UNESCAPED_UNICODE)); return $this; } public function toArray(): array { $response = [ 'jsonrpc' => $this->jsonRpcVersion, 'id' => $this->id, ]; if ($this->error) { $response['error'] = $this->error; } else { $response['result'] = $this->result; } return $response; } public function toJson(): bool|string { return json_encode($this->toArray()); } }