Response.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\Engine\WebSocket;
  12. use Hyperf\Engine\Contract\WebSocket\FrameInterface;
  13. use Hyperf\Engine\Contract\WebSocket\ResponseInterface;
  14. use Hyperf\Engine\Exception\InvalidArgumentException;
  15. use Swoole\Http\Request;
  16. use Swoole\Http\Response as SwooleResponse;
  17. use Swoole\WebSocket\Frame as SwooleFrame;
  18. use Swoole\WebSocket\Server;
  19. use function Hyperf\Engine\swoole_get_flags_from_frame;
  20. class Response implements ResponseInterface
  21. {
  22. protected int $fd = 0;
  23. public function __construct(protected mixed $connection)
  24. {
  25. }
  26. public function push(FrameInterface $frame): bool
  27. {
  28. $data = (string) $frame->getPayloadData();
  29. $flags = swoole_get_flags_from_frame($frame);
  30. if ($this->connection instanceof SwooleResponse) {
  31. $this->connection->push($data, $frame->getOpcode(), $flags);
  32. return true;
  33. }
  34. if ($this->connection instanceof Server) {
  35. $this->connection->push($this->fd, $data, $frame->getOpcode(), $flags);
  36. return true;
  37. }
  38. throw new InvalidArgumentException('The websocket connection is invalid.');
  39. }
  40. public function init(mixed $frame): static
  41. {
  42. switch (true) {
  43. case is_int($frame):
  44. $this->fd = $frame;
  45. break;
  46. case $frame instanceof Request || $frame instanceof SwooleFrame:
  47. $this->fd = $frame->fd;
  48. break;
  49. }
  50. return $this;
  51. }
  52. public function getFd(): int
  53. {
  54. return $this->fd;
  55. }
  56. public function close(): bool
  57. {
  58. if ($this->connection instanceof SwooleResponse) {
  59. return $this->connection->close();
  60. }
  61. if ($this->connection instanceof Server) {
  62. return $this->connection->disconnect($this->fd);
  63. }
  64. return false;
  65. }
  66. }