diff --git a/src/Response.php b/src/Response.php new file mode 100644 index 0000000..4ba6d27 --- /dev/null +++ b/src/Response.php @@ -0,0 +1,69 @@ + $data, + 'code' => 200, + 'message' => $message ?: 'success', + ]; + } + + /** + * 错误响应. + * @param int $code 错误码 + * @param string $message 错误消息 + * @param null|mixed $data 附加数据 + */ + public static function error(string $message = 'fail', int $code = -1, mixed $data = null): array + { + return [ + 'code' => $code, + 'data' => $data, + 'message' => $message ?: self::getDefaultMessage($code), + ]; + } + + public static function page($list, int $total, int $page, int $size): array + { + return [ + 'code' => 200, + 'message' => 'ok', + 'list' => [ + 'list' => $list, + 'page' => $page, + 'size' => $size, + 'total' => $total, + 'pages' => (int) ceil($total / $size), + ], + ]; + } + + /** + * 获取默认错误消息. + */ + private static function getDefaultMessage(int $code): string + { + $messages = [ + 400 => '请求参数错误', + 401 => '未授权', + 403 => '禁止访问', + 404 => '资源不存在', + 500 => '服务器内部错误', + 10001 => '校区不存在', + ]; + + return $messages[$code] ?? '未知错误'; + } +}