src/EventSubscriber/DoctrineSlowQuerySubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Doctrine\Logging\ChainSqlLogger;
  4. use App\Doctrine\Logging\SlowQuerySqlLogger;
  5. use Doctrine\DBAL\Connection;
  6. use Symfony\Component\Console\ConsoleEvents;
  7. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class DoctrineSlowQuerySubscriber implements EventSubscriberInterface
  12. {
  13.     private Connection $connection;
  14.     private SlowQuerySqlLogger $slowQuerySqlLogger;
  15.     private bool $initialized false;
  16.     public function __construct(Connection $connectionSlowQuerySqlLogger $slowQuerySqlLogger)
  17.     {
  18.         $this->connection $connection;
  19.         $this->slowQuerySqlLogger $slowQuerySqlLogger;
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::REQUEST => ['onKernelRequest'1000],
  25.             ConsoleEvents::COMMAND => ['onConsoleCommand'1000],
  26.         ];
  27.     }
  28.     public function onKernelRequest(RequestEvent $event): void
  29.     {
  30.         if (!$event->isMainRequest()) {
  31.             return;
  32.         }
  33.         $this->enableSlowQueryLogger();
  34.     }
  35.     public function onConsoleCommand(ConsoleCommandEvent $event): void
  36.     {
  37.         $this->enableSlowQueryLogger();
  38.     }
  39.     private function enableSlowQueryLogger(): void
  40.     {
  41.         if ($this->initialized) {
  42.             return;
  43.         }
  44.         $configuration $this->connection->getConfiguration();
  45.         $currentLogger $configuration->getSQLLogger();
  46.         if ($currentLogger instanceof SlowQuerySqlLogger || $currentLogger instanceof ChainSqlLogger) {
  47.             $this->initialized true;
  48.             return;
  49.         }
  50.         if ($currentLogger !== null) {
  51.             $configuration->setSQLLogger(new ChainSqlLogger([$currentLogger$this->slowQuerySqlLogger]));
  52.         } else {
  53.             $configuration->setSQLLogger($this->slowQuerySqlLogger);
  54.         }
  55.         $this->initialized true;
  56.     }
  57. }