| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- // +----------------------------------------------------------------------
- // | Workerman 响应封装类
- // +----------------------------------------------------------------------
- namespace app\services\workerman;
- use Workerman\Connection\TcpConnection;
- class Response
- {
- protected $connection;
- public function connection(TcpConnection $connection)
- {
- $this->connection = $connection;
- return $this;
- }
- public function send(string $type, ?array $data = null, bool $close = false, array $other = [])
- {
- $this->connection->lastMessageTime = time();
- $res = compact('type');
- if (!is_null($data)) $res['data'] = $data;
- $data = array_merge($res, $other);
- if ($close) $data['close'] = true;
- $json = json_encode($data);
- return $close ? $this->connection->close($json) : $this->connection->send($json);
- }
- public function success($type = 'success', ?array $data = null)
- {
- if (is_array($type)) {
- $data = $type;
- $type = 'success';
- }
- return $this->send($type, $data);
- }
- public function fail($type = 'error', ?array $data = null)
- {
- if (is_array($type)) {
- $data = $type;
- $type = 'error';
- }
- return $this->send($type, $data);
- }
- public function close($type = 'error', ?array $data = null)
- {
- if (is_array($type)) {
- $data = $type;
- $type = 'error';
- }
- return $this->send($type, $data, true);
- }
- }
|