Response.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services\workerman;
  12. use Workerman\Connection\TcpConnection;
  13. class Response
  14. {
  15. /**
  16. * @var TcpConnection
  17. */
  18. protected $connection;
  19. /**
  20. * 设置用户
  21. *
  22. * @param TcpConnection $connection
  23. * @return $this
  24. */
  25. public function connection(TcpConnection $connection)
  26. {
  27. $this->connection = $connection;
  28. return $this;
  29. }
  30. /**
  31. * 发送请求
  32. *
  33. * @param string $type
  34. * @param array|null $data
  35. * @param bool $close
  36. * @param array $other
  37. * @return bool|null
  38. */
  39. public function send(string $type, ?array $data = null, bool $close = false, array $other = [])
  40. {
  41. $this->connection->lastMessageTime = time();
  42. $res = compact('type');
  43. if (!is_null($data)) $res['data'] = $data;
  44. $data = array_merge($res, $other);
  45. if ($close)
  46. $data['close'] = true;
  47. $json = json_encode($data);
  48. return $close
  49. ? ($this->connection->close($json))
  50. : $this->connection->send($json);
  51. }
  52. /**
  53. * 成功
  54. *
  55. * @param string $message
  56. * @param array|null $data
  57. * @return bool|null
  58. */
  59. public function success($type = 'success', ?array $data = null)
  60. {
  61. if (is_array($type)) {
  62. $data = $type;
  63. $type = 'success';
  64. }
  65. return $this->send($type, $data);
  66. }
  67. /**
  68. * 失败
  69. *
  70. * @param string $message
  71. * @param array|null $data
  72. * @return bool|null
  73. */
  74. public function fail($type = 'error', ?array $data = null)
  75. {
  76. if (is_array($type)) {
  77. $data = $type;
  78. $type = 'error';
  79. }
  80. return $this->send($type, $data);
  81. }
  82. /**
  83. * 关闭连接
  84. *
  85. * @param string $type
  86. * @param array|null $data
  87. * @return bool|null
  88. */
  89. public function close($type = 'error', ?array $data = null)
  90. {
  91. if (is_array($type)) {
  92. $data = $type;
  93. $type = 'error';
  94. }
  95. return $this->send($type, $data, true);
  96. }
  97. }