Completed
Push — master ( 7f2a01...44feb9 )
by
unknown
06:18 queued 04:12
created

DoctrineDataCollector::getGroupedQueries()   D

Complexity

Conditions 9
Paths 13

Size

Total Lines 42
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 42
rs 4.909
c 0
b 0
f 0
cc 9
eloc 28
nc 13
nop 0
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\DataCollector;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Doctrine\ORM\Cache\Logging\CacheLoggerChain;
7
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
8
use Doctrine\ORM\Configuration;
9
use Doctrine\ORM\Mapping\ClassMetadataFactory;
10
use Doctrine\ORM\Tools\SchemaValidator;
11
use Doctrine\ORM\Version;
12
use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector as BaseCollector;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
16
/**
17
 * DoctrineDataCollector.
18
 */
19
class DoctrineDataCollector extends BaseCollector
20
{
21
    /** @var ManagerRegistry */
22
    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...
23
24
    /** @var int|null */
25
    private $invalidEntityCount;
26
27
    public function __construct(ManagerRegistry $registry)
28
    {
29
        $this->registry = $registry;
30
31
        parent::__construct($registry);
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function collect(Request $request, Response $response, \Exception $exception = null)
38
    {
39
        parent::collect($request, $response, $exception);
40
41
        $errors   = [];
42
        $entities = [];
43
        $caches   = [
44
            'enabled' => false,
45
            'log_enabled' => false,
46
            'counts' => [
47
                'puts' => 0,
48
                'hits' => 0,
49
                'misses' => 0,
50
            ],
51
            'regions' => [
52
                'puts' => [],
53
                'hits' => [],
54
                'misses' => [],
55
            ],
56
        ];
57
58
        foreach ($this->registry->getManagers() as $name => $em) {
59
            $entities[$name] = [];
60
            /** @var ClassMetadataFactory $factory */
61
            $factory   = $em->getMetadataFactory();
62
            $validator = new SchemaValidator($em);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Common\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Common\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...
63
64
            /** @var $class \Doctrine\ORM\Mapping\ClassMetadataInfo */
65
            foreach ($factory->getLoadedMetadata() as $class) {
66
                if (isset($entities[$name][$class->getName()])) {
67
                    continue;
68
                }
69
70
                $classErrors                        = $validator->validateClass($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\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\Common\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...
71
                $entities[$name][$class->getName()] = $class->getName();
72
73
                if (empty($classErrors)) {
74
                    continue;
75
                }
76
77
                $errors[$name][$class->getName()] = $classErrors;
78
            }
79
80
            if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
81
                continue;
82
            }
83
84
            /** @var Configuration $emConfig */
85
            $emConfig   = $em->getConfiguration();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\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...
86
            $slcEnabled = $emConfig->isSecondLevelCacheEnabled();
87
88
            if (! $slcEnabled) {
89
                continue;
90
            }
91
92
            $caches['enabled'] = true;
93
94
            /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */
95
            /** @var CacheLoggerChain $cacheLoggerChain */
96
            $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration();
97
            $cacheLoggerChain   = $cacheConfiguration->getCacheLogger();
98
99
            if (! $cacheLoggerChain || ! $cacheLoggerChain->getLogger('statistics')) {
100
                continue;
101
            }
102
103
            /** @var StatisticsCacheLogger $cacheLoggerStats */
104
            $cacheLoggerStats      = $cacheLoggerChain->getLogger('statistics');
105
            $caches['log_enabled'] = true;
106
107
            $caches['counts']['puts']   += $cacheLoggerStats->getPutCount();
108
            $caches['counts']['hits']   += $cacheLoggerStats->getHitCount();
109
            $caches['counts']['misses'] += $cacheLoggerStats->getMissCount();
110
111 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...
112
                if (! isset($caches['regions']['puts'][$key])) {
113
                    $caches['regions']['puts'][$key] = 0;
114
                }
115
116
                $caches['regions']['puts'][$key] += $value;
117
            }
118
119 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...
120
                if (! isset($caches['regions']['hits'][$key])) {
121
                    $caches['regions']['hits'][$key] = 0;
122
                }
123
124
                $caches['regions']['hits'][$key] += $value;
125
            }
126
127 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...
128
                if (! isset($caches['regions']['misses'][$key])) {
129
                    $caches['regions']['misses'][$key] = 0;
130
                }
131
132
                $caches['regions']['misses'][$key] += $value;
133
            }
134
        }
