lib/boab/cms-bundle/src/EventListener/ApiResponseListener.php line 22

Open in your IDE?
  1. <?php
  2. namespace Boab\CmsBundle\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpKernel\Event\ViewEvent;
  5. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  6. use Symfony\Component\Serializer\Normalizer\NormalizerInterface as nic;
  7. use Symfony\Component\Serializer\SerializerInterface;
  8. class ApiResponseListener
  9. {
  10.     private $serializer;
  11.     public function __construct(SerializerInterface $serializer)
  12.     {
  13.         $this->serializer $serializer;
  14.     }
  15.     public function onKernelView(ViewEvent $event)
  16.     {
  17.         $request $event->getRequest();
  18.         $controllerResult $event->getControllerResult();
  19.         if(!$request->attributes->has('_api')){
  20.             return;
  21.         }
  22.         if(is_array($controllerResult)){
  23.             $response = new JsonResponse($controllerResult);
  24.         }else{
  25.             $response = new JsonResponse();
  26.             $response->setContent($controllerResult);
  27.         }
  28.         
  29.         $response->setStatusCode(200);
  30.         $event->setResponse($response);
  31.     }
  32.     public function onKernelResponse(ResponseEvent $event)
  33.     {
  34.         $request $event->getRequest();
  35.         $result $event->getResponse();
  36.         if($result instanceof SelfAwareNormalizerInterface || $result instanceof NormalizerInterface ){
  37.             $json $this->serializer->serialize($result);
  38.             $jsonResponse = new JsonResponse($json);
  39.             $event->setResponse($jsonResponse);
  40.             return;
  41.         }
  42.     }