Debian Codegraph @

vendor/zircote/swagger-php/src/Console/GenerateCommand.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi\Console;
8
9 use OpenApi\Annotations as OA;
10 use OpenApi\Generator;
11 use OpenApi\SourceFinder;
12 use Symfony\Component\Console\Attribute\AsCommand;
13 use Symfony\Component\Console\Attribute\MapInput;
14 use Symfony\Component\Console\Logger\ConsoleLogger;
15 use Symfony\Component\Console\Output\OutputInterface;
16 use Symfony\Component\Console\Style\SymfonyStyle;
17
18 #[AsCommand(
19 name: 'openapi',
20 description: 'Generate OpenAPI documentation',
21 )]
22 class GenerateCommand
23 {
24 public function __construct(
25 private ConsoleLogger $logger,
26 ) {
27 }
28
29 public function __invoke(#[MapInput] GenerateInput $input, SymfonyStyle $io): int
30 {
31 $io->setVerbosity($input->debug ? OutputInterface::VERBOSITY_DEBUG : $io->getVerbosity());
32
33 foreach ($input->getBootstrapFilenames() as $filename) {
34 if ($io->isVerbose()) {
35 $io->info('Bootstrapping: ' . $filename);
36 }
37
38 require_once($filename);
39 }
40
41 if ($input->defaults) {
42 $io->title('Default config');
43 $io->writeln(json_encode((new Generator())->getDefaultConfig(), JSON_PRETTY_PRINT));
44
45 return 0;
46 }
47
48 $openapi = $this->generate($input);
49
50 if (!$input->output) {
51 if ($input->format->isJson()) {
52 echo $openapi->toJson();
53 } else {
54 echo $openapi->toYaml();
55 }
56 echo "\n";
57 } else {
58 $outputPath = $input->output;
59 if (is_dir($outputPath)) {
60 $outputPath .= '/openapi.yaml';
61 }
62 $openapi->saveAs($outputPath, $input->format->value);
63 }
64
65 return $this->logger->hasErrored() ? 1 : 0;
66 }
67
68 private function generate(GenerateInput $input): OA\OpenApi
69 {
70 $generator = new Generator($this->logger);
71
72 foreach ($input->addProcessor as $processor) {
73 $class = '\OpenApi\Processors\\' . ucfirst((string) $processor);
74 if (class_exists($class)) {
75 $processor = new $class();
76 } elseif (class_exists($processor)) {
77 $processor = new $processor();
78 }
79 $generator->getProcessorPipeline()->add($processor);
80 }
81
82 foreach ($input->removeProcessor as $processor) {
83 $class = class_exists($processor)
84 ? $processor
85 : '\OpenApi\Processors\\' . ucfirst((string) $processor);
86 $generator->getProcessorPipeline()->remove($class);
87 }
88
89 return $generator
90 ->setVersion($input->version)
91 ->setConfig($input->config)
92 ->generate(new SourceFinder($input->paths, $input->exclude, $input->pattern));
93 }
94 }