Debian Codegraph @

vendor/zircote/swagger-php/src/Generator.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi;
8
9 use OpenApi\Analysers\AnalyserInterface;
10 use OpenApi\Analysers\AttributeAnnotationFactory;
11 use OpenApi\Analysers\DocBlockAnnotationFactory;
12 use OpenApi\Analysers\ReflectionAnalyser;
13 use OpenApi\Annotations as OA;
14 use OpenApi\Loggers\DefaultLogger;
15 use OpenApi\Type\TypeInfoTypeResolver;
16 use Psr\Log\LoggerInterface;
17
18 /**
19 * OpenApi spec generator.
20 *
21 * Scans PHP source code and generates OpenApi specifications from the found OpenApi annotations.
22 */
23 class Generator
24 {
25 /**
26 * Allows Annotation classes to know the context of the annotation that is being processed.
27 */
28 public static ?Context $context = null;
29
30 /** @var string Magic value to differentiate between null and undefined. */
31 public const UNDEFINED = '@OA\Generator::UNDEFINED🙈';
32
33 /** @var array<string,string> */
34 public const DEFAULT_ALIASES = ['oa' => 'OpenApi\\Annotations'];
35
36 /** @var list<string> */
37 public const DEFAULT_NAMESPACES = ['OpenApi\\Annotations\\'];
38
39 /** @var array<string,string> Map of namespace aliases to be supported by doctrine. */
40 protected array $aliases;
41
42 /** @var array<string>|null List of annotation namespaces to be autoloaded by doctrine. */
43 protected ?array $namespaces;
44
45 protected ?AnalyserInterface $analyser = null;
46
47 /** @var array<string,mixed> */
48 protected array $config = [];
49
50 protected ?Pipeline $processorPipeline = null;
51
52 protected ?TypeResolverInterface $typeResolver = null;
53
54 protected ?LoggerInterface $logger = null;
55
56 /**
57 * OpenApi version override.
58 *
59 * If set, it will override the version set in the <code>OpenApi</code> annotation.
60 *
61 * Due to the order of processing, any conditional code using this (via <code>Context::$version</code>)
62 * must come only after the analysis is finished.
63 */
64 protected ?string $version = null;
65
66 public function __construct(?LoggerInterface $logger = null)
67 {
68 $this->logger = $logger;
69
70 $this->setAliases(self::DEFAULT_ALIASES);
71 $this->setNamespaces(self::DEFAULT_NAMESPACES);
72 }
73
74 public static function isDefault(...$value): bool
75 {
76 foreach ($value as $v) {
77 if ($v !== Generator::UNDEFINED) {
78 return false;
79 }
80 }
81
82 return true;
83 }
84
85 /**
86 * @return array<string, string>
87 */
88 public function getAliases(): array
89 {
90 return $this->aliases;
91 }
92
93 public function addAlias(string $alias, string $namespace): Generator
94 {
95 $this->aliases[$alias] = $namespace;
96
97 return $this;
98 }
99
100 public function setAliases(array $aliases): Generator
101 {
102 $this->aliases = $aliases;
103
104 return $this;
105 }
106
107 /**
108 * @return list<string>|null
109 */
110 public function getNamespaces(): ?array
111 {
112 return $this->namespaces;
113 }
114
115 public function addNamespace(string $namespace): Generator
116 {
117 $namespaces = (array) $this->getNamespaces();
118 $namespaces[] = $namespace;
119
120 return $this->setNamespaces(array_unique($namespaces));
121 }
122
123 public function setNamespaces(?array $namespaces): Generator
124 {
125 $this->namespaces = $namespaces;
126
127 return $this;
128 }
129
130 public function getAnalyser(): AnalyserInterface
131 {
132 $generatorConfig = $this->getConfig()['generator'];
133 $this->analyser = $this->analyser ?: new ReflectionAnalyser([
134 new AttributeAnnotationFactory($generatorConfig['ignoreOtherAttributes']),
135 new DocBlockAnnotationFactory(),
136 ]);
137 $this->analyser->setGenerator($this);
138
139 return $this->analyser;
140 }
141
142 public function setAnalyser(?AnalyserInterface $analyser): Generator
143 {
144 $this->analyser = $analyser;
145
146 return $this;
147 }
148
149 public function getDefaultConfig(): array
150 {
151 return [
152 'generator' => [
153 'ignoreOtherAttributes' => false,
154 ],
155 'mergeIntoOpenApi' => [
156 'mergeComponents' => false,
157 ],
158 'expandEnums' => [
159 'enumNames' => null,
160 ],
161 'augmentParameters' => [
162 'augmentOperationParameters' => true,
163 ],
164 'pathFilter' => [
165 'tags' => [],
166 'paths' => [],
167 ],
168 'cleanUnusedComponents' => [
169 'enabled' => false,
170 ],
171 'augmentTags' => [
172 'whitelist' => [],
173 'withDescription' => true,
174 ],
175 'operationId' => [
176 'hash' => true,
177 ],
178 ];
179 }
180
181 public function getConfig(): array
182 {
183 return $this->config + $this->getDefaultConfig();
184 }
185
186 protected function normaliseConfig(array $config): array
187 {
188 $normalised = [];
189 foreach ($config as $key => $value) {
190 if (is_numeric($key)) {
191 $token = explode('=', (string) $value);
192 if (2 === count($token)) {
193 // 'operationId.hash=false'
194 [$key, $value] = $token;
195 }
196 }
197
198 if (in_array($value, ['true', 'false'])) {
199 $value = 'true' == $value;
200 }
201
202 if ($isList = (str_ends_with((string) $key, '[]'))) {
203 $key = substr((string) $key, 0, -2);
204 }
205 $token = explode('.', (string) $key);
206 if (2 === count($token)) {
207 // 'operationId.hash' => false
208 // namespaced / processor
209 if ($isList) {
210 $normalised[$token[0]][$token[1]][] = $value;
211 } else {
212 $normalised[$token[0]][$token[1]] = $value;
213 }
214 } else {
215 if ($isList) {
216 $normalised[$key][] = $value;
217 } else {
218 $normalised[$key] = $value;
219 }
220 }
221 }
222
223 return $normalised;
224 }
225
226 /**
227 * Set generator and/or processor config.
228 *
229 * @param array<string,mixed> $config
230 */
231 public function setConfig(array $config): Generator
232 {
233 $this->config = $this->normaliseConfig($config) + $this->config;
234
235 return $this;
236 }
237
238 public function getProcessorPipeline(): Pipeline
239 {
240 if (!$this->processorPipeline instanceof Pipeline) {
241 $this->processorPipeline = new Pipeline([
242 new Processors\DocBlockDescriptions(),
243 new Processors\MergeIntoOpenApi(),
244 new Processors\MergeIntoComponents(),
245 new Processors\ExpandClasses(),
246 new Processors\ExpandInterfaces(),
247 new Processors\ExpandTraits(),
248 new Processors\ExpandEnums(),
249 new Processors\AugmentSchemas(),
250 new Processors\AugmentRequestBody(),
251 new Processors\AugmentProperties(),
252 new Processors\AugmentDiscriminators(),
253 new Processors\BuildPaths(),
254 new Processors\AugmentParameters(),
255 new Processors\AugmentRefs(),
256 new Processors\AugmentItems(),
257 new Processors\MergeJsonContent(),
258 new Processors\MergeXmlContent(),
259 new Processors\AugmentMediaType(),
260 new Processors\OperationId(),
261 new Processors\CleanUnmerged(),
262 new Processors\PathFilter(),
263 new Processors\CleanUnusedComponents(),
264 new Processors\AugmentTags(),
265 ]);
266 }
267
268 $config = $this->getConfig();
269 $walker = function (callable $pipe) use ($config): void {
270 $rc = new \ReflectionClass($pipe);
271
272 // apply config
273 $processorKey = lcfirst($rc->getShortName());
274 if (array_key_exists($processorKey, $config)) {
275 foreach ($config[$processorKey] as $name => $value) {
276 $setter = 'set' . ucfirst($name);
277 if (method_exists($pipe, $setter)) {
278 $pipe->{$setter}($value);
279 }
280 }
281 }
282
283 if (is_a($pipe, GeneratorAwareInterface::class)) {
284 $pipe->setGenerator($this);
285 }
286 };
287
288 return $this->processorPipeline->walk($walker);
289 }
290
291 public function setProcessorPipeline(?Pipeline $processor): Generator
292 {
293 $this->processorPipeline = $processor;
294
295 $walker = function (callable $pipe): void {
296 if (is_a($pipe, GeneratorAwareInterface::class)) {
297 $pipe->setGenerator($this);
298 }
299 };
300
301 if ($this->processorPipeline) {
302 $this->processorPipeline->walk($walker);
303 }
304
305 return $this;
306 }
307
308 /**
309 * Chainable method that allows to modify the processor pipeline.
310 *
311 * @param callable $with callable with the current processor pipeline passed in
312 */
313 public function withProcessorPipeline(callable $with): Generator
314 {
315 $with($this->getProcessorPipeline());
316
317 return $this;
318 }
319
320 public function setTypeResolver(?TypeResolverInterface $typeResolver): Generator
321 {
322 $this->typeResolver = $typeResolver;
323
324 return $this;
325 }
326
327 public function getTypeResolver(): TypeResolverInterface
328 {
329 $this->typeResolver ??= new TypeInfoTypeResolver();
330
331 return $this->typeResolver;
332 }
333
334 public function getLogger(): ?LoggerInterface
335 {
336 $this->logger ??= new DefaultLogger();
337
338 return $this->logger;
339 }
340
341 public function getVersion(): ?string
342 {
343 return $this->version;
344 }
345
346 public function setVersion(?string $version): Generator
347 {
348 $this->version = $version;
349
350 return $this;
351 }
352
353 /**
354 * Run code in the context of this generator.
355 *
356 * @param callable $callable Callable in the form of
357 * <code>function(Generator $generator, Analysis $analysis, Context $context): mixed</code>
358 *
359 * @return mixed the result of the <code>callable</code>
360 */
361 public function withContext(callable $callable)
362 {
363 $rootContext = new Context([
364 'version' => $this->getVersion(),
365 'logger' => $this->getLogger(),
366 ]);
367 $analysis = new Analysis([], $rootContext);
368
369 return $callable($this, $analysis, $rootContext);
370 }
371
372 /**
373 * Generate OpenAPI spec by scanning the given source files.
374 *
375 * @param iterable $sources PHP source files to scan.
376 * Supported sources:
377 * * string - file / directory name
378 * * \SplFileInfo
379 * * \Symfony\Component\Finder\Finder
380 * @param null|Analysis $analysis custom analysis instance
381 * @param bool $validate flag to enable/disable validation of the returned spec
382 */
383 public function generate(iterable $sources, ?Analysis $analysis = null, bool $validate = true): ?OA\OpenApi
384 {
385 $rootContext = new Context([
386 'version' => $this->getVersion(),
387 'logger' => $this->getLogger(),
388 ]);
389
390 $analysis = $analysis ?: new Analysis([], $rootContext);
391 $analysis->context = $analysis->context ?: $rootContext;
392
393 $this->scanSources($sources, $analysis, $rootContext);
394
395 // post-processing
396 $this->getProcessorPipeline()->process($analysis);
397
398 if ($analysis->openapi) {
399 // overwrite default/annotated version
400 $analysis->openapi->openapi = $this->getVersion() ?: $analysis->openapi->openapi;
401 // update context to provide the same to validation/serialisation code
402 $rootContext->version = $analysis->openapi->openapi;
403 }
404
405 // validation
406 if ($validate) {
407 $analysis->validate();
408 }
409
410 return $analysis->openapi;
411 }
412
413 protected function scanSources(iterable $sources, Analysis $analysis, Context $rootContext): void
414 {
415 $analyser = $this->getAnalyser();
416
417 foreach ($sources as $source) {
418 if (is_iterable($source)) {
419 $this->scanSources($source, $analysis, $rootContext);
420 } else {
421 $resolvedSource = $source instanceof \SplFileInfo ? $source->getPathname() : realpath($source);
422 if (!$resolvedSource) {
423 $rootContext->logger->warning(sprintf('Skipping invalid source: %s', $source));
424 continue;
425 }
426 if (is_dir($resolvedSource)) {
427 $this->scanSources(new SourceFinder($resolvedSource), $analysis, $rootContext);
428 } else {
429 $rootContext->logger->debug(sprintf('Analysing source: %s', $resolvedSource));
430 $analysis->addAnalysis($analyser->fromFile($resolvedSource, $rootContext));
431 }
432 }
433 }
434 }
435 }