-
Notifications
You must be signed in to change notification settings - Fork 938
/
Generator.php
551 lines (468 loc) · 17.5 KB
/
Generator.php
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi;
use Doctrine\Common\Annotations\AnnotationRegistry;
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 OpenApi\Processors\ProcessorInterface;
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 `\OpenApi\scan()` function and
* static class properties of the `Analyzer` and `Analysis` classes.
*/
class Generator
{
/**
* Allows Annotation classes to know the context of the annotation that is being processed.
*
* @var Context|null
*/
public static $context;
/** @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 $aliases;
/** @var array<string>|null List of annotation namespaces to be autoloaded by doctrine. */
protected $namespaces;
/** @var AnalyserInterface|null The configured analyzer. */
protected $analyser = null;
/** @var array<string,mixed> */
protected $config = [];
/** @var Pipeline|null */
protected $processorPipeline = null;
/** @var LoggerInterface|null PSR logger. */
protected $logger = null;
/**
* OpenApi version override.
*
* If set, it will override the version set in the `OpenApi` annotation.
*
* Due to the order of processing any conditional code using this (via `Context::$version`)
* must come only after the analysis is finished.
*
* @var string|null
*/
protected $version = null;
private $configStack;
public function __construct(?LoggerInterface $logger = null)
{
$this->logger = $logger;
$this->setAliases(self::DEFAULT_ALIASES);
$this->setNamespaces(self::DEFAULT_NAMESPACES);
// kinda config stack to stay BC...
// @deprecated Can be removed once doctrine/annotations 2.0 becomes mandatory
$this->configStack = new class() {
protected $generator;
public function push(Generator $generator): void
{
$this->generator = $generator;
/* @phpstan-ignore-next-line */
if (class_exists(AnnotationRegistry::class, true) && method_exists(AnnotationRegistry::class, 'registerLoader')) {
// keeping track of &this->generator allows to 'disable' the loader after we are done;
// no unload, unfortunately :/
$gref = &$this->generator;
AnnotationRegistry::registerLoader(
function (string $class) use (&$gref): bool {
if ($gref) {
foreach ($gref->getNamespaces() as $namespace) {
if (strtolower(substr($class, 0, strlen($namespace))) === strtolower($namespace)) {
$loaded = class_exists($class);
if (!$loaded && $namespace === 'OpenApi\\Annotations\\') {
if (in_array(strtolower(substr($class, 20)), ['definition', 'path'])) {
// Detected an 2.x annotation?
throw new OpenApiException('The annotation @SWG\\' . substr($class, 20) . '() is deprecated. Found in ' . Generator::$context . "\nFor more information read the migration guide: https://github.com/zircote/swagger-php/blob/master/docs/Migrating-to-v3.md");
}
}
return $loaded;
}
}
}
return false;
}
);
}
}
public function pop(): void
{
$this->generator = null;
}
};
}
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 DocBlockAnnotationFactory(), new AttributeAnnotationFactory()]);
$this->analyser->setGenerator($this);
return $this->analyser;
}
public function setAnalyser(?AnalyserInterface $analyser): Generator
{
$this->analyser = $analyser;
return $this;
}
public function getDefaultConfig(): array
{
return [
'operationId' => [
'hash' => true,
],
];
}
public function getConfig(): array
{
return $this->config + $this->getDefaultConfig();
}
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 (null === $this->processorPipeline) {
$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\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;
}
/**
* @return array<ProcessorInterface|callable>
*
* @deprecated
*/
public function getProcessors(): array
{
return $this->getProcessorPipeline()->pipes();
}
/**
* @param array<ProcessorInterface|callable>|null $processors
*
* @deprecated
*/
public function setProcessors(?array $processors): Generator
{
$this->processorPipeline = null !== $processors ? new Pipeline($processors) : null;
return $this;
}
/**
* @param callable|ProcessorInterface $processor
* @param class-string|null $before
*
* @deprecated
*/
public function addProcessor($processor, ?string $before = null): Generator
{
$processors = $this->processorPipeline ?: $this->getProcessorPipeline();
if (!$before) {
$processors->add($processor);
} else {
$matcher = function (array $pipes) use ($before) {
foreach ($pipes as $ii => $current) {
if ($current instanceof $before) {
return $ii;
}
}
return null;
};
$processors->insert($processor, $matcher);
}
$this->processorPipeline = $processors;
return $this;
}
/**
* @param callable|ProcessorInterface $processor
*
* @deprecated
*/
public function removeProcessor($processor, bool $silent = false): Generator
{
$processors = $this->processorPipeline ?: $this->getProcessorPipeline();
$processors->remove($processor);
$this->processorPipeline = $processors;
return $this;
}
/**
* Update/replace an existing processor with a new one.
*
* @param ProcessorInterface|callable $processor the new processor
* @param null|callable $matcher Optional matcher callable to identify the processor to replace.
* If none given, matching is based on the processors class.
*
* @deprecated
*/
public function updateProcessor($processor, ?callable $matcher = null): Generator
{
$matcher = $matcher ?: function ($other) use ($processor): bool {
$otherClass = get_class($other);
return $processor instanceof $otherClass;
};
$processors = array_map(function ($other) use ($processor, $matcher) {
return $matcher($other) ? $processor : $other;
}, $this->getProcessors());
$this->setProcessors($processors);
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
* `function(Generator $generator, Analysis $analysis, Context $context): mixed`
*
* @return mixed the result of the `callable`
*/
public function withContext(callable $callable)
{
$rootContext = new Context([
'version' => $this->getVersion(),
'logger' => $this->getLogger(),
]);
$analysis = new Analysis([], $rootContext);
$this->configStack->push($this);
try {
return $callable($this, $analysis, $rootContext);
} finally {
$this->configStack->pop();
}
}
/**
* 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->configStack->push($this);
try {
$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();
}
} finally {
$this->configStack->pop();
}
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));
}
}
}
}
}