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

  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. class CommandDataCollector extends DataCollector
  18. {
  19.     /** @var CommandLogger */
  20.     private $commandLogger;
  21.     public function __construct(CommandLogger $commandLogger)
  22.     {
  23.         $this->commandLogger $commandLogger;
  24.     }
  25.     public function collect(Request $requestResponse $response, ?Throwable $exception null): void
  26.     {
  27.         $this->data = [
  28.             'num_commands' => count($this->commandLogger),
  29.             'commands' => array_map(
  30.                 static function (Command $command): array {
  31.                     $dbProperty '$db';
  32.                     return [
  33.                         'database' => $command->getCommand()->$dbProperty ?? '',
  34.                         'command' => json_decode(toCanonicalExtendedJSON(fromPHP($command->getCommand()))),
  35.                         'durationMicros' => $command->getDurationMicros(),
  36.                     ];
  37.                 },
  38.                 $this->commandLogger->getAll()
  39.             ),
  40.             'time' => array_reduce(
  41.                 $this->commandLogger->getAll(),
  42.                 static function (int $totalCommand $command): int {
  43.                     return $total $command->getDurationMicros();
  44.                 },
  45.                 0
  46.             ),
  47.         ];
  48.     }
  49.     public function reset(): void
  50.     {
  51.         $this->commandLogger->clear();
  52.         $this->data = [
  53.             'num_commands' => 0,
  54.             'commands' => [],
  55.         ];
  56.     }
  57.     public function getCommandCount(): int
  58.     {
  59.         return $this->data['num_commands'];
  60.     }
  61.     public function getTime(): int
  62.     {
  63.         return $this->data['time'];
  64.     }
  65.     /**
  66.      * @return array<array{database: string, command: stdClass, durationMicros: int}>
  67.      */
  68.     public function getCommands(): array
  69.     {
  70.         return $this->data['commands'];
  71.     }
  72.     public function getName(): string
  73.     {
  74.         return 'mongodb';
  75.     }
  76. }