ServerFactory.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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\Server;
  12. use Hyperf\Server\Entry\EventDispatcher;
  13. use Hyperf\Server\Entry\Logger;
  14. use Psr\Container\ContainerInterface;
  15. use Psr\EventDispatcher\EventDispatcherInterface;
  16. use Psr\Log\LoggerInterface;
  17. class ServerFactory
  18. {
  19. protected ?LoggerInterface $logger = null;
  20. protected ?EventDispatcherInterface $eventDispatcher = null;
  21. protected ?ServerInterface $server = null;
  22. protected ?ServerConfig $config = null;
  23. public function __construct(protected ContainerInterface $container)
  24. {
  25. }
  26. public function configure(array $config): void
  27. {
  28. $this->config = new ServerConfig($config);
  29. $this->getServer()->init($this->config);
  30. }
  31. public function start(): void
  32. {
  33. $this->getServer()->start();
  34. }
  35. public function getServer(): ServerInterface
  36. {
  37. if (! $this->server instanceof ServerInterface) {
  38. $serverName = $this->config->getType();
  39. $this->server = new $serverName(
  40. $this->container,
  41. $this->getLogger(),
  42. $this->getEventDispatcher()
  43. );
  44. }
  45. return $this->server;
  46. }
  47. public function setServer(Server $server): static
  48. {
  49. $this->server = $server;
  50. return $this;
  51. }
  52. public function getEventDispatcher(): EventDispatcherInterface
  53. {
  54. if ($this->eventDispatcher instanceof EventDispatcherInterface) {
  55. return $this->eventDispatcher;
  56. }
  57. return $this->getDefaultEventDispatcher();
  58. }
  59. public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): static
  60. {
  61. $this->eventDispatcher = $eventDispatcher;
  62. return $this;
  63. }
  64. public function getLogger(): LoggerInterface
  65. {
  66. if ($this->logger instanceof LoggerInterface) {
  67. return $this->logger;
  68. }
  69. return $this->getDefaultLogger();
  70. }
  71. public function setLogger(LoggerInterface $logger): static
  72. {
  73. $this->logger = $logger;
  74. return $this;
  75. }
  76. public function getConfig(): ?ServerConfig
  77. {
  78. return $this->config;
  79. }
  80. private function getDefaultEventDispatcher(): EventDispatcherInterface
  81. {
  82. return new EventDispatcher();
  83. }
  84. private function getDefaultLogger(): LoggerInterface
  85. {
  86. return new Logger();
  87. }
  88. }