|
| 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 | +use Throwable; |
| 10 | + |
| 11 | +use function get_object_vars; |
| 12 | +use function in_array; |
| 13 | +use function json_encode; |
| 14 | + |
| 15 | +use const JSON_THROW_ON_ERROR; |
| 16 | + |
| 17 | +/** @internal */ |
| 18 | +final class CommandSubscriber implements CommandSubscriberInterface |
| 19 | +{ |
| 20 | + /** @var array<string, CommandStartedEvent> */ |
| 21 | + private array $commands = []; |
| 22 | + |
| 23 | + public function __construct(private Connection $connection) |
| 24 | + { |
| 25 | + } |
| 26 | + |
| 27 | + public function commandStarted(CommandStartedEvent $event) |
| 28 | + { |
| 29 | + $this->commands[$event->getOperationId()] = $event; |
| 30 | + } |
| 31 | + |
| 32 | + public function commandFailed(CommandFailedEvent $event) |
| 33 | + { |
| 34 | + $this->logQuery($event); |
| 35 | + } |
| 36 | + |
| 37 | + public function commandSucceeded(CommandSucceededEvent $event) |
| 38 | + { |
| 39 | + $this->logQuery($event); |
| 40 | + } |
| 41 | + |
| 42 | + private function logQuery(CommandSucceededEvent|CommandFailedEvent $event): void |
| 43 | + { |
| 44 | + $startedEvent = $this->commands[$event->getOperationId()]; |
| 45 | + unset($this->commands[$event->getOperationId()]); |
| 46 | + |
| 47 | + $command = ''; |
| 48 | + foreach (get_object_vars($startedEvent->getCommand()) as $key => $value) { |
| 49 | + if ($key[0] !== '$' && ! in_array($key, ['lsid', 'txnNumber'])) { |
| 50 | + $command .= ($command ? ', ' : '{') . json_encode($key) . ':'; |
| 51 | + try { |
| 52 | + $command .= json_encode($value, JSON_THROW_ON_ERROR); |
| 53 | + } catch (Throwable $e) { |
| 54 | + $command .= json_encode('Invalid JSON: ' . $e->getMessage()); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + $command .= $command ? '}' : '{}'; |
| 60 | + |
| 61 | + $this->connection->logQuery($command, [], $event->getDurationMicros()); |
| 62 | + } |
| 63 | +} |
0 commit comments