Skip to content

Versioning in Swagger Api Platform #61

@michnaadam33

Description

@michnaadam33

I had to use versioning-bundle on ApliPlatform so I had to create simple normalizer for that.

use ApiPlatform\Core\Documentation\Documentation;
use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
use Shivas\VersioningBundle\Service\VersionManager;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class SwaggerVersionNormalizer implements
    NormalizerInterface,
    NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    public const ALREADY_CALLED = 'SWAGGER_DECORATOR_NORMALIZER_ALREADY_CALLED';

    /** @var VersionManager  */
    private $versionManager;

    public function __construct(VersionManager $versionManager)
    {
        $this->versionManager = $versionManager;
    }

    /**
     * @param Documentation $object
     * @param string $format
     * @param array $context
     * @return array
     * @throws \Psr\Cache\InvalidArgumentException
     * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
     */
    public function normalize($object, $format = null, array $context = []): array
    {
        $context[self::ALREADY_CALLED] = true;
        $result = $this->normalizer->normalize($object, $format, $context);

        if (isset($result['info'])) {
            $result['info']['version'] = $this->versionManager->getVersion()->getVersionString();
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsNormalization($data, $format = null, array $context = [])
    {
        if (isset($context[self::ALREADY_CALLED])) {
            return false;
        }
        return DocumentationNormalizer::FORMAT === $format && $data instanceof Documentation;
    }
}

I think it can be helpful for someone.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions