shivas / versioning-bundle

Simple way to version (semantic versioning 2.0.0) your Symfony2/3/4/5/6 application
MIT License
112 stars 30 forks source link

Versioning in Swagger Api Platform #61

Open michnaadam33 opened 5 years ago

michnaadam33 commented 5 years ago

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.

Jayfrown commented 3 years ago

@michnaadam33 thanks I was looking for something like this :)