-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathOpenApiRouteLoader.php
More file actions
207 lines (168 loc) · 7.37 KB
/
OpenApiRouteLoader.php
File metadata and controls
207 lines (168 loc) · 7.37 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php
declare(strict_types=1);
namespace Tobion\OpenApiSymfonyRouting;
use OpenApi\Analysers\AttributeAnnotationFactory;
use OpenApi\Analysers\DocBlockAnnotationFactory;
use OpenApi\Analysers\ReflectionAnalyser;
use OpenApi\Analysis;
use OpenApi\Annotations\OpenApi;
use OpenApi\Annotations\Operation;
use OpenApi\Generator;
use OpenApi\Processors\DocBlockDescriptions;
use OpenApi\Processors\OperationId;
use Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class OpenApiRouteLoader implements RouteLoaderInterface
{
/**
* @var Finder
*/
private $finder;
/**
* @var array<string, int>
*/
private $routeNames = [];
/**
* @var string
*/
private static $openApiUndefined;
public function __construct(Finder $finder)
{
$this->finder = $finder;
if (!isset(self::$openApiUndefined)) {
self::$openApiUndefined = \class_exists(Generator::class) ? Generator::UNDEFINED : \OpenApi\UNDEFINED;
}
}
public static function fromDirectories(string $dir, string ...$moreDirs): self
{
return new self(
(new Finder())->in($dir)->in($moreDirs)->files()->name('*.php')->sortByName()->followLinks()
);
}
/**
* Looks for OpenAPI/Swagger annotations in the symfony flex default "src" directory based on a composer install.
*/
public static function fromSrcDirectory(): self
{
return self::fromDirectories(__DIR__.'/../../../../src');
}
public function __invoke(): RouteCollection
{
$openApi = $this->createOpenApi();
$routeCollection = new RouteCollection();
$globalFormatSuffixConfig = FormatSuffixConfig::fromAnnotation($openApi);
foreach ($openApi->paths as $path) {
$pathFormatSuffixConfig = FormatSuffixConfig::fromAnnotation($path, $globalFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->get, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->put, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->post, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->delete, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->options, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->head, $pathFormatSuffixConfig);
$this->addRouteFromOpenApiOperation($routeCollection, $path->patch, $pathFormatSuffixConfig);
}
$this->routeNames = [];
return $routeCollection;
}
private function createOpenApi(): OpenApi
{
if (!\class_exists(Generator::class)) {
return \OpenApi\scan($this->finder);
}
if (method_exists(Analysis::class, 'processors')) {
$processors = array_filter(Analysis::processors(), static function ($processor): bool {
// remove OperationId processor which would hash the controller starting in 3.2.2 breaking the default route name logic
return !$processor instanceof OperationId && !$processor instanceof DocBlockDescriptions;
});
return (new Generator())->setProcessors($processors)->generate($this->finder);
}
$analyser = new ReflectionAnalyser([
new AttributeAnnotationFactory(),
new DocBlockAnnotationFactory()]
);
return (new Generator())
->setAnalyser($analyser)
->generate($this->finder);
}
/**
* @param Operation|string $operation
*/
private function addRouteFromOpenApiOperation(RouteCollection $routeCollection, $operation, FormatSuffixConfig $parentFormatSuffixConfig): void
{
if (self::$openApiUndefined === $operation || !$operation instanceof Operation) {
return;
}
$controller = $this->getControllerFromOpenApiOperation($operation);
$name = $this->getRouteName($operation, $controller);
$route = $this->createRoute($operation, $controller, $parentFormatSuffixConfig);
$priority = $this->getRoutePriority($operation);
$routeCollection->add($name, $route, $priority);
}
private function createRoute(Operation $operation, string $controller, FormatSuffixConfig $parentFormatSuffixConfig): Route
{
$formatSuffixConfig = FormatSuffixConfig::fromAnnotation($operation, $parentFormatSuffixConfig);
$path = $formatSuffixConfig->enabled ? $operation->path.'.{_format}' : $operation->path;
$route = new Route($path);
$route->setMethods($operation->method);
$route->setDefault('_controller', $controller);
if ($formatSuffixConfig->enabled) {
$route->setDefault('_format', null);
if (null !== $formatSuffixConfig->pattern) {
$route->setRequirement('_format', $formatSuffixConfig->pattern);
}
}
if (self::$openApiUndefined !== $operation->parameters) {
foreach ($operation->parameters as $parameter) {
if ('path' === $parameter->in && self::$openApiUndefined !== $parameter->schema && self::$openApiUndefined !== $parameter->schema->pattern) {
$route->setRequirement($parameter->name, $parameter->schema->pattern);
}
}
}
return $route;
}
private function getControllerFromOpenApiOperation(Operation $operation): string
{
$classOrService = ltrim($operation->_context->fullyQualifiedName($operation->_context->class), '\\');
return $classOrService.'::'.$operation->_context->method;
}
private function getRouteName(Operation $operation, string $controller): string
{
// swagger-php v3 adds the controller as operationId automatically, see \OpenApi\Processors\OperationId.
// This must be ignored as it is not viable with multiple annotations on the same controller.
return self::$openApiUndefined === $operation->operationId || $controller === $operation->operationId ? $this->getDefaultRouteName($controller) : $operation->operationId;
}
private function getRoutePriority(Operation $operation): int
{
if (isset($operation->x['priority']) && is_int($operation->x['priority'])) {
return $operation->x['priority'];
}
return 0;
}
/**
* @see \Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader::getDefaultRouteName
*/
private function getDefaultRouteName(string $controller): string
{
$name = str_replace(['\\', '::'], '_', $controller);
$name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
$name = preg_replace([
'/(bundle|controller)_/',
'/action(_\d+)?$/',
'/__/',
], [
'_',
'\\1',
'_',
], $name);
// handle several routes for the same controller
if (isset($this->routeNames[$name])) {
++$this->routeNames[$name];
$name .= '_'.$this->routeNames[$name];
} else {
$this->routeNames[$name] = 0;
}
return $name;
}
}