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

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.     /**
  68.      * {@inheritdoc}
  69.      */
  70.     public function collect(Request $requestResponse $response, ?Throwable $exception null)
  71.     {
  72.         parent::collect($request$response$exception);
  73.         $errors   = [];
  74.         $entities = [];
  75.         $caches   = [
  76.             'enabled' => false,
  77.             'log_enabled' => false,
  78.             'counts' => [
  79.                 'puts' => 0,
  80.                 'hits' => 0,
  81.                 'misses' => 0,
  82.             ],
  83.             'regions' => [
  84.                 'puts' => [],
  85.                 'hits' => [],
  86.                 'misses' => [],
  87.             ],
  88.         ];
  89.         foreach ($this->registry->getManagers() as $name => $em) {
  90.             assert($em instanceof EntityManagerInterface);
  91.             if ($this->shouldValidateSchema) {
  92.                 $entities[$name] = [];
  93.                 $factory   $em->getMetadataFactory();
  94.                 $validator = new SchemaValidator($em);
  95.                 assert($factory instanceof AbstractClassMetadataFactory);
  96.                 foreach ($factory->getLoadedMetadata() as $class) {
  97.                     assert($class instanceof ClassMetadataInfo);
  98.                     if (isset($entities[$name][$class->getName()])) {
  99.                         continue;
  100.                     }
  101.                     $classErrors                        $validator->validateClass($class);
  102.                     $entities[$name][$class->getName()] = $class->getName();
  103.                     if (empty($classErrors)) {
  104.                         continue;
  105.                     }
  106.                     $errors[$name][$class->getName()] = $classErrors;
  107.                 }
  108.             }
  109.             $emConfig $em->getConfiguration();
  110.             assert($emConfig instanceof Configuration);
  111.             $slcEnabled $emConfig->isSecondLevelCacheEnabled();
  112.             if (! $slcEnabled) {
  113.                 continue;
  114.             }
  115.             $caches['enabled'] = true;
  116.             $cacheConfiguration $emConfig->getSecondLevelCacheConfiguration();
  117.             assert($cacheConfiguration instanceof CacheConfiguration);
  118.             $cacheLoggerChain $cacheConfiguration->getCacheLogger();
  119.             assert($cacheLoggerChain instanceof CacheLoggerChain || $cacheLoggerChain === null);
  120.             if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) {
  121.                 continue;
  122.             }
  123.             $cacheLoggerStats $cacheLoggerChain->getLogger('statistics');
  124.             assert($cacheLoggerStats instanceof StatisticsCacheLogger);
  125.             $caches['log_enabled'] = true;
  126.             $caches['counts']['puts']   += $cacheLoggerStats->getPutCount();
  127.             $caches['counts']['hits']   += $cacheLoggerStats->getHitCount();
  128.             $caches['counts']['misses'] += $cacheLoggerStats->getMissCount();
  129.             foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) {
  130.                 if (! isset($caches['regions']['puts'][$key])) {
  131.                     $caches['regions']['puts'][$key] = 0;
  132.                 }
  133.                 $caches['regions']['puts'][$key] += $value;
  134.             }
  135.             foreach ($cacheLoggerStats->getRegionsHit() as $key => $value) {
  136.                 if (! isset($caches['regions']['hits'][$key])) {
  137.                     $caches['regions']['hits'][$key] = 0;
  138.                 }
  139.                 $caches['regions']['hits'][$key] += $value;
  140.             }
  141.             foreach ($cacheLoggerStats->getRegionsMiss() as $key => $value) {
  142.                 if (! isset($caches['regions']['misses'][$key])) {
  143.                     $caches['regions']['misses'][$key] = 0;
  144.                 }
  145.                 $caches['regions']['misses'][$key] += $value;
  146.             }
  147.         }
  148.         $this->data['entities'] = $entities;
  149.         $this->data['errors']   = $errors;
  150.         $this->data['caches']   = $caches;
  151.         $this->groupedQueries   null;
  152.     }
  153.     /** @return array<string, array<string, string>> */
  154.     public function getEntities()
  155.     {
  156.         return $this->data['entities'];
  157.     }
  158.     /** @return array<string, array<string, list<string>>> */
  159.     public function getMappingErrors()
  160.     {
  161.         return $this->data['errors'];
  162.     }
  163.     /** @return int */
  164.     public function getCacheHitsCount()
  165.     {
  166.         return $this->data['caches']['counts']['hits'];
  167.     }
  168.     /** @return int */
  169.     public function getCachePutsCount()
  170.     {
  171.         return $this->data['caches']['counts']['puts'];
  172.     }
  173.     /** @return int */
  174.     public function getCacheMissesCount()
  175.     {
  176.         return $this->data['caches']['counts']['misses'];
  177.     }
  178.     /** @return bool */
  179.     public function getCacheEnabled()
  180.     {
  181.         return $this->data['caches']['enabled'];
  182.     }
  183.     /**
  184.      * @return array<string, array<string, int>>
  185.      * @psalm-return array<"puts"|"hits"|"misses", array<string, int>>
  186.      */
  187.     public function getCacheRegions()
  188.     {
  189.         return $this->data['caches']['regions'];
  190.     }
  191.     /** @return array<string, int> */
  192.     public function getCacheCounts()
  193.     {
  194.         return $this->data['caches']['counts'];
  195.     }
  196.     /** @return int */
  197.     public function getInvalidEntityCount()
  198.     {
  199.         return $this->invalidEntityCount ??= array_sum(array_map('count'$this->data['errors']));
  200.     }
  201.     /**
  202.      * @return string[][]
  203.      * @psalm-return array<string, list<QueryType&array{count: int, index: int, executionPercent: float}>>
  204.      */
  205.     public function getGroupedQueries()
  206.     {
  207.         if ($this->groupedQueries !== null) {
  208.             return $this->groupedQueries;
  209.         }
  210.         $this->groupedQueries = [];
  211.         $totalExecutionMS     0;
  212.         foreach ($this->data['queries'] as $connection => $queries) {
  213.             $connectionGroupedQueries = [];
  214.             foreach ($queries as $i => $query) {
  215.                 $key $query['sql'];
  216.                 if (! isset($connectionGroupedQueries[$key])) {
  217.                     $connectionGroupedQueries[$key]                = $query;
  218.                     $connectionGroupedQueries[$key]['executionMS'] = 0;
  219.                     $connectionGroupedQueries[$key]['count']       = 0;
  220.                     $connectionGroupedQueries[$key]['index']       = $i// "Explain query" relies on query index in 'queries'.
  221.                 }
  222.                 $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS'];
  223.                 $connectionGroupedQueries[$key]['count']++;
  224.                 $totalExecutionMS += $query['executionMS'];
  225.             }
  226.             usort($connectionGroupedQueries, static function ($a$b) {
  227.                 if ($a['executionMS'] === $b['executionMS']) {
  228.                     return 0;
  229.                 }
  230.                 return $a['executionMS'] < $b['executionMS'] ? : -1;
  231.             });
  232.             $this->groupedQueries[$connection] = $connectionGroupedQueries;
  233.         }
  234.         foreach ($this->groupedQueries as $connection => $queries) {
  235.             foreach ($queries as $i => $query) {
  236.                 $this->groupedQueries[$connection][$i]['executionPercent'] =
  237.                     $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
  238.             }
  239.         }
  240.         return $this->groupedQueries;
  241.     }
  242.     private function executionTimePercentage(float $executionTimeMSfloat $totalExecutionTimeMS): float
  243.     {
  244.         if (! $totalExecutionTimeMS) {
  245.             return 0;
  246.         }
  247.         return $executionTimeMS $totalExecutionTimeMS 100;
  248.     }
  249.     /** @return int */
  250.     public function getGroupedQueryCount()
  251.     {
  252.         $count 0;
  253.         foreach ($this->getGroupedQueries() as $connectionGroupedQueries) {
  254.             $count += count($connectionGroupedQueries);
  255.         }
  256.         return $count;
  257.     }
  258. }