Compare commits

...

3 Commits

Author SHA1 Message Date
李东云
480f406ccc refactor(migrate): 迁移注解以支持hyperf3 2023-01-13 23:01:06 +08:00
李东云
91db3c731f refactor(migrate): 迁移注解以支持hyperf3 2023-01-13 22:39:08 +08:00
李东云
9fedbb40f4 build: 迁移到hyperf3 2023-01-13 20:33:21 +08:00
10 changed files with 618 additions and 864 deletions

2
.idea/HDK-Core.iml generated
View File

@@ -139,10 +139,10 @@
<excludeFolder url="file://$MODULE_DIR$/vendor/phpstan/phpstan" />
<excludeFolder url="file://$MODULE_DIR$/vendor/pestphp/pest-plugin" />
<excludeFolder url="file://$MODULE_DIR$/vendor/friendsofphp/php-cs-fixer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/facade/ignition-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/spatie/pest-plugin-test-time" />
<excludeFolder url="file://$MODULE_DIR$/vendor/filp/whoops" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/deprecations" />
<excludeFolder url="file://$MODULE_DIR$/vendor/hyperf/coordinator" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />

2
.idea/php.xml generated
View File

@@ -150,7 +150,6 @@
<path value="$PROJECT_DIR$/vendor/pestphp/pest-plugin" />
<path value="$PROJECT_DIR$/vendor/filp/whoops" />
<path value="$PROJECT_DIR$/vendor/nunomaduro/collision" />
<path value="$PROJECT_DIR$/vendor/facade/ignition-contracts" />
<path value="$PROJECT_DIR$/vendor/spatie/test-time" />
<path value="$PROJECT_DIR$/vendor/spatie/pest-plugin-test-time" />
<path value="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer" />
@@ -158,6 +157,7 @@
<path value="$PROJECT_DIR$/vendor/symfony/stopwatch" />
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan" />
<path value="$PROJECT_DIR$/vendor/doctrine/deprecations" />
<path value="$PROJECT_DIR$/vendor/hyperf/coordinator" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.0" />

View File

@@ -20,17 +20,17 @@
"ext-swoole": "*",
"composer/composer": ">=2.0",
"ergebnis/http-method": "^2.2",
"hyperf/config": "^2.2",
"hyperf/constants": "^2.2",
"hyperf/context": "^2.2",
"hyperf/database": "^2.2",
"hyperf/di": "^2.2",
"hyperf/framework": "^2.2",
"hyperf/http-server": "^2.2",
"hyperf/logger": "^2.2",
"hyperf/redis": "^2.2",
"hyperf/resource": "^2.2",
"hyperf/translation": "^2.2",
"hyperf/config": "3.0.*",
"hyperf/constants": "3.0.*",
"hyperf/context": "3.0.*",
"hyperf/database": "3.0.*",
"hyperf/di": "3.0.*",
"hyperf/framework": "3.0.*",
"hyperf/http-server": "3.0.*",
"hyperf/logger": "3.0.*",
"hyperf/redis": "3.0.*",
"hyperf/resource": "3.0.*",
"hyperf/translation": "3.0.*",
"jetbrains/phpstorm-attributes": "^1.0",
"lmc/http-constants": "^1.2",
"myclabs/php-enum": "^1.8",
@@ -43,8 +43,8 @@
"firebase/php-jwt": "^6.1",
"friendsofphp/php-cs-fixer": "^3.13",
"guzzlehttp/guzzle": "^7.5",
"hyperf/session": "^2.2",
"hyperf/validation": "^2.2",
"hyperf/session": "3.0.*",
"hyperf/validation": "3.0.*",
"pestphp/pest": "^1.22",
"phpstan/phpstan": "^1.9",
"phpunit/phpunit": "^9.5",

