Files
spacestation/common/libraries/websocket/WsResponse.php
T
2025-11-17 09:33:36 +08:00

85 lines
2.2 KiB
PHP

<?php
class WsResponse
{
// 定义标准响应码
const CODE_SUCCESS = 0;
const CODE_ERROR = 500;
const CODE_BAD_REQUEST = 400;
const CODE_UNAUTHORIZED = 401; //授权时错误
const CODE_FORBIDDEN = 403;
const CODE_NOT_FOUND = 404;
const MST_TYPE_MSG = 'notice'; //消息类型
const MST_TYPE_CONNECT = 'connect'; //连接类型
const MST_TYPE_PONG = 'heartbeat'; //心跳检测
/**
* 创建标准成功响应
*
* @param string $type 响应类型
* @param string $message 响应消息
* @param array $data 响应数据
* @return string 标准响应数组
*/
public static function success($type = '', $message = '操作成功', $data = [])
{
return self::toJson([
'code' => self::CODE_SUCCESS,
'type' => $type,
'msg' => $message,
'data' => $data
]);
}
/**
* 创建标准错误响应
*
* @param int $code 错误码
* @param string $message 错误消息
* @param string $type 错误类型
* @return string 标准错误响应数组
*/
public static function error($type = '', $message = '服务器内部错误', $code = self::CODE_ERROR, $data = [])
{
return self::toJson([
'code' => $code,
'type' => $type,
'msg' => $message,
'data' => $data
]);
}
/**
* 创建认证错误响应
*
* @param string $message 错误消息
* @return string 认证错误响应
*/
public static function unauthorized($message = '未授权访问')
{
return self::error(self::CODE_UNAUTHORIZED, $message, 'unauthorized');
}
/**
* 创建参数错误响应
*
* @param string $message 错误消息
* @return string 参数错误响应
*/
public static function badRequest($message = '请求参数错误')
{
return self::error(self::CODE_BAD_REQUEST, $message, 'bad_request');
}
/**
* 将响应转换为JSON格式
*
* @param array $response 响应数组
* @return string JSON格式的响应
*/
public static function toJson($response)
{
return json_encode($response, JSON_UNESCAPED_UNICODE);
}
}