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

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\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Throwable;
  17. use function array_map;
  18. use function array_sum;
  19. use function assert;
  20. use function count;
  21. use function usort;
  22. /**
  23.  * @psalm-type QueryType = array{
  24.  *    executionMS: float,
  25.  *    explainable: bool,
  26.  *    sql: string,
  27.  *    params: ?array<array-key, mixed>,
  28.  *    runnable: bool,
  29.  *    types: ?array<array-key, Type|int|string|null>,
  30.  * }
  31.  * @psalm-type DataType = array{
  32.  *    caches: array{
  33.  *       enabled: bool,
  34.  *       counts: array<"puts"|"hits"|"misses", int>,
  35.  *       log_enabled: bool,
  36.  *       regions: array<"puts"|"hits"|"misses", array<string, int>>,
  37.  *    },
  38.  *    connections: list<string>,
  39.  *    entities: array<string, array<class-string, class-string>>,
  40.  *    errors: array<string, array<class-string, list<string>>>,
  41.  *    managers: list<string>,
  42.  *    queries: array<string, list<QueryType>>,
  43.  * }
  44.  * @psalm-property DataType $data
  45.  */
  46. class DoctrineDataCollector extends BaseCollector
  47. {
  48.     /** @var ManagerRegistry */
  49.     private $registry;
  50.     /** @var int|null */
  51.     private $invalidEntityCount;
  52.     /**
  53.      * @var mixed[][]
  54.      * @psalm-var ?array<string, list<QueryType&array{count: int, index: int, executionPercent: float}>>
  55.      */
  56.     private $groupedQueries;
  57.     /** @var bool */
  58.     private $shouldValidateSchema;
  59.     public function __construct(ManagerRegistry $registrybool $shouldValidateSchema true)
  60.     {
  61.         $this->registry             $registry;
  62.         $this->shouldValidateSchema $shouldValidateSchema;
  63.         parent::__construct($registry);
  64.     }
  65.     /**
  66.      * {@inheritdoc}
  67.      */
  68.     public function collect(Request $requestResponse $response, ?Throwable $exception null)
  69.     {
  70.         parent::collect($request$response$exception);
  71.         $errors   = [];
  72.         $entities = [];
  73.         $caches   = [
  74.             'enabled' => false,
  75.             'log_enabled' => false,
  76.             'counts' => [
  77.                 'puts' => 0,
  78.                 'hits' => 0,
  79.                 'misses' => 0,
  80.             ],
  81.             'regions' => [
  82.                 'puts' => [],
  83.                 'hits' => [],
  84.                 'misses' => [],
  85.             ],
  86.         ];
  87.         foreach ($this->registry->getManagers() as $name => $em) {
  88.             assert($em instanceof EntityManagerInterface);
  89.             if ($this->shouldValidateSchema) {
  90.                 $entities[$name] = [];
  91.                 $factory   $em->getMetadataFactory();
  92.                 $validator = new SchemaValidator($em);
  93.                 assert($factory instanceof AbstractClassMetadataFactory);
  94.                 foreach ($factory->getLoadedMetadata() as $class) {
  95.                     assert($class instanceof ClassMetadataInfo);
  96.                     if (isset($entities[$name][$class->getName()])) {
  97.                         continue;
  98.                     }
  99.                     $classErrors                        $validator->validateClass($class);
  100.                     $entities[$name][$class->getName()] = $class->getName();
  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<string, string>> */
  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.         if ($this->invalidEntityCount === null) {
  198.             $this->invalidEntityCount array_sum(array_map('count'$this->data['errors']));
  199.         }
  200.         return $this->invalidEntityCount;
  201.     }
  202.     /**
  203.      * @return string[][]
  204.      * @psalm-return array<string, list<QueryType&array{count: int, index: int, executionPercent: float}>>
  205.      */
  206.     public function getGroupedQueries()
  207.     {
  208.         if ($this->groupedQueries !== null) {
  209.             return $this->groupedQueries;
  210.         }
  211.         $this->groupedQueries = [];
  212.         $totalExecutionMS     0;
  213.         foreach ($this->data['queries'] as $connection => $queries) {
  214.             $connectionGroupedQueries = [];
  215.             foreach ($queries as $i => $query) {
  216.                 $key $query['sql'];
  217.                 if (! isset($connectionGroupedQueries[$key])) {
  218.                     $connectionGroupedQueries[$key]                = $query;
  219.                     $connectionGroupedQueries[$key]['executionMS'] = 0;
  220.                     $connectionGroupedQueries[$key]['count']       = 0;
  221.                     $connectionGroupedQueries[$key]['index']       = $i// "Explain query" relies on query index in 'queries'.
  222.                 }
  223.                 $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS'];
  224.                 $connectionGroupedQueries[$key]['count']++;
  225.                 $totalExecutionMS += $query['executionMS'];
  226.             }
  227.             usort($connectionGroupedQueries, static function ($a$b) {
  228.                 if ($a['executionMS'] === $b['executionMS']) {
  229.                     return 0;
  230.                 }
  231.                 return $a['executionMS'] < $b['executionMS'] ? : -1;
  232.             });
  233.             $this->groupedQueries[$connection] = $connectionGroupedQueries;
  234.         }
  235.         foreach ($this->groupedQueries as $connection => $queries) {
  236.             foreach ($queries as $i => $query) {
  237.                 $this->groupedQueries[$connection][$i]['executionPercent'] =
  238.                     $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
  239.             }
  240.         }
  241.         return $this->groupedQueries;
  242.     }
  243.     private function executionTimePercentage(float $executionTimeMSfloat $totalExecutionTimeMS): float
  244.     {
  245.         if (! $totalExecutionTimeMS) {
  246.             return 0;
  247.         }
  248.         return $executionTimeMS $totalExecutionTimeMS 100;
  249.     }
  250.     /** @return int */
  251.     public function getGroupedQueryCount()
  252.     {
  253.         $count 0;
  254.         foreach ($this->getGroupedQueries() as $connectionGroupedQueries) {
  255.             $count += count($connectionGroupedQueries);
  256.         }
  257.         return $count;
  258.     }
  259. }