diff --git a/.idea/HDK-Core.iml b/.idea/HDK-Core.iml
index 67b0141..8e68431 100644
--- a/.idea/HDK-Core.iml
+++ b/.idea/HDK-Core.iml
@@ -136,6 +136,12 @@
+
+
+
+
+
+
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
index aa8a5bb..3dcef58 100644
--- a/.idea/inspectionProfiles/Project_Default.xml
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -2,5 +2,6 @@
+
\ No newline at end of file
diff --git a/.idea/php-test-framework.xml b/.idea/php-test-framework.xml
new file mode 100644
index 0000000..7c50033
--- /dev/null
+++ b/.idea/php-test-framework.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/php.xml b/.idea/php.xml
index c0eecbe..89f0f94 100644
--- a/.idea/php.xml
+++ b/.idea/php.xml
@@ -4,11 +4,20 @@
+
+
+
+
+
+
+
+
+
@@ -142,10 +151,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php
new file mode 100644
index 0000000..1c72787
--- /dev/null
+++ b/.php-cs-fixer.dist.php
@@ -0,0 +1,23 @@
+
+ * Powered by PhpStorm
+ * Created on 2023/1/9
+ */
+
+$finder = PhpCsFixer\Finder::create()->in([
+ __DIR__ . '/publish',
+ __DIR__ . '/src',
+ __DIR__ . '/tests',
+]);
+
+$config = new PhpCsFixer\Config();
+return $config->setRules([
+ '@PSR12' => true,
+ 'strict_param' => true,
+ 'array_syntax' => ['syntax' => 'short'],
+])
+ ->setUsingCache(false)
+ ->setFinder($finder);
diff --git a/composer.json b/composer.json
index a5077ac..b13fedf 100755
--- a/composer.json
+++ b/composer.json
@@ -79,13 +79,13 @@
"prefer-stable": true,
"scripts": {
"post-root-package-install": [],
- "test": "vendor/bin/pest",
- "cs-fix": "vendor/bin/php-cs-fixer fix $1",
- "analyse": "vendor/bin/phpstan analyse -l 0 $1",
+ "test": "vendor/bin/pest $1",
+ "cs-fix": "vendor/bin/php-cs-fixer fix $1 --rules=@PSR12 --allow-risky=yes",
+ "analyse": "vendor/bin/phpstan analyse $1",
"ci": [
- "vendor/bin/pest --ci",
- "@cs-fix .",
"@analyse publish/ src/ tests/",
+ "@cs-fix",
+ "@test --ci",
"echo CI Success"
]
},
diff --git a/phpstan.dist.neon b/phpstan.dist.neon
new file mode 100644
index 0000000..e76ecf2
--- /dev/null
+++ b/phpstan.dist.neon
@@ -0,0 +1,9 @@
+parameters:
+ level: 6
+ paths:
+ - publish
+ - src
+ - tests
+ ignoreErrors:
+ - '#Constant BASE_PATH not found#'
+ - '#Property [a-zA-Z0-9\\_]+::\$[a-zA-Z0-9]+ is never written, only read.#'
\ No newline at end of file
diff --git a/publish/common.php b/publish/common.php
index d7f39b6..2ed121e 100644
--- a/publish/common.php
+++ b/publish/common.php
@@ -17,18 +17,18 @@ return [
'message_name' => 'message', // 错误信息名称
'data_name' => 'data', // 响应数据字段名称
],
-
+
// 鉴权相关
'token' => [
// jwt 必需,否则无效
'jwt' => [
// 过期时间
'expire_time' => 30 * 24 * 60 * 60,
-
+
'private_key' => '', // 用于加密 jwt
'public_key' => '', // 用于解密 jwt
],
-
+
// session 必需,否则无效
'session' => [
// 'expire_time' => null, // 始终为 session 的过期时间
@@ -39,7 +39,7 @@ return [
'prefix_key' => 'token:',
],
],
-
+
// redis 补充配置
'redis' => [
'prefix' => sprintf(
@@ -48,7 +48,7 @@ return [
env('APP_ENV', 'product')
), // 强烈建议按此格式划分
],
-
+
// account http请求配置
'http_request' => [
'account' => [
@@ -56,7 +56,7 @@ return [
'rpc_base_uri' => env('RPC_BASE_URI', ''),
],
],
-
+
// 第三方服务
'third_party' => [
'email' => [
@@ -79,4 +79,4 @@ return [
],
],
],
-];
\ No newline at end of file
+];
diff --git a/publish/languages/en/common_error.php b/publish/languages/en/common_error.php
index 9af1266..e561b00 100644
--- a/publish/languages/en/common_error.php
+++ b/publish/languages/en/common_error.php
@@ -25,7 +25,7 @@ return [
'delete' => 'An internal error is occurred, try again later',
],
],
-
+
// 参数校验
'params' => [
'method' => [
@@ -33,7 +33,7 @@ return [
],
// 参数非法
'format_error' => 'Format error :param',
-
+
// 数据错误
'error' => [
'default' => 'Failed verification',
@@ -75,7 +75,7 @@ return [
],
],
],
-
+
// 鉴权
'auth' => [
'default' => 'Please login',
@@ -120,7 +120,7 @@ return [
'default' => 'Please login',
]
],
-
+
// 服务出错
'server' => [
'cache' => [
@@ -146,7 +146,7 @@ return [
],
],
],
-
+
'not_found' => [
'route' => [
'default' => 'The route does not exist',
diff --git a/publish/languages/zh_CN/common_error.php b/publish/languages/zh_CN/common_error.php
index c640244..a9490ef 100644
--- a/publish/languages/zh_CN/common_error.php
+++ b/publish/languages/zh_CN/common_error.php
@@ -25,7 +25,7 @@ return [
'delete' => '服务器开小差了,稍后再来试试吧',
],
],
-
+
// 参数校验
'params' => [
'method' => [
@@ -33,7 +33,7 @@ return [
],
// 参数非法
'format_error' => '参数 :param 格式错误',
-
+
// 数据错误
'error' => [
'default' => '校验失败',
@@ -77,7 +77,7 @@ return [
],
],
],
-
+
// 鉴权
'auth' => [
'default' => '请先登录',
@@ -129,7 +129,7 @@ return [
'default' => '登录失效,请重新登录',
]
],
-
+
// 服务出错
'server' => [
'cache' => [
@@ -155,7 +155,7 @@ return [
],
],
],
-
+
'not_found' => [
'route' => [
'default' => '当前路由不存在',
diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php
index 5283437..6d71981 100644
--- a/src/ConfigProvider.php
+++ b/src/ConfigProvider.php
@@ -17,8 +17,10 @@ use Hyperf\Framework\Logger\StdoutLogger;
class ConfigProvider
{
+ /** @phpstan-ignore-next-line */
public function __invoke(): array
{
+ /** @noinspection PhpUndefinedConstantInspection */
return [
// 合并到 config/autoload/dependencies.php 文件
'dependencies' => [
diff --git a/src/Constants/CommonErrorCode.php b/src/Constants/CommonErrorCode.php
index e1acdd0..f6a496b 100644
--- a/src/Constants/CommonErrorCode.php
+++ b/src/Constants/CommonErrorCode.php
@@ -23,288 +23,288 @@ use Hyperf\Constants\Annotation\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")
*/
@@ -315,82 +315,82 @@ class CommonErrorCode extends AbstractConstants
* @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")
*/
public const DOCUMENT_NOT_EXISTS = 4020201;
-}
\ No newline at end of file
+}
diff --git a/src/Controller/AbstractController.php b/src/Controller/AbstractController.php
index b336c5b..41eec7b 100644
--- a/src/Controller/AbstractController.php
+++ b/src/Controller/AbstractController.php
@@ -41,7 +41,7 @@ abstract class AbstractController
use DontSerialise;
use DontDeserialise;
use DontToString;
-
+
/**
* @Inject
* @var ContainerInterface
@@ -53,17 +53,16 @@ abstract class AbstractController
* @var RequestInterface
*/
protected RequestInterface $request;
-
+
/**
* @Inject
* @var ResponseInterface
*/
protected ResponseInterface $response;
-
+
/**
* @Inject
* @var \Hyperf\Contract\StdoutLoggerInterface
*/
protected StdoutLoggerInterface $stdoutLogger;
-
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/Authentication.php b/src/Enumerations/Http/Header/Authentication.php
index 4e4acca..17c7a49 100644
--- a/src/Enumerations/Http/Header/Authentication.php
+++ b/src/Enumerations/Http/Header/Authentication.php
@@ -37,4 +37,4 @@ interface Authentication extends
AWS,
SM3
{
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/Extend/SM3.php b/src/Enumerations/Http/Header/Extend/SM3.php
index 79259d0..52128d6 100644
--- a/src/Enumerations/Http/Header/Extend/SM3.php
+++ b/src/Enumerations/Http/Header/Extend/SM3.php
@@ -25,4 +25,4 @@ interface SM3
* @link http://www.sca.gov.cn/sca/xwdt/2010-12/17/1002389/files/302a3ada057c4a73830536d03e683110.pdf SM3密码杂凑算法
*/
public const SCRAM_SM3 = 'SCRAM-SM3';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC4559.php b/src/Enumerations/Http/Header/RFCs/RFC4559.php
index d0ac6d7..9f40304 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC4559.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC4559.php
@@ -22,5 +22,4 @@ interface RFC4559
* @link https://www.ietf.org/rfc/rfc4559.txt RFC 4559
*/
public const NEGOTIATE_NTLM = 'Negotiate';
-
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC6750.php b/src/Enumerations/Http/Header/RFCs/RFC6750.php
index dd64b6e..8045222 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC6750.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC6750.php
@@ -26,4 +26,4 @@ interface RFC6750
* @codingStandardsIgnoreEnd
*/
public const Bearer = 'Bearer';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC7486.php b/src/Enumerations/Http/Header/RFCs/RFC7486.php
index f23a163..7f32ac8 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC7486.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC7486.php
@@ -26,4 +26,4 @@ interface RFC7486
* @codingStandardsIgnoreEnd
*/
public const HOBA = 'HOBA';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC7616.php b/src/Enumerations/Http/Header/RFCs/RFC7616.php
index 67fdba6..92495bd 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC7616.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC7616.php
@@ -31,5 +31,4 @@ interface RFC7616
* @codingStandardsIgnoreStart
*/
public const DIGEST = Header::DIGEST;
-
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC7617.php b/src/Enumerations/Http/Header/RFCs/RFC7617.php
index b9c785b..1c8d931 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC7617.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC7617.php
@@ -26,4 +26,4 @@ interface RFC7617
* @codingStandardsIgnoreEnd
*/
public const BASIC = 'Basic';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC7804.php b/src/Enumerations/Http/Header/RFCs/RFC7804.php
index 4d6b912..e1533a2 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC7804.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC7804.php
@@ -24,4 +24,4 @@ interface RFC7804
* @link https://datatracker.ietf.org/doc/html/rfc7804 RFC 7804
*/
public const SCRAM_SHA_256 = 'SCRAM-SHA-256';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC8120.php b/src/Enumerations/Http/Header/RFCs/RFC8120.php
index 947d9ee..ad86c2a 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC8120.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC8120.php
@@ -22,4 +22,4 @@ interface RFC8120
* @link https://datatracker.ietf.org/doc/html/rfc8120 RFC 8120
*/
public const MUTUAL = 'Mutual';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/RFCs/RFC8292.php b/src/Enumerations/Http/Header/RFCs/RFC8292.php
index 5e2c6d3..3494b2a 100644
--- a/src/Enumerations/Http/Header/RFCs/RFC8292.php
+++ b/src/Enumerations/Http/Header/RFCs/RFC8292.php
@@ -24,4 +24,4 @@ interface RFC8292
* @link https://datatracker.ietf.org/doc/html/rfc8292 RFC 8292
*/
public const VAPID = 'vapid';
-}
\ No newline at end of file
+}
diff --git a/src/Enumerations/Http/Header/Vendor/AWS.php b/src/Enumerations/Http/Header/Vendor/AWS.php
index 3a21fe3..ce4ace1 100644
--- a/src/Enumerations/Http/Header/Vendor/AWS.php
+++ b/src/Enumerations/Http/Header/Vendor/AWS.php
@@ -24,4 +24,4 @@ interface AWS
* @link https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html AWS Doc
*/
public const AWS4_HMAC_SHA256 = 'AWS4-HMAC-SHA256';
-}
\ No newline at end of file
+}
diff --git a/src/Exceptions/DbException.php b/src/Exceptions/DbException.php
index 7804579..7366511 100644
--- a/src/Exceptions/DbException.php
+++ b/src/Exceptions/DbException.php
@@ -29,4 +29,4 @@ class DbException extends HttpException
$previous
);
}
-}
\ No newline at end of file
+}
diff --git a/src/Exceptions/Forbidden.php b/src/Exceptions/Forbidden.php
index ff46eab..76583df 100644
--- a/src/Exceptions/Forbidden.php
+++ b/src/Exceptions/Forbidden.php
@@ -28,4 +28,4 @@ class Forbidden extends HttpException
$previous
);
}
-}
\ No newline at end of file
+}
diff --git a/src/Exceptions/Handler/CommonHandler.php b/src/Exceptions/Handler/CommonHandler.php
index db8f894..a3d676d 100644
--- a/src/Exceptions/Handler/CommonHandler.php
+++ b/src/Exceptions/Handler/CommonHandler.php
@@ -137,7 +137,7 @@ class CommonHandler extends ExceptionHandler
if (is_numeric($data)) {
$code = (int)$data;
- $data = CommonErrorCode::getMessage($data);
+ $data = CommonErrorCode::getMessage($code);
}
$data = [
$code_name => $code ?? CommonErrorCode::REQUEST_PARAMS_ERROR,
@@ -149,9 +149,9 @@ class CommonHandler extends ExceptionHandler
$message = $throwable->getMessage();
$data = [
$code_name => $code,
- $message_name => $message ?? CommonErrorCode::getMessage($code, [
- 'param' => $throwable->getFieldName(),
- ]),
+ $message_name => empty($message) ? CommonErrorCode::getMessage($code, [
+ 'param' => $throwable->getFieldName(),
+ ]) : $message,
];
if ($is_debug) {
$data['currentValue'] = $throwable->getCurrentValue();
@@ -231,7 +231,7 @@ class CommonHandler extends ExceptionHandler
// 其他错误
if ($throwable instanceof HttpException) {
$data = [
- $code_name => $throwable->getCode() ?? $throwable->getStatusCode(),
+ $code_name => $throwable->getCode() ?: $throwable->getStatusCode(),
$message_name => $throwable->getMessage(),
];
}
diff --git a/src/Exceptions/ThirdPartyException.php b/src/Exceptions/ThirdPartyException.php
index e34341e..a45b93d 100644
--- a/src/Exceptions/ThirdPartyException.php
+++ b/src/Exceptions/ThirdPartyException.php
@@ -6,5 +6,4 @@ use Hyperf\Server\Exception\ServerException;
class ThirdPartyException extends ServerException
{
-
}
diff --git a/src/Exceptions/Unauthorized.php b/src/Exceptions/Unauthorized.php
index f681a6b..781f339 100644
--- a/src/Exceptions/Unauthorized.php
+++ b/src/Exceptions/Unauthorized.php
@@ -22,7 +22,7 @@ class Unauthorized extends HttpException
$previous_code = $previous?->getCode();
$code = empty($previous_code) ? $code : $previous_code;
}
-
+
parent::__construct(
RFC7235::UNAUTHORIZED,
CommonErrorCode::getMessage($code),
@@ -30,9 +30,9 @@ class Unauthorized extends HttpException
$previous
);
}
-
+
public function getAuthenticationType(): string
{
return $this->authenticationType;
}
-}
\ No newline at end of file
+}
diff --git a/src/Exceptions/ValidateException.php b/src/Exceptions/ValidateException.php
index 1136fc6..fbcc8dc 100644
--- a/src/Exceptions/ValidateException.php
+++ b/src/Exceptions/ValidateException.php
@@ -12,6 +12,14 @@ use Throwable;
*/
class ValidateException extends HttpException
{
+ /**
+ * @param int $code
+ * @param string|null $message
+ * @param string $field
+ * @param mixed|null $currentValue
+ * @param array $availableValue
+ * @param Throwable|null $previous
+ */
public function __construct(
int $code = CommonErrorCode::FORMATTER_ERROR,
?string $message = null,
@@ -37,12 +45,12 @@ class ValidateException extends HttpException
$previous
);
}
-
+
public function getFieldName(): string
{
return $this->field;
}
-
+
/**
* @return mixed
*/
@@ -50,12 +58,12 @@ class ValidateException extends HttpException
{
return $this->currentValue;
}
-
+
/**
- * @return array
+ * @return array
*/
public function getAvailableValue(): array
{
return $this->availableValue;
}
-}
\ No newline at end of file
+}
diff --git a/src/Middleware/ClassicCoreMiddleware.php b/src/Middleware/ClassicCoreMiddleware.php
index eec8777..dcfe305 100644
--- a/src/Middleware/ClassicCoreMiddleware.php
+++ b/src/Middleware/ClassicCoreMiddleware.php
@@ -35,26 +35,26 @@ class ClassicCoreMiddleware extends CoreMiddleware
* @var \Singularity\HDK\Core\Service\UtilsService
*/
private UtilsService $utilsService;
-
+
/**
* Transfer the non-standard response content to a standard response object.
*
- * @param null|array|Arrayable|Jsonable|string $response
+ * @param null|array|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', $paginator->perPage())
- ->withHeader('Total', $paginator->total())
- ->withHeader('Current-Page', $paginator->currentPage())
- ->withHeader('Total-Pages', $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,
@@ -86,7 +86,7 @@ class ClassicCoreMiddleware extends CoreMiddleware
);
}
// 可 Json 化的数据结构
- if ($response instanceof Jsonable) {
+ if ($response instanceof Jsonable && $response instanceof Arrayable) {
$response = [
$code_name => 200,
$message_name => 'ok',
@@ -96,7 +96,7 @@ class ClassicCoreMiddleware extends CoreMiddleware
->withAddedHeader(Header::CONTENT_TYPE, 'application/json')
->withBody(new SwooleStream(Json::encode($response)));
}
-
+
// 普通数组
if (is_array($response) || $response instanceof Arrayable) {
$response = [
@@ -108,7 +108,7 @@ class ClassicCoreMiddleware extends CoreMiddleware
->withAddedHeader(Header::CONTENT_TYPE, 'application/json')
->withBody(new SwooleStream(Json::encode($response)));
}
-
+
// 其他默认按字符串处理
return $this->response()
->withAddedHeader(Header::CONTENT_TYPE, 'text/plain')
@@ -116,4 +116,4 @@ class ClassicCoreMiddleware extends CoreMiddleware
new SwooleStream((string)$response)
);
}
-}
\ No newline at end of file
+}
diff --git a/src/Middleware/CorsMiddleware.php b/src/Middleware/CorsMiddleware.php
index 319f246..0e5faaa 100644
--- a/src/Middleware/CorsMiddleware.php
+++ b/src/Middleware/CorsMiddleware.php
@@ -35,7 +35,7 @@ class CorsMiddleware implements MiddlewareInterface, Method
$response = $response
->withHeader(
Header::ACCESS_CONTROL_ALLOW_ORIGIN,
- $request->getHeaderLine('Origin') ?? '',
+ $request->getHeaderLine('Origin'),
)
->withHeader(Header::ACCESS_CONTROL_ALLOW_CREDENTIALS, 'true')
->withHeader(
@@ -74,13 +74,13 @@ class CorsMiddleware implements MiddlewareInterface, Method
Header::WWW_AUTHENTICATE,
])
);
-
+
Context::set(ResponseInterface::class, $response);
-
+
if ($request->getMethod() == self::OPTIONS) {
return $response;
}
-
+
return $handler->handle($request);
}
-}
\ No newline at end of file
+}
diff --git a/src/Middleware/ExtendsMiddleware.php b/src/Middleware/ExtendsMiddleware.php
index 540d77a..0612fb6 100644
--- a/src/Middleware/ExtendsMiddleware.php
+++ b/src/Middleware/ExtendsMiddleware.php
@@ -19,7 +19,7 @@ class ExtendsMiddleware implements MiddlewareInterface
* @var \Singularity\HDK\Core\Service\ExtendService
*/
private ExtendService $service;
-
+
/**
* @inheritDoc
*/
@@ -28,7 +28,7 @@ class ExtendsMiddleware implements MiddlewareInterface
RequestHandlerInterface $handler
): ResponseInterface {
$this->service->parse($request);
-
+
return $handler->handle($request);
}
-}
\ No newline at end of file
+}
diff --git a/src/Middleware/InternationalizationMiddleware.php b/src/Middleware/InternationalizationMiddleware.php
index 75da92e..edd43cb 100644
--- a/src/Middleware/InternationalizationMiddleware.php
+++ b/src/Middleware/InternationalizationMiddleware.php
@@ -26,7 +26,7 @@ class InternationalizationMiddleware implements MiddlewareInterface
* @var TranslatorInterface
*/
private TranslatorInterface $translator;
-
+
/**
* @inheritDoc
*/
@@ -41,11 +41,11 @@ class InternationalizationMiddleware implements MiddlewareInterface
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);
}
-}
\ No newline at end of file
+}
diff --git a/src/Resource/ClassicResponse.php b/src/Resource/ClassicResponse.php
index 4ce9005..8e158c7 100644
--- a/src/Resource/ClassicResponse.php
+++ b/src/Resource/ClassicResponse.php
@@ -26,4 +26,4 @@ trait ClassicResponse
'message' => 'ok',
];
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/Base64Wrapper.php b/src/Service/Base64Wrapper.php
index b5f14fc..5de8bae 100644
--- a/src/Service/Base64Wrapper.php
+++ b/src/Service/Base64Wrapper.php
@@ -14,10 +14,10 @@ class Base64Wrapper
$base64String = strtr($base64String, '+', '-');
return strtr($base64String, '/', '_');
}
-
+
public function decode(string $decoder): string
{
$origin_string = strtr($decoder, '_', '/');
return strtr($origin_string, '-', '+');
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/EmailService.php b/src/Service/EmailService.php
index 4c239c5..6dc4ff9 100644
--- a/src/Service/EmailService.php
+++ b/src/Service/EmailService.php
@@ -12,6 +12,7 @@ declare(strict_types=1);
namespace Singularity\HDK\Core\Service;
use JetBrains\PhpStorm\Deprecated;
+use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Address;
@@ -23,22 +24,25 @@ use Symfony\Component\Mime\Email;
class EmailService
{
private Mailer $mailer;
-
+
private string $from;
-
- public function __construct($dsn = null, $mailSenderName = null, $mailSender = null)
- {
+
+ public function __construct(
+ ?string $dsn = null,
+ ?string $mailSenderName = null,
+ ?string $mailSender = null
+ ) {
$dsn ??= config('common.third_party.email.dsn');
$transport = Transport::fromDsn($dsn);
$this->mailer = new Mailer($transport);
-
+
$this->from = sprintf(
"%s <%s>",
$mailSenderName ?? config('common.third_party.email.mailer_sender_name'),
$mailSender ?? config('common.third_party.email.mailer_sender')
);
}
-
+
/**
* 发送邮件
*
@@ -47,9 +51,9 @@ class EmailService
* @param string $text
*
* @return bool
- * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
- * @see \Singularity\HDK\Core\Service\EmailService::sendText()
- * @see \Singularity\HDK\Core\Service\EmailService::sendHtml()
+ * @throws TransportExceptionInterface
+ * @see EmailService::sendText
+ * @see EmailService::sendHtml
*/
#[Deprecated]
public function sendCode(
@@ -59,15 +63,15 @@ class EmailService
): bool {
return $this->sendText($target, $subject, $text);
}
-
+
/**
- * @param string|array $target
- * @param string $subject
- * @param string $text
- * @param array $cc
+ * @param string|array $target
+ * @param string $subject
+ * @param string $text
+ * @param array $cc
*
* @return bool
- * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
+ * @throws TransportExceptionInterface
*/
public function sendText(
string|array $target,
@@ -81,22 +85,22 @@ class EmailService
->cc(...$cc)
->subject($subject)
->text($text);
-
+
$this->mailer->send($email);
-
+
return true;
}
-
+
/**
* 以 HTML 格式发送邮件
*
- * @param string|array $target
- * @param string $subject
- * @param string $html
- * @param array $cc
+ * @param string|array $target
+ * @param string $subject
+ * @param string $html
+ * @param array $cc
*
* @return bool
- * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
+ * @throws TransportExceptionInterface
*/
public function sendHtml(
string|array $target,
@@ -110,9 +114,9 @@ class EmailService
->cc(...$cc)
->subject($subject)
->html($html);
-
+
$this->mailer->send($email);
-
+
return true;
}
}
diff --git a/src/Service/ExtendService.php b/src/Service/ExtendService.php
index 8b4c9aa..3c290f1 100644
--- a/src/Service/ExtendService.php
+++ b/src/Service/ExtendService.php
@@ -11,8 +11,8 @@ use Psr\Http\Message\ServerRequestInterface;
class ExtendService
{
/**
- * @param \Psr\Http\Message\ServerRequestInterface $request
- *
+ * @param ServerRequestInterface|null $request
+ * @param array|null $params
* @return string[]
*/
public function parse(
@@ -30,7 +30,7 @@ class ExtendService
}
/**
- * @return array
+ * @return array
*/
public function getExtends(): array
{
@@ -48,4 +48,4 @@ class ExtendService
{
return Context::has(self::class) && isset(array_flip(Context::get(self::class))[$field]);
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/HttpRequestService.php b/src/Service/HttpRequestService.php
deleted file mode 100644
index fee0db4..0000000
--- a/src/Service/HttpRequestService.php
+++ /dev/null
@@ -1,86 +0,0 @@
- 20,
- 'headers' => $headers
- ];
- if (!empty($base_uri)) {
- $options['base_uri'] = $base_uri;
- }
- if (!empty($cookie)) {
- $options['cookies'] = CookieJar::fromArray(
- [
- $this->cookie['key'] => $this->cookie['value']
- ],
- parse_url($base_uri)['host']
- );
- }
-
- $this->client = new Client($options);
- }
-
- protected function get($uri, $params = [])
- {
- return $this->bar($uri, $params);
- }
-
- protected function post($uri, $params = [])
- {
- return $this->bar($uri, $params, 'post');
- }
-
- protected function put($uri, $params = [])
- {
- return $this->bar($uri, $params, 'put');
- }
-
- protected function delete($uri, $params = [])
- {
- return $this->bar($uri, $params, 'delete');
- }
-
- protected function patch($uri, $params = [])
- {
- return $this->bar($uri, $params, 'patch');
- }
-
- private function bar($uri, $params = [], $method = 'get')
- {
-
- try {
- $http = $this->client->{$method}($uri, ['json' => $params]);
- $result = $this->jsonToArray($http);
- } catch (ClientException|ServerException $e) {
- $response = $e->getResponse();
- $result = $this->jsonToArray($response);
- $result['httpCode'] = $response->getStatusCode();
- }
-
- return $result;
- }
-
- private function jsonToArray($http)
- {
- return json_decode($http->getBody()->getContents(), true);
- }
-}
\ No newline at end of file
diff --git a/src/Service/OssService.php b/src/Service/OssService.php
index 8fe91d1..e0b2cb2 100644
--- a/src/Service/OssService.php
+++ b/src/Service/OssService.php
@@ -14,38 +14,49 @@ use Hyperf\Utils\Codec\Json;
class OssService
{
/**
- * @const 30s 过期
+ * @param string|null $accessKeyId 不传则取配置文件
+ * @param string|null $accessKeySecret 不传则取配置文件
+ * @param string|null $host 不传则取配置文件
+ * @param int|null $expiration 过期时间,默认30s
*/
- public const EXPIRE = 30;
-
- protected string $accessKeyId;
- protected string $accessKeySecret;
- protected string $host;
-
- public function __construct()
- {
- $this->accessKeyId = config('common.third_party.storage.oss.access_key_id');
- $this->accessKeySecret = config('common.third_party.storage.oss.access_key_secret');
- $this->host = config('common.third_party.storage.oss.oss_host');
+ public function __construct(
+ public ?string $accessKeyId = null,
+ public ?string $accessKeySecret = null,
+ public ?string $host = null,
+ public ?string $callbackUrl = null,
+ public ?int $expiration = 30
+ ) {
+ $this->accessKeyId ??= config('common.third_party.storage.oss.access_key_id');
+ $this->accessKeySecret ??= config('common.third_party.storage.oss.access_key_secret');
+ $this->host ??= config('common.third_party.storage.oss.oss_host');
+ $this->callbackUrl ??= config('oss_callback');
}
-
+
/**
* 生成签证
*
* @param string|null $dir
- * @param bool $isImage
- * @param int $maxFileSize 最大文件大小(单位:b)
+ * @param bool $isImage
+ * @param int $maxFileSize 最大文件大小(单位:b)
*
- * @return array
+ * @return array{
+ * 'accessid' : string,
+ * 'host' : string,
+ * 'policy': string,
+ * 'signature': string,
+ * 'expire' : int,
+ * 'dir' : string,
+ * 'callback':string
+ * }
*/
public function generatePolicy(
string $dir = null,
bool $isImage = false,
int $maxFileSize = 1048576000
): array {
- $expire_time = time() + self::EXPIRE;
+ $expire_time = time() + $this->expiration;
$expiration = $this->gmtIso8601($expire_time);
-
+
//最大文件大小.用户可以自己设置
$condition = [
0 => 'Content-Length-Range',
@@ -53,7 +64,7 @@ class OssService
2 => $maxFileSize,
];
$conditions[] = $condition;
-
+
// 表示用户上传的数据,必须是以$dir开始,不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录。
if ($dir) {
$start = [
@@ -63,8 +74,8 @@ class OssService
];
$conditions[] = $start;
}
-
-
+
+
$policy = Json::encode([
'expiration' => $expiration,
'conditions' => $conditions,
@@ -72,9 +83,9 @@ class OssService
$base64_policy = base64_encode($policy);
$string_to_sign = $base64_policy;
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->accessKeySecret, true));
-
+
$callback = Json::encode([
- 'callbackUrl' => config('oss_callback'),
+ 'callbackUrl' => $this->callbackUrl,
'callbackBody' => $isImage ? <<<'callbackBody'
{
"bucket": ${bucket},
@@ -91,7 +102,7 @@ class OssService
"name": ${x:name},
"hash": ${x:hash}
}
-callbackBody: <<<'callbackBody'
+callbackBody : <<<'callbackBody'
{
"bucket": ${bucket},
"object": ${object},
@@ -105,7 +116,7 @@ callbackBody: <<<'callbackBody'
callbackBody,
'callbackBodyType' => 'application/json',
]);
-
+
return [
'accessid' => $this->accessKeyId,
'host' => $this->host,
@@ -116,7 +127,7 @@ callbackBody,
'callback' => base64_encode($callback),
];
}
-
+
/**
* 将时间戳转化为 ISO8601 格式
*
@@ -128,4 +139,4 @@ callbackBody,
{
return str_replace('+00:00', '.000Z', gmdate('c', $time));
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/SmsService.php b/src/Service/SmsService.php
index 1d0c585..d4ca128 100644
--- a/src/Service/SmsService.php
+++ b/src/Service/SmsService.php
@@ -20,12 +20,12 @@ class SmsService
* @var \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi
*/
private Dysmsapi $client;
-
+
public function __construct()
{
$this->client = $this->createClient();
}
-
+
/**
* 初始化实例
*
@@ -40,13 +40,13 @@ class SmsService
$config->accessKeySecret = config('common.third_party.sms.aliyun.access_key_secret');
return new Dysmsapi($config);
}
-
+
/**
* 国内短信
*
* @param string $phone 接收短信的手机号码
* @param string|null $templateCode 短信模板CODE
- * @param array|null $templateParam 短信模板变量对应的实际值(不支持空数组)
+ * @param array|null $templateParam 短信模板变量对应的实际值(不支持空数组)
* @param string|null $signName 短信签名名称
*
* @return bool
@@ -62,7 +62,7 @@ class SmsService
throw new \UnexpectedValueException('不支持空数组,请用 null 代替或不传', CommonErrorCode::FORMATTER_ERROR);
}
$phone_number = strtr($phone, ['#' => '']);
-
+
$sendSmsRequest = new SendSmsRequest(
[
"signName" => $signName ?? config('common.third_party.sms.aliyun.sign_name'),
@@ -71,10 +71,10 @@ class SmsService
"templateParam" => Json::encode($templateParam),
]
);
-
+
try {
$response = $this->client->sendSms($sendSmsRequest);
-
+
$response_code = $response->body->code;
$message = $response->body->message;
if ($response_code !== 'OK') {
@@ -83,10 +83,10 @@ class SmsService
} catch (TeaError $error) {
$data = $error->getErrorInfo();
$data = $data['data'] ?? $data['body'];
-
+
$code = $data['Code'];
$message = $data['Message'];
-
+
// 频率太高
if ($code === 'isv.BUSINESS_LIMIT_CONTROL') {
$error_code = match (mb_substr($message, 2, 2)) {
@@ -95,12 +95,12 @@ class SmsService
'分钟' => CommonErrorCode::REQUEST_PARAMS_ERROR_CODE_MAX_TIMES_MINUTE,
default => null
};
-
+
if (isset($error_code)) {
throw new ValidateException($error_code);
}
}
-
+
throw new HttpException(
500,
$message,
@@ -108,7 +108,7 @@ class SmsService
$error
);
}
-
+
return true;
}
}
diff --git a/src/Service/UtilsService.php b/src/Service/UtilsService.php
index dc910c3..2a6f253 100644
--- a/src/Service/UtilsService.php
+++ b/src/Service/UtilsService.php
@@ -10,7 +10,6 @@ use Generator;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
-use JetBrains\PhpStorm\ArrayShape;
use JetBrains\PhpStorm\Pure;
use Psr\Http\Message\ResponseInterface;
@@ -21,16 +20,16 @@ class UtilsService
{
/**
* @Inject
- * @var \Hyperf\HttpServer\Contract\RequestInterface
+ * @var RequestInterface
*/
private RequestInterface $request;
-
+
/**
* @Inject()
- * @var \Hyperf\Contract\StdoutLoggerInterface
+ * @var StdoutLoggerInterface
*/
private StdoutLoggerInterface $logger;
-
+
/**
* 生成验证码
*
@@ -46,32 +45,32 @@ class UtilsService
}
return $code;
}
-
+
public function getRealIpAddress(): string
{
$ip = $this->request->server('remote_addr');
if (empty($ip) or in_array(
- $ip,
- [
- 'localhost',
- '127.0.0.1',
- ]
- )) {
+ $ip,
+ [
+ 'localhost',
+ '127.0.0.1',
+ ]
+ )) {
$ip = $this->request->header('x-real-ip');
}
return $ip ?? 'unknown';
}
-
+
/**
* 在响应头中添加 Link 字段
*
- * @param \Psr\Http\Message\ResponseInterface $response
- * @param string|null $urlReference
- * @param string $rel
- * @param array $params
- * @param bool $trimQuote
+ * @param ResponseInterface $response
+ * @param string|null $urlReference
+ * @param string $rel
+ * @param array $params
+ * @param bool $trimQuote
*
- * @return \Psr\Http\Message\ResponseInterface
+ * @return ResponseInterface
*/
public function extendLinkToHeader(
ResponseInterface $response,
@@ -83,14 +82,14 @@ class UtilsService
if (is_null($urlReference)) {
return $response;
}
-
+
$params['rel'] = $rel;
if (!$trimQuote) {
foreach ($params as &$value) {
- $value = '"' . trim($value, '"') . '"';
+ $value = sprintf("\"%s\"", trim($value, '"'));
}
}
-
+
$link_list = [];
if ($response->hasHeader('Link')) {
$link = $response->getHeaderLine('Link');
@@ -98,64 +97,68 @@ class UtilsService
$link_list = array_map('trim', $link_list);
}
$link_list[] = "<$urlReference>; " . http_build_query($params, '', '; ');
-
+
return $response->withHeader(
'Link',
join(',', $link_list)
);
}
-
+
/**
* 构建 URL
*
* @param string $url
- * @param array $params
+ * @param array $params
*
* @return string
*/
public function buildUrl(string $url, array $params = []): string
{
$url_info = parse_url($url);
- $base_url = str_replace(('?' . $url_info['query'] ?? ''), '', $url);
+ $base_url = str_replace('?' . $url_info['query'], '', $url);
parse_str($url_info['query'], $origin_params);
$origin_params += $params;
-
+
return $base_url . '?' . http_build_query($origin_params);
}
-
+
/**
* 以迭代器的形式响应
*
* @param string $fullName
*
- * @return \Generator
- * @throws \Exception
+ * @return Generator
+ * @throws Exception
*/
public function csvReaderGenerator(string $fullName): Generator
{
if (!is_file($fullName)) {
throw new Exception('指定的 csv 文件不存在');
}
-
+
$file = fopen($fullName, 'r');
while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
yield $data;
}
-
+
fclose($file);
}
-
+
/**
* 以数组形式响应
*
- * @throws \Exception
+ * @param string $fullName
+ * @param array $headers
+ * @param int|null $batchNumber
+ * @return array
+ * @throws Exception
*/
public function csvReader(string $fullName, array $headers = [], ?int $batchNumber = null): array
{
if (!is_file($fullName)) {
throw new Exception($fullName . ' 不存在');
}
-
+
$file = fopen($fullName, 'r');
$result = [];
$row_number = 0;
@@ -171,20 +174,20 @@ class UtilsService
$result[] = $data;
}
}
-
+
fclose($file);
return $result;
}
-
+
/**
* (level倒序)快速无极分类(时间复杂度 O(n),空间复杂度 O(1))
* 条件:数组索引是数据parent_id对应的id,只支持level倒序
*
- * @param array $list
- * @param int $level
- * @param string $parentIdName
- * @param string $childrenName
- * @param \Closure|null $filterCallback
+ * @param array $list
+ * @param int $level
+ * @param string $parentIdName
+ * @param string $childrenName
+ * @param Closure|null $filterCallback
*
* @return void
*/
@@ -203,7 +206,7 @@ class UtilsService
if (!isset($item[$parentIdName])) {
break;
}
-
+
unset($list[$i]);
$item = isset($filterCallback) ? $filterCallback($item) : $item;
//判定非顶级的pid是否存在,如果存在,则再pid所在的数组下面加入一个字段items,来将本身存进去
@@ -211,7 +214,7 @@ class UtilsService
$list[$item[$parentIdName]][$childrenName][] = $item;
continue;
}
-
+
//取出顶级
if ($item['level'] === $level) {
$list[$childrenName][] = $item;
@@ -220,25 +223,22 @@ class UtilsService
$list = $list[$childrenName];
$end_time = microtime(true);
$this->logger->debug("快速无极分类循环{$current_times}次,数组元素数量$max_times");
-
+
$cost_time = ($end_time - $start_time) * 1000;
$this->logger->debug("快速无极分类用时{$cost_time}ms");
}
-
-
+
+
/**
* 将内存/硬盘大小转化为带单位大小
*
- * @param float|int|string $size 空间大小(单位:Byte)
- * @param bool $unitToUpper 单位转换为大写(默认 false)
- * @param int $precision 小数点后保留的位数(默认 2)
+ * @param float|int|string $size 空间大小(单位:Byte)
+ * @param bool $unitToUpper 单位转换为大写(默认 false)
+ * @param int $precision 小数点后保留的位数(默认 2)
*
- * @return array
+ * @return array{'size': float, 'unit': string}
*/
- #[
- ArrayShape(['size' => 'float', 'unit' => 'string']),
- Pure
- ]
+ #[Pure]
public function convertStorageSize(
float|int|string $size,
bool $unitToUpper = false,
@@ -257,23 +257,18 @@ class UtilsService
'unit' => $unitToUpper ? strtoupper($unit[$i]) : $unit[$i],
];
}
-
+
/**
* 将时长转换为带单位时间
*
* @param int|float $duration 时长(单位:ms)
- * @param bool $unitToUpper
- * @param bool $format
- * @param integer $precision
+ * @param bool $unitToUpper
+ * @param bool $format
+ * @param integer $precision
*
- * @return array
+ * @return array{'duration': float, 'unit': string}
*/
- #[
- ArrayShape([
- 'duration' => 'float',
- 'unit' => 'string',
- ])
- ]
+ #[Pure]
public function convertDuration(
int|float $duration,
bool $unitToUpper = false,
@@ -281,7 +276,7 @@ class UtilsService
int $precision = 3
): array {
$unit = ['ms', 's'];
-
+
if ($duration > 1) {
$i = floor(log($duration, 1000));
$duration = round($duration / pow(1000, $i), $precision);
@@ -296,4 +291,4 @@ class UtilsService
'unit' => $unitToUpper ? strtoupper($unit[$i]) : $unit[$i],
];
}
-}
\ No newline at end of file
+}
diff --git a/tests/Pest.php b/tests/Pest.php
index c316d3e..e86fb45 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -24,7 +24,7 @@
|
*/
-function something()
+/*function something()
{
// ..
-}
+}*/
diff --git a/tests/Unit/Base64WrapperTest.php b/tests/Unit/Base64WrapperTest.php
index 09ab878..a11b4c5 100644
--- a/tests/Unit/Base64WrapperTest.php
+++ b/tests/Unit/Base64WrapperTest.php
@@ -12,7 +12,7 @@ namespace Singularity\HDK\Test\Core\Unit;
use Singularity\HDK\Core\Service\Base64Wrapper;
use PHPUnit\Framework\TestCase;
-it('assertions base64 wrapper ENCODE', function(string $source, string $expected) {
+it('assertions base64 wrapper ENCODE', function (string $source, string $expected) {
$encoded = (new Base64Wrapper())->encode($source);
expect($expected)->toBe($encoded);
@@ -22,7 +22,7 @@ it('assertions base64 wrapper ENCODE', function(string $source, string $expected
['YWJ/+j', 'YWJ_-j']
]);
-it('assertions base64 wrapper DECODE', function(string $source, string $expected) {
+it('assertions base64 wrapper DECODE', function (string $source, string $expected) {
$decoded = (new Base64Wrapper())->decode($source);
expect($expected)->toBe($decoded);
diff --git a/tests/Unit/EmailServiceTest.php b/tests/Unit/EmailServiceTest.php
index 4232dc3..004a063 100644
--- a/tests/Unit/EmailServiceTest.php
+++ b/tests/Unit/EmailServiceTest.php
@@ -26,7 +26,7 @@ it('assertions that send HTML is available', function () use ($email) {
HTML
);
expect($result)->toBeTrue();
-})->skip();
+});
it('assertions that send Text is available', function () use ($email) {
$result = $email->sendText(
@@ -37,7 +37,7 @@ it('assertions that send Text is available', function () use ($email) {
Text
);
expect($result)->toBeTrue();
-})->skip();
+});
it('assertions Error Receiver can be catch', function () use ($email) {
try {