Compare commits

...

10 Commits

Author SHA1 Message Date
ch4o5
50885c57e2 chore(release): 0.2.2 2023-01-13 18:17:21 +00:00
李东云
9f9ff31a83 perf(exceptions.handler): 优化trace显示格式 2023-01-14 02:16:37 +08:00
ch4o5
990c247cf6 chore(release): 0.2.1 2023-01-13 17:32:24 +00:00
李东云
3989f5913e fix(composer): 修复ConfigProvider命名空间 2023-01-14 01:30:23 +08:00
ch4o5
ab44630db8 chore(release): 0.2.1-0 2023-01-13 17:15:17 +00:00
李东云
3bc4e275a7 build(version): 添加changelog配置及脚本 2023-01-14 01:14:53 +08:00
李东云
82e257f7b4 Merge branch 'develop' into 0.2.x 2023-01-14 00:47:41 +08:00
李东云
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
14 changed files with 703 additions and 868 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/phpstan/phpstan" />
<excludeFolder url="file://$MODULE_DIR$/vendor/pestphp/pest-plugin" /> <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/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/spatie/pest-plugin-test-time" />
<excludeFolder url="file://$MODULE_DIR$/vendor/filp/whoops" /> <excludeFolder url="file://$MODULE_DIR$/vendor/filp/whoops" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/deprecations" /> <excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/deprecations" />
<excludeFolder url="file://$MODULE_DIR$/vendor/hyperf/coordinator" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <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/pestphp/pest-plugin" />
<path value="$PROJECT_DIR$/vendor/filp/whoops" /> <path value="$PROJECT_DIR$/vendor/filp/whoops" />
<path value="$PROJECT_DIR$/vendor/nunomaduro/collision" /> <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/test-time" />
<path value="$PROJECT_DIR$/vendor/spatie/pest-plugin-test-time" /> <path value="$PROJECT_DIR$/vendor/spatie/pest-plugin-test-time" />
<path value="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer" /> <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/symfony/stopwatch" />
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan" /> <path value="$PROJECT_DIR$/vendor/phpstan/phpstan" />
<path value="$PROJECT_DIR$/vendor/doctrine/deprecations" /> <path value="$PROJECT_DIR$/vendor/doctrine/deprecations" />
<path value="$PROJECT_DIR$/vendor/hyperf/coordinator" />
</include_path> </include_path>
</component> </component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.0" /> <component name="PhpProjectSharedConfiguration" php_language_level="8.0" />

View File

