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

Open in your IDE?
  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\ResponseEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. /**
  18.  * @author Christian Flothmann <christian.flothmann@sensiolabs.de>
  19.  */
  20. class ResponseStatusCodeListener implements EventSubscriberInterface
  21. {
  22.     private $exceptionValueMap;
  23.     private $responseStatusCode;
  24.     public function __construct(ExceptionValueMap $exceptionValueMap)
  25.     {
  26.         $this->exceptionValueMap $exceptionValueMap;
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             KernelEvents::EXCEPTION => 'getResponseStatusCodeFromThrowable',
  32.             KernelEvents::RESPONSE => 'setResponseStatusCode',
  33.         ];
  34.     }
  35.     /**
  36.      * @param ExceptionEvent $event
  37.      */
  38.     public function getResponseStatusCodeFromThrowable($event): void
  39.     {
  40.         if (!$event->isMasterRequest()) {
  41.             return;
  42.         }
  43.         $request $event->getRequest();
  44.         if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTEtrue)) {
  45.             return;
  46.         }
  47.         if (method_exists($event'getThrowable')) {
  48.             $throwable $event->getThrowable();
  49.         } else {
  50.             $throwable $event->getException();
  51.         }
  52.         $statusCode $this->exceptionValueMap->resolveThrowable($throwable);
  53.         if (is_int($statusCode)) {
  54.             $this->responseStatusCode $statusCode;
  55.         }
  56.     }
  57.     /**
  58.      * @param ResponseEvent $event
  59.      */
  60.     public function setResponseStatusCode($event): void
  61.     {
  62.         if (!$event->isMasterRequest()) {
  63.             return;
  64.         }
  65.         if (null !== $this->responseStatusCode) {
  66.             $event->getResponse()->setStatusCode($this->responseStatusCode);
  67.             $this->responseStatusCode null;
  68.         }
  69.     }
  70. }