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

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