<?php
namespace App\Events;
use App\Entity\CommunityPost;
use App\Entity\GardenProjectDocument;
use ReflectionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Services\Api\Community\ResponseService;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Entity\CommunityServiceResponse;
use App\Entity\NormeResponseInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ResponseSubscriber implements EventSubscriberInterface
{
/**
* @var ResponseService
*/
private $responseService;
public function __construct(ResponseService $responseService)
{
$this->responseService = $responseService;
}
/**
* @param ResponseEvent $event
* @return void
* @throws ReflectionException
*/
public function onKernelResponse(ResponseEvent $event): void
{
// dd($event);
$request = $event->getRequest();
$object = $request->attributes->get('_api_resource_class');
$isObject = $object && (new \ReflectionClass($object))->implementsInterface(NormeResponseInterface::class);
if ($object and $isObject) {
$response = $event->getResponse();
if ($request->attributes->get('_controller') === 'api_platform.action.get_subresource') {
$this->responseService->checkResult($response);
}
if (str_contains($response->headers->get('Content-Type'), 'json')) {
$responseDataChange = null;
if ($object == CommunityPost::class || $object == CommunityServiceResponse::class) {
$responseDataChange = $this->responseService->formatPostData($response, $request);
}
$data = $this->responseService->norme($responseDataChange, $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));
}
}
}
/**
* @return array|string[]
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}