vendor/ezsystems/ezpublish-kernel/eZ/Bundle/EzPublishRestBundle/EventListener/ResponseListener.php line 68

Open in your IDE?
  1. <?php
  2. /**
  3.  * @copyright Copyright (C) eZ Systems AS. All rights reserved.
  4.  * @license For full copyright and license information view LICENSE file distributed with this source code.
  5.  */
  6. namespace eZ\Bundle\EzPublishRestBundle\EventListener;
  7. use eZ\Publish\Core\REST\Server\View\AcceptHeaderVisitorDispatcher;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  11. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  12. /**
  13.  * REST Response Listener.
  14.  *
  15.  * Converts responses from REST controllers to REST Responses, depending on the Accept-Header value.
  16.  */
  17. class ResponseListener implements EventSubscriberInterface
  18. {
  19.     /** @var AcceptHeaderVisitorDispatcher */
  20.     private $viewDispatcher;
  21.     /**
  22.      * @param $viewDispatcher AcceptHeaderVisitorDispatcher
  23.      */
  24.     public function __construct(AcceptHeaderVisitorDispatcher $viewDispatcher)
  25.     {
  26.         $this->viewDispatcher $viewDispatcher;
  27.     }
  28.     /**
  29.      * @return array
  30.      */
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             KernelEvents::VIEW => 'onKernelResultView',
  35.             // Must happen BEFORE the Core ExceptionListener.
  36.             KernelEvents::EXCEPTION => ['onKernelExceptionView'20],
  37.         ];
  38.     }
  39.     /**
  40.      * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
  41.      */
  42.     public function onKernelResultView(GetResponseForControllerResultEvent $event)
  43.     {
  44.         if (!$event->getRequest()->attributes->get('is_rest_request')) {
  45.             return;
  46.         }
  47.         $event->setResponse(
  48.             $this->viewDispatcher->dispatch(
  49.                 $event->getRequest(),
  50.                 $event->getControllerResult()
  51.             )
  52.         );
  53.         $event->stopPropagation();
  54.     }
  55.     /**
  56.      * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  57.      *
  58.      * @throws \Exception
  59.      */
  60.     public function onKernelExceptionView(GetResponseForExceptionEvent $event)
  61.     {
  62.         if (!$event->getRequest()->attributes->get('is_rest_request')) {
  63.             return;
  64.         }
  65.         $event->setResponse(
  66.             $this->viewDispatcher->dispatch(
  67.                 $event->getRequest(),
  68.                 $event->getException()
  69.             )
  70.         );
  71.         $event->stopPropagation();
  72.     }
  73. }