2025-03-16 17:43:30 +08:00
|
|
|
<?php
|
2025-04-22 15:04:38 +08:00
|
|
|
|
|
|
|
|
namespace library;
|
2025-03-16 17:43:30 +08:00
|
|
|
|
2025-05-08 15:56:07 +08:00
|
|
|
use think\response\Json as JsonResponse;
|
|
|
|
|
|
2025-03-16 17:43:30 +08:00
|
|
|
class ResponseHelper
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* 成功响应
|
2025-04-22 15:04:38 +08:00
|
|
|
*
|
2025-05-08 15:56:07 +08:00
|
|
|
* @param mixed $data
|
|
|
|
|
* @param string $msg
|
|
|
|
|
* @param int $code
|
|
|
|
|
* @return JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
*/
|
2025-05-08 15:56:07 +08:00
|
|
|
public static function success($data = null, string $msg = 'success', int $code = 200): JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
{
|
|
|
|
|
return json([
|
|
|
|
|
'code' => $code,
|
2025-05-08 15:56:07 +08:00
|
|
|
'msg' => $msg,
|
2025-03-16 17:43:30 +08:00
|
|
|
'data' => $data
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 错误响应
|
2025-04-22 15:04:38 +08:00
|
|
|
*
|
2025-05-08 15:56:07 +08:00
|
|
|
* @param string $msg
|
|
|
|
|
* @param int $code
|
|
|
|
|
* @param mixed $data
|
|
|
|
|
* @return JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
*/
|
2025-05-08 15:56:07 +08:00
|
|
|
public static function error(string $msg = 'fail', int $code = 400, $data = []): JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
{
|
|
|
|
|
return json([
|
|
|
|
|
'code' => $code,
|
2025-05-08 15:56:07 +08:00
|
|
|
'msg' => $msg,
|
2025-03-16 17:43:30 +08:00
|
|
|
'data' => $data
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 未授权响应
|
2025-04-22 15:04:38 +08:00
|
|
|
*
|
2025-03-16 17:43:30 +08:00
|
|
|
* @param string $msg 错误消息
|
2025-05-08 15:56:07 +08:00
|
|
|
* @return JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
*/
|
2025-05-08 15:56:07 +08:00
|
|
|
public static function unauthorized(string $msg = 'unauthorized access'): JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
{
|
2025-05-08 15:56:07 +08:00
|
|
|
return static::error($msg, 401);
|
2025-03-16 17:43:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 禁止访问响应
|
2025-04-22 15:04:38 +08:00
|
|
|
*
|
2025-03-16 17:43:30 +08:00
|
|
|
* @param string $msg 错误消息
|
2025-05-08 15:56:07 +08:00
|
|
|
* @return JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
*/
|
2025-05-08 15:56:07 +08:00
|
|
|
public static function forbidden(string $msg = 'access denied'): JsonResponse
|
2025-03-16 17:43:30 +08:00
|
|
|
{
|
2025-05-08 15:56:07 +08:00
|
|
|
return static::error($msg, 403);
|
2025-03-16 17:43:30 +08:00
|
|
|
}
|
|
|
|
|
}
|