build(ci): 完善 style-fix/syntax-check/unit-test

This commit is contained in:
李东云
2023-01-09 18:22:10 +08:00
parent 4b7f1189d3
commit 52ff5ccb04
45 changed files with 392 additions and 388 deletions

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

@@ -136,6 +136,12 @@
<excludeFolder url="file://$MODULE_DIR$/vendor/filp/whoops" />
<excludeFolder url="file://$MODULE_DIR$/vendor/nunomaduro/collision" />
<excludeFolder url="file://$MODULE_DIR$/vendor/facade/ignition-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/spatie/test-time" />
<excludeFolder url="file://$MODULE_DIR$/vendor/spatie/pest-plugin-test-time" />
<excludeFolder url="file://$MODULE_DIR$/vendor/friendsofphp/php-cs-fixer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/options-resolver" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/stopwatch" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpstan/phpstan" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />

View File

@@ -2,5 +2,6 @@
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PhpPropertyOnlyWrittenInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="PhpStanGlobal" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>

14
.idea/php-test-framework.xml generated Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PhpTestFrameworkSettings">
<test_tools>
<tool tool_name="Pest">
<settings>
<configurations>
<local_configuration configuration_file_path="$PROJECT_DIR$/phpunit.xml" executable_path="$PROJECT_DIR$/vendor/pestphp/pest/bin/pest" use_configuration_file="true" />
</configurations>
</settings>
</tool>
</test_tools>
</component>
</project>

21
.idea/php.xml generated
View File

@@ -4,11 +4,20 @@
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="allowRiskyRules" value="true" />
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PhpCSFixer">
<phpcsfixer_settings>
<PhpCSFixerConfiguration standards="PSR1;PSR2;Symfony;DoctrineAnnotation;PHP70Migration;PHP71Migration" tool_path="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer/php-cs-fixer" />
</phpcsfixer_settings>
</component>
<component name="PhpExternalFormatter">
<option name="externalFormatter" value="PHP_CBF" />
</component>
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
@@ -142,10 +151,22 @@
<path value="$PROJECT_DIR$/vendor/filp/whoops" />
<path value="$PROJECT_DIR$/vendor/nunomaduro/collision" />
<path value="$PROJECT_DIR$/vendor/facade/ignition-contracts" />
<path value="$PROJECT_DIR$/vendor/spatie/test-time" />
<path value="$PROJECT_DIR$/vendor/spatie/pest-plugin-test-time" />
<path value="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer" />
<path value="$PROJECT_DIR$/vendor/symfony/options-resolver" />
<path value="$PROJECT_DIR$/vendor/symfony/stopwatch" />
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.0" />
<component name="PhpStan">
<PhpStan_settings>
<PhpStanConfiguration tool_path="$PROJECT_DIR$/vendor/bin/phpstan" />
</PhpStan_settings>
</component>
<component name="PhpStanOptionsConfiguration">
<option name="memoryLimit" value="300M" />
<option name="transferred" value="true" />
</component>
<component name="PhpUnit">

23
.php-cs-fixer.dist.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
/**
* .php-cs-fixer.dist.php@HDK-Core
*
* @author 李东云 <Dongyun.Li@LuxCreo.Ai>
* 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);

View File

@@ -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"
]
},

9
phpstan.dist.neon Normal file
View File

@@ -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.#'

View File

@@ -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 [
],
],
],
];
];

View File

@@ -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',

View File

@@ -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' => '当前路由不存在',

View File

@@ -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' => [

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -37,4 +37,4 @@ interface Authentication extends
AWS,
SM3
{
}
}

View File

@@ -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';
}
}

View File

@@ -22,5 +22,4 @@ interface RFC4559
* @link https://www.ietf.org/rfc/rfc4559.txt RFC 4559
*/
public const NEGOTIATE_NTLM = 'Negotiate';
}
}

View File

@@ -26,4 +26,4 @@ interface RFC6750
* @codingStandardsIgnoreEnd
*/
public const Bearer = 'Bearer';
}
}

View File

@@ -26,4 +26,4 @@ interface RFC7486
* @codingStandardsIgnoreEnd
*/
public const HOBA = 'HOBA';
}
}

View File

@@ -31,5 +31,4 @@ interface RFC7616
* @codingStandardsIgnoreStart
*/
public const DIGEST = Header::DIGEST;
}
}

View File

@@ -26,4 +26,4 @@ interface RFC7617
* @codingStandardsIgnoreEnd
*/
public const BASIC = 'Basic';
}
}

View File

@@ -24,4 +24,4 @@ interface RFC7804
* @link https://datatracker.ietf.org/doc/html/rfc7804 RFC 7804
*/
public const SCRAM_SHA_256 = 'SCRAM-SHA-256';
}
}

View File

@@ -22,4 +22,4 @@ interface RFC8120
* @link https://datatracker.ietf.org/doc/html/rfc8120 RFC 8120
*/
public const MUTUAL = 'Mutual';
}
}

View File

@@ -24,4 +24,4 @@ interface RFC8292
* @link https://datatracker.ietf.org/doc/html/rfc8292 RFC 8292
*/
public const VAPID = 'vapid';
}
}

View File

@@ -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';
}
}

View File

@@ -29,4 +29,4 @@ class DbException extends HttpException
$previous
);
}
}
}

View File

@@ -28,4 +28,4 @@ class Forbidden extends HttpException
$previous
);
}
}
}

View File

@@ -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(),
];
}

View File

@@ -6,5 +6,4 @@ use Hyperf\Server\Exception\ServerException;
class ThirdPartyException extends ServerException
{
}

View File

@@ -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;
}
}
}

View File

@@ -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<int, mixed> $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<int, mixed>
*/
public function getAvailableValue(): array
{
return $this->availableValue;
}
}
}

View File

@@ -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<string, mixed>|Arrayable<string, mixed>|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)
);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -26,4 +26,4 @@ trait ClassicResponse
'message' => 'ok',
];
}
}
}

View File

@@ -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, '-', '+');
}
}
}

View File

@@ -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<string> $target
* @param string $subject
* @param string $text
* @param array<string> $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<string> $target
* @param string $subject
* @param string $html
* @param array<string> $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;
}
}

View File

@@ -11,8 +11,8 @@ use Psr\Http\Message\ServerRequestInterface;
class ExtendService
{
/**
* @param \Psr\Http\Message\ServerRequestInterface $request
*
* @param ServerRequestInterface|null $request
* @param array<string, string>|null $params
* @return string[]
*/
public function parse(
@@ -30,7 +30,7 @@ class ExtendService
}
/**
* @return array
* @return array<string, string>
*/
public function getExtends(): array
{
@@ -48,4 +48,4 @@ class ExtendService
{
return Context::has(self::class) && isset(array_flip(Context::get(self::class))[$field]);
}
}
}

View File

@@ -1,86 +0,0 @@
<?php
namespace Singularity\HDK\Core\Service;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
/**
* 发起 Http 请求的类
*/
class HttpRequestService
{
/**
* @var \GuzzleHttp\Client
*/
protected Client $client;
protected function __construct(array $headers = [], string $base_uri = '', array $cookie = [])
{
$options = [
'timeout' => 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);
}
}

View File

@@ -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));
}
}
}

View File

@@ -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<string, string>|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;
}
}

View File

@@ -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<string, string> $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<string, string> $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<string> $headers
* @param int|null $batchNumber
* @return array<int, mixed>
* @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<int, mixed> $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],
];
}
}
}

View File

@@ -24,7 +24,7 @@
|
*/
function something()
/*function something()
{
// ..
}
}*/

View File

@@ -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);

View File

@@ -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 {