vendor/doctrine/mongodb-odm-bundle/DataCollector/CommandDataCollector.php line 43

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Bundle\MongoDBBundle\DataCollector;
  4. use Doctrine\ODM\MongoDB\APM\Command;
  5. use Doctrine\ODM\MongoDB\APM\CommandLogger;
  6. use stdClass;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\DataCollector\DataCollector;
  10. use Throwable;
  11. use function array_map;
  12. use function array_reduce;
  13. use function count;
  14. use function json_decode;
  15. use function MongoDB\BSON\fromPHP;
  16. use function MongoDB\BSON\toCanonicalExtendedJSON;
  17. /** @internal since version 4.7.0 */
  18. class CommandDataCollector extends DataCollector
  19. {
  20.     public function __construct(private CommandLogger $commandLogger)
  21.     {
  22.     }
  23.     public function collect(Request $request, Response $response, ?Throwable $exception = null): void
  24.     {
  25.         $this->data = [
  26.             'num_commands' => count($this->commandLogger),
  27.             'commands' => array_map(
  28.                 static function (Command $command): array {
  29.                     $dbProperty = '$db';
  30.                     return [
  31.                         'database' => $command->getCommand()->$dbProperty ?? '',
  32.                         'command' => json_decode(toCanonicalExtendedJSON(fromPHP($command->getCommand()))),
  33.                         'durationMicros' => $command->getDurationMicros(),
  34.                     ];
  35.                 },
  36.                 $this->commandLogger->getAll(),
  37.             ),
  38.             'time' => array_reduce(
  39.                 $this->commandLogger->getAll(),
  40.                 static fn (int $total, Command $command): int => $total + $command->getDurationMicros(),
  41.                 0,
  42.             ),
  43.         ];
  44.     }
  45.     public function reset(): void
  46.     {
  47.         $this->commandLogger->clear();
  48.         $this->data = [
  49.             'num_commands' => 0,
  50.             'commands' => [],
  51.         ];
  52.     }
  53.     public function getCommandCount(): int
  54.     {
  55.         return $this->data['num_commands'];
  56.     }
  57.     public function getTime(): int
  58.     {
  59.         return $this->data['time'];
  60.     }
  61.     /** @return array<array{database: string, command: stdClass, durationMicros: int}> */
  62.     public function getCommands(): array
  63.     {
  64.         return $this->data['commands'];
  65.     }
  66.     public function getName(): string
  67.     {
  68.         return 'mongodb';
  69.     }
  70. }