<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class HeaderSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => ['addHeaders', EventPriorities::POST_RESPOND],
];
}
public function addHeaders(ResponseEvent $event): void {
$request = $event->getRequest();
if (($data = $request->attributes->get('data')) && $data instanceof Paginator) {
$response = $event->getResponse();
$response->headers->add([
'X-Total' => $data->getTotalItems(),
]);
$event->setResponse($response);
}
}
}