DoctrineMongoDbDataCollector   D
last analyzed

Complexity

Total Complexity 82

Size/Duplication

Total Lines 248
Duplicated Lines 16.53 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 82
lcom 1
cbo 1
dl 41
loc 248
rs 4.8717
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A logQuery() 0 4 1
A getQueryCount() 0 4 1
A getQueries() 0 4 1
A setBatchInsertThreshold() 0 4 1
F collect() 41 148 53
C bsonEncode() 0 59 23
A getName() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DoctrineMongoDbDataCollector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DoctrineMongoDbDataCollector, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Doctrine MongoDBBundle
5
 *
6
 * The code was originally distributed inside the Symfony framework.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 * (c) Doctrine Project
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 Saxulum\SaxulumWebProfiler\DataCollector;
16
17
use Doctrine\MongoDB\GridFSFile;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
21
22
/**
23
 * A data collector that formats pretty queries.
24
 *
25
 * @author Kris Wallsmith <[email protected]>
26
 */
27
class DoctrineMongoDbDataCollector extends DataCollector
0 ignored issues
show
Bug introduced by
There is one abstract method reset in this class; you could implement it, or declare this class as abstract.
Loading history...
28
{
29
    private $batchInsertThreshold;
30
31
    private $queries;
32
33
    public function __construct()
34
    {
35
        $this->queries = array();
36
    }
37
38
    public function logQuery(array $query)
39
    {
40
        $this->queries[] = $query;
41
    }
42
43
    public function getQueryCount()
44
    {
45
        return $this->data['nb_queries'];
46
    }
47
48
    public function getQueries()
49
    {
50
        return $this->data['queries'];
51
    }
52
53
    public function setBatchInsertThreshold($batchInsertThreshold)
54
    {
55
        $this->batchInsertThreshold = $batchInsertThreshold;
56
    }
57
58
    public function collect(Request $request, Response $response, \Exception $exception = null)
59
    {
60
        $this->data['queries'] = array();
61
        $this->data['nb_queries'] = 0;
62
63
        $grouped = array();
64
        $ordered = array();
65
        foreach ($this->queries as $query) {
66
            if (!isset($query['query']) || !isset($query['fields'])) {
67
                // no grouping necessary
68
                $ordered[] = array($query);
69
                continue;
70
            }
71
72
            $cursor = serialize($query['query']).serialize($query['fields']);
73
74
            // append if issued from cursor (currently just "sort")
75
            if (isset($query['sort'])) {
76
                unset($query['query'], $query['fields']);
77
                $grouped[$cursor][count($grouped[$cursor]) - 1][] = $query;
78
            } else {
79
                $grouped[$cursor][] = array($query);
80
                $ordered[] =& $grouped[$cursor][count($grouped[$cursor]) - 1];
81
            }
82
        }
83
84
        $i = 0;
85
        $db = '';
86
        $query = '';
87
        foreach ($ordered as $logs) {
88
            foreach ($logs as $log) {
89
                if (isset($log['db']) && $db != $log['db']) {
90
                    // for readability
91
                    $this->data['queries'][$i++] = 'use '.$log['db'].';';
92
                    $db = $log['db'];
93
                }
94
95
                if (isset($log['collection'])) {
96
                    // flush the previous and start a new query
97 View Code Duplication
                    if (!empty($query)) {
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...
98
                        if ('.' == $query[0]) {
99
                            $query  = 'db'.$query;
100
                        }
101
102
                        $this->data['queries'][$i++] = $query.';';
103
                        ++$this->data['nb_queries'];
104
                    }
105
106
                    $query = 'db.'.$log['collection'];
107
                }
108
109
                // format the method call
110
                if (isset($log['authenticate'])) {
111
                    $query .= '.authenticate()';
112
                } elseif (isset($log['batchInsert'])) {
113
                    if (1 === $log['num']) {
114
                        $query .= '.insert('.$this->bsonEncode($log['data']).')';
115
                    } elseif (null !== $this->batchInsertThreshold && $this->batchInsertThreshold <= $log['num']) {
116
                        $query .= '.batchInsert(**'.$log['num'].' items**)';
117
                    } else {
118
                        $query .= '.batchInsert('.$this->bsonEncode($log['data']).')';
119
                    }
120
                } elseif (isset($log['command'])) {
121
                    $query .= '.runCommand('.$this->bsonEncode($log['data']).')';
122
                } elseif (isset($log['count'])) {
123
                    $query .= '.count(';
124
                    if ($log['query'] || $log['limit'] || $log['skip']) {
125
                        $query .= $this->bsonEncode($log['query']);
126 View Code Duplication
                        if ($log['limit'] || $log['skip']) {
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...
127
                            $query .= ', '.$this->bsonEncode($log['limit']);
128
                            if ($log['skip']) {
129
                                $query .= ', '.$this->bsonEncode($log['skip']);
130
                            }
131
                        }
132
                    }
133
                    $query .= ')';
134
                } elseif (isset($log['skip'])) {
135
                    $query .= '.skip('.$log['skipNum'].')';
136
                } elseif (isset($log['limit'])) {
137
                    $query .= '.limit('.$log['limitNum'].')';
138
                } elseif (isset($log['createCollection'])) {
139
                    $query .= '.createCollection()';
140
                } elseif (isset($log['createDBRef'])) {
141
                    $query .= '.createDBRef()';
142
                } elseif (isset($log['deleteIndex'])) {
143
                    $query .= '.dropIndex('.$this->bsonEncode($log['keys']).')';
144
                } elseif (isset($log['deleteIndexes'])) {
145
                    $query .= '.dropIndexes()';
146
                } elseif (isset($log['drop'])) {
147
                    $query .= '.drop()';
148
                } elseif (isset($log['dropDatabase'])) {
149
                    $query .= '.dropDatabase()';
150 View Code Duplication
                } elseif (isset($log['ensureIndex'])) {
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...
151
                    $query .= '.ensureIndex('.$this->bsonEncode($log['keys']).', '.$this->bsonEncode($log['options']).')';
152
                } elseif (isset($log['execute'])) {
153
                    $query .= '.execute()';
154
                } elseif (isset($log['find'])) {
155
                    $query .= '.find(';
156 View Code Duplication
                    if ($log['query'] || $log['fields']) {
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...
157
                        $query .= $this->bsonEncode($log['query']);
158
                        if ($log['fields']) {
159
                            $query .= ', '.$this->bsonEncode($log['fields']);
160
                        }
161
                    }
162
                    $query .= ')';
163
                } elseif (isset($log['findOne'])) {
164
                    $query .= '.findOne(';
165 View Code Duplication
                    if ($log['query'] || $log['fields']) {
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...
166
                        $query .= $this->bsonEncode($log['query']);
167
                        if ($log['fields']) {
168
                            $query .= ', '.$this->bsonEncode($log['fields']);
169
                        }
170
                    }
171
                    $query .= ')';
172
                } elseif (isset($log['getDBRef'])) {
173
                    $query .= '.getDBRef()';
174
                } elseif (isset($log['group'])) {
175
                    $query .= '.group('.$this->bsonEncode(array(
176
                            'key'    => $log['keys'],
177
                            'initial' => $log['initial'],
178
                            'reduce'  => $log['reduce'],
179
                        )).')';
180
                } elseif (isset($log['insert'])) {
181
                    $query .= '.insert('.$this->bsonEncode($log['document']).')';
182
                } elseif (isset($log['remove'])) {
183
                    $query .= '.remove('.$this->bsonEncode($log['query']).')';
184
                } elseif (isset($log['save'])) {
185
                    $query .= '.save('.$this->bsonEncode($log['document']).')';
186
                } elseif (isset($log['sort'])) {
187
                    $query .= '.sort('.$this->bsonEncode($log['sortFields']).')';
188 View Code Duplication
                } elseif (isset($log['update'])) {
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...
189
                    // todo: include $log['options']
190
                    $query .= '.update('.$this->bsonEncode($log['query']).', '.$this->bsonEncode($log['newObj']).')';
191
                } elseif (isset($log['validate'])) {
192
                    $query .= '.validate()';
193
                }
194
            }
195
        }
196
197 View Code Duplication
        if (!empty($query)) {
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...
198
            if ('.' == $query[0]) {
199
                $query  = 'db'.$query;
200
            }
201
202
            $this->data['queries'][$i++] = $query.';';
203
            ++$this->data['nb_queries'];
204
        }
205
    }
206
207
    /**
208
     * @todo Move this to a collaborator
209
     */
210
    private function bsonEncode($query, $array = true)
211
    {
212
        $parts = array();
213
214
        foreach ($query as $key => $value) {
215
            if (!is_numeric($key)) {
216
                $array = false;
217
            }
218
219
            if (null === $value) {
220
                $formatted = 'null';
221
            } elseif (is_bool($value)) {
222
                $formatted = $value ? 'true' : 'false';
223
            } elseif (is_int($value) || is_float($value)) {
224
                $formatted = $value;
225
            } elseif (is_scalar($value)) {
226
                $formatted = '"'.$value.'"';
227
            } elseif (is_array($value)) {
228
                $formatted = $this->bsonEncode($value);
229
            } elseif ($value instanceof \MongoId) {
230
                $formatted = 'ObjectId("'.$value.'")';
231
            } elseif ($value instanceof \MongoDate) {
232
                $formatted = 'new ISODate("'.date('c', $value->sec).'")';
233
            } elseif ($value instanceof \DateTime) {
234
                $formatted = 'new ISODate("'.date('c', $value->getTimestamp()).'")';
235
            } elseif ($value instanceof \MongoRegex) {
236
                $formatted = 'new RegExp("'.$value->regex.'", "'.$value->flags.'")';
237
            } elseif ($value instanceof \MongoMinKey) {
238
                $formatted = 'new MinKey()';
239
            } elseif ($value instanceof \MongoMaxKey) {
240
                $formatted = 'new MaxKey()';
241
            } elseif ($value instanceof \MongoBinData) {
242
                $formatted = 'new BinData('.$value->type.', "'.base64_encode($value->bin).'")';
243
            } elseif ($value instanceof \MongoGridFSFile || $value instanceof GridFSFile) {
244
                $formatted = 'new MongoGridFSFile("'.$value->getFilename().'")';
245
            } elseif ($value instanceof \stdClass) {
246
                $formatted = $this->bsonEncode((array) $value);
247
            } else {
248
                $formatted = (string) $value;
249
            }
250
251
            $parts['"'.$key.'"'] = $formatted;
252
        }
253
254
        if (0 == count($parts)) {
255
            return $array ? '[ ]' : '{ }';
256
        }
257
258
        if ($array) {
259
            return '[ '.implode(', ', $parts).' ]';
260
        } else {
261
            $mapper = function($key, $value)
262
            {
263
                return $key.': '.$value;
264
            };
265
266
            return '{ '.implode(', ', array_map($mapper, array_keys($parts), array_values($parts))).' }';
267
        }
268
    }
269
270
    public function getName()
271
    {
272
        return 'mongodb';
273
    }
274
}
275