98 lines
2.0 KiB
PHP
98 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* Author: ykxiao
|
|
* Date: 2024/6/3
|
|
* Time: 22:45
|
|
* Description:
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use Hyperf\Logger\LoggerFactory;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
/**
|
|
* Author: ykxiao
|
|
* Date: 2025/1/3
|
|
* Time: 下午8:33
|
|
* Description: JsonRpc响应类.
|
|
*
|
|
* (c) ykxiao <yk_9001@hotmail.com>
|
|
*
|
|
* 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());
|
|
}
|
|
}
|