Completed
Push — master ( 81250e...eb6e4f )
by Mike
02:26
created

DoctrineDataCollector::collect()   F

Complexity

Conditions 18
Paths 242

Size

Total Lines 110
Code Lines 60

Duplication

Lines 21
Ratio 19.09 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 21
loc 110
rs 3.8051
cc 18
eloc 60
nc 242
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
/*
4
 * This file is part of the Doctrine Bundle
5
 *
6
 * The code was originally distributed inside the Symfony framework.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 * (c) Doctrine Project, Benjamin Eberlei <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Doctrine\Bundle\DoctrineBundle\DataCollector;
16
17
use Doctrine\Common\Persistence\ManagerRegistry;
18
use Doctrine\ORM\Tools\SchemaValidator;
19
use Doctrine\ORM\Version;
20
use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector as BaseCollector;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\VarDumper\Cloner\Data;
24
25
/**
26
 * DoctrineDataCollector.
27
 *
28
 * @author Christophe Coevoet <[email protected]>
29
 */
30
class DoctrineDataCollector extends BaseCollector
31
{
32
    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...
33
    private $invalidEntityCount;
34
35
    public function __construct(ManagerRegistry $registry)
36
    {
37
        $this->registry = $registry;
38
39
        parent::__construct($registry);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function collect(Request $request, Response $response, \Exception $exception = null)
46
    {
47
        parent::collect($request, $response, $exception);
48
49
        $errors = array();
50
        $entities = array();
51
        $caches = array(
52
            'enabled' => false,
53
            'log_enabled' => false,
54
            'counts' => array(
55
                'puts' => 0,
56
                'hits' => 0,
57
                'misses' => 0,
58
            ),
59
            'regions' => array(
60
                'puts' => array(),
61
                'hits' => array(),
62
                'misses' => array(),
63
            ),
64
        );
65
66
        foreach ($this->registry->getManagers() as $name => $em) {
67
            $entities[$name] = array();
68
            /** @var $factory \Doctrine\ORM\Mapping\ClassMetadataFactory */
69
            $factory = $em->getMetadataFactory();
70
            $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...
71
72
            /** @var $class \Doctrine\ORM\Mapping\ClassMetadataInfo */
73
            foreach ($factory->getLoadedMetadata() as $class) {
74
                if (!isset($entities[$name][$class->getName()])) {
75
                    $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...
76
                    $entities[$name][$class->getName()] = $class->getName();
77
78
                    if (!empty($classErrors)) {
79
                        $errors[$name][$class->getName()] = $classErrors;
80
                    }
81
                }
82
            }
83
84
            if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
85
                continue;
86
            }
87
88
            /** @var $emConfig \Doctrine\ORM\Configuration */
89
            $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...
90
            $slcEnabled = $emConfig->isSecondLevelCacheEnabled();
91
92
            if (!$slcEnabled) {
93
                continue;
94
            }
95
96
            $caches['enabled'] = true;
97
98
            /** @var $cacheConfiguration \Doctrine\ORM\Cache\CacheConfiguration */
99
            /** @var $cacheLoggerChain \Doctrine\ORM\Cache\Logging\CacheLoggerChain */
100
            $cacheConfiguration = $emConfig->getSecondLevelCacheConfiguration();
101
            $cacheLoggerChain = $cacheConfiguration->getCacheLogger();
102
103
            if (!$cacheLoggerChain || !$cacheLoggerChain->getLogger('statistics')) {
104
                continue;
105
            }
106
107
            /** @var $cacheLoggerStats \Doctrine\ORM\Cache\Logging\StatisticsCacheLogger */
108
            $cacheLoggerStats = $cacheLoggerChain->getLogger('statistics');
109
            $caches['log_enabled'] = true;
110
111
            $caches['counts']['puts'] += $cacheLoggerStats->getPutCount();
112
            $caches['counts']['hits'] += $cacheLoggerStats->getHitCount();
113
            $caches['counts']['misses'] += $cacheLoggerStats->getMissCount();
114
115 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...
116
                if (!isset($caches['regions']['puts'][$key])) {
117
                    $caches['regions']['puts'][$key] = 0;
118
                }
119
120
                $caches['regions']['puts'][$key] += $value;
121
            }
122
123 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...
124
                if (!isset($caches['regions']['hits'][$key])) {
125
                    $caches['regions']['hits'][$key] = 0;
126
                }
127
128
                $caches['regions']['hits'][$key] += $value;
129
            }
130
131 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...
132
                if (!isset($caches['regions']['misses'][$key])) {
133
                    $caches['regions']['misses'][$key] = 0;
134
                }
135
136
                $caches['regions']['misses'][$key] += $value;
137
            }
138
        }
139
140
        // HttpKernel < 3.2 compatibility layer
141
        if (method_exists($this, 'cloneVar')) {
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
                }
148
            }
149
        }
150
151
        $this->data['entities'] = $entities;
152
        $this->data['errors'] = $errors;
153
        $this->data['caches'] = $caches;
154
    }
155
156
    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...
157
    {
158
        return $this->data['entities'];
159
    }
160
161
    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...
162
    {
163
        return $this->data['errors'];
164
    }
165
166
    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...
167
    {
168
        return $this->data['caches']['counts']['hits'];
169
    }
170
171
    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...
172
    {
173
        return $this->data['caches']['counts']['puts'];
174
    }
175
176
    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...
177
    {
178
        return $this->data['caches']['counts']['misses'];
179
    }
180
181
    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...
182
    {
183
        return $this->data['caches']['enabled'];
184
    }
185
186
    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...
187
    {
188
        return $this->data['caches']['regions'];
189
    }
190
191
    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...
192
    {
193
        return $this->data['caches']['counts'];
194
    }
195
196
    public function getInvalidEntityCount()
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...
197
    {
198
        if (null === $this->invalidEntityCount) {
199
            $this->invalidEntityCount = array_sum(array_map('count', $this->data['errors']));
200
        }
201
202
        return $this->invalidEntityCount;
203
    }
204
205
    public function getGroupedQueries()
206
    {
207
        static $groupedQueries = null;
208
209
        if ($groupedQueries !== null) {
210
            return $groupedQueries;
211
        }
212
213
        $groupedQueries = array();
214
        $totalExecutionMS = 0;
215
        foreach ($this->data['queries'] as $connection => $queries) {
216
            $connectionGroupedQueries = array();
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, function ($a, $b) {
230
                if ($a['executionMS'] === $b['executionMS']) {
231
                    return 0;
232
                }
233
                return ($a['executionMS'] < $b['executionMS']) ? 1 : -1;
234
            });
235
            $groupedQueries[$connection] = $connectionGroupedQueries;
236
        }
237
238
        foreach ($groupedQueries as $connection => $queries) {
239
            foreach ($queries as $i => $query) {
240
                $groupedQueries[$connection][$i]['executionPercent'] =
241
                    $this->executionTimePercentage($query['executionMS'], $totalExecutionMS);
242
            }
243
        }
244
245
        return $groupedQueries;
246
    }
247
248
    private function executionTimePercentage($executionTimeMS, $totalExecutionTimeMS)
249
    {
250
        if ($totalExecutionTimeMS === 0.0 || $totalExecutionTimeMS === 0) {
251
            return 0;
252
        }
253
254
        return $executionTimeMS / $totalExecutionTimeMS * 100;
255
    }
256
257
    public function getGroupedQueryCount()
258
    {
259
        $count = 0;
260
        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...
261
            $count += count($connectionGroupedQueries);
262
        }
263
264
        return $count;
265
    }
266
}
267