Protocol.php 2.7 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\Rpc;
  12. use Hyperf\Contract\NormalizerInterface;
  13. use Hyperf\Contract\PackerInterface;
  14. use Hyperf\Rpc\Contract\DataFormatterInterface;
  15. use Hyperf\Rpc\Contract\PathGeneratorInterface;
  16. use Hyperf\Rpc\Contract\TransporterInterface;
  17. use InvalidArgumentException;
  18. use Psr\Container\ContainerInterface;
  19. use function Hyperf\Support\make;
  20. class Protocol
  21. {
  22. public function __construct(private ContainerInterface $container, private ProtocolManager $protocolManager, private string $name, private array $options = [])
  23. {
  24. }
  25. public function getName(): string
  26. {
  27. return $this->name;
  28. }
  29. public function getPacker(): PackerInterface
  30. {
  31. $packer = $this->protocolManager->getPacker($this->name);
  32. if (! $this->container->has($packer)) {
  33. throw new InvalidArgumentException("Packer {$packer} for {$this->name} does not exist");
  34. }
  35. return make($packer, [$this->options]);
  36. }
  37. public function getTransporter(): TransporterInterface
  38. {
  39. $transporter = $this->protocolManager->getTransporter($this->name);
  40. if (! $this->container->has($transporter)) {
  41. throw new InvalidArgumentException("Transporter {$transporter} for {$this->name} does not exist");
  42. }
  43. return make($transporter, ['config' => $this->options]);
  44. }
  45. public function getPathGenerator(): PathGeneratorInterface
  46. {
  47. $pathGenerator = $this->protocolManager->getPathGenerator($this->name);
  48. if (! $this->container->has($pathGenerator)) {
  49. throw new InvalidArgumentException("PathGenerator {$pathGenerator} for {$this->name} does not exist");
  50. }
  51. return $this->container->get($pathGenerator);
  52. }
  53. public function getDataFormatter(): DataFormatterInterface
  54. {
  55. $dataFormatter = $this->protocolManager->getDataFormatter($this->name);
  56. if (! $this->container->has($dataFormatter)) {
  57. throw new InvalidArgumentException("DataFormatter {$dataFormatter} for {$this->name} does not exist");
  58. }
  59. return $this->container->get($dataFormatter);
  60. }
  61. public function getNormalizer(): NormalizerInterface
  62. {
  63. $normalizer = $this->protocolManager->getNormalizer($this->name);
  64. if (! $this->container->has($normalizer)) {
  65. throw new InvalidArgumentException("Normalizer {$normalizer} for {$this->name} does not exist");
  66. }
  67. return $this->container->get($normalizer);
  68. }
  69. }