ProtocolManager.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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\ConfigInterface;
  13. use Hyperf\Contract\NormalizerInterface;
  14. use Hyperf\Stringable\Str;
  15. use Hyperf\Stringable\StrCache;
  16. use InvalidArgumentException;
  17. use JetBrains\PhpStorm\ArrayShape;
  18. class ProtocolManager
  19. {
  20. public function __construct(private ConfigInterface $config)
  21. {
  22. }
  23. public function register(
  24. string $name,
  25. #[ArrayShape([
  26. 'packer' => 'string', // \Hyperf\RpcMultiplex\Packer\JsonPacker::class,
  27. 'transporter' => 'string', // \Hyperf\RpcMultiplex\Transporter::class,
  28. 'path-generator' => 'string', // \Hyperf\RpcMultiplex\PathGenerator::class,
  29. 'data-formatter' => 'string', // \Hyperf\RpcMultiplex\DataFormatter::class,
  30. 'normalizer' => 'string', // \Hyperf\JsonRpc\JsonRpcNormalizer::class,
  31. ])]
  32. array $data
  33. ): void {
  34. $this->config->set('protocols.' . $name, $data);
  35. }
  36. public function registerOrAppend(string $name, array $data): void
  37. {
  38. $key = 'protocols.' . $name;
  39. $this->config->set($key, array_merge($this->config->get($key, []), $data));
  40. }
  41. public function getProtocol(string $name): array
  42. {
  43. return $this->config->get('protocols.' . $name, []);
  44. }
  45. public function getPacker(string $name): string
  46. {
  47. return $this->getTarget($name, 'packer');
  48. }
  49. public function getTransporter(string $name): string
  50. {
  51. return $this->getTarget($name, 'transporter');
  52. }
  53. public function getPathGenerator(string $name): string
  54. {
  55. return $this->getTarget($name, 'path-generator');
  56. }
  57. public function getDataFormatter(string $name): string
  58. {
  59. return $this->getTarget($name, 'data-formatter');
  60. }
  61. public function getNormalizer(string $name): string
  62. {
  63. return $this->getTarget($name, 'normalizer', NormalizerInterface::class);
  64. }
  65. private function getTarget(string $name, string $target, ?string $default = null): string
  66. {
  67. $result = $this->config->get('protocols.' . Str::lower($name) . '.' . Str::lower($target));
  68. if (! is_string($result)) {
  69. if ($default) {
  70. return $default;
  71. }
  72. throw new InvalidArgumentException(sprintf('%s is not exists.', StrCache::studly($target, ' ')));
  73. }
  74. return $result;
  75. }
  76. }