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

@@ -65,5 +65,4 @@ abstract class AbstractController
* @var \Hyperf\Contract\StdoutLoggerInterface
*/
protected StdoutLoggerInterface $stdoutLogger;
}

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

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

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, [
$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

@@ -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,
@@ -52,7 +60,7 @@ class ValidateException extends HttpException
}
/**
* @return array
* @return array<int, mixed>
*/
public function getAvailableValue(): array
{

View File

@@ -39,7 +39,7 @@ class ClassicCoreMiddleware extends CoreMiddleware
/**
* 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
{
@@ -50,10 +50,10 @@ class ClassicCoreMiddleware extends CoreMiddleware
// 分页数据
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(
@@ -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',

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(

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;
@@ -26,8 +27,11 @@ class EmailService
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);
@@ -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(
@@ -61,13 +65,13 @@ class EmailService
}
/**
* @param string|array $target
* @param string|array<string> $target
* @param string $subject
* @param string $text
* @param array $cc
* @param array<string> $cc
*
* @return bool
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
* @throws TransportExceptionInterface
*/
public function sendText(
string|array $target,
@@ -90,13 +94,13 @@ class EmailService
/**
* 以 HTML 格式发送邮件
*
* @param string|array $target
* @param string|array<string> $target
* @param string $subject
* @param string $html
* @param array $cc
* @param array<string> $cc
*
* @return bool
* @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
* @throws TransportExceptionInterface
*/
public function sendHtml(
string|array $target,

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
{

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,19 +14,22 @@ 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');
}
/**
@@ -36,14 +39,22 @@ class OssService
* @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);
//最大文件大小.用户可以自己设置
@@ -74,7 +85,7 @@ class OssService
$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},

View File

@@ -46,7 +46,7 @@ class SmsService
*
* @param string $phone 接收短信的手机号码
* @param string|null $templateCode 短信模板CODE
* @param array|null $templateParam 短信模板变量对应的实际值(不支持空数组)
* @param array<string, string>|null $templateParam 短信模板变量对应的实际值(不支持空数组)
* @param string|null $signName 短信签名名称
*
* @return bool

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,13 +20,13 @@ class UtilsService
{
/**
* @Inject
* @var \Hyperf\HttpServer\Contract\RequestInterface
* @var RequestInterface
*/
private RequestInterface $request;
/**
* @Inject()
* @var \Hyperf\Contract\StdoutLoggerInterface
* @var StdoutLoggerInterface
*/
private StdoutLoggerInterface $logger;
@@ -65,13 +64,13 @@ class UtilsService
/**
* 在响应头中添加 Link 字段
*
* @param \Psr\Http\Message\ResponseInterface $response
* @param ResponseInterface $response
* @param string|null $urlReference
* @param string $rel
* @param array $params
* @param array<string, string> $params
* @param bool $trimQuote
*
* @return \Psr\Http\Message\ResponseInterface
* @return ResponseInterface
*/
public function extendLinkToHeader(
ResponseInterface $response,
@@ -87,7 +86,7 @@ class UtilsService
$params['rel'] = $rel;
if (!$trimQuote) {
foreach ($params as &$value) {
$value = '"' . trim($value, '"') . '"';
$value = sprintf("\"%s\"", trim($value, '"'));
}
}
@@ -109,14 +108,14 @@ class UtilsService
* 构建 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;
@@ -128,8 +127,8 @@ class UtilsService
*
* @param string $fullName
*
* @return \Generator
* @throws \Exception
* @return Generator
* @throws Exception
*/
public function csvReaderGenerator(string $fullName): Generator
{
@@ -148,7 +147,11 @@ class UtilsService
/**
* 以数组形式响应
*
* @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
{
@@ -180,11 +183,11 @@ class UtilsService
* level倒序快速无极分类时间复杂度 O(n),空间复杂度 O(1)
* 条件数组索引是数据parent_id对应的id只支持level倒序
*
* @param array $list
* @param array<int, mixed> $list
* @param int $level
* @param string $parentIdName
* @param string $childrenName
* @param \Closure|null $filterCallback
* @param Closure|null $filterCallback
*
* @return void
*/
@@ -233,12 +236,9 @@ class UtilsService
* @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,
@@ -266,14 +266,9 @@ class UtilsService
* @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,

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 {