<?php
// src/EventListener/CustomCollectionResponseListener.php
namespace App\EventListener;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class CollectionResponseListener implements EventSubscriberInterface
{
private ResourceMetadataFactoryInterface $resourceMetadataFactory;
private ParameterBagInterface $parameterBag;
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, ParameterBagInterface $parameterBag)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->parameterBag = $parameterBag;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE],
];
}
public function onKernelView(ViewEvent $event): void
{
$request = $event->getRequest();
$result = json_decode($event->getControllerResult(), true);
if ($request->isMethod(Request::METHOD_GET) && array_key_exists('hydra:view', $result)) {
$resourceClass = $request->attributes->get('_api_resource_class');
if ($resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$itemsPerPage = $resourceMetadata->getCollectionOperationAttribute('get', 'pagination_items_per_page', 30, true);
$result['hydra:itemsPerPage'] = $itemsPerPage; // Add your custom data here
$event->setControllerResult($result);
} else {
$itemsPerPage = $this->parameterBag->get('api_platform.collection.pagination.items_per_page');
$result['hydra:itemsPerPage'] = $itemsPerPage; // Add your custom data here
$event->setControllerResult($result);
}
$event->setControllerResult(json_encode($result));
}
}
}