Client.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\RpcClient;
  12. use Hyperf\Contract\NormalizerInterface;
  13. use Hyperf\Contract\PackerInterface;
  14. use Hyperf\Rpc\Contract\TransporterInterface;
  15. use InvalidArgumentException;
  16. class Client
  17. {
  18. private ?PackerInterface $packer = null;
  19. private ?TransporterInterface $transporter = null;
  20. private ?NormalizerInterface $normalizer = null;
  21. public function send($data)
  22. {
  23. if (! $this->packer) {
  24. throw new InvalidArgumentException('Packer missing.');
  25. }
  26. if (! $this->transporter) {
  27. throw new InvalidArgumentException('Transporter missing.');
  28. }
  29. $packer = $this->getPacker();
  30. $packedData = $packer->pack($data);
  31. $response = $this->getTransporter()->send($packedData);
  32. return $packer->unpack((string) $response);
  33. }
  34. public function recv()
  35. {
  36. $packer = $this->getPacker();
  37. $response = $this->getTransporter()->recv();
  38. return $packer->unpack((string) $response);
  39. }
  40. public function getPacker(): PackerInterface
  41. {
  42. return $this->packer;
  43. }
  44. public function setPacker(PackerInterface $packer): self
  45. {
  46. $this->packer = $packer;
  47. return $this;
  48. }
  49. public function getNormalizer(): ?NormalizerInterface
  50. {
  51. return $this->normalizer;
  52. }
  53. public function setNormalizer(?NormalizerInterface $normalizer): self
  54. {
  55. $this->normalizer = $normalizer;
  56. return $this;
  57. }
  58. public function getTransporter(): TransporterInterface
  59. {
  60. return $this->transporter;
  61. }
  62. public function setTransporter(TransporterInterface $transporter): self
  63. {
  64. $this->transporter = $transporter;
  65. return $this;
  66. }
  67. }