GrpcFactory.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Nacos;
  12. use Hyperf\Context\ApplicationContext;
  13. use Hyperf\Nacos\Exception\InvalidArgumentException;
  14. use Psr\Container\ContainerInterface;
  15. class GrpcFactory
  16. {
  17. /**
  18. * @var array<string, array<string, GrpcClient>>
  19. */
  20. protected array $clients = [];
  21. public function __construct(protected Application $app, protected Config $config)
  22. {
  23. if (! $this->config->getGrpc()['enable']) {
  24. throw new InvalidArgumentException('GRPC module is disable, please set `nacos.default.grpc.enable = true`.');
  25. }
  26. }
  27. public function get(string $namespaceId, Module|string $module = 'config'): GrpcClient
  28. {
  29. $module instanceof Module && $module = $module->value;
  30. if (isset($this->clients[$namespaceId][$module])) {
  31. return $this->clients[$namespaceId][$module];
  32. }
  33. return $this->clients[$namespaceId][$module] = new GrpcClient($this->app, $this->config, $this->container(), $namespaceId, $module);
  34. }
  35. /**
  36. * @return array<string, array<string, GrpcClient>> array<namespaceId, <module, GrpcClient>>
  37. */
  38. public function getClients(): array
  39. {
  40. return $this->clients;
  41. }
  42. /**
  43. * @param string $module config or naming
  44. * @return array<string, GrpcClient> array<namespaceId, GrpcClient>
  45. */
  46. public function moduleClients(Module|string $module): array
  47. {
  48. $module instanceof Module && $module = $module->value;
  49. $result = [];
  50. foreach ($this->clients as $namespaceId => $clients) {
  51. foreach ($clients as $key => $client) {
  52. if ($key === $module) {
  53. $result[$namespaceId] = $client;
  54. }
  55. }
  56. }
  57. return $result;
  58. }
  59. private function container(): ContainerInterface
  60. {
  61. return ApplicationContext::getContainer();
  62. }
  63. }