NormalizeDataFormatter.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\Contract\NormalizerInterface;
  13. use Hyperf\Rpc\Context;
  14. use Hyperf\Rpc\ErrorResponse;
  15. use Hyperf\Rpc\Request;
  16. use Hyperf\Rpc\Response;
  17. use Throwable;
  18. class NormalizeDataFormatter extends DataFormatter
  19. {
  20. public function __construct(private NormalizerInterface $normalizer, Context $context)
  21. {
  22. parent::__construct($context);
  23. }
  24. public function formatRequest(Request $request): array
  25. {
  26. return parent::formatRequest(
  27. $request->setParams(
  28. $this->normalizer->normalize($request->getParams())
  29. )
  30. );
  31. }
  32. public function formatResponse(Response $response): array
  33. {
  34. return parent::formatResponse(
  35. $response->setResult(
  36. $this->normalizer->normalize($response->getResult())
  37. )
  38. );
  39. }
  40. public function formatErrorResponse(ErrorResponse $response): array
  41. {
  42. $exception = $response->getException();
  43. if ($exception instanceof Throwable) {
  44. $exception = [
  45. 'class' => get_class($exception),
  46. 'attributes' => $this->normalizer->normalize($exception),
  47. ];
  48. }
  49. return parent::formatErrorResponse($response->setException($exception));
  50. }
  51. }