vendor/doctrine/doctrine-bundle/DataCollector/DoctrineDataCollector.php line 76

Open in your IDE?
  1. <?php
  2. namespace Doctrine\Bundle\DoctrineBundle\DataCollector;
  3. use Doctrine\DBAL\Types\Type;
  4. use Doctrine\ORM\Cache\CacheConfiguration;
  5. use Doctrine\ORM\Cache\Logging\CacheLoggerChain;
  6. use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
  7. use Doctrine\ORM\Configuration;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  10. use Doctrine\ORM\Tools\SchemaValidator;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Doctrine\Persistence\Mapping\AbstractClassMetadataFactory;
  13. use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector as BaseCollector;
  14. use Symfony\Bridge\Doctrine\Middleware\Debug\DebugDataHolder;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Throwable;
  18. use function array_map;
  19. use function array_sum;
  20. use function assert;
  21. use function count;
  22. use function usort;
  23. /**
  24.  * @psalm-type QueryType = array{
  25.  *    executionMS: float,
  26.  *    explainable: bool,
  27.  *    sql: string,
  28.  *    params: ?array<array-key, mixed>,
  29.  *    runnable: bool,
  30.  *    types: ?array<array-key, Type|int|string|null>,
  31.  * }
  32.  * @psalm-type DataType = array{
  33.  *    caches: array{
  34.  *       enabled: bool,
  35.  *       counts: array<"puts"|"hits"|"misses", int>,
  36.  *       log_enabled: bool,
  37.  *       regions: array<"puts"|"hits"|"misses", array<string, int>>,
  38.  *    },
  39.  *    connections: list<string>,
  40.  *    entities: array<string, array<class-string, class-string>>,
  41.  *    errors: array<string, array<class-string, list<string>>>,
  42.  *    managers: list<string>,
  43.  *    queries: array<string, list<QueryType>>,
  44.  * }
  45.  * @psalm-property DataType $data
  46.  */
  47. class DoctrineDataCollector extends BaseCollector
  48. {
  49.     private ManagerRegistry $registry;
  50.     private ?int $invalidEntityCount null;
  51.     /**
  52.      * @var mixed[][]|null
  53.      * @psalm-var ?array<string, list<QueryType&array{count: int, index: int, executionPercent: float}>>
  54.      */
  55.     private ?array $groupedQueries null;
  56.     private bool $shouldValidateSchema;
  57.     public function __construct(ManagerRegistry $registrybool $shouldValidateSchema true, ?DebugDataHolder $debugDataHolder null)
  58.     {
  59.         $this->registry             $registry;
  60.         $this->shouldValidateSchema $shouldValidateSchema;
  61.         if ($debugDataHolder === null) {
  62.             parent::__construct($registry);
  63.         } else {
  64.             parent::__construct($registry$debugDataHolder);
  65.         }
  66.     }
  67.     public function collect(Request $requestResponse $response, ?Throwable $exception null): void
  68.     {
  69.         parent::collect($request$response$exception);
  70.         $errors   = [];
  71.         $entities = [];
  72.         $caches   = [
  73.             'enabled' => false,
  74.             'log_enabled' => false,
  75.             'counts' => [
  76.                 'puts' => 0,
  77.                 'hits' => 0,
  78.                 'misses' => 0,
  79.             ],
  80.             'regions' => [
  81.                 'puts' => [],
  82.                 'hits' => [],
  83.                 'misses' => [],
  84.             ],
  85.         ];
  86.         foreach ($this->registry->getManagers() as $name => $em) {
  87.             assert($em instanceof EntityManagerInterface);
  88.             if ($this->shouldValidateSchema) {
  89.                 $entities[$name] = [];
  90.                 $factory   $em->getMetadataFactory();
  91.                 $validator = new SchemaValidator($em);
  92.                 assert($factory instanceof AbstractClassMetadataFactory);
  93.                 foreach ($factory->getLoadedMetadata() as $class) {
  94.                     assert($class instanceof ClassMetadataInfo);
  95.                     if (isset($entities[$name][$class->getName()])) {
  96.                         continue;
  97.                     }
  98.                     $classErrors                        $validator->validateClass($class);
  99.                     $r                                  $class->getReflectionClass();
  100.                     $entities[$name][$class->getName()] = [
  101.                         'class' => $class->getName(),
  102.                         'file' => $r->getFileName(),
  103.                         'line' => $r->getStartLine(),
  104.                     ];
  105.                     if (empty($classErrors)) {
  106.                         continue;
  107.                     }
  108.                     $errors[$name][$class->getName()] = $classErrors;
  109.                 }
  110.             }
  111.             $emConfig $em->getConfiguration();
  112.             assert($emConfig instanceof Configuration);
  113.             $slcEnabled $emConfig->isSecondLevelCacheEnabled();
  114.             if (! $slcEnabled) {
  115.                 continue;
  116.             }
  117.             $caches['enabled'] = true;
  118.             $cacheConfiguration $emConfig->getSecondLevelCacheConfiguration();
  119.             assert($cacheConfiguration instanceof CacheConfiguration);
  120.             $cacheLoggerChain $cacheConfiguration->getCacheLogger();
  121.             assert($cacheLoggerChain instanceof CacheLoggerChain || $cacheLoggerChain === null);
  122.             if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) {
  123.                 continue;
  124.             }
  125.             $cacheLoggerStats $cacheLoggerChain->getLogger('statistics');
  126.             assert($cacheLoggerStats instanceof StatisticsCacheLogger);
  127.             $caches['log_enabled'] = true;
  128.             $caches['counts']['puts']   += $cacheLoggerStats->getPutCount();
  129.             $caches['counts']['hits']   += $cacheLoggerStats->getHitCount();
  130.             $caches['counts']['misses'] += $cacheLoggerStats->getMissCount();
  131.             foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) {
  132.                 if (! isset($caches['regions']['puts'][$key])) {
  133.                     $caches['regions']['puts'][$key] = 0;
  134.                 }
  135.                 $caches['regions']['puts'][$key] += $value;
  136.             }
  137.             foreach ($cacheLoggerStats->getRegionsHit() as $key => $value) {
  138.                 if (! isset($caches['regions']['hits'][$key])) {
  139.                     $caches['regions']['hits'][$key] = 0;
  140.                 }
  141.                 $caches['regions']['hits'][$key] += $value;
  142.             }
  143.             foreach ($cacheLoggerStats->getRegionsMiss() as $key => $value) {
  144.                 if (! isset($caches['regions']['misses'][$key])) {
  145.                     $caches['regions']['misses'][$key] = 0;
  146.                 }
  147.                 $caches['regions']['misses'][$key] += $value;
  148.             }
  149.         }
  150.         $this->data['entities'] = $entities;
  151.         $this->data['errors']   = $errors;
  152.         $this->data['caches']   = $caches;
  153.         $this->groupedQueries   null;
  154.     }
  155.     /** @return array<string, array<string, string>> */
  156.     public function getEntities()
  157.     {
  158.         return $this->data['entities'];
  159.     }
  160.     /** @return array<string, array<string, list<string>>> */
  161.     public function getMappingErrors()
  162.     {
  163.         return $this->data['errors'];
  164.     }
  165.     /** @return int */
  166.     public function getCacheHitsCount()
  167.     {
  168.         return $this->data['caches']['counts']['hits'];
  169.     }
  170.     /** @return int */
  171.     public function getCachePutsCount()
  172.     {
  173.         return $this->data['caches']['counts']['puts'];
  174.     }
  175.     /** @return int */
  176.     public function getCacheMissesCount()
  177.     {
  178.         return $this->data['caches']['counts']['misses'];
  179.     }
  180.     /** @return bool */
  181.     public function getCacheEnabled()
  182.     {
  183.         return $this->data['caches']['enabled'];
  184.     }
  185.     /**
  186.      * @return array<string, array<string, int>>
  187.      * @psalm-return array<"puts"|"hits"|"misses", array<string, int>>
  188.      */
  189.     public function getCacheRegions()
  190.     {
  191.         return $this->data['caches']['regions'];
  192.     }
  193.     /** @return array<string, int> */
  194.     public function getCacheCounts()
  195.     {
  196.         return $this->data['caches']['counts'];
  197.     }
  198.     /** @return int */
  199.     public function getInvalidEntityCount()
  200.     {
  201.         return $this->invalidEntityCount ??= array_sum(array_map('count'$this->data['errors']));
  202.     }
  203.     /**
  204.      * @return string[][]
  205.      * @psalm-return array<string, list<QueryType&array{count: int, index: int, executionPercent: float}>>
  206.      */
  207.     public function getGroupedQueries()
  208.     {
  209.         if ($this->groupedQueries !== null) {
  210.             return $this->groupedQueries;
  211.         }
  212.         $this->groupedQueries = [];
  213.         $totalExecutionMS     0;
  214.         foreach ($this->data['queries'] as $connection => $queries) {
  215.             $connectionGroupedQueries = [];
  216.             foreach ($queries as $i => $query) {
  217.                 $key $query['sql'];
  218.                 if (! isset($connectionGroupedQueries[$key])) {
  219.                     $connectionGroupedQueries[$key]                = $query;
  220.                     $connectionGroupedQueries[$key]['executionMS'] = 0;
  221.                     $connectionGroupedQueries[$key]['count']       = 0;
  222.                     $connectionGroupedQueries[$key]['index']       = $i// "Explain query" relies on query index in 'queries'.
  223.                 }
  224.                 $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS'];
  225.                 $connectionGroupedQueries[$key]['count']++;
  226.                 $totalExecutionMS += $query['executionMS'];
  227.             }
  228.             usort($connectionGroupedQueries, static function ($a$b) {
  229.                 if ($a['executionMS'] === $b['executionMS']) {
  230.                     return 0;
  231.                 }
  232.                 return $a['executionMS'] < $b['executionMS'] ? : -1;
  233.             });
  234.             $this->groupedQueries[$connection] = $connectionGroupedQueries;
  235.         }
  236.         foreach ($this->groupedQueries as $connection => $queries) {
  237.             foreach ($queries as $i => $query) {
  238.                 $this->groupedQueries[$connection][$i]['executionPercent'] =
  239.                     $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
  240.             }
  241.         }
  242.         return $this->groupedQueries;
  243.     }
  244.     private function executionTimePercentage(float $executionTimeMSfloat $totalExecutionTimeMS): float
  245.     {
  246.         if (! $totalExecutionTimeMS) {
  247.             return 0;
  248.         }
  249.         return $executionTimeMS $totalExecutionTimeMS 100;
  250.     }
  251.     /** @return int */
  252.     public function getGroupedQueryCount()
  253.     {
  254.         $count 0;
  255.         foreach ($this->getGroupedQueries() as $connectionGroupedQueries) {
  256.             $count += count($connectionGroupedQueries);
  257.         }
  258.         return $count;
  259.     }
  260. }