-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathCommandSubscriber.php
53 lines (42 loc) · 1.54 KB
/
CommandSubscriber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace MongoDB\Laravel;
use MongoDB\BSON\Document;
use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSubscriber as CommandSubscriberInterface;
use MongoDB\Driver\Monitoring\CommandSucceededEvent;
use function get_object_vars;
use function in_array;
/** @internal */
final class CommandSubscriber implements CommandSubscriberInterface
{
/** @var array<string, CommandStartedEvent> */
private array $commands = [];
public function __construct(private Connection $connection)
{
}
public function commandStarted(CommandStartedEvent $event): void
{
$this->commands[$event->getOperationId()] = $event;
}
public function commandFailed(CommandFailedEvent $event): void
{
$this->logQuery($event);
}
public function commandSucceeded(CommandSucceededEvent $event): void
{
$this->logQuery($event);
}
private function logQuery(CommandSucceededEvent|CommandFailedEvent $event): void
{
$startedEvent = $this->commands[$event->getOperationId()];
unset($this->commands[$event->getOperationId()]);
$command = [];
foreach (get_object_vars($startedEvent->getCommand()) as $key => $value) {
if ($key[0] !== '$' && ! in_array($key, ['lsid', 'txnNumber'])) {
$command[$key] = $value;
}
}
$this->connection->logQuery(Document::fromPHP($command)->toCanonicalExtendedJSON(), [], $event->getDurationMicros());
}
}