Repository navigation
Expand file tree
/
Copy pathGenerator.php
More file actions
95 lines (81 loc) · 3.13 KB
/
Copy pathGenerator.php
File metadata and controls
95 lines (81 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Swagger;
use Hyperf\Codec\Json;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Swagger\Processor\BuildPathsProcessor;
use InvalidArgumentException;
use OpenApi\Processors;
class Generator
{
public function __construct(public ConfigInterface $config)
{
}
public function generate(): void
{
$paths = $this->config->get('swagger.scan.paths', null);
if ($paths === null) {
$paths = $this->config->get('annotations.scan.paths', []);
}
$userProcessors = $this->config->get('swagger.processors', []);
if (! is_array($userProcessors)) {
throw new InvalidArgumentException('The processors of swagger must be array.');
}
$servers = (array) $this->config->get('swagger.server', []);
$generator = new \OpenApi\Generator();
$openapi = $generator->setAliases(\OpenApi\Generator::DEFAULT_ALIASES)
->setNamespaces(\OpenApi\Generator::DEFAULT_NAMESPACES)
->setProcessors([
new Processors\DocBlockDescriptions(),
new Processors\MergeIntoOpenApi(),
new Processors\MergeIntoComponents(),
new Processors\ExpandClasses(),
new Processors\ExpandInterfaces(),
new Processors\ExpandTraits(),
new Processors\ExpandEnums(),
new Processors\AugmentSchemas(),
new Processors\AugmentProperties(),
new BuildPathsProcessor(),
new Processors\AugmentParameters(),
new Processors\AugmentRefs(),
new Processors\MergeJsonContent(),
new Processors\MergeXmlContent(),
new Processors\OperationId(),
new Processors\CleanUnmerged(),
...$userProcessors,
])
->generate($paths, validate: false);
$jsonArray = Json::decode($openapi->toJson());
$paths = $jsonArray['paths'] ?? [];
$jsonArray['paths'] = [];
$result = [];
foreach ($paths as $key => $path) {
[$serverName, $key] = explode('|', $key, 2);
if (empty($result[$serverName])) {
$result[$serverName] = $jsonArray;
}
if ($svs = $servers[$serverName]['servers'] ?? null) {
$result[$serverName]['servers'] = $svs;
}
if ($info = $servers[$serverName]['info'] ?? null) {
$result[$serverName]['info'] = $info;
}
$result[$serverName]['paths'][$key] = $path;
}
$path = $this->config->get('swagger.json_dir', BASE_PATH . '/storage/swagger');
foreach ($result as $serverName => $json) {
if (! is_dir($path)) {
@mkdir($path, 0755, true);
}
file_put_contents(rtrim($path, '/') . '/' . $serverName . '.json', Json::encode($json));
}
}
}