2020
2121namespace MongoDB \Bundle \DataCollector ;
2222
23- use MongoDB \Client ;
2423use MongoDB \Driver \Monitoring \CommandFailedEvent ;
2524use MongoDB \Driver \Monitoring \CommandStartedEvent ;
2625use MongoDB \Driver \Monitoring \CommandSubscriber ;
2726use MongoDB \Driver \Monitoring \CommandSucceededEvent ;
27+ use Symfony \Component \Stopwatch \Stopwatch ;
2828use Symfony \Contracts \Service \ResetInterface ;
2929
3030/** @internal */
@@ -34,10 +34,12 @@ final class DriverEventSubscriber implements CommandSubscriber, ResetInterface
3434 * @var list<CommandFailedEvent|CommandStartedEvent|CommandSucceededEvent>
3535 */
3636 private array $ events = [];
37+ private array $ stopwatchEvents = [];
3738
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+ ) {
4143 }
4244
4345 /**
@@ -51,16 +53,33 @@ public function getEvents(): array
5153 public function commandFailed (CommandFailedEvent $ event ): void
5254 {
5355 $ this ->events [] = $ event ;
56+
57+ if (isset ($ this ->stopwatchEvents [$ event ->getRequestId ()])) {
58+ $ this ->stopwatchEvents [$ event ->getRequestId ()]->stop ();
59+ unset($ this ->stopwatchEvents [$ event ->getRequestId ()]);
60+ }
5461 }
5562
5663 public function commandStarted (CommandStartedEvent $ event ): void
5764 {
5865 $ 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+ }
5973 }
6074
6175 public function commandSucceeded (CommandSucceededEvent $ event ): void
6276 {
6377 $ this ->events [] = $ event ;
78+
79+ if (isset ($ this ->stopwatchEvents [$ event ->getRequestId ()])) {
80+ $ this ->stopwatchEvents [$ event ->getRequestId ()]->stop ();
81+ unset($ this ->stopwatchEvents [$ event ->getRequestId ()]);
82+ }
6483 }
6584
6685 public function reset (): void
0 commit comments