Skip to content

Commit

Permalink
支持可变变量
Browse files Browse the repository at this point in the history
  • Loading branch information
tw2066 committed Aug 10, 2023
1 parent 3ab7452 commit 69f2c26
Show file tree
Hide file tree
Showing 9 changed files with 134 additions and 38 deletions.
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,22 @@ class Image extends BaseValidation
protected $rule = 'image';
}
```


### 验证器Validation

1. 大家都习惯了框架的`required|date|after:start_date`写法
```php
//可以通过Validation实现
#[Validation('required|date|after:start_date')]
```
2. 需要支持数组里面是int数据情况 `'intArr.*' => 'integer'`的情况
```php
//可以通过Validation中customKey来自定义key实现
#[Validation('integer', customKey: 'intArr.*')]
public array $intArr;
```
上面写法和`'intArr.*' => 'integer'`效果相同

## 注意
### 数组类型的问题
> PHP原生暂不支持`int[]``Class[]`类型, 使用示例
Expand Down Expand Up @@ -293,8 +308,20 @@ return [
],
];
```

### `AutoController`注解
> 控制器中使用`AutoController`注解,只收集了`POST`方法
>
## RPC 返回PHP对象
> 当框架导入 symfony/serializer (^5.0) 和 symfony/property-access (^5.0) 后,并在 dependencies.php 中配置一下映射关系
```php
use Hyperf\DTO\Serializer\SerializerFactory;
use Hyperf\Utils\Serializer\Serializer;

return [
Hyperf\Contract\NormalizerInterface::class => new SerializerFactory(Serializer::class),
];
```
## Swagger界面
![hMvJnQ](https://gitee.com/tw666/source/raw/master/img/swagger.png)

Expand Down
20 changes: 10 additions & 10 deletions example/Enum/StatusEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@

namespace HyperfExample\ApiDocs\Enum;
// PHP>=8.1
if (PHP_VERSION_ID >= 80100) {
// enum StatusEnum: string
// {
// case SUCCESS = 'success';
//
// case CLOSED = 'closed';
// }
} else {
class StatusEnum
//if (PHP_VERSION_ID >= 80100) {
enum StatusEnum: string
{
case SUCCESS = 'success';

case CLOSED = 'closed';
}
}
//} else {
// class StatusEnum
// {
//
// }
//}


7 changes: 3 additions & 4 deletions src/Annotation/ApiResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ class ApiResponse extends AbstractMultipleAnnotation
* @param null|string $type class类或简单类型
*/
public function __construct(
public string|int|null $response = null,
public string $description = '',
public ?string $type = null,
public bool $isArray = false,
public null|string|object|array $returnType = null,
public string|int|null $response = '200',
public string $description = 'success',
) {
}
}
16 changes: 16 additions & 0 deletions src/Annotation/ApiVariable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Hyperf\ApiDocs\Annotation;

use Attribute;
use Hyperf\Di\Annotation\AbstractAnnotation;

#[Attribute(Attribute::TARGET_PROPERTY)]
class ApiVariable extends AbstractAnnotation
{
public function __construct(public string $value = '')
{
}
}
7 changes: 7 additions & 0 deletions src/Listener/BootAppRouteListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Hyperf\ApiDocs\Listener;

use Hyperf\ApiDocs\Swagger\GenericProxyClass;
use Hyperf\ApiDocs\Swagger\SwaggerConfig;
use Hyperf\ApiDocs\Swagger\SwaggerController;
use Hyperf\Contract\ConfigInterface;
Expand All @@ -28,6 +29,7 @@ public function __construct(
private ConfigInterface $config,
private DispatcherFactory $dispatcherFactory,
private SwaggerConfig $swaggerConfig,
private GenericProxyClass $genericProxyClass,
) {
}

Expand Down Expand Up @@ -68,6 +70,9 @@ public function process(object $event): void
$this->logger->warning('Swagger: http Service not started');
return;
}
//泛型生成代理
// $this->genericProxyClass->generate();
// $this->generateGenericProxyClasse();
// 添加路由
$httpServerRouter->addGroup($prefix, function ($route) {
$route->get('', [SwaggerController::class, 'index']);
Expand All @@ -79,4 +84,6 @@ public function process(object $event): void

static::$massage = 'Swagger docs url at http://' . $httpServer['host'] . ':' . $httpServer['port'] . $prefix;
}


}
57 changes: 44 additions & 13 deletions src/Swagger/GenerateResponses.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Hyperf\ApiDocs\Swagger;

