ChannelManager.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\Utils\Channel;
  12. use Hyperf\Engine\Channel;
  13. class ChannelManager
  14. {
  15. /**
  16. * @var Channel[]
  17. */
  18. protected $channels = [];
  19. /**
  20. * @var int
  21. */
  22. protected $size = 1;
  23. public function __construct(int $size = 1)
  24. {
  25. $this->size = $size;
  26. }
  27. public function get(int $id, bool $initialize = false): ?Channel
  28. {
  29. if (isset($this->channels[$id])) {
  30. return $this->channels[$id];
  31. }
  32. if ($initialize) {
  33. return $this->channels[$id] = $this->make($this->size);
  34. }
  35. return null;
  36. }
  37. public function make(int $limit): Channel
  38. {
  39. return new Channel($limit);
  40. }
  41. public function close(int $id): void
  42. {
  43. if ($channel = $this->channels[$id] ?? null) {
  44. $channel->close();
  45. }
  46. unset($this->channels[$id]);
  47. }
  48. public function getChannels(): array
  49. {
  50. return $this->channels;
  51. }
  52. public function flush(): void
  53. {
  54. $channels = $this->getChannels();
  55. foreach ($channels as $id => $channel) {
  56. $this->close($id);
  57. }
  58. }
  59. }