src/EventListener/CollectionResponseListener.php line 37

Open in your IDE?
  1. <?php
  2. // src/EventListener/CustomCollectionResponseListener.php
  3. namespace App\EventListener;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  6. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. class CollectionResponseListener implements EventSubscriberInterface
  12. {
  13.     private ResourceMetadataFactoryInterface $resourceMetadataFactory;
  14.     private ParameterBagInterface $parameterBag;
  15.     public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactoryParameterBagInterface $parameterBag)
  16.     {
  17.         $this->resourceMetadataFactory $resourceMetadataFactory;
  18.         $this->parameterBag $parameterBag;
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return [
  23.             KernelEvents::VIEW => ['onKernelView'EventPriorities::POST_SERIALIZE],
  24.         ];
  25.     }
  26.     public function onKernelView(ViewEvent $event): void
  27.     {
  28.         $request $event->getRequest();
  29.         $result json_decode($event->getControllerResult(), true);
  30.         if ($request->isMethod(Request::METHOD_GET) && array_key_exists('hydra:view'$result)) {
  31.             $resourceClass $request->attributes->get('_api_resource_class');
  32.             if ($resourceClass) {
  33.                 $resourceMetadata $this->resourceMetadataFactory->create($resourceClass);
  34.                 $itemsPerPage $resourceMetadata->getCollectionOperationAttribute('get''pagination_items_per_page'30true);
  35.                 $result['hydra:itemsPerPage'] = $itemsPerPage// Add your custom data here
  36.                 $event->setControllerResult($result);
  37.             } else {
  38.                 $itemsPerPage $this->parameterBag->get('api_platform.collection.pagination.items_per_page');
  39.                 $result['hydra:itemsPerPage'] = $itemsPerPage// Add your custom data here
  40.                 $event->setControllerResult($result);
  41.             }
  42.             $event->setControllerResult(json_encode($result));
  43.         }
  44.     }
  45. }