@@ -30,6 +30,10 @@
"type": "perf", "type": "perf",
"section": "⚡ Performance Improvements | 性能优化" "section": "⚡ Performance Improvements | 性能优化"
}, },
{
"type": "tests",
"section": "✅ Tests | 测试"
},
{ {
"type": "test", "type": "test",
"section": "✅ Tests | 测试" "section": "✅ Tests | 测试"
@@ -53,7 +57,7 @@
], ],
"bumpFiles": [ "bumpFiles": [
{ {
"filename": "MY_VERSION_TRACKER.txt", "filename": "VERSION_TRACKER.txt",
"type": "plain-text" "type": "plain-text"
}, },
{ {

70
CHANGELOG.md Normal file
View File

@@ -0,0 +1,70 @@
# 版本更新日志
### [0.2.2](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/compare/v0.2.1...v0.2.2) (2023-01-13)
### ⚡ Performance Improvements | 性能优化
* **exceptions.handler:** 优化trace显示格式 ([9f9ff31](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/9f9ff31a83ea5662500c688471b78f02ff67eb15))
### 0.2.1 (2023-01-13)
### 🎉 Init | 初始化
* **core:** 初始化代码 ([f564d01](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/f564d01766f52fc57f07aa05bd995a5662c2ae45))
* 初始化项目 ([a13779a](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/a13779ab3fb617189227b9d2c0462588be8ceee5))
### ✅ Tests | 测试
* **oss:** 增加 oss 票据生成的测试文件 ([b5970d5](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/b5970d543435495706502c5b67897ff1cfd5fb85))
* **service:** 添加了base64Wrapper的测试 ([69ce665](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/69ce66561f19e44d35b134c6d032ff69f48201a3))
* **service:** 添加了发送邮件的测试 ([65e3485](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/65e34857e2978a9952ee89df71b1e0c9101ec69c))
* **service:** 添加了解析 extends 的测试 ([da1d6c6](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/da1d6c68d21b2739c8bb1701243e6419eae14975))
### ✨ Features | 新功能
* **utils:** 重写了构造URL的方法增加对应的单元测试 ([9f79d14](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/9f79d1465ba6ed4b4c0d0c30e23ffa34bbeece65))
* 迁移到了 Core 命名空间下 ([a8a582f](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/a8a582f3aa0948c982e31bf8938b6f3331d8dc6d))
### ✏️ Documentation | 文档
* **core:** 添加作者信息 ([096d4e5](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/096d4e56ed30c23de1338bb6f057a91e629c6ea5))
* **README:** 增加说明文件 ([4cf16ae](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/4cf16ae0cdcf6f7a1eb99fde95a6c3ef01bd7b2b))
### ⚡ Performance Improvements | 性能优化
* **utils:** 获取真实IP方法增加apache的处理 ([47e522c](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/47e522c67bf595282df7671f1d045e44593022bf))
### ♻️ Code Refactoring | 代码重构
* **migrate:** 迁移注解以支持hyperf3 ([480f406](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/480f406cccde21f5fb39ba431b6f633c562e5f96))
* **migrate:** 迁移注解以支持hyperf3 ([91db3c7](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/91db3c731f651e178f830953bf97958c5ddc973d))
### 📦‍ Build System | 打包构建
* **ci:** 完善 style-fix/syntax-check/unit-test ([52ff5cc](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/52ff5ccb048d41d003b7e044c446c2f04a013bdb))
* **ci:** 完善 style-fix/syntax-check/unit-test ([4b7f118](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/4b7f1189d33e8871091d05d330ed16fa98048dd9))
* **composer:** update dependencies ([e004ab4](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/e004ab402df9185ead225a3398077f3e39dffe92))
* **composer:** 更新依赖 ([1e4fbe5](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/1e4fbe59276ed2913aa21973f9502505115d2628))
* **composer:** 添加依赖到开发环境 ([9f5699f](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/9f5699f39cd7a89c37e9365322c6082a97a973f4))
* **version:** 添加changelog配置 ([4deffe0](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/4deffe055ebe8586a183103d84dcd5b97969ca7d))
* **version:** 添加changelog配置及脚本 ([3bc4e27](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/3bc4e275a761bf71bb0ca227770b82c3d5ec76bb))
* 迁移到hyperf3 ([9fedbb4](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/9fedbb40f4c9f3221a97986dc7063d049c914728))
### 🚀 Chore | 构建/工程依赖/工具
* **release:** 0.2.1-0 ([ab44630](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/ab44630db8c2d05c21bccdf0899569f911b01473))
* 移除调试用的打印语句 ([37ed1ce](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/37ed1cef77d094f6cd78dd1c97f5d2e3cf6376a3))
* **tests:** 移除了示例测试文件 ([e705bed](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/e705bedd5d3e72887e9e5fac35926237db844116))
### 🐛 Bug Fixes | Bug 修复
* **composer:** 修复ConfigProvider命名空间 ([3989f59](http://124.126.16.154:8888/singularity/HyperfDevelopmentKitCore/commit/3989f5913ea56cba8751afc225c19b8f6730d2c3))

1
VERSION_TRACKER.txt Normal file
View File

@@ -0,0 +1 @@
0.2.2

View File

@@ -5,7 +5,7 @@
"description": "Common Hyperf Development Kit", "description": "Common Hyperf Development Kit",
"extra": { "extra": {
"hyperf": { "hyperf": {
"config": "Singularity\\HDK\\ConfigProvider" "config": "Singularity\\HDK\\Core\\ConfigProvider"
} }
}, },
"authors": [ "authors": [
@@ -20,17 +20,17 @@
"ext-swoole": "*", "ext-swoole": "*",
"composer/composer": ">=2.0", "composer/composer": ">=2.0",
"ergebnis/http-method": "^2.2", "ergebnis/http-method": "^2.2",
"hyperf/config": "^2.2", "hyperf/config": "3.0.*",
"hyperf/constants": "^2.2", "hyperf/constants": "3.0.*",
"hyperf/context": "^2.2", "hyperf/context": "3.0.*",
"hyperf/database": "^2.2", "hyperf/database": "3.0.*",
"hyperf/di": "^2.2", "hyperf/di": "3.0.*",
"hyperf/framework": "^2.2", "hyperf/framework": "3.0.*",
"hyperf/http-server": "^2.2", "hyperf/http-server": "3.0.*",
"hyperf/logger": "^2.2", "hyperf/logger": "3.0.*",
"hyperf/redis": "^2.2", "hyperf/redis": "3.0.*",
"hyperf/resource": "^2.2", "hyperf/resource": "3.0.*",
"hyperf/translation": "^2.2", "hyperf/translation": "3.0.*",
"jetbrains/phpstorm-attributes": "^1.0", "jetbrains/phpstorm-attributes": "^1.0",
"lmc/http-constants": "^1.2", "lmc/http-constants": "^1.2",
"myclabs/php-enum": "^1.8", "myclabs/php-enum": "^1.8",
@@ -43,8 +43,8 @@
"firebase/php-jwt": "^6.1", "firebase/php-jwt": "^6.1",
"friendsofphp/php-cs-fixer": "^3.13", "friendsofphp/php-cs-fixer": "^3.13",
"guzzlehttp/guzzle": "^7.5", "guzzlehttp/guzzle": "^7.5",
"hyperf/session": "^2.2", "hyperf/session": "3.0.*",
"hyperf/validation": "^2.2", "hyperf/validation": "3.0.*",
"pestphp/pest": "^1.22", "pestphp/pest": "^1.22",
"phpstan/phpstan": "^1.9", "phpstan/phpstan": "^1.9",
"phpunit/phpunit": "^9.5", "phpunit/phpunit": "^9.5",
@@ -106,5 +106,6 @@
"type": "composer", "type": "composer",
"url": "https://repo.huaweicloud.com/repository/php/" "url": "https://repo.huaweicloud.com/repository/php/"
} }
} },
"version": "0.2.2"
} }

1110
composer.lock generated

File diff suppressed because it is too large Load Diff

5
scripts/release.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/env sh
docker run --rm -it \
-v $(pwd):/app -e "GIT_AUTHOR_NAME=ch4o5" -e "EMAIL=dongyun.li@luxcreo.ai" \
detouched/standard-version:latest $1

View File

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

View File

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

View File

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

View File

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

View File

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