vendor/symfony/monolog-bridge/Processor/RouteProcessor.php line 53

  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\Bridge\Monolog\Processor;
  11. use Monolog\LogRecord;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. use Symfony\Contracts\Service\ResetInterface;
  17. /**
  18.  * Adds the current route information to the log entry.
  19.  *
  20.  * @author Piotr Stankowski <git@trakos.pl>
  21.  *
  22.  * @final
  23.  */
  24. class RouteProcessor implements EventSubscriberInterfaceResetInterface
  25. {
  26.     private array $routeData = [];
  27.     private bool $includeParams;
  28.     public function __construct(bool $includeParams true)
  29.     {
  30.         $this->includeParams $includeParams;
  31.         $this->reset();
  32.     }
  33.     public function __invoke(array|LogRecord $record): array|LogRecord
  34.     {
  35.         if ($this->routeData && !isset($record['extra']['requests'])) {
  36.             $record['extra']['requests'] = array_values($this->routeData);
  37.         }
  38.         return $record;
  39.     }
  40.     public function reset()
  41.     {
  42.         $this->routeData = [];
  43.     }
  44.     public function addRouteData(RequestEvent $event)
  45.     {
  46.         if ($event->isMainRequest()) {
  47.             $this->reset();
  48.         }
  49.         $request $event->getRequest();
  50.         if (!$request->attributes->has('_controller')) {
  51.             return;
  52.         }
  53.         $currentRequestData = [
  54.             'controller' => $request->attributes->get('_controller'),
  55.             'route' => $request->attributes->get('_route'),
  56.         ];
  57.         if ($this->includeParams) {
  58.             $currentRequestData['route_params'] = $request->attributes->get('_route_params');
  59.         }
  60.         $this->routeData[spl_object_id($request)] = $currentRequestData;
  61.     }
  62.     public function removeRouteData(FinishRequestEvent $event)
  63.     {
  64.         $requestId spl_object_id($event->getRequest());
  65.         unset($this->routeData[$requestId]);
  66.     }
  67.     public static function getSubscribedEvents(): array
  68.     {
  69.         return [
  70.             KernelEvents::REQUEST => ['addRouteData'1],
  71.             KernelEvents::FINISH_REQUEST => ['removeRouteData'1],
  72.         ];
  73.     }
  74. }