1108
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
<?php
/**
* CommonErrorCode.php@hyperf-development-kit
*
@@ -13,382 +14,305 @@ use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;
/**
* @Constants
* Singularity\HyperfDevelopmentKit\Utils\Constants\CommonErrorCode@hyperf-development-kit
*
* @author 李东云<dongyun.li@luxcreo.cn>
* Powered by PhpStorm
* Created on 2022/4/25
*/
#[Constants]
class CommonErrorCode extends AbstractConstants
{
// =============== 9 服务器异常 =================
/**
* @Message("common_error.server_common_error")
*/
public const SERVER_ERROR = 9000000;
/**
* @Message("common_error.program.default")
*/
public const PROGRAM_ERROR = 9000000;
// 901 逻辑错误
/**
* @Message("common_error.program.syntax.default")
*/
public const PROGRAM_SYNTAX_ERROR = 9010001;
// 902 SQL 错误
/**
* @Message("common_error.program.sql.default")
*/
public const PROGRAM_SQL_ERROR = 9020001;
/**
* @Message("common_error.program.sql.update")
*/
public const PROGRAM_SQL_UPDATE_ERROR = 9020101;
// 90201 字段不存在
/**
* @Message("common_error.program.sql.column_not_found")
*/
public const PROGRAM_SQL_COLUMN_NOT_FOUND = 9020101;
/**
* @Message("common_error.program.sql.insert")
*/
public const PROGRAM_SQL_INSERT_ERROR = 9020201;
// =============== 1 请求错误 =================
// 101 请求方式有误
/**
* @Message("common_error.params.method.default")
*/
public const REQUEST_METHOD_ERROR = 1010001;
// 102 参数非法
/**
* 参数非法.
* @Message("common_error.params.format_error")
*/
public const FORMATTER_ERROR = 1020001;
/**
* 缺少参数.
* @Message("common_error.params.error.default")
*/
public const REQUEST_PARAMS_MISS = 1020002;
/**
* 签名非法.
* @Message("common_error.params.error.default")
*/
public const REQUEST_SIGN_ERROR = 1020003;
// 103 参数错误
/**
* @Message("common_error.params.error.default")
*/
public const REQUEST_PARAMS_ERROR = 1030001;
// 10301 用户信息错误
/**
* @Message("common_error.params.error.user.default")
*/
public const REQUEST_PARAMS_ERROR_USER = 1030101;
/**
* @Message("common_error.params.error.user.sign_up.default")
*/
public const REQUEST_PARAMS_ERROR_USER_REGISTERED = 1030102;
/**
* @Message("common_error.params.error.user.username.unique")
*/
public const REQUEST_PARAMS_ERROR_USER_USERNAME_UNIQUE = 1030111;
/**
* @Message("common_error.params.error.user.sec_phone.unique")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_PHONE_UNIQUE = 1030121;
/**
* @Message("common_error.params.error.user.sec_phone.required")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_PHONE_REQUIRED = 1030122;
/**
* @Message("common_error.params.error.user.sec_phone.undefined")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_PHONE_UNDEFINED = 1030123;
/**
* @Message("common_error.params.error.user.sec_email.unique")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_EMAIL_UNIQUE = 1030131;
/**
* @Message("common_error.params.error.user.sec_email.required")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_EMAIL_REQUIRED = 1030132;
/**
* @Message("common_error.params.error.user.sec_email.undefined")
*/
public const REQUEST_PARAMS_ERROR_USER_SEC_EMAIL_UNDEFINED = 1030133;
/**
* @Message("common_error.params.error.user.action.error")
*/
public const REQUEST_PARAMS_ERROR_USER_ACTION_ERROR = 1030141;
// 10302 验证码错误
/**
* @Message("common_error.params.error.code.error")
*/
public const REQUEST_PARAMS_ERROR_CODE_ERROR = 1030201;
/**
* @Message("common_error.params.error.code.timeout")
*/
public const REQUEST_PARAMS_ERROR_CODE_TIMEOUT = 1030202;
/**
* @Message("common_error.params.error.code.limit.minute")
*/
public const REQUEST_PARAMS_ERROR_CODE_MAX_TIMES_MINUTE = 1030301;
/**
* @Message("common_error.params.error.code.limit.hour")
*/
public const REQUEST_PARAMS_ERROR_CODE_MAX_TIMES_HOUR = 1030302;
/**
* @Message("common_error.params.error.code.limit.day")
*/
public const REQUEST_PARAMS_ERROR_CODE_MAX_TIMES_DAY = 1030303;
/**
* @Message("common_error.params.error.target.format")
*/
public const REQUEST_PARAMS_ERROR_TARGET_FORMAT = 1030401;
/**
* @Message("common_error.params.error.target.missing")
*/
public const REQUEST_PARAMS_ERROR_TARGET_MISSING = 1030402;
// =============== 2 鉴权问题 =================
// 201 JWT 鉴权失败
/**
* @Message("common_error.auth.default")
*/
public const UNAUTHORIZED = 200000;
/**
* @Message("common_error.auth.jwt.default")
*/
public const AUTH_JWT_ERROR = 201000;
// 20101 验证
/**
* @Message("common_error.auth.jwt.iat")
*/
public const AUTH_JWT_IAT_ERROR = 2010101;
/**
* @Message("common_error.auth.jwt.nbf")
*/
public const AUTH_JWT_NBF_ERROR = 2010102;
/**
* @Message("common_error.auth.jwt.exp")
*/
public const AUTH_JWT_EXP_TIMEOUT = 2010103;
/**
* @Message("common_error.auth.jwt.iss")
*/
public const AUTH_JWT_ISS_ERROR = 2010104;
/**
* @Message("common_error.auth.jwt.uid")
*/
public const AUTH_JWT_UID_ERROR = 2010105;
// 202 Session 鉴权
/**
* @Message("common_error.auth.session.default")
*/
public const AUTH_SESSION_ERROR = 202000;
// 20201 验证
/**
* @Message("common_error.auth.session.uid")
*/
public const AUTH_SESSION_UID_ERROR = 2020101;
/**
* @Message("common_error.auth.session.created_at")
*/
public const AUTH_SESSION_CREATED_AT_ERROR = 2020102;
// 203 SAML 鉴权
/**
* @Message("common_error.auth.saml.default")
*/
public const AUTH_SAML_ERROR = 203000;
// 20301 验证
/**
* @Message("common_error.auth.saml.params.default")
*/
public const AUTH_SAML_REQUEST_PARAMS_ERROR = 2030100;
/**
* @Message("common_error.auth.saml.params.saml_request")
*/
public const AUTH_SAML_REQUEST_PARAMS_SAML_REQUEST = 2030101;
// 204 无权访问
/**
* @Message("common_error.auth.forbidden.default")
*/
public const FORBIDDEN = 204000;
// 20401 无权访问
/**
* @Message("common_error.auth.forbidden.read.default")
*/
public const FORBIDDEN_READ_ERROR = 2040101;
// 20402 无权修改
/**
* @Message("common_error.auth.forbidden.update.default")
*/
public const FORBIDDEN_UPDATE_ERROR = 2040201;
/**
* @Message("common_error.auth.forbidden.update.address.unique")
*/
public const FORBIDDEN_UPDATE_ADDRESS_DEFAULT_UNIQUE_ERROR = 2040211;
// 20403 无权创建
/**
* @Message("common_error.auth.forbidden.create.default")
*/
public const FORBIDDEN_CREATE_ERROR = 2040301;
/**
* @Message("common_error.auth.forbidden.create.wechat.redundant")
*/
public const FORBIDDEN_CREATE_WECHAT_REDUNDANT_ERROR = 2040311;
// 20404 无权删除
/**
* @Message("common_error.auth.forbidden.delete.default")
*/
public const FORBIDDEN_DELETE_ERROR = 2040401;
/**
* @Message("common_error.auth.forbidden.delete.wechat.only")
*/
public const FORBIDDEN_DELETE_ONLY_USERNAME_WITH_WECHAT = 2040411;
// 205 App 鉴权
/**
* @Message("common_error.auth.app.default")
*/
public const AUTH_APP_ERROR = 205000;
// ============== 3 依赖服务出错 ===============
// 303 缓存异常
// 30301 Redis 异常
/**
* @Message("common_error.server.cache.redis.default")
*/
public const SERVER_CACHE_REDIS_ERROR = 3030101;
/**
* @Message("common_error.server.cache.redis.refused")
*/
public const SERVER_CACHE_REDIS_REFUSED_ERROR = 3030110;
// 30302 SMS 异常
/**
* @Message("common_error.server.dependency_sms_common_error")
*/
public const SERVER_DEPENDENCY_SMS_ERROR = 3030201;
// 30303 微信错误
/**
* @Message("common_error.server.dependency.wechat.default")
*/
public const SERVER_DEPENDENCY_WECHAT_ERROR = 3030301;
/**
* @Message("common_error.server.dependency.wechat.code")
*/
public const SERVER_DEPENDENCY_WECHAT_CODE_ERROR = 3030302;
/**
* @Message("common_error.server.dependency.wechat.timeout")
*/
public const SERVER_DEPENDENCY_WECHAT_CODE_TIMEOUT_ERROR = 3030311;
// 306 消息异常
// 30601 自建邮箱发件服务异常
/**
* @Message("common_error.server.message.email.default")
*/
public const SERVER_MESSAGE_EMAIL_ERROR = 3060101;
/**
* @Message("common_error.server.message.email.not_found")
*/
public const SERVER_MESSAGE_EMAIL_NOT_FOUND = 3060102;
// =============== 4 资源不存在 ================
// 401 路由不存在
/**
* @Message("common_error.not_found.route.default")
*/
public const ROUTE_NOT_FOUND = 4010001;
// 402 模型不存在
/**
* @Message("common_error.model.not_found")
*/
public const MODEL_NOT_FOUND = 4020001;
// 40201 用户不存在
/**
* @Message("common_error.model.user.default")
* @note !!!这个码一定不要改,前端根据这个做判断了!!!!
*/
public const USER_NOT_FOUND = 4020101;
/**
* @Message("common_error.model.user.not_valid")
*/
public const USER_NOT_VALID = 4020102;
/**
* @Message("common_error.model.document.default")
*/

View File

@@ -1,4 +1,5 @@
<?php
/**
* AbstractController.php@hyperf-development-kit
*
@@ -41,28 +42,24 @@ abstract class AbstractController
use DontSerialise;
use DontDeserialise;
use DontToString;
/**
* @Inject
* @var ContainerInterface
*/
#[Inject]
protected ContainerInterface $container;
/**
* @Inject
* @var RequestInterface
*/
#[Inject]
protected RequestInterface $request;
/**
* @Inject
* @var ResponseInterface
*/
#[Inject]
protected ResponseInterface $response;
/**
* @Inject
* @var \Hyperf\Contract\StdoutLoggerInterface
*/
#[Inject]
protected StdoutLoggerInterface $stdoutLogger;
}

