<?php
declare(strict_types=1);
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class VersionDeprecationHeaderListener
*/
class VersionDeprecationHeaderListener implements EventSubscriberInterface
{
private $lastVersion;
private $sunsetVersions;
private $unsupportedVersions;
public function __construct(
string $apiUnsupportedVersions,
string $apiSunsetVersions,
string $apiLastVersion
) {
$this->unsupportedVersions = explode(',', $apiUnsupportedVersions);
$this->sunsetVersions = explode(',', $apiSunsetVersions);
$this->lastVersion = $apiLastVersion;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'addVersionDeprecationHeader',
];
}
public function addVersionDeprecationHeader(ResponseEvent $event): void
{
$response = $event->getResponse();
if (!$response instanceof JsonResponse) {
return;
}
$routeArray = explode('/', $event->getRequest()->getRequestUri());
if ($routeArray[1] !== 'api') {
return;
}
$currentVersion = $routeArray[2];
if (strpos($currentVersion, 'v') !== 0) {
return;
}
$isSupported = in_array($currentVersion, $this->unsupportedVersions, true) ? false : true;
$headers['Api-Supported'] = $isSupported;
$headers['Api-Last-Version'] = $this->lastVersion;
$headers['Api-Current-Version'] = $currentVersion;
$response->headers->add($headers);
}
}