vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/APM/CommandLogger.php line 52

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ODM\MongoDB\APM;
  4. use Countable;
  5. use MongoDB\Driver\Monitoring\CommandFailedEvent;
  6. use MongoDB\Driver\Monitoring\CommandStartedEvent;
  7. use MongoDB\Driver\Monitoring\CommandSucceededEvent;
  8. use function count;
  9. use function MongoDB\Driver\Monitoring\addSubscriber;
  10. use function MongoDB\Driver\Monitoring\removeSubscriber;
  11. final class CommandLogger implements CountableCommandLoggerInterface
  12. {
  13.     /** @var Command[] */
  14.     private $commands = [];
  15.     /** @var CommandStartedEvent[] */
  16.     private $startedCommands = [];
  17.     /** @var bool */
  18.     private $registered false;
  19.     public function register(): void
  20.     {
  21.         if ($this->registered) {
  22.             return;
  23.         }
  24.         $this->registered true;
  25.         addSubscriber($this);
  26.     }
  27.     public function unregister(): void
  28.     {
  29.         if (! $this->registered) {
  30.             return;
  31.         }
  32.         removeSubscriber($this);
  33.         $this->registered false;
  34.     }
  35.     public function commandStarted(CommandStartedEvent $event)
  36.     {
  37.         $this->startedCommands[$event->getRequestId()] = $event;
  38.     }
  39.     public function commandSucceeded(CommandSucceededEvent $event)
  40.     {
  41.         $commandStartedEvent $this->findAndRemoveCommandStartedEvent($event->getRequestId());
  42.         if (! $commandStartedEvent) {
  43.             return;
  44.         }
  45.         $this->logCommand(Command::createForSucceededCommand($commandStartedEvent$event));
  46.     }
  47.     public function commandFailed(CommandFailedEvent $event)
  48.     {
  49.         $commandStartedEvent $this->findAndRemoveCommandStartedEvent($event->getRequestId());
  50.         if (! $commandStartedEvent) {
  51.             return;
  52.         }
  53.         $this->logCommand(Command::createForFailedCommand($commandStartedEvent$event));
  54.     }
  55.     public function clear(): void
  56.     {
  57.         $this->commands = [];
  58.     }
  59.     public function count(): int
  60.     {
  61.         return count($this->commands);
  62.     }
  63.     /**
  64.      * @return Command[]
  65.      */
  66.     public function getAll(): array
  67.     {
  68.         return $this->commands;
  69.     }
  70.     private function findAndRemoveCommandStartedEvent(string $requestId): ?CommandStartedEvent
  71.     {
  72.         $startedEvent $this->startedCommands[$requestId] ?? null;
  73.         unset($this->startedCommands[$requestId]);
  74.         return $startedEvent;
  75.     }
  76.     private function logCommand(Command $command): void
  77.     {
  78.         $this->commands[] = $command;
  79.     }
  80. }