View File

@@ -45,142 +45,86 @@ use Throwable;
class CommonHandler extends ExceptionHandler
{
/**
* @Inject(required=false)
*
* @var RequestInterface|null
*/
#[Inject(required: false)]
private ?RequestInterface $request;
/**
* @Inject
* @var StdoutLogger
*/
#[Inject]
private StdoutLogger $logger;
/**
* {@inheritDoc}
*/
public function handle(
Throwable $throwable,
ResponseInterface $response
): ResponseInterface {
public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
{
// 阻止异常冒泡
$this->stopPropagation();
$restful = config('common.response.restful');
$code_name = config('common.response.code_name');
$message_name = config('common.response.message_name');
$is_testing = config('app_status') === true;
$this->request?->url();
$is_debug = $this->request?->hasHeader('Postman-Token')
|| str_starts_with($this->request?->header('User-Agent'), 'apifox');
$is_debug = $this->request?->hasHeader('Postman-Token') || str_starts_with($this->request?->header('User-Agent'), 'apifox');
$error_type = $throwable::class;
$request_time = date('Y-m-d H:i:s');
$request_data = Json::encode($this->request?->getParsedBody());
$request_headers = Json::encode($this->request?->getHeaders());
// 901 程序语法错误
// 902 SQL 语法错误
if ($throwable instanceof QueryException) {
$code = match ($throwable->getCode()) {
'42S22' => CommonErrorCode::PROGRAM_SQL_COLUMN_NOT_FOUND,
default => CommonErrorCode::PROGRAM_SQL_ERROR
default => CommonErrorCode::PROGRAM_SQL_ERROR,
};
$data = [
$code_name => $code,
$message_name => CommonErrorCode::getMessage(
$is_testing
? $code
: CommonErrorCode::PROGRAM_SQL_ERROR
),
];
$data = [$code_name => $code, $message_name => CommonErrorCode::getMessage($is_testing ? $code : CommonErrorCode::PROGRAM_SQL_ERROR)];
if ($is_testing) {
$data['details'] = [
'sql' => $throwable->getSql(),
'error' => $throwable->getMessage(),
];
$data['details'] = ['sql' => $throwable->getSql(), 'error' => $throwable->getMessage()];
}
}
// 101 请求方式错误
if ($throwable instanceof MethodNotAllowedHttpException) {
$message = explode(': ', $throwable->getMessage());
$allow_method = explode(', ', $message[1]);
$code = CommonErrorCode::REQUEST_METHOD_ERROR;
$data = [
$code_name => $code,
$message_name => CommonErrorCode::getMessage($code, [
'methods' => join(', ', $allow_method),
]),
'currentMethod' => $this->request?->getMethod(),
'allowedMethod' => $allow_method,
];
$data = [$code_name => $code, $message_name => CommonErrorCode::getMessage($code, ['methods' => join(', ', $allow_method)]), 'currentMethod' => $this->request?->getMethod(), 'allowedMethod' => $allow_method];
}
// 验证失败
if ($throwable instanceof BadRequestHttpException) {
$data = [
$code_name => CommonErrorCode::REQUEST_PARAMS_ERROR,
$message_name => $is_testing
? $throwable->getMessage()
: CommonErrorCode::getMessage(CommonErrorCode::SERVER_ERROR),
];
$data = [$code_name => CommonErrorCode::REQUEST_PARAMS_ERROR, $message_name => $is_testing ? $throwable->getMessage() : CommonErrorCode::getMessage(CommonErrorCode::SERVER_ERROR)];
}
if ($throwable instanceof ValidationException) {
$data = $throwable->validator->errors()->first();
if (is_numeric($data)) {
$code = (int)$data;
$code = (int) $data;
$data = CommonErrorCode::getMessage($code);
}
$data = [
$code_name => $code ?? CommonErrorCode::REQUEST_PARAMS_ERROR,
$message_name => $data,
];
$data = [$code_name => $code ?? CommonErrorCode::REQUEST_PARAMS_ERROR, $message_name => $data];
}
if ($throwable instanceof ValidateException) {
$code = $throwable->getCode();
$message = $throwable->getMessage();
$data = [
$code_name => $code,
$message_name => empty($message) ? CommonErrorCode::getMessage($code, [
'param' => $throwable->getFieldName(),
]) : $message,
];
$data = [$code_name => $code, $message_name => empty($message) ? CommonErrorCode::getMessage($code, ['param' => $throwable->getFieldName()]) : $message];
if ($is_debug) {
$data['currentValue'] = $throwable->getCurrentValue();
$data['availableValue'] = $throwable->getAvailableValue();
}
}
// 路由不存在
if ($throwable instanceof NotFoundHttpException) {
$code = CommonErrorCode::ROUTE_NOT_FOUND;
$data = [
$code_name => $code,
$message_name => CommonErrorCode::getMessage($code),
];
$data = [$code_name => $code, $message_name => CommonErrorCode::getMessage($code)];
$status_code = 404;
}
// 模型不存在
if ($throwable instanceof ModelNotFoundException) {
$code = empty($throwable->getCode()) ? CommonErrorCode::MODEL_NOT_FOUND : $throwable->getCode();
$message = empty($throwable->getCode()) ? CommonErrorCode::getMessage($code, [
'resource' => '资源',
]) : $throwable->getMessage();
$data = [
$code_name => $code,
$message_name => $message,
];
$message = empty($throwable->getCode()) ? CommonErrorCode::getMessage($code, ['resource' => '资源']) : $throwable->getMessage();
$data = [$code_name => $code, $message_name => $message];
$status_code = 404;
}
// 300 服务出错
// 303 缓存异常
if ($throwable instanceof RedisException) {
@@ -188,16 +132,8 @@ class CommonHandler extends ExceptionHandler
if ($throwable->getMessage() === 'Connection refused') {
$code = CommonErrorCode::SERVER_CACHE_REDIS_REFUSED_ERROR;
}
$data = [
$code_name => $code,
$message_name => CommonErrorCode::getMessage(
$is_testing
? $code
: CommonErrorCode::SERVER_CACHE_REDIS_ERROR
),
];
$data = [$code_name => $code, $message_name => CommonErrorCode::getMessage($is_testing ? $code : CommonErrorCode::SERVER_CACHE_REDIS_ERROR)];
}
// 306 消息异常
// 30601 邮箱发件异常
if ($throwable instanceof TransportException) {
@@ -205,63 +141,34 @@ class CommonHandler extends ExceptionHandler
if (strpos($throwable->getMessage(), '500 Error: bad syntax')) {
$code = CommonErrorCode::SERVER_MESSAGE_EMAIL_NOT_FOUND;
}
$data = [
$code_name => $code,
$message_name => CommonErrorCode::getMessage(
$is_testing
? $code
: CommonErrorCode::SERVER_MESSAGE_EMAIL_ERROR
),
];
$data = [$code_name => $code, $message_name => CommonErrorCode::getMessage($is_testing ? $code : CommonErrorCode::SERVER_MESSAGE_EMAIL_ERROR)];
}
if (empty($data)) {
// 其他情况
$data = [
$code_name => $is_testing
? ($throwable->getCode() == 0
? CommonErrorCode::SERVER_ERROR
: $throwable->getCode())
: CommonErrorCode::SERVER_ERROR,
$message_name => $is_testing ? $throwable->getMessage() : __(
CommonErrorCode::getMessage(CommonErrorCode::SERVER_ERROR)
),
];
$data = [$code_name => $is_testing ? $throwable->getCode() == 0 ? CommonErrorCode::SERVER_ERROR : $throwable->getCode() : CommonErrorCode::SERVER_ERROR, $message_name => $is_testing ? $throwable->getMessage() : __(CommonErrorCode::getMessage(CommonErrorCode::SERVER_ERROR))];
// 其他错误
if ($throwable instanceof HttpException) {
$data = [
$code_name => $throwable->getCode() ?: $throwable->getStatusCode(),
$message_name => $throwable->getMessage(),
];
$data = [$code_name => $throwable->getCode() ?: $throwable->getStatusCode(), $message_name => $throwable->getMessage()];
}
}
$response = $response->withHeader(
Header::CONTENT_TYPE,
'application/json; charset=utf-8'
);
$response = $response->withHeader(Header::CONTENT_TYPE, 'application/json; charset=utf-8');
if ($is_debug && $is_testing) {
$data['trace'] = [
'errorType' => $error_type,
'errorTrack' => $throwable->getTrace(),
];
$data['trace'] = ['errorType' => $error_type, 'errorTrack' => $throwable->getTrace()];
}
$cookies = json_encode($this->request->getCookieParams(), JSON_UNESCAPED_UNICODE);
$this->logger->error(
<<<ERROR_LOG
TYPE: $error_type
[$data[$code_name]] $data[$message_name]
TYPE: {$error_type}
[{$data[$code_name]}] {$data[$message_name]}
{$throwable->getMessage()}
-------------------------------
REQUEST_TIME: $request_time
REQUEST_TIME: {$request_time}
-------------------------------
REQUEST_HEADERS:
$request_headers
{$request_headers}
-------------------------------
REQUEST_COOKIES:
$cookies
{$cookies}
-------------------------------
REQUEST_METHOD:
{$this->request?->getMethod()}
@@ -273,7 +180,7 @@ REQUEST_QUERY:
{$this->request?->getQueryString()}
-------------------------------
REQUEST_DATA:
$request_data
{$request_data}
-------------------------------
TRACE:
{$throwable->getTraceAsString()}
@@ -282,21 +189,11 @@ TRACE:
ERROR_LOG
);
$data = Json::encode($data);
if ($restful) {
$response = $response->withStatus(
$status_code ??
$throwable->status ??
$throwable->statusCode ??
RFC7231::INTERNAL_SERVER_ERROR
);
$response = $response->withStatus($status_code ?? $throwable->status ?? $throwable->statusCode ?? RFC7231::INTERNAL_SERVER_ERROR);
}
return $response
->withBody(
new SwooleStream($data)
);
return $response->withBody(new SwooleStream($data));
}
/**
* 判断该异常处理器是否要对该异常进行处理.
*/

View File

@@ -1,4 +1,5 @@
<?php
/**
* ClassicCoreMiddleware.php@hyperf-development-kit
*
@@ -31,89 +32,41 @@ use Singularity\HDK\Core\Service\UtilsService;
class ClassicCoreMiddleware extends CoreMiddleware
{
/**
* @Inject()
* @var \Singularity\HDK\Core\Service\UtilsService
*/
#[Inject]
private UtilsService $utilsService;
/**
* Transfer the non-standard response content to a standard response object.
*
* @param null|array<string, mixed>|Arrayable<string, mixed>|Jsonable|string $response
* @param null|array<string, mixed>|Arrayable|Jsonable|string $response
*/
protected function transferToResponse($response, ServerRequestInterface $request): ResponseInterface
{
$code_name = config('common.response.code_name');
$message_name = config('common.response.message_name');
$data_name = config('common.response.data_name');
// 分页数据
if ($response instanceof LengthAwarePaginatorInterface) {
$paginator = $response;
$fact_response = $this->response()->withHeader('Per-Page', (string)$paginator->perPage())
->withHeader('Total', (string)$paginator->total())
->withHeader('Current-Page', (string)$paginator->currentPage())
->withHeader('Total-Pages', (string)$paginator->hasPages());
$fact_response = $this->response()->withHeader('Per-Page', (string) $paginator->perPage())->withHeader('Total', (string) $paginator->total())->withHeader('Current-Page', (string) $paginator->currentPage())->withHeader('Total-Pages', (string) $paginator->hasPages());
$fact_response = $this->utilsService->extendLinkToHeader($fact_response, $paginator->nextPageUrl(), 'next');
$fact_response = $this->utilsService->extendLinkToHeader(
$fact_response,
$paginator->url($paginator->lastPage()),
'last'
);
$fact_response = $this->utilsService->extendLinkToHeader($fact_response, $paginator->url($paginator->lastPage()), 'last');
$fact_response = $this->utilsService->extendLinkToHeader($fact_response, $paginator->url(1), 'first');
$fact_response = $this->utilsService->extendLinkToHeader(
$fact_response,
$paginator->previousPageUrl(),
'prev'
);
return $fact_response
->withAddedHeader(Header::CONTENT_TYPE, 'application/json')
->withBody(
new SwooleStream(
Json::encode([
$code_name => 200,
$message_name => 'ok',
$data_name => $response->items(),
'meta' => [
'currentPage' => $paginator->currentPage(),
'lastPage' => $paginator->lastPage(),
'perPage' => $paginator->perPage(),
'total' => $paginator->total(),
],
])
)
);
$fact_response = $this->utilsService->extendLinkToHeader($fact_response, $paginator->previousPageUrl(), 'prev');
return $fact_response->withAddedHeader(Header::CONTENT_TYPE, 'application/json')->withBody(new SwooleStream(Json::encode([$code_name => 200, $message_name => 'ok', $data_name => $response->items(), 'meta' => ['currentPage' => $paginator->currentPage(), 'lastPage' => $paginator->lastPage(), 'perPage' => $paginator->perPage(), 'total' => $paginator->total()]])));
}
// 可 Json 化的数据结构
if ($response instanceof Jsonable && $response instanceof Arrayable) {
$response = [
$code_name => 200,
$message_name => 'ok',
$data_name => $response->toArray(),
];
return $this->response()
->withAddedHeader(Header::CONTENT_TYPE, 'application/json')
->withBody(new SwooleStream(Json::encode($response)));
$response = [$code_name => 200, $message_name => 'ok', $data_name => $response->toArray()];
return $this->response()->withAddedHeader(Header::CONTENT_TYPE, 'application/json')->withBody(new SwooleStream(Json::encode($response)));
}
// 普通数组
if (is_array($response) || $response instanceof Arrayable) {
$response = [
$code_name => 200,
$message_name => 'ok',
$data_name => $response,
];
return $this->response()
->withAddedHeader(Header::CONTENT_TYPE, 'application/json')
->withBody(new SwooleStream(Json::encode($response)));
$response = [$code_name => 200, $message_name => 'ok', $data_name => $response];
return $this->response()->withAddedHeader(Header::CONTENT_TYPE, 'application/json')->withBody(new SwooleStream(Json::encode($response)));
}
// 其他默认按字符串处理
return $this->response()
->withAddedHeader(Header::CONTENT_TYPE, 'text/plain')
->withBody(
new SwooleStream((string)$response)
);
return $this->response()->withAddedHeader(Header::CONTENT_TYPE, 'text/plain')->withBody(new SwooleStream((string) $response));
}
}

View File

@@ -15,20 +15,16 @@ use Singularity\HDK\Core\Service\ExtendService;
class ExtendsMiddleware implements MiddlewareInterface
{
/**
* @Inject
* @var \Singularity\HDK\Core\Service\ExtendService
*/
#[Inject]
private ExtendService $service;
/**
* @inheritDoc
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->service->parse($request);
return $handler->handle($request);
}
}

View File

@@ -22,11 +22,10 @@ use Psr\Http\Server\RequestHandlerInterface;
class InternationalizationMiddleware implements MiddlewareInterface
{
/**
* @Inject
* @var TranslatorInterface
*/
#[Inject]
private TranslatorInterface $translator;
/**
* @inheritDoc
*/
@@ -38,14 +37,12 @@ class InternationalizationMiddleware implements MiddlewareInterface
$language = match (strtolower($language)) {
'en', 'en_us', 'en-us', 'en-uk', 'en_uk' => 'en',
'zh', 'zh_cn', 'zh-cn' => 'zh_CN',
default => config('translation.locale')
default => config('translation.locale'),
};
$this->translator->setLocale($language);
$response = $response->withAddedHeader('Content-Language', strtr($this->translator->getLocale(), '_', '-'));
Context::set(ResponseInterface::class, $response);
}
return $handler->handle($request);
}
}