20
20
21
21
namespace MongoDB \Bundle \DataCollector ;
22
22
23
- use MongoDB \Client ;
24
23
use MongoDB \Driver \Monitoring \CommandFailedEvent ;
25
24
use MongoDB \Driver \Monitoring \CommandStartedEvent ;
26
25
use MongoDB \Driver \Monitoring \CommandSubscriber ;
27
26
use MongoDB \Driver \Monitoring \CommandSucceededEvent ;
27
+ use Symfony \Component \Stopwatch \Stopwatch ;
28
28
use Symfony \Contracts \Service \ResetInterface ;
29
29
30
30
/** @internal */
@@ -34,10 +34,12 @@ final class DriverEventSubscriber implements CommandSubscriber, ResetInterface
34
34
* @var list<CommandFailedEvent|CommandStartedEvent|CommandSucceededEvent>
35
35
*/
36
36
private array $ events = [];
37
+ private array $ stopwatchEvents = [];
37
38
38
- public function subscribe (Client $ client ): void
39
- {
40
- $ client ->getManager ()->addSubscriber ($ this );
39
+ public function __construct (
40
+ private string $ clientName ,
41
+ private ?Stopwatch $ stopwatch = null ,
42
+ ) {
41
43
}
42
44
43
45
/**
@@ -51,16 +53,33 @@ public function getEvents(): array
51
53
public function commandFailed (CommandFailedEvent $ event ): void
52
54
{
53
55
$ this ->events [] = $ event ;
56
+
57
+ if (isset ($ this ->stopwatchEvents [$ event ->getRequestId ()])) {
58
+ $ this ->stopwatchEvents [$ event ->getRequestId ()]->stop ();
59
+ unset($ this ->stopwatchEvents [$ event ->getRequestId ()]);
60
+ }
54
61
}
55
62
56
63
public function commandStarted (CommandStartedEvent $ event ): void
57
64
{
58
65
$ this ->events [] = $ event ;
66
+
67
+ if ($ this ->stopwatch ) {
68
+ $ this ->stopwatchEvents [$ event ->getRequestId ()] = $ this ->stopwatch ->start (
69
+ 'mongodb. ' .$ this ->clientName .'. ' .$ event ->getCommandName (),
70
+ 'mongodb ' ,
71
+ );
72
+ }
59
73
}
60
74
61
75
public function commandSucceeded (CommandSucceededEvent $ event ): void
62
76
{
63
77
$ this ->events [] = $ event ;
78
+
79
+ if (isset ($ this ->stopwatchEvents [$ event ->getRequestId ()])) {
80
+ $ this ->stopwatchEvents [$ event ->getRequestId ()]->stop ();
81
+ unset($ this ->stopwatchEvents [$ event ->getRequestId ()]);
82
+ }
64
83
}
65
84
66
85
public function reset (): void
0 commit comments