src/EventSubscriber/ResponseFormatterSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  4. use App\Entity\NormResponseInterface;
  5. use App\Services\ResponseFormatterService;
  6. use ReflectionClass;
  7. use ReflectionException;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class ResponseFormatterSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var ResponseFormatterService
  15.      */
  16.     private $responseService;
  17.     public function __construct(ResponseFormatterService $responseService)
  18.     {
  19.         $this->responseService $responseService;
  20.     }
  21.     /**
  22.      * @return array<mixed>
  23.      */
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::RESPONSE => ['onKernelResponse', -10],
  28.         ];
  29.     }
  30.     /**
  31.      * @param ResponseEvent $event
  32.      * @return void
  33.      * @throws ReflectionException
  34.      */
  35.     public function onKernelResponse(ResponseEvent $event): void
  36.     {
  37.         $request $event->getRequest();
  38.         $className $request->attributes->get('_api_resource_class');
  39.         $isNormalizable $className && (new ReflectionClass($className))->implementsInterface(NormResponseInterface::class);
  40.         if ($isNormalizable) {
  41.             $response $event->getResponse();
  42.             if (str_contains($response->headers->get('Content-Type'), 'json')) {
  43.                 $data $this->responseService->norm(null$response);
  44.                 if (($_data $request->attributes->get('data')) && $_data instanceof Paginator) {
  45.                     if (!is_null($data['data']) && array_key_first($data['data']) === 0) {
  46.                         $data['total'] = $_data->getTotalItems();
  47.                         $data['current_page'] = $_data->getCurrentPage();
  48.                         $data['last_page'] = $_data->getLastPage();
  49.                     }
  50.                 }
  51.                 $response->setContent(json_encode($data));
  52.             }
  53.         }
  54.     }
  55. }