vendor/friendsofsymfony/rest-bundle/EventListener/ResponseStatusCodeListener.php line 43

  1. <?php
  2. /*
  3.  * This file is part of the FOSRestBundle package.
  4.  *
  5.  * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace FOS\RestBundle\EventListener;
  11. use FOS\RestBundle\FOSRestBundle;
  12. use FOS\RestBundle\Util\ExceptionValueMap;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  15. use Symfony\Component\HttpKernel\Event\KernelEvent;
  16. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. /**
  19.  * @author Christian Flothmann <christian.flothmann@sensiolabs.de>
  20.  */
  21. class ResponseStatusCodeListener implements EventSubscriberInterface
  22. {
  23.     private $exceptionValueMap;
  24.     private $responseStatusCode;
  25.     public function __construct(ExceptionValueMap $exceptionValueMap)
  26.     {
  27.         $this->exceptionValueMap $exceptionValueMap;
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             KernelEvents::EXCEPTION => 'getResponseStatusCodeFromThrowable',
  33.             KernelEvents::RESPONSE => 'setResponseStatusCode',
  34.         ];
  35.     }
  36.     public function getResponseStatusCodeFromThrowable(ExceptionEvent $event): void
  37.     {
  38.         if (!$this->isMainRequest($event)) {
  39.             return;
  40.         }
  41.         $request $event->getRequest();
  42.         if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTEtrue)) {
  43.             return;
  44.         }
  45.         $statusCode $this->exceptionValueMap->resolveFromClassName(get_class($event->getThrowable()));
  46.         if (is_int($statusCode)) {
  47.             $this->responseStatusCode $statusCode;
  48.         }
  49.     }
  50.     public function setResponseStatusCode(ResponseEvent $event): void
  51.     {
  52.         if (!$this->isMainRequest($event)) {
  53.             return;
  54.         }
  55.         if (null !== $this->responseStatusCode) {
  56.             $event->getResponse()->setStatusCode($this->responseStatusCode);
  57.             $this->responseStatusCode null;
  58.         }
  59.     }
  60.     private function isMainRequest(KernelEvent $event): bool
  61.     {
  62.         if (method_exists($event'isMainRequest')) {
  63.             return $event->isMainRequest();
  64.         }
  65.         return $event->isMasterRequest();
  66.     }
  67. }