src/EventSubscriber/AddPaginationHeaders.php line 26

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  5. use App\Lib\CustomPaginator;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. final class AddPaginationHeaders implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * {@inheritdoc}
  14.      */
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             KernelEvents::RESPONSE => 'addHeaders'
  19.         ];
  20.     }
  21.     public function addHeaders(ResponseEvent $event): void
  22.     {
  23.         $request $event->getRequest();
  24.         if($request->headers->has("query-pagination")){
  25.             $response $event->getResponse();
  26.             $response->headers->add((array)json_decode($request->headers->get("query-pagination")));
  27.         }else if(stripos($request->getPathInfo(),"canvas")=== false && $request->getMethod() !== 'OPTIONS'
  28.             || (!is_null($request->query->get('pagination')) && (int)$request->query->get('pagination') !== 0)) {
  29.             //Todo revisar esto para eliminarlo en el futuro
  30.             if (($data $request->attributes->get('data')) && $data instanceof Paginator) {
  31.                 $from $data->count() ? ($data->getCurrentPage() - 1) * $data->getItemsPerPage() : 0;
  32.                 $to $data->getCurrentPage() < $data->getLastPage() ? $data->getCurrentPage() * $data->getItemsPerPage() : $data->getTotalItems();
  33.                 $response $event->getResponse();
  34.                 $response->headers->add([
  35.                     'pagination-content-range' => \sprintf('%u-%u/%u'$from$to$data->getTotalItems()),
  36.                     'pagination-items-per-page' => $data->getItemsPerPage(),
  37.                     //Todo el count del paginator no coincide con la consulta SQL en la bd, al menos no para la entidad ticket
  38.                     'pagination-total-items' => $data->getTotalItems(),
  39.                     'pagination-current-page' => $data->getCurrentPage(),
  40.                     'pagination-last-page' => $data->getLastPage(),
  41.                     'access-control-expose-headers' => array('pagination-content-range',
  42.                         'pagination-items-per-page',
  43.                         'pagination-total-items',
  44.                         'pagination-current-page',
  45.                         'pagination-last-page',
  46.                         'ETag',
  47.                         'Date',
  48.                         'x-switch-user')
  49.                 ]);
  50.             }
  51.         }
  52.     }
  53. }