DoctrineDataCollector::collect()   F
last analyzed

Complexity

Conditions 17
Paths 177

Size

Total Lines 114

Duplication

Lines 21
Ratio 18.42 %

Importance

Changes 0
Metric Value
dl 21
loc 114
rs 3.66
c 0
b 0
f 0
cc 17
nc 177
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\DataCollector;
4
5
use Doctrine\ORM\Cache\Logging\CacheLoggerChain;
6
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
7
use Doctrine\ORM\Configuration;
8
use Doctrine\ORM\EntityManager;
9
use Doctrine\ORM\Mapping\ClassMetadataFactory;
10
use Doctrine\ORM\Mapping\ClassMetadataInfo;
11
use Doctrine\ORM\Tools\SchemaValidator;
12
use Doctrine\Persistence\ManagerRegistry;
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
18
class DoctrineDataCollector extends BaseCollector
19
{
20
    /** @var ManagerRegistry */
21
    private $registry;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
22
23
    /** @var int|null */
24
    private $invalidEntityCount;
25
26
    /** @var string[] */
27
    private $groupedQueries;
28
29
    /** @var bool */
30
    private $shouldValidateSchema;
31
32
    public function __construct(ManagerRegistry $registry, bool $shouldValidateSchema = true)
33
    {
34
        $this->registry             = $registry;
35
        $this->shouldValidateSchema = $shouldValidateSchema;
36
37
        parent::__construct($registry);
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function collect(Request $request, Response $response, Throwable $exception = null)
44
    {
45
        parent::collect($request, $response, $exception);
46
47
        $errors   = [];
48
        $entities = [];
49
        $caches   = [
50
            'enabled' => false,
51
            'log_enabled' => false,
52
            'counts' => [
53
                'puts' => 0,
54
                'hits' => 0,
55
                'misses' => 0,
56
            ],
57
            'regions' => [
58
                'puts' => [],
59
                'hits' => [],
60
                'misses' => [],
61
            ],
62
        ];
63
64
        /** @var EntityManager $em */
65
        foreach ($this->registry->getManagers() as $name => $em) {
66
            if ($this->shouldValidateSchema) {
67
                $entities[$name] = [];
68
69
                /** @var ClassMetadataFactory $factory */
70
                $factory   = $em->getMetadataFactory();
71
                $validator = new SchemaValidator($em);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
72
73
                /** @var ClassMetadataInfo $class */
74
                foreach ($factory->getLoadedMetadata() as $class) {
75
                    if (isset($entities[$name][$class->getName()])) {
76
                        continue;
77
                    }
78
79
                    $classErrors                        = $validator->validateClass($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Persiste...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ORM\Mapping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
80
                    $entities[$name][$class->getName()] = $class->getName();
81
82
                    if (empty($classErrors)) {
83
                        continue;
84
                    }
85
86
                    $errors[$name][$class->getName()] = $classErrors;
87
                }
88
            }
89
90
            /** @var Configuration $emConfig */
91
            $emConfig   = $em->getConfiguration();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectManager as the method getConfiguration() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
92
            $slcEnabled = $emConfig->isSecondLevelCacheEnabled();
93
94
            if (! $slcEnabled) {
95
                continue;
96
            }
97
98
            $caches['enabled'] = true;
99
100
            /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */
101
            /** @var CacheLoggerChain $cacheLoggerChain */
102
            $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration();
103
            $cacheLoggerChain   = $cacheConfiguration->getCacheLogger();
104
105
            if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) {
106
                continue;
107
            }
108
109
            /** @var StatisticsCacheLogger $cacheLoggerStats */
110
            $cacheLoggerStats      = $cacheLoggerChain->getLogger('statistics');
111
            $caches['log_enabled'] = true;
112
113
            $caches['counts']['puts']   += $cacheLoggerStats->getPutCount();
114
            $caches['counts']['hits']   += $cacheLoggerStats->getHitCount();
115
            $caches['counts']['misses'] += $cacheLoggerStats->getMissCount();
116
117 View Code Duplication
            foreach ($cacheLoggerStats->getRegionsPut() as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
                if (! isset($caches['regions']['puts'][$key])) {
119
                    $caches['regions']['puts'][$key] = 0;
120
                }
121
122
                $caches['regions']['puts'][$key] += $value;
123
            }
124
125 View Code Duplication
            foreach ($cacheLoggerStats->getRegionsHit() as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
                if (! isset($caches['regions']['hits'][$key])) {
127
                    $caches['regions']['hits'][$key] = 0;
128
                }
129
130
                $caches['regions']['hits'][$key] += $value;
131
            }
132
133 View Code Duplication
            foreach ($cacheLoggerStats->getRegionsMiss() as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
                if (! isset($caches['regions']['misses'][$key])) {
135
                    $caches['regions']['misses'][$key] = 0;
136
                }
137
138
                $caches['regions']['misses'][$key] += $value;
139
            }
140
        }
141
142
        // Might be good idea to replicate this block in doctrine bridge so we can drop this from here after some time.
143
        // This code is compatible with such change, because cloneVar is supposed to check if input is already cloned.
144
        foreach ($this->data['queries'] as &$queries) {
145
            foreach ($queries as &$query) {
146
                $query['params'] = $this->cloneVar($query['params']);
147
                // To be removed when the required minimum version of symfony/doctrine-bridge is >= 4.4
148
                $query['runnable'] = $query['runnable'] ?? true;
149
            }
150
        }
151
152
        $this->data['entities'] = $entities;
153
        $this->data['errors']   = $errors;
154
        $this->data['caches']   = $caches;
155
        $this->groupedQueries   = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,string> of property $groupedQueries.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
156
    }
157
158
    public function getEntities()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
159
    {
160
        return $this->data['entities'];
161
    }
162
163
    public function getMappingErrors()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
164
    {
165
        return $this->data['errors'];
166
    }
167
168
    public function getCacheHitsCount()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
169
    {
170
        return $this->data['caches']['counts']['hits'];
171
    }
172
173
    public function getCachePutsCount()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
174
    {
175
        return $this->data['caches']['counts']['puts'];
176
    }
177
178
    public function getCacheMissesCount()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
179
    {
180
        return $this->data['caches']['counts']['misses'];
181
    }
182
183
    public function getCacheEnabled()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
184
    {
185
        return $this->data['caches']['enabled'];
186
    }
187
188
    public function getCacheRegions()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
189
    {
190
        return $this->data['caches']['regions'];
191
    }
192
193
    public function getCacheCounts()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
194
    {
195
        return $this->data['caches']['counts'];
196
    }
197
198
    public function getInvalidEntityCount()
199
    {
200
        if ($this->invalidEntityCount === null) {
201
            $this->invalidEntityCount = array_sum(array_map('count', $this->data['errors']));
0 ignored issues
show
Documentation Bug introduced by
It seems like array_sum(array_map('cou...$this->data['errors'])) can also be of type double. However, the property $invalidEntityCount is declared as type integer|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
202
        }
203
204
        return $this->invalidEntityCount;
205
    }
206
207
    public function getGroupedQueries()
208
    {
209
        if ($this->groupedQueries !== null) {
210
            return $this->groupedQueries;
211
        }
212
213
        $this->groupedQueries = [];
214
        $totalExecutionMS     = 0;
215
        foreach ($this->data['queries'] as $connection => $queries) {
216
            $connectionGroupedQueries = [];
217
            foreach ($queries as $i => $query) {
218
                $key = $query['sql'];
219
                if (! isset($connectionGroupedQueries[$key])) {
220
                    $connectionGroupedQueries[$key]                = $query;
221
                    $connectionGroupedQueries[$key]['executionMS'] = 0;
222
                    $connectionGroupedQueries[$key]['count']       = 0;
223
                    $connectionGroupedQueries[$key]['index']       = $i; // "Explain query" relies on query index in 'queries'.
224
                }
225
                $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS'];
226
                $connectionGroupedQueries[$key]['count']++;
227
                $totalExecutionMS += $query['executionMS'];
228
            }
229
            usort($connectionGroupedQueries, static function ($a, $b) {
230
                if ($a['executionMS'] === $b['executionMS']) {
231
                    return 0;
232
                }
233
234
                return $a['executionMS'] < $b['executionMS'] ? 1 : -1;
235
            });
236
            $this->groupedQueries[$connection] = $connectionGroupedQueries;
237
        }
238
239
        foreach ($this->groupedQueries as $connection => $queries) {
240
            foreach ($queries as $i => $query) {
241
                $this->groupedQueries[$connection][$i]['executionPercent'] =
242
                    $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
243
            }
244
        }
245
246
        return $this->groupedQueries;
247
    }
248
249
    private function executionTimePercentage($executionTimeMS, $totalExecutionTimeMS)
250
    {
251
        if ($totalExecutionTimeMS === 0.0 || $totalExecutionTimeMS === 0) {
252
            return 0;
253
        }
254
255
        return $executionTimeMS / $totalExecutionTimeMS * 100;
256
    }
257
258
    public function getGroupedQueryCount()
259
    {
260
        $count = 0;
261
        foreach ($this->getGroupedQueries() as $connectionGroupedQueries) {
262
            $count += count($connectionGroupedQueries);
263
        }
264
265
        return $count;
266
    }
267
}
268