vendor/symfony/http-kernel/EventListener/ErrorListener.php line 45

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\HttpKernel\EventListener;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  16. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  17. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  18. use Symfony\Component\HttpKernel\Exception\HttpException;
  19. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  20. use Symfony\Component\HttpKernel\HttpKernelInterface;
  21. use Symfony\Component\HttpKernel\KernelEvents;
  22. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  23. /**
  24.  * @author Fabien Potencier <fabien@symfony.com>
  25.  */
  26. class ErrorListener implements EventSubscriberInterface
  27. {
  28.     protected $controller;
  29.     protected $logger;
  30.     protected $debug;
  31.     protected $exceptionsMapping;
  32.     public function __construct(string|object|array|null $controllerLoggerInterface $logger nullbool $debug false, array $exceptionsMapping = [])
  33.     {
  34.         $this->controller $controller;
  35.         $this->logger $logger;
  36.         $this->debug $debug;
  37.         $this->exceptionsMapping $exceptionsMapping;
  38.     }
  39.     public function logKernelException(ExceptionEvent $event)
  40.     {
  41.         $throwable $event->getThrowable();
  42.         $logLevel null;
  43.         foreach ($this->exceptionsMapping as $class => $config) {
  44.             if ($throwable instanceof $class && $config['log_level']) {
  45.                 $logLevel $config['log_level'];
  46.                 break;
  47.             }
  48.         }
  49.         foreach ($this->exceptionsMapping as $class => $config) {
  50.             if (!$throwable instanceof $class || !$config['status_code']) {
  51.                 continue;
  52.             }
  53.             if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() !== $config['status_code']) {
  54.                 $headers $throwable instanceof HttpExceptionInterface $throwable->getHeaders() : [];
  55.                 $throwable = new HttpException($config['status_code'], $throwable->getMessage(), $throwable$headers);
  56.                 $event->setThrowable($throwable);
  57.             }
  58.             break;
  59.         }
  60.         $e FlattenException::createFromThrowable($throwable);
  61.         $this->logException($throwablesprintf('Uncaught PHP Exception %s: "%s" at %s line %s'$e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()), $logLevel);
  62.     }
  63.     public function onKernelException(ExceptionEvent $event)
  64.     {
  65.         if (null === $this->controller) {
  66.             return;
  67.         }
  68.         $throwable $event->getThrowable();
  69.         $request $this->duplicateRequest($throwable$event->getRequest());
  70.         try {
  71.             $response $event->getKernel()->handle($requestHttpKernelInterface::SUB_REQUESTfalse);
  72.         } catch (\Exception $e) {
  73.             $f FlattenException::createFromThrowable($e);
  74.             $this->logException($esprintf('Exception thrown when handling an exception (%s: %s at %s line %s)'$f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine()));
  75.             $prev $e;
  76.             do {
  77.                 if ($throwable === $wrapper $prev) {
  78.                     throw $e;
  79.                 }
  80.             } while ($prev $wrapper->getPrevious());
  81.             $prev = new \ReflectionProperty($wrapper instanceof \Exception \Exception::class : \Error::class, 'previous');
  82.             $prev->setValue($wrapper$throwable);
  83.             throw $e;
  84.         }
  85.         $event->setResponse($response);
  86.         if ($this->debug) {
  87.             $event->getRequest()->attributes->set('_remove_csp_headers'true);
  88.         }
  89.     }
  90.     public function removeCspHeader(ResponseEvent $event): void
  91.     {
  92.         if ($this->debug && $event->getRequest()->attributes->get('_remove_csp_headers'false)) {
  93.             $event->getResponse()->headers->remove('Content-Security-Policy');
  94.         }
  95.     }
  96.     public function onControllerArguments(ControllerArgumentsEvent $event)
  97.     {
  98.         $e $event->getRequest()->attributes->get('exception');
  99.         if (!$e instanceof \Throwable || false === $k array_search($e$event->getArguments(), true)) {
  100.             return;
  101.         }
  102.         $r = new \ReflectionFunction($event->getController()(...));
  103.         $r $r->getParameters()[$k] ?? null;
  104.         if ($r && (!($r $r->getType()) instanceof \ReflectionNamedType || FlattenException::class === $r->getName())) {
  105.             $arguments $event->getArguments();
  106.             $arguments[$k] = FlattenException::createFromThrowable($e);
  107.             $event->setArguments($arguments);
  108.         }
  109.     }
  110.     public static function getSubscribedEvents(): array
  111.     {
  112.         return [
  113.             KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments',
  114.             KernelEvents::EXCEPTION => [
  115.                 ['logKernelException'0],
  116.                 ['onKernelException', -128],
  117.             ],
  118.             KernelEvents::RESPONSE => ['removeCspHeader', -128],
  119.         ];
  120.     }
  121.     /**
  122.      * Logs an exception.
  123.      */
  124.     protected function logException(\Throwable $exceptionstring $messagestring $logLevel null): void
  125.     {
  126.         if (null !== $this->logger) {
  127.             if (null !== $logLevel) {
  128.                 $this->logger->log($logLevel$message, ['exception' => $exception]);
  129.             } elseif (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
  130.                 $this->logger->critical($message, ['exception' => $exception]);
  131.             } else {
  132.                 $this->logger->error($message, ['exception' => $exception]);
  133.             }
  134.         }
  135.     }
  136.     /**
  137.      * Clones the request for the exception.
  138.      */
  139.     protected function duplicateRequest(\Throwable $exceptionRequest $request): Request
  140.     {
  141.         $attributes = [
  142.             '_controller' => $this->controller,
  143.             'exception' => $exception,
  144.             'logger' => $this->logger instanceof DebugLoggerInterface $this->logger null,
  145.         ];
  146.         $request $request->duplicate(nullnull$attributes);
  147.         $request->setMethod('GET');
  148.         return $request;
  149.     }
  150. }