Last active
April 5, 2021 14:25
-
-
Save jgauthi/060f35a989e8f2e3ed6b768a6951f54d to your computer and use it in GitHub Desktop.
[Symfony] Export Apidoc to YAML File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// src/Command/ExportSwaggerCommand.php | |
namespace App\Command; | |
use Nelmio\ApiDocBundle\ApiDocGenerator; | |
use Symfony\Component\Console\Command\Command; | |
use Symfony\Component\Console\Input\{InputArgument, InputInterface}; | |
use Symfony\Component\Console\Output\OutputInterface; | |
use Symfony\Component\Console\Style\SymfonyStyle; | |
use Symfony\Component\Yaml\Yaml; | |
class ExportSwaggerCommand extends Command | |
{ | |
public const NAME = 'api:swagger:export'; | |
private const YAML_INLINE = 20; | |
private const YAML_INDENT = 2; | |
public function __construct(private string $kernelProjectDir, private ApiDocGenerator $apiDocGenerator) | |
{ | |
parent::__construct(); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
protected function configure(): void | |
{ | |
$this | |
->setName(self::NAME) | |
->addArgument('output_path', InputArgument::OPTIONAL, 'The output path of the swagger.yml file', './var') | |
->setDescription('Exports a swagger file for the API') | |
->setHelp('This command allows you to export the swagger definition yml file of the API') | |
; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
protected function execute(InputInterface $input, OutputInterface $output): int | |
{ | |
$io = new SymfonyStyle($input, $output); | |
$io->title($this->getDescription()); | |
$spec = $this->apiDocGenerator->generate()->toArray(); | |
$swaggerFile = $this->kernelProjectDir .'/'. $input->getArgument('output_path') . '/swagger.yaml'; | |
$io->writeln(sprintf('Writing file <info>%s</info>...', $swaggerFile)); | |
$exportFile = file_put_contents( | |
$swaggerFile, | |
Yaml::dump( | |
$spec, | |
self::YAML_INLINE, | |
self::YAML_INDENT, | |
Yaml::DUMP_OBJECT_AS_MAP | Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK | Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | |
) | |
); | |
return (($exportFile) ? Command::SUCCESS : Command::FAILURE); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/services.yaml | |
services: | |
_defaults: | |
# ... | |
bind: | |
$kernelProjectDir: '%kernel.project_dir%' | |
Nelmio\ApiDocBundle\ApiDocGenerator: '@nelmio_api_doc.generator.default' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment