Channel.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\Pool;
  12. use Hyperf\Contract\ConnectionInterface;
  13. use Hyperf\Engine\Channel as CoChannel;
  14. use Hyperf\Utils\Coroutine;
  15. class Channel
  16. {
  17. protected $size;
  18. /**
  19. * @var CoChannel
  20. */
  21. protected $channel;
  22. /**
  23. * @var \SplQueue
  24. */
  25. protected $queue;
  26. public function __construct(int $size)
  27. {
  28. $this->size = $size;
  29. $this->channel = new CoChannel($size);
  30. $this->queue = new \SplQueue();
  31. }
  32. /**
  33. * @return ConnectionInterface|false
  34. */
  35. public function pop(float $timeout)
  36. {
  37. if ($this->isCoroutine()) {
  38. return $this->channel->pop($timeout);
  39. }
  40. return $this->queue->shift();
  41. }
  42. /**
  43. * @param ConnectionInterface $data
  44. * @return bool
  45. */
  46. public function push($data)
  47. {
  48. if ($this->isCoroutine()) {
  49. return $this->channel->push($data);
  50. }
  51. $this->queue->push($data);
  52. return true;
  53. }
  54. public function length(): int
  55. {
  56. if ($this->isCoroutine()) {
  57. return $this->channel->getLength();
  58. }
  59. return $this->queue->count();
  60. }
  61. protected function isCoroutine(): bool
  62. {
  63. return Coroutine::id() > 0;
  64. }
  65. }