llmbackend/app/Http/Controllers/Controller.php
2024-12-04 16:41:43 +08:00

103 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
abstract class Controller
{
/**
* 成功响应
*
* @param mixed $data 响应数据
* @param string|null $message 成功消息
* @param int $code HTTP状态码
*/
protected function success(mixed $data = null, ?string $message = null, int $code = Response::HTTP_OK): JsonResponse
{
$response = [
'success' => true,
];
if ($data !== null) {
$response['data'] = $data;
}
if ($message !== null) {
$response['message'] = $message;
}
return response()->json($response, $code);
}
/**
* 错误响应
*
* @param string $error 错误代码
* @param string $message 错误消息
* @param mixed $errors 详细错误信息
* @param int $code HTTP状态码
*/
protected function error(
string $error,
string $message,
mixed $errors = null,
int $code = Response::HTTP_BAD_REQUEST
): JsonResponse {
$response = [
'success' => false,
'error' => $error,
'message' => $message,
];
if ($errors !== null) {
$response['errors'] = $errors;
}
return response()->json($response, $code);
}
/**
* 分页响应
*
* @param array $items 分页数据
* @param array $meta 分页元数据
* @param string|null $message 成功消息
*/
protected function paginate(array $items, array $meta, ?string $message = null): JsonResponse
{
$response = [
'success' => true,
'data' => $items,
'meta' => $meta,
];
if ($message !== null) {
$response['message'] = $message;
}
return response()->json($response);
}
/**
* 创建成功响应
*
* @param mixed $data 创建的资源数据
* @param string|null $message 成功消息
*/
protected function created(mixed $data, ?string $message = null): JsonResponse
{
return $this->success($data, $message, Response::HTTP_CREATED);
}
/**
* 无内容响应
*/
protected function noContent(): JsonResponse
{
return response()->json(null, Response::HTTP_NO_CONTENT);
}
}