|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Fazland\ApiPlatformBundle\HttpKernel; |
| 4 | + |
| 5 | +use Fazland\ApiPlatformBundle\Annotation\Sunset; |
| 6 | +use Fazland\ApiPlatformBundle\Annotation\View as ViewAnnotation; |
| 7 | +use Fazland\ApiPlatformBundle\HttpKernel\View\Context; |
| 8 | +use Fazland\ApiPlatformBundle\HttpKernel\View\View; |
| 9 | +use Kcs\Serializer\Exception\UnsupportedFormatException; |
| 10 | +use Kcs\Serializer\Type\Type; |
| 11 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 12 | +use Symfony\Component\HttpFoundation\Response; |
| 13 | +use Symfony\Component\HttpKernel\Event\FilterResponseEvent; |
| 14 | +use Symfony\Component\HttpKernel\KernelEvents; |
| 15 | + |
| 16 | +/** |
| 17 | + * Adds Sunset header field if Sunset annotation is found. |
| 18 | + * |
| 19 | + * @see https://tools.ietf.org/html/draft-wilde-sunset-header-10 |
| 20 | + */ |
| 21 | +class SunsetHandler implements EventSubscriberInterface |
| 22 | +{ |
| 23 | + /** |
| 24 | + * Modify the response adding a Sunset header if needed. |
| 25 | + * |
| 26 | + * @param FilterResponseEvent $event |
| 27 | + */ |
| 28 | + public function onResponse(FilterResponseEvent $event): void |
| 29 | + { |
| 30 | + $request = $event->getRequest(); |
| 31 | + |
| 32 | + $annotation = $request->attributes->get('_rest_sunset'); |
| 33 | + if (! $annotation instanceof Sunset) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + $date = new \DateTimeImmutable($annotation->date); |
| 38 | + |
| 39 | + $response = $event->getResponse(); |
| 40 | + $response->headers->set('Sunset', $date->format(\DateTime::RFC2822)); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * {@inheritdoc} |
| 45 | + */ |
| 46 | + public static function getSubscribedEvents(): array |
| 47 | + { |
| 48 | + return [ |
| 49 | + KernelEvents::RESPONSE => 'onResponse', |
| 50 | + ]; |
| 51 | + } |
| 52 | +} |
0 commit comments