<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Lib\CustomPaginator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class AddPaginationHeaders implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'addHeaders'
];
}
public function addHeaders(ResponseEvent $event): void
{
$request = $event->getRequest();
if($request->headers->has("query-pagination")){
$response = $event->getResponse();
$response->headers->add((array)json_decode($request->headers->get("query-pagination")));
}else if(stripos($request->getPathInfo(),"canvas")=== false && $request->getMethod() !== 'OPTIONS'
|| (!is_null($request->query->get('pagination')) && (int)$request->query->get('pagination') !== 0)) {
//Todo revisar esto para eliminarlo en el futuro
if (($data = $request->attributes->get('data')) && $data instanceof Paginator) {
$from = $data->count() ? ($data->getCurrentPage() - 1) * $data->getItemsPerPage() : 0;
$to = $data->getCurrentPage() < $data->getLastPage() ? $data->getCurrentPage() * $data->getItemsPerPage() : $data->getTotalItems();
$response = $event->getResponse();
$response->headers->add([
'pagination-content-range' => \sprintf('%u-%u/%u', $from, $to, $data->getTotalItems()),
'pagination-items-per-page' => $data->getItemsPerPage(),
//Todo el count del paginator no coincide con la consulta SQL en la bd, al menos no para la entidad ticket
'pagination-total-items' => $data->getTotalItems(),
'pagination-current-page' => $data->getCurrentPage(),
'pagination-last-page' => $data->getLastPage(),
'access-control-expose-headers' => array('pagination-content-range',
'pagination-items-per-page',
'pagination-total-items',
'pagination-current-page',
'pagination-last-page',
'ETag',
'Date',
'x-switch-user')
]);
}
}
}
}