Files
hyperf_data/extend/Aether/PHP/Hyperf/AetherResponse.php
Aether 9a1c120c4f ..
2025-09-29 10:15:17 +08:00

70 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace Aether;
class AetherResponse
{
/**
* 成功响应.
* @param null|mixed $data 数据
* @param string $message 消息
*/
public static function success(mixed $data = null, string $message = '操作成功'): array
{
return [
Config::RESPONSE_FIELD_KEY_DATA => $data,
Config::RESPONSE_FIELD_KEY_CODE => Config::RESPONSE_SUCCESS_CODE,
Config::RESPONSE_FIELD_KEY_MESSAGE => $message ?: Config::RESPONSE_SUCCESS_MESSAGE,
];
}
/**
* 错误响应.
* @param int $code 错误码
* @param string $message 错误消息
* @param null|mixed $data 附加数据
*/
public static function error(string $message = '', int $code = Config::RESPONSE_FAIL_CODE, mixed $data = null): array
{
return [
Config::RESPONSE_FIELD_KEY_CODE => $code,
Config::RESPONSE_FIELD_KEY_DATA => $data,
Config::RESPONSE_FIELD_KEY_MESSAGE => $message ?: self::getDefaultMessage($code),
];
}
public static function page($list, int $total, int $page, int $size): array
{
return [
Config::RESPONSE_FIELD_KEY_CODE => Config::RESPONSE_SUCCESS_CODE,
Config::RESPONSE_FIELD_KEY_MESSAGE => 'success',
Config::RESPONSE_FIELD_KEY_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] ?? '未知错误';
}
}