src/EventListener/VersionDeprecationHeaderListener.php line 38

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventListener;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. /**
  9.  * Class VersionDeprecationHeaderListener
  10.  */
  11. class VersionDeprecationHeaderListener implements EventSubscriberInterface
  12. {
  13.     private $lastVersion;
  14.     private $sunsetVersions;
  15.     private $unsupportedVersions;
  16.     public function __construct(
  17.         string $apiUnsupportedVersions,
  18.         string $apiSunsetVersions,
  19.         string $apiLastVersion
  20.     ) {
  21.         $this->unsupportedVersions explode(','$apiUnsupportedVersions);
  22.         $this->sunsetVersions explode(','$apiSunsetVersions);
  23.         $this->lastVersion $apiLastVersion;
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::RESPONSE => 'addVersionDeprecationHeader',
  29.         ];
  30.     }
  31.     public function addVersionDeprecationHeader(ResponseEvent $event): void
  32.     {
  33.         $response $event->getResponse();
  34.         if (!$response instanceof JsonResponse) {
  35.             return;
  36.         }
  37.         $routeArray explode('/'$event->getRequest()->getRequestUri());
  38.         if ($routeArray[1] !== 'api') {
  39.             return;
  40.         }
  41.         $currentVersion $routeArray[2];
  42.         if (strpos($currentVersion'v') !== 0) {
  43.             return;
  44.         }
  45.         $isSupported in_array($currentVersion$this->unsupportedVersionstrue) ? false true;
  46.         $headers['Api-Supported'] = $isSupported;
  47.         $headers['Api-Last-Version'] = $this->lastVersion;
  48.         $headers['Api-Current-Version'] = $currentVersion;
  49.         $response->headers->add($headers);
  50.     }
  51. }