DataFormatter.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\JsonRpc;
  12. use Hyperf\Rpc\Context;
  13. use Hyperf\Rpc\Contract\DataFormatterInterface;
  14. use Hyperf\Rpc\ErrorResponse;
  15. use Hyperf\Rpc\Request;
  16. use Hyperf\Rpc\Response;
  17. use Throwable;
  18. class DataFormatter implements DataFormatterInterface
  19. {
  20. public function __construct(protected Context $context)
  21. {
  22. }
  23. public function formatRequest(Request $request): array
  24. {
  25. return [
  26. 'jsonrpc' => '2.0',
  27. 'method' => $request->getPath(),
  28. 'params' => $request->getParams(),
  29. 'id' => $request->getId(),
  30. 'context' => $this->context->getData(),
  31. ];
  32. }
  33. public function formatResponse(Response $response): array
  34. {
  35. return [
  36. 'jsonrpc' => '2.0',
  37. 'id' => $response->getId(),
  38. 'result' => $response->getResult(),
  39. 'context' => $this->context->getData(),
  40. ];
  41. }
  42. public function formatErrorResponse(ErrorResponse $response): array
  43. {
  44. $exception = $response->getException();
  45. if ($exception instanceof Throwable) {
  46. $exception = [
  47. 'class' => get_class($exception),
  48. 'code' => $exception->getCode(),
  49. 'message' => $exception->getMessage(),
  50. ];
  51. }
  52. return [
  53. 'jsonrpc' => '2.0',
  54. 'id' => $response->getId(),
  55. 'error' => [
  56. 'code' => $response->getCode(),
  57. 'message' => $response->getMessage(),
  58. 'data' => $exception,
  59. ],
  60. 'context' => $this->context->getData(),
  61. ];
  62. }
  63. }