use Hyperf\ApiDocs\Annotation\ApiResponse;
use Hyperf\ApiDocs\DTO\ReturnResponse;
use Hyperf\Collection\Arr;
use Hyperf\Di\MethodDefinitionCollectorInterface;
use Hyperf\Di\ReflectionType;
Expand All @@ -14,15 +15,17 @@
class GenerateResponses
{
public function __construct(
private string $className,
private string $methodName,
private array $apiResponseArr,
private SwaggerConfig $swaggerConfig,
private string $className,
private string $methodName,
private array $apiResponseArr,
private SwaggerConfig $swaggerConfig,
private MethodDefinitionCollectorInterface $methodDefinitionCollector,
private ContainerInterface $container,
private SwaggerComponents $swaggerComponents,
private SwaggerCommon $common,
) {
private ContainerInterface $container,
private SwaggerComponents $swaggerComponents,
private SwaggerCommon $common,
private GenericProxyClass $genericProxyClass,
)
{
}

/**
Expand Down Expand Up @@ -53,8 +56,31 @@ public function generate(): array
return array_values($arr);
}

protected function getContent(string $returnTypeClassName, bool $isArray = false): array
protected function getReturnJsonContent(string $returnTypeClassName, bool $isArray = false): array
{
$arr = [];
$mediaType = new OA\MediaType();
$mediaTypeStr = 'application/json';
$returnResponse = 'ReturnResponse';
$mediaType->schema = $this->getJsonContent($returnTypeClassName, $isArray);
$arr[$mediaTypeStr] = $mediaType;
$mediaType->mediaType = $mediaTypeStr;
return $arr;

}

protected function getContent(string|object $returnTypeClassName, bool $isArray = false): array
{
$globalReturnResponsesClass = $this->swaggerConfig->getGlobalReturnResponsesClass();
if($globalReturnResponsesClass){
$returnTypeClassName = \Hyperf\Support\make($globalReturnResponsesClass,[$returnTypeClassName]);
}

if (is_object($returnTypeClassName)
&& $this->genericProxyClass->getGenericClass($returnTypeClassName::class)) {
$returnTypeClassName = $this->genericProxyClass->generate($returnTypeClassName);
}

$arr = [];
$mediaType = new OA\MediaType();

Expand Down Expand Up @@ -115,8 +141,8 @@ protected function getGlobalResp(): array
$apiResponse = new ApiResponse();
$apiResponse->response = $value['response'] ?? null;
$apiResponse->description = $value['description'] ?? null;
! empty($value['type']) && $apiResponse->type = $value['type'];
! empty($value['isArray']) && $apiResponse->isArray = $value['isArray'];
!empty($value['returnType']) && $apiResponse->returnType = $value['returnType'];
!empty($value['isArray']) && $apiResponse->isArray = $value['isArray'];

$resp[$apiResponse->response] = $this->getOAResp($apiResponse);
}
Expand All @@ -128,8 +154,13 @@ protected function getOAResp(ApiResponse $apiResponse): OA\Response
$response = new OA\Response();
$response->response = $apiResponse->response;
$response->description = $apiResponse->description;
if (! empty($apiResponse->type)) {
$content = $this->getContent($apiResponse->type, $apiResponse->isArray);
if (!empty($apiResponse->returnType)) {
$isArray = is_array($apiResponse->returnType);
$returnType = $apiResponse->returnType;
if ($isArray) {
$returnType = $apiResponse->returnType[0] ?? null;
}
$content = $this->getContent($returnType, $isArray);
$content && $response->content = $content;
}
return $response;
Expand Down
6 changes: 5 additions & 1 deletion src/Swagger/SwaggerCommon.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ public function getComponentsName(string $className): string
/**
* 获取简单php类名.
*/
public function getSimpleClassName(string $className): string
public function getSimpleClassName(?string $className): string
{
if($className === null){
$className = 'Null';
}

$className = '\\' . trim($className, '\\');
if (isset(self::$className[$className])) {
return self::$className[$className];
Expand Down
20 changes: 13 additions & 7 deletions src/Swagger/SwaggerComponents.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public function getProperties(string $className): array
return ['propertyArr' => [], 'requiredArr' => []];
}

$obj = make($className);
$rc = ReflectionManager::reflectClass($className);
$propertyArr = [];
$requiredArr = [];
Expand All @@ -58,6 +57,9 @@ public function getProperties(string $className): array
if ($apiModelProperty->hidden) {
continue;
}
if (! $reflectionProperty->isPublic()) {
continue;
}
// 字段名称
$property->property = $fieldName;

Expand All @@ -67,8 +69,12 @@ public function getProperties(string $className): array
$apiModelProperty->required && $requiredArr[] = $fieldName;
}
$property->example = $apiModelProperty->example;
if ($reflectionProperty->isPublic() && $reflectionProperty->isInitialized($obj)) {
$property->default = $reflectionProperty->getValue($obj);
try {
$obj = make($className);
if ($reflectionProperty->isPublic() && $reflectionProperty->isInitialized($obj)) {
$property->default = $reflectionProperty->getValue($obj);
}
} catch (\Throwable) {
}

$propertyClass = PropertyManager::getProperty($className, $fieldName);
Expand All @@ -77,6 +83,8 @@ public function getProperties(string $className): array

// 枚举:in
if (! empty($inAnnotation)) {
var_dump($inAnnotation[0]);die();
// $inAnnotation
$property->type = $swaggerType;
$property->enum = $inAnnotation->getValue();
}
Expand All @@ -92,13 +100,11 @@ public function getProperties(string $className): array
// 普通简单类型
$property->type = $swaggerType;
}
}
// 枚举类型
} // 枚举类型
elseif ($propertyClass->enum) {
$property->type = $this->common->getSwaggerType($propertyClass->enum->backedType);
$property->enum = $propertyClass->enum->valueList;
}
// 普通类
} // 普通类
else {
if ($swaggerType == 'array') {
$property->type = 'array';
Expand Down
10 changes: 8 additions & 2 deletions src/Swagger/SwaggerConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class SwaggerConfig

private string $format = 'json';

private string $global_return_responses_class = '';

public function __construct(ConfigInterface $config)
{
$data = $config->get('api_docs', []);
Expand Down Expand Up @@ -99,8 +101,12 @@ public function getPrefixResources(): string
return $this->prefix_resources ?: $this->getPrefixUrl();
}

public function setPrefixResources(string $prefix_resources): void
/**
* @return string
*/
public function getGlobalReturnResponsesClass(): string
{
$this->prefix_resources = $prefix_resources;
return $this->global_return_responses_class;
}

}

0 comments on commit 69f2c26

Please sign in to comment.