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

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