Response.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace crmeb\services\workerman;
  3. use Workerman\Connection\TcpConnection;
  4. class Response
  5. {
  6. /**
  7. * @var TcpConnection
  8. */
  9. protected $connection;
  10. /**
  11. * 设置用户
  12. *
  13. * @param TcpConnection $connection
  14. * @return $this
  15. */
  16. public function connection(TcpConnection $connection)
  17. {
  18. $this->connection = $connection;
  19. return $this;
  20. }
  21. /**
  22. * 发送请求
  23. *
  24. * @param string $type
  25. * @param array|null $data
  26. * @param bool $close
  27. * @param array $other
  28. * @return bool|null
  29. */
  30. public function send(string $type, ?array $data = null, bool $close = false, array $other = [])
  31. {
  32. $this->connection->lastMessageTime = time();
  33. $res = compact('type');
  34. if (!is_null($data)) $res['data'] = $data;
  35. $data = array_merge($res, $other);
  36. if ($close)
  37. $data['close'] = true;
  38. $json = json_encode($data);
  39. return $close
  40. ? ($this->connection->close($json) && true)
  41. : $this->connection->send($json);
  42. }
  43. /**
  44. * 成功
  45. *
  46. * @param string $message
  47. * @param array|null $data
  48. * @return bool|null
  49. */
  50. public function success($type = 'success', ?array $data = null)
  51. {
  52. if (is_array($type)) {
  53. $data = $type;
  54. $type = 'success';
  55. }
  56. return $this->send($type, $data);
  57. }
  58. /**
  59. * 失败
  60. *
  61. * @param string $message
  62. * @param array|null $data
  63. * @return bool|null
  64. */
  65. public function fail($type = 'error', ?array $data = null)
  66. {
  67. if (is_array($type)) {
  68. $data = $type;
  69. $type = 'error';
  70. }
  71. return $this->send($type, $data);
  72. }
  73. /**
  74. * 关闭连接
  75. *
  76. * @param string $type
  77. * @param array|null $data
  78. * @return bool|null
  79. */
  80. public function close($type = 'error', ?array $data = null)
  81. {
  82. if (is_array($type)) {
  83. $data = $type;
  84. $type = 'error';
  85. }
  86. return $this->send($type, $data, true);
  87. }
  88. }