135
136
        // HttpKernel < 3.2 compatibility layer
137
        if (method_exists($this, 'cloneVar')) {
138
            // Might be good idea to replicate this block in doctrine bridge so we can drop this from here after some time.
139
            // This code is compatible with such change, because cloneVar is supposed to check if input is already cloned.
140
            foreach ($this->data['queries'] as &$queries) {
141
                foreach ($queries as &$query) {
142
                    $query['params'] = $this->cloneVar($query['params']);
143
                }
144
            }
145
        }
146
147
        $this->data['entities'] = $entities;
148
        $this->data['errors']   = $errors;
149
        $this->data['caches']   = $caches;
150
    }
151
152
    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...
153
    {
154
        return $this->data['entities'];
155
    }
156
157
    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...
158
    {
159
        return $this->data['errors'];
160
    }
161
162
    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...
163
    {
164
        return $this->data['caches']['counts']['hits'];
165
    }
166
167
    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...
168
    {
169
        return $this->data['caches']['counts']['puts'];
170
    }
171
172
    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...
173
    {
174
        return $this->data['caches']['counts']['misses'];
175
    }
176
177
    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...
178
    {
179
        return $this->data['caches']['enabled'];
180
    }
181
182
    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...
183
    {
184
        return $this->data['caches']['regions'];
185
    }
186
187
    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...
188
    {
189
        return $this->data['caches']['counts'];
190
    }
191
192
    public function getInvalidEntityCount()
193
    {
194
        if ($this->invalidEntityCount === null) {
195
            $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...
196
        }
197
198
        return $this->invalidEntityCount;
199
    }
200
201
    public function getGroupedQueries()
202
    {
203
        static $groupedQueries = null;
204
205
        if ($groupedQueries !== null) {
206
            return $groupedQueries;
207
        }
208
209
        $groupedQueries   = [];
210
        $totalExecutionMS = 0;
211
        foreach ($this->data['queries'] as $connection => $queries) {
212
            $connectionGroupedQueries = [];
213
            foreach ($queries as $i => $query) {
214
                $key = $query['sql'];
215
                if (! isset($connectionGroupedQueries[$key])) {
216
                    $connectionGroupedQueries[$key]                = $query;
217
                    $connectionGroupedQueries[$key]['executionMS'] = 0;
218
                    $connectionGroupedQueries[$key]['count']       = 0;
219
                    $connectionGroupedQueries[$key]['index']       = $i; // "Explain query" relies on query index in 'queries'.
220
                }
221
                $connectionGroupedQueries[$key]['executionMS'] += $query['executionMS'];
222
                $connectionGroupedQueries[$key]['count']++;
223
                $totalExecutionMS += $query['executionMS'];
224
            }
225
            usort($connectionGroupedQueries, function ($a, $b) {
226
                if ($a['executionMS'] === $b['executionMS']) {
227
                    return 0;
228
                }
229
                return ($a['executionMS'] < $b['executionMS']) ? 1 : -1;
230
            });
231
            $groupedQueries[$connection] = $connectionGroupedQueries;
232
        }
233
234
        foreach ($groupedQueries as $connection => $queries) {
235
            foreach ($queries as $i => $query) {
236
                $groupedQueries[$connection][$i]['executionPercent'] =
237
                    $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
238
            }
239
        }
240
241
        return $groupedQueries;
242
    }
243
244
    private function executionTimePercentage($executionTimeMS, $totalExecutionTimeMS)
245
    {
246
        if ($totalExecutionTimeMS === 0.0 || $totalExecutionTimeMS === 0) {
247
            return 0;
248
        }
249
250
        return $executionTimeMS / $totalExecutionTimeMS * 100;
251
    }
252
253
    public function getGroupedQueryCount()
254
    {
255
        $count = 0;
256
        foreach ($this->getGroupedQueries() as $connectionGroupedQueries) {
0 ignored issues
show
Bug introduced by
The expression $this->getGroupedQueries() of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
257
            $count += count($connectionGroupedQueries);
258
        }
259
260
        return $count;
261
    }
262
}
263