forked from zircote/swagger-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerator.php
More file actions
419 lines (354 loc) · 12.8 KB
/
Copy pathGenerator.php
File metadata and controls
419 lines (354 loc) · 12.8 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi;
use OpenApi\Analysers\AnalyserInterface;
use OpenApi\Analysers\AttributeAnnotationFactory;
use OpenApi\Analysers\DocBlockAnnotationFactory;
use OpenApi\Analysers\ReflectionAnalyser;
use OpenApi\Annotations as OA;
use OpenApi\Loggers\DefaultLogger;
use Psr\Log\LoggerInterface;
/**
* OpenApi spec generator.
*
* Scans PHP source code and generates OpenApi specifications from the found OpenApi annotations.
*
* This is an object-oriented alternative to using the now deprecated <code>\OpenApi\scan()</code> function and
* static class properties of the <code>Analyzer</code> and <code>Analysis</code> classes.
*
* Supported generator config:
* <code>
* [
* 'generator' => [
* 'ignoreOtherAttributes' => true|false,
* ]
* ]
* </code>
*/
class Generator
{
/**
* Allows Annotation classes to know the context of the annotation that is being processed.
*/
public static ?Context $context = null;
/** @var string Magic value to differentiate between null and undefined. */
public const UNDEFINED = '@OA\Generator::UNDEFINED🙈';
/** @var array<string,string> */
public const DEFAULT_ALIASES = ['oa' => 'OpenApi\\Annotations'];
/** @var array<string> */
public const DEFAULT_NAMESPACES = ['OpenApi\\Annotations\\'];
/** @var array<string,string> Map of namespace aliases to be supported by doctrine. */
protected array $aliases;
/** @var array<string>|null List of annotation namespaces to be autoloaded by doctrine. */
protected ?array $namespaces;
protected ?AnalyserInterface $analyser = null;
/** @var array<string,mixed> */
protected array $config = [];
protected ?Pipeline $processorPipeline = null;
protected ?LoggerInterface $logger = null;
/**
* OpenApi version override.
*
* If set, it will override the version set in the <code>OpenApi</code> annotation.
*
* Due to the order of processing any conditional code using this (via <code>Context::$version</code>)
* must come only after the analysis is finished.
*/
protected ?string $version = null;
public function __construct(?LoggerInterface $logger = null)
{
$this->logger = $logger;
$this->setAliases(self::DEFAULT_ALIASES);
$this->setNamespaces(self::DEFAULT_NAMESPACES);
}
public static function isDefault($value): bool
{
return $value === Generator::UNDEFINED;
}
/**
* @return array<string>
*/
public function getAliases(): array
{
return $this->aliases;
}
public function addAlias(string $alias, string $namespace): Generator
{
$this->aliases[$alias] = $namespace;
return $this;
}
public function setAliases(array $aliases): Generator
{
$this->aliases = $aliases;
return $this;
}
/**
* @return array<string>|null
*/
public function getNamespaces(): ?array
{
return $this->namespaces;
}
public function addNamespace(string $namespace): Generator
{
$namespaces = (array) $this->getNamespaces();
$namespaces[] = $namespace;
return $this->setNamespaces(array_unique($namespaces));
}
public function setNamespaces(?array $namespaces): Generator
{
$this->namespaces = $namespaces;
return $this;
}
public function getAnalyser(): AnalyserInterface
{
$this->analyser = $this->analyser ?: new ReflectionAnalyser([new AttributeAnnotationFactory(), new DocBlockAnnotationFactory()]);
$this->analyser->setGenerator($this);
return $this->analyser;
}
public function setAnalyser(?AnalyserInterface $analyser): Generator
{
$this->analyser = $analyser;
return $this;
}
/**
* @deprecated
*/
public function getDefaultConfig(): array
{
return [
'operationId' => [
'hash' => true,
],
];
}
public function getConfig(): array
{
return $this->config + $this->getDefaultConfig() + [
'generator' => [
'ignoreOtherAttributes' => false,
],
];
}
public function isIgnoreOtherAttributes(): bool
{
return $this->getConfig()['generator']['ignoreOtherAttributes'];
}
protected function normaliseConfig(array $config): array
{
$normalised = [];
foreach ($config as $key => $value) {
if (is_numeric($key)) {
$token = explode('=', $value);
if (2 == count($token)) {
// 'operationId.hash=false'
[$key, $value] = $token;
}
}
if (in_array($value, ['true', 'false'])) {
$value = 'true' == $value;
}
if ($isList = ('[]' === substr($key, -2))) {
$key = substr($key, 0, -2);
}
$token = explode('.', $key);
if (2 == count($token)) {
// 'operationId.hash' => false
// namespaced / processor
if ($isList) {
$normalised[$token[0]][$token[1]][] = $value;
} else {
$normalised[$token[0]][$token[1]] = $value;
}
} else {
if ($isList) {
$normalised[$key][] = $value;
} else {
$normalised[$key] = $value;
}
}
}
return $normalised;
}
/**
* Set generator and/or processor config.
*
* @param array<string,mixed> $config
*/
public function setConfig(array $config): Generator
{
$this->config = $this->normaliseConfig($config) + $this->config;
return $this;
}
public function getProcessorPipeline(): Pipeline
{
if (!$this->processorPipeline instanceof Pipeline) {
$this->processorPipeline = new Pipeline([
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\AugmentRequestBody(),
new Processors\AugmentProperties(),
new Processors\AugmentDiscriminators(),
new Processors\BuildPaths(),
new Processors\AugmentParameters(),
new Processors\AugmentRefs(),
new Processors\MergeJsonContent(),
new Processors\MergeXmlContent(),
new Processors\OperationId(),
new Processors\CleanUnmerged(),
new Processors\PathFilter(),
new Processors\CleanUnusedComponents(),
new Processors\AugmentTags(),
]);
}
$config = $this->getConfig();
$walker = function (callable $pipe) use ($config) {
$rc = new \ReflectionClass($pipe);
// apply config
$processorKey = lcfirst($rc->getShortName());
if (array_key_exists($processorKey, $config)) {
foreach ($config[$processorKey] as $name => $value) {
$setter = 'set' . ucfirst($name);
if (method_exists($pipe, $setter)) {
$pipe->{$setter}($value);
}
}
}
};
return $this->processorPipeline->walk($walker);
}
public function setProcessorPipeline(?Pipeline $processor): Generator
{
$this->processorPipeline = $processor;
return $this;
}
/**
* Chainable method that allows to modify the processor pipeline.
*
* @param callable $with callable with the current processor pipeline passed in
*/
public function withProcessor(callable $with): Generator
{
$with($this->getProcessorPipeline());
return $this;
}
public function getLogger(): ?LoggerInterface
{
return $this->logger ?: new DefaultLogger();
}
public function getVersion(): ?string
{
return $this->version;
}
public function setVersion(?string $version): Generator
{
$this->version = $version;
return $this;
}
public static function scan(iterable $sources, array $options = []): ?OA\OpenApi
{
// merge with defaults
$config = $options + [
'aliases' => self::DEFAULT_ALIASES,
'namespaces' => self::DEFAULT_NAMESPACES,
'analyser' => null,
'analysis' => null,
'processor' => null,
'processors' => null,
'config' => [],
'logger' => null,
'validate' => true,
'version' => null,
];
$processorPipeline = $config['processor'] ??
($config['processors'] ? new Pipeline($config['processors']) : null);
return (new Generator($config['logger']))
->setVersion($config['version'])
->setAliases($config['aliases'])
->setNamespaces($config['namespaces'])
->setAnalyser($config['analyser'])
->setProcessorPipeline($processorPipeline)
->setConfig($config['config'])
->generate($sources, $config['analysis'], $config['validate']);
}
/**
* Run code in the context of this generator.
*
* @param callable $callable Callable in the form of
* <code>function(Generator $generator, Analysis $analysis, Context $context): mixed</code>
*
* @return mixed the result of the <code>callable</code>
*/
public function withContext(callable $callable)
{
$rootContext = new Context([
'version' => $this->getVersion(),
'logger' => $this->getLogger(),
]);
$analysis = new Analysis([], $rootContext);
return $callable($this, $analysis, $rootContext);
}
/**
* Generate OpenAPI spec by scanning the given source files.
*
* @param iterable $sources PHP source files to scan.
* Supported sources:
* * string - file / directory name
* * \SplFileInfo
* * \Symfony\Component\Finder\Finder
* @param null|Analysis $analysis custom analysis instance
* @param bool $validate flag to enable/disable validation of the returned spec
*/
public function generate(iterable $sources, ?Analysis $analysis = null, bool $validate = true): ?OA\OpenApi
{
$rootContext = new Context([
'version' => $this->getVersion(),
'logger' => $this->getLogger(),
]);
$analysis = $analysis ?: new Analysis([], $rootContext);
$analysis->context = $analysis->context ?: $rootContext;
$this->scanSources($sources, $analysis, $rootContext);
// post-processing
$this->getProcessorPipeline()->process($analysis);
if ($analysis->openapi) {
// overwrite default/annotated version
$analysis->openapi->openapi = $this->getVersion() ?: $analysis->openapi->openapi;
// update context to provide the same to validation/serialisation code
$rootContext->version = $analysis->openapi->openapi;
}
// validation
if ($validate) {
$analysis->validate();
}
return $analysis->openapi;
}
protected function scanSources(iterable $sources, Analysis $analysis, Context $rootContext): void
{
$analyser = $this->getAnalyser();
foreach ($sources as $source) {
if (is_iterable($source)) {
$this->scanSources($source, $analysis, $rootContext);
} else {
$resolvedSource = $source instanceof \SplFileInfo ? $source->getPathname() : realpath($source);
if (!$resolvedSource) {
$rootContext->logger->warning(sprintf('Skipping invalid source: %s', $source));
continue;
}
if (is_dir($resolvedSource)) {
$this->scanSources(Util::finder($resolvedSource), $analysis, $rootContext);
} else {
$rootContext->logger->debug(sprintf('Analysing source: %s', $resolvedSource));
$analysis->addAnalysis($analyser->fromFile($resolvedSource, $rootContext));
}
}
}
}
}