Response.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Workerman 响应封装类
  4. // +----------------------------------------------------------------------
  5. namespace app\services\workerman;
  6. use Workerman\Connection\TcpConnection;
  7. class Response
  8. {
  9. protected $connection;
  10. public function connection(TcpConnection $connection)
  11. {
  12. $this->connection = $connection;
  13. return $this;
  14. }
  15. public function send(string $type, ?array $data = null, bool $close = false, array $other = [])
  16. {
  17. $this->connection->lastMessageTime = time();
  18. $res = compact('type');
  19. if (!is_null($data)) $res['data'] = $data;
  20. $data = array_merge($res, $other);
  21. if ($close) $data['close'] = true;
  22. $json = json_encode($data);
  23. return $close ? $this->connection->close($json) : $this->connection->send($json);
  24. }
  25. public function success($type = 'success', ?array $data = null)
  26. {
  27. if (is_array($type)) {
  28. $data = $type;
  29. $type = 'success';
  30. }
  31. return $this->send($type, $data);
  32. }
  33. public function fail($type = 'error', ?array $data = null)
  34. {
  35. if (is_array($type)) {
  36. $data = $type;
  37. $type = 'error';
  38. }
  39. return $this->send($type, $data);
  40. }
  41. public function close($type = 'error', ?array $data = null)
  42. {
  43. if (is_array($type)) {
  44. $data = $type;
  45. $type = 'error';
  46. }
  47. return $this->send($type, $data, true);
  48. }
  49. }