<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Entity\NormResponseInterface;
use App\Services\ResponseFormatterService;
use ReflectionClass;
use ReflectionException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ResponseFormatterSubscriber implements EventSubscriberInterface
{
/**
* @var ResponseFormatterService
*/
private $responseService;
public function __construct(ResponseFormatterService $responseService)
{
$this->responseService = $responseService;
}
/**
* @return array<mixed>
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', -10],
];
}
/**
* @param ResponseEvent $event
* @return void
* @throws ReflectionException
*/
public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
$className = $request->attributes->get('_api_resource_class');
$isNormalizable = $className && (new ReflectionClass($className))->implementsInterface(NormResponseInterface::class);
if ($isNormalizable) {
$response = $event->getResponse();
if (str_contains($response->headers->get('Content-Type'), 'json')) {
$data = $this->responseService->norm(null, $response);
if (($_data = $request->attributes->get('data')) && $_data instanceof Paginator) {
if (!is_null($data['data']) && array_key_first($data['data']) === 0) {
$data['total'] = $_data->getTotalItems();
$data['current_page'] = $_data->getCurrentPage();
$data['last_page'] = $_data->getLastPage();
}
}
$response->setContent(json_encode($data));
}
}
}
}