|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace MongoDB\Laravel; |
| 4 | + |
| 5 | +use MongoDB\Driver\Monitoring\CommandFailedEvent; |
| 6 | +use MongoDB\Driver\Monitoring\CommandStartedEvent; |
| 7 | +use MongoDB\Driver\Monitoring\CommandSubscriber as CommandSubscriberInterface; |
| 8 | +use MongoDB\Driver\Monitoring\CommandSucceededEvent; |
| 9 | + |
| 10 | +use function get_object_vars; |
| 11 | +use function json_encode; |
| 12 | + |
| 13 | +use const JSON_THROW_ON_ERROR; |
| 14 | + |
| 15 | +/** @internal */ |
| 16 | +final class CommandSubscriber implements CommandSubscriberInterface |
| 17 | +{ |
| 18 | + /** @var array<string, CommandStartedEvent> */ |
| 19 | + private array $commands = []; |
| 20 | + |
| 21 | + public function __construct(private Connection $connection) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + public function commandStarted(CommandStartedEvent $event) |
| 26 | + { |
| 27 | + $this->commands[$event->getOperationId()] = $event; |
| 28 | + } |
| 29 | + |
| 30 | + public function commandFailed(CommandFailedEvent $event) |
| 31 | + { |
| 32 | + $this->logQuery($event); |
| 33 | + } |
| 34 | + |
| 35 | + public function commandSucceeded(CommandSucceededEvent $event) |
| 36 | + { |
| 37 | + $this->logQuery($event); |
| 38 | + } |
| 39 | + |
| 40 | + private function logQuery(CommandSucceededEvent|CommandFailedEvent $event): void |
| 41 | + { |
| 42 | + $startedEvent = $this->commands[$event->getOperationId()]; |
| 43 | + unset($this->commands[$event->getOperationId()]); |
| 44 | + |
| 45 | + $command = clone $startedEvent->getCommand(); |
| 46 | + unset($command->lsid, $command->txnNumber); |
| 47 | + foreach (get_object_vars($command) as $key => $value) { |
| 48 | + if ($key[0] === '$') { |
| 49 | + unset($command->{$key}); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + $this->connection->logQuery(json_encode($command, JSON_THROW_ON_ERROR), [], $event->getDurationMicros()); |
| 54 | + } |
| 55 | +} |
0 commit comments