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

  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 Psr\Log\LogLevel;
  13. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
  17. use Symfony\Component\HttpKernel\Attribute\WithLogLevel;
  18. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  19. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  20. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  21. use Symfony\Component\HttpKernel\Exception\HttpException;
  22. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  23. use Symfony\Component\HttpKernel\HttpKernelInterface;
  24. use Symfony\Component\HttpKernel\KernelEvents;
  25. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  26. /**
  27.  * @author Fabien Potencier <fabien@symfony.com>
  28.  */
  29. class ErrorListener implements EventSubscriberInterface
  30. {
  31.     protected $controller;
  32.     protected $logger;
  33.     protected $debug;
  34.     /**
  35.      * @var array<class-string, array{log_level: string|null, status_code: int<100,599>|null}>
  36.      */
  37.     protected $exceptionsMapping;
  38.     /**
  39.      * @param array<class-string, array{log_level: string|null, status_code: int<100,599>|null}> $exceptionsMapping
  40.      */
  41.     public function __construct(string|object|array|null $controllerLoggerInterface $logger nullbool $debug false, array $exceptionsMapping = [])
  42.     {
  43.         $this->controller $controller;
  44.         $this->logger $logger;
  45.         $this->debug $debug;
  46.         $this->exceptionsMapping $exceptionsMapping;
  47.     }
  48.     /**
  49.      * @return void
  50.      */
  51.     public function logKernelException(ExceptionEvent $event)
  52.     {
  53.         $throwable $event->getThrowable();
  54.         $logLevel $this->resolveLogLevel($throwable);
  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.         // There's no specific status code defined in the configuration for this exception
  67.         if (!$throwable instanceof HttpExceptionInterface) {
  68.             $class = new \ReflectionClass($throwable);
  69.             do {
  70.                 if ($attributes $class->getAttributes(WithHttpStatus::class, \ReflectionAttribute::IS_INSTANCEOF)) {
  71.                     /** @var WithHttpStatus $instance */
  72.                     $instance $attributes[0]->newInstance();
  73.                     $throwable = new HttpException($instance->statusCode$throwable->getMessage(), $throwable$instance->headers);
  74.                     $event->setThrowable($throwable);
  75.                     break;
  76.                 }
  77.             } while ($class $class->getParentClass());
  78.         }
  79.         $e FlattenException::createFromThrowable($throwable);
  80.         $this->logException($throwablesprintf('Uncaught PHP Exception %s: "%s" at %s line %s'$e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()), $logLevel);
  81.     }
  82.     /**
  83.      * @return void
  84.      */
  85.     public function onKernelException(ExceptionEvent $event)
  86.     {
  87.         if (null === $this->controller) {
  88.             return;
  89.         }
  90.         $throwable $event->getThrowable();
  91.         $request $this->duplicateRequest($throwable$event->getRequest());
  92.         try {
  93.             $response $event->getKernel()->handle($requestHttpKernelInterface::SUB_REQUESTfalse);
  94.         } catch (\Exception $e) {
  95.             $f FlattenException::createFromThrowable($e);
  96.             $this->logException($esprintf('Exception thrown when handling an exception (%s: %s at %s line %s)'$f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine()));
  97.             $prev $e;
  98.             do {
  99.                 if ($throwable === $wrapper $prev) {
  100.                     throw $e;
  101.                 }
  102.             } while ($prev $wrapper->getPrevious());
  103.             $prev = new \ReflectionProperty($wrapper instanceof \Exception \Exception::class : \Error::class, 'previous');
  104.             $prev->setValue($wrapper$throwable);
  105.             throw $e;
  106.         }
  107.         $event->setResponse($response);
  108.         if ($this->debug) {
  109.             $event->getRequest()->attributes->set('_remove_csp_headers'true);
  110.         }
  111.     }
  112.     public function removeCspHeader(ResponseEvent $event): void
  113.     {
  114.         if ($this->debug && $event->getRequest()->attributes->get('_remove_csp_headers'false)) {
  115.             $event->getResponse()->headers->remove('Content-Security-Policy');
  116.         }
  117.     }
  118.     /**
  119.      * @return void
  120.      */
  121.     public function onControllerArguments(ControllerArgumentsEvent $event)
  122.     {
  123.         $e $event->getRequest()->attributes->get('exception');
  124.         if (!$e instanceof \Throwable || false === $k array_search($e$event->getArguments(), true)) {
  125.             return;
  126.         }
  127.         $r = new \ReflectionFunction($event->getController()(...));
  128.         $r $r->getParameters()[$k] ?? null;
  129.         if ($r && (!($r $r->getType()) instanceof \ReflectionNamedType || FlattenException::class === $r->getName())) {
  130.             $arguments $event->getArguments();
  131.             $arguments[$k] = FlattenException::createFromThrowable($e);
  132.             $event->setArguments($arguments);
  133.         }
  134.     }
  135.     public static function getSubscribedEvents(): array
  136.     {
  137.         return [
  138.             KernelEvents::CONTROLLER_ARGUMENTS => 'onControllerArguments',
  139.             KernelEvents::EXCEPTION => [
  140.                 ['logKernelException'0],
  141.                 ['onKernelException', -128],
  142.             ],
  143.             KernelEvents::RESPONSE => ['removeCspHeader', -128],
  144.         ];
  145.     }
  146.     /**
  147.      * Logs an exception.
  148.      */
  149.     protected function logException(\Throwable $exceptionstring $messagestring $logLevel null): void
  150.     {
  151.         if (null === $this->logger) {
  152.             return;
  153.         }
  154.         $logLevel ??= $this->resolveLogLevel($exception);
  155.         $this->logger->log($logLevel$message, ['exception' => $exception]);
  156.     }
  157.     /**
  158.      * Resolves the level to be used when logging the exception.
  159.      */
  160.     private function resolveLogLevel(\Throwable $throwable): string
  161.     {
  162.         foreach ($this->exceptionsMapping as $class => $config) {
  163.             if ($throwable instanceof $class && $config['log_level']) {
  164.                 return $config['log_level'];
  165.             }
  166.         }
  167.         $class = new \ReflectionClass($throwable);
  168.         do {
  169.             if ($attributes $class->getAttributes(WithLogLevel::class)) {
  170.                 /** @var WithLogLevel $instance */
  171.                 $instance $attributes[0]->newInstance();
  172.                 return $instance->level;
  173.             }
  174.         } while ($class $class->getParentClass());
  175.         if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() >= 500) {
  176.             return LogLevel::CRITICAL;
  177.         }
  178.         return LogLevel::ERROR;
  179.     }
  180.     /**
  181.      * Clones the request for the exception.
  182.      */
  183.     protected function duplicateRequest(\Throwable $exceptionRequest $request): Request
  184.     {
  185.         $attributes = [
  186.             '_controller' => $this->controller,
  187.             'exception' => $exception,
  188.             'logger' => $this->logger instanceof DebugLoggerInterface $this->logger null,
  189.         ];
  190.         $request $request->duplicate(nullnull$attributes);
  191.         $request->setMethod('GET');
  192.         return $request;
  193.     }
  194. }