Skip to content

Commit 0e7e118

Browse files
committed
Optimize the code
1 parent 298593e commit 0e7e118

9 files changed

Lines changed: 73 additions & 49 deletions

src/Exception/ApiDocsException.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,23 @@
88

99
class ApiDocsException extends RuntimeException
1010
{
11+
public static function fileNotFound(string $path): self
12+
{
13+
return new self("File not found: {$path}");
14+
}
15+
16+
public static function directoryCreationFailed(string $path): self
17+
{
18+
return new self("Failed to create directory: {$path}");
19+
}
20+
21+
public static function invalidClass(string $className): self
22+
{
23+
return new self("Invalid class: {$className}");
24+
}
25+
26+
public static function typeResolutionFailed(string $className, string $field): self
27+
{
28+
return new self("Type resolution failed for field: {$className}::{$field}");
29+
}
1130
}

src/Swagger/GenerateProxyClass.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public function __construct(
3232
$proxyDir = $this->swaggerConfig->getProxyDir();
3333
if (file_exists($proxyDir) === false) {
3434
if (mkdir($proxyDir, 0755, true) === false) {
35-
throw new ApiDocsException("Failed to create a directory : {$proxyDir}");
35+
throw ApiDocsException::directoryCreationFailed($proxyDir);
3636
}
3737
}
3838
}

src/Swagger/GenerateResponses.php

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,16 @@ public function generate(): array
5656
return array_values($arr);
5757
}
5858

59-
// protected function getReturnJsonContent(string $returnTypeClassName, bool $isArray = false): array
60-
// {
61-
// $arr = [];
62-
// $mediaType = new OA\MediaType();
63-
// $mediaTypeStr = 'application/json';
64-
// $mediaType->schema = $this->getJsonContent($returnTypeClassName, $isArray);
65-
// $arr[$mediaTypeStr] = $mediaType;
66-
// $mediaType->mediaType = $mediaTypeStr;
67-
// return $arr;
68-
// }
59+
// protected function getReturnJsonContent(string $returnTypeClassName, bool $isArray = false): array
60+
// {
61+
// $arr = [];
62+
// $mediaType = new OA\MediaType();
63+
// $mediaTypeStr = 'application/json';
64+
// $mediaType->schema = $this->getJsonContent($returnTypeClassName, $isArray);
65+
// $arr[$mediaTypeStr] = $mediaType;
66+
// $mediaType->mediaType = $mediaTypeStr;
67+
// return $arr;
68+
// }
6969

7070
protected function getContent(array|object|string $returnTypeClassName): array
7171
{

src/Swagger/SwaggerCommon.php

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212

1313
class SwaggerCommon extends DtoCommon
1414
{
15-
protected static array $className = [];
15+
protected array $classNameCache = [];
1616

17-
protected static array $simpleClassName = [];
17+
protected array $simpleClassNameCache = [];
1818

1919
public function getComponentsName(string $className): string
2020
{
@@ -23,8 +23,8 @@ public function getComponentsName(string $className): string
2323

2424
public function simpleClassNameClear(): void
2525
{
26-
static::$className = [];
27-
static::$simpleClassName = [];
26+
$this->classNameCache = [];
27+
$this->simpleClassNameCache = [];
2828
}
2929

3030
/**
@@ -36,8 +36,8 @@ public function getSimpleClassName(?string $className): string
3636
$className = 'Null';
3737
}
3838
$className = ltrim($className, '\\');
39-
if (isset(self::$className[$className])) {
40-
return self::$className[$className];
39+
if (isset($this->classNameCache[$className])) {
40+
return $this->classNameCache[$className];
4141
}
4242
$pos = strrpos($className, '\\');
4343
$simpleClassName = $className;
@@ -46,7 +46,7 @@ public function getSimpleClassName(?string $className): string
4646
}
4747

4848
$simpleClassName = $this->getSimpleClassNameNum(ucfirst($simpleClassName));
49-
self::$className[$className] = $simpleClassName;
49+
$this->classNameCache[$className] = $simpleClassName;
5050
return $simpleClassName;
5151
}
5252

@@ -89,7 +89,7 @@ public function getPhpType(mixed $type): string
8989
return $type->getValue();
9090
}
9191

92-
if (is_object($type) && $type::class != 'stdClass') {
92+
if (is_object($type) && $type::class !== 'stdClass') {
9393
return '\\' . $type::class;
9494
}
9595
if (is_string($type) && class_exists($type)) {
@@ -98,7 +98,7 @@ public function getPhpType(mixed $type): string
9898
return 'mixed';
9999
}
100100

101-
public function getPropertyDefaultValue(string $className, ReflectionProperty $reflectionProperty)
101+
public function getPropertyDefaultValue(string $className, ReflectionProperty $reflectionProperty): mixed
102102
{
103103
$default = Generator::UNDEFINED;
104104
try {
@@ -109,21 +109,20 @@ public function getPropertyDefaultValue(string $className, ReflectionProperty $r
109109
} catch (Throwable) {
110110
$fieldName = $reflectionProperty->getName();
111111
$classVars = get_class_vars($className);
112-
// 别名会获取不到默认值
113112
if (isset($classVars[$fieldName])) {
114113
$default = $classVars[$fieldName];
115114
}
116115
}
117116
return $default;
118117
}
119118

120-
private function getSimpleClassNameNum(string $className, $num = 0): string
119+
private function getSimpleClassNameNum(string $className, int $num = 0): string
121120
{
122121
$simpleClassName = $className . ($num > 0 ? '_' . $num : '');
123-
if (isset(self::$simpleClassName[$simpleClassName])) {
122+
if (isset($this->simpleClassNameCache[$simpleClassName])) {
124123
return $this->getSimpleClassNameNum($className, $num + 1);
125124
}
126-
self::$simpleClassName[$simpleClassName] = $num;
125+
$this->simpleClassNameCache[$simpleClassName] = $num;
127126
return $simpleClassName;
128127
}
129128
}

src/Swagger/SwaggerComponents.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
class SwaggerComponents
2323
{
24-
protected static array $schemas = [];
24+
protected array $schemas = [];
2525

2626
public function __construct(
2727
protected SwaggerCommon $common,
@@ -32,12 +32,12 @@ public function __construct(
3232

3333
public function getSchemas(): array
3434
{
35-
return self::$schemas;
35+
return $this->schemas;
3636
}
3737

3838
public function setSchemas(array $schemas): void
3939
{
40-
self::$schemas = $schemas;
40+
$this->schemas = $schemas;
4141
}
4242

4343
public function getProperties(string $className): array
@@ -135,7 +135,7 @@ public function getProperties(string $className): array
135135
$property->ref = $this->common->getComponentsName($propertyManager->className);
136136
$this->generateSchemas($propertyManager->className);
137137
} else {
138-
throw new ApiDocsException("field:{$className}-{$fieldName} type resolved not found");
138+
throw ApiDocsException::typeResolutionFailed($className, $fieldName);
139139
}
140140
}
141141
$propertyArr[] = $property;
@@ -146,8 +146,8 @@ public function getProperties(string $className): array
146146
public function generateSchemas(string $className)
147147
{
148148
$simpleClassName = $this->common->getSimpleClassName($className);
149-
if (isset(static::$schemas[$simpleClassName])) {
150-
return static::$schemas[$simpleClassName];
149+
if (isset($this->schemas[$simpleClassName])) {
150+
return $this->schemas[$simpleClassName];
151151
}
152152
$schema = new OA\Schema();
153153
$schema->schema = $simpleClassName;
@@ -160,7 +160,7 @@ public function generateSchemas(string $className)
160160
$schema->description = $apiModel->value;
161161
}
162162
$data['requiredArr'] && $schema->required = $data['requiredArr'];
163-
self::$schemas[$simpleClassName] = $schema;
164-
return self::$schemas[$simpleClassName];
163+
$this->schemas[$simpleClassName] = $schema;
164+
return $this->schemas[$simpleClassName];
165165
}
166166
}

src/Swagger/SwaggerController.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class SwaggerController
2727

2828
protected array $swaggerFileList;
2929

30-
public function __construct(protected SwaggerConfig $swaggerConfig, protected ResponseInterface $response,protected SwaggerOpenApi $swaggerOpenApi,)
30+
public function __construct(protected SwaggerConfig $swaggerConfig, protected ResponseInterface $response, protected SwaggerOpenApi $swaggerOpenApi)
3131
{
3232
$this->outputDir = $this->swaggerConfig->getOutputDir();
3333
$this->uiFileList = is_dir($this->swaggerUiPath) ? scandir($this->swaggerUiPath) : [];
@@ -36,8 +36,8 @@ public function __construct(protected SwaggerConfig $swaggerConfig, protected Re
3636

3737
public function getFile(string $file): PsrResponseInterface
3838
{
39-
if (!in_array($file, $this->uiFileList)) {
40-
throw new ApiDocsException('File does not exist');
39+
if (! in_array($file, $this->uiFileList)) {
40+
throw ApiDocsException::fileNotFound($file);
4141
}
4242
$file = $this->swaggerUiPath . '/' . $file;
4343
return $this->fileResponse($file);
@@ -46,8 +46,8 @@ public function getFile(string $file): PsrResponseInterface
4646
public function getJsonFile(string $httpName): PsrResponseInterface
4747
{
4848
$file = $httpName . '.json';
49-
if (!in_array($file, $this->swaggerFileList)) {
50-
throw new ApiDocsException('File does not exist');
49+
if (! in_array($file, $this->swaggerFileList)) {
50+
throw ApiDocsException::fileNotFound($file);
5151
}
5252
$filePath = $this->outputDir . '/' . $file;
5353
return $this->fileResponse($filePath);
@@ -56,16 +56,16 @@ public function getJsonFile(string $httpName): PsrResponseInterface
5656
public function getYamlFile(string $httpName): PsrResponseInterface
5757
{
5858
$file = $httpName . '.yaml';
59-
if (!in_array($file, $this->swaggerFileList)) {
60-
throw new ApiDocsException('File does not exist');
59+
if (! in_array($file, $this->swaggerFileList)) {
60+
throw ApiDocsException::fileNotFound($file);
6161
}
6262
$filePath = $this->outputDir . '/' . $file;
6363
return $this->fileResponse($filePath);
6464
}
6565

6666
protected function fileResponse(string $filePath)
6767
{
68-
if (!$this->pharRunning() && Constant::ENGINE == 'Swoole') { // phar报错
68+
if (! $this->pharRunning() && Constant::ENGINE == 'Swoole') { // phar报错
6969
$stream = new SwooleFileStream($filePath);
7070
} elseif (Constant::ENGINE == 'Swow') {
7171
/* @phpstan-ignore-next-line */

src/Swagger/SwaggerOpenApi.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ public function save(string $serverName): void
135135
$outputDir = $this->swaggerConfig->getOutputDir();
136136
if (file_exists($outputDir) === false) {
137137
if (mkdir($outputDir, 0755, true) === false) {
138-
throw new ApiDocsException("Failed to create a directory : {$outputDir}");
138+
throw ApiDocsException::directoryCreationFailed($outputDir);
139139
}
140140
}
141141
$outputFile = $outputDir . '/' . $serverName . '.' . $this->swaggerConfig->getFormat();

src/Swagger/SwaggerPaths.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class SwaggerPaths
3030

3131
protected array $classMethodArray = [];
3232

33-
protected static array $operationIds = [];
33+
protected array $operationIds = [];
3434

3535
public function __construct(
3636
public string $serverName,
@@ -148,13 +148,13 @@ protected function getClassMethodPath(string $fullClassName, string $methodName)
148148
*/
149149
protected function getOperationId(string $route, string $methods): string
150150
{
151-
$route = str_replace(['{','}'], '', $route);
151+
$route = str_replace(['{', '}'], '', $route);
152152
$operationId = Str::camel(str_replace('/', '_', $route));
153153
if (empty($operationId)) {
154154
$operationId = '-';
155155
}
156-
if (! isset(self::$operationIds[$operationId])) {
157-
self::$operationIds[$operationId] = true;
156+
if (! isset($this->operationIds[$operationId])) {
157+
$this->operationIds[$operationId] = true;
158158
return $operationId;
159159
}
160160
return $this->getOperationId($operationId . ucfirst(strtolower($methods)), $methods);

src/Swagger/SwaggerUiController.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,15 +98,21 @@ public function swaggerConfig(): array
9898

9999
public function knife4jFile(string $file): PsrResponseInterface
100100
{
101-
$file = str_replace('..', '', $file);
102-
$file = '/webjars/' . $file;
103-
$file = $this->swaggerUiPath . '/' . $file;
104-
return $this->fileResponse($file);
101+
$file = $this->sanitizeFilePath($file);
102+
$filePath = $this->swaggerUiPath . '/webjars/' . $file;
103+
return $this->fileResponse($filePath);
105104
}
106105

107106
public function favicon(): PsrResponseInterface
108107
{
109108
$file = $this->docsWebPath . '/favicon.png';
110109
return $this->fileResponse($file);
111110
}
111+
112+
protected function sanitizeFilePath(string $file): string
113+
{
114+
$file = str_replace(['..', '\\', "\0"], '', $file);
115+
116+
return ltrim($file, '/');
117+
}
112118
}

0 commit comments

Comments
 (0)