Completed
Pull Request — master (#331)
by Elan
01:21
created

MongoSearcher   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 353
Duplicated Lines 0.85 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 37
lcom 2
cbo 2
dl 3
loc 353
rs 9.44
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A latest() 0 9 1
A query() 0 7 1
A get() 0 6 1
A getForUrl() 0 12 1
B getPercentileForUrl() 3 76 7
B getAvgsForUrl() 0 41 5
A getAll() 0 4 1
A delete() 0 4 1
A truncate() 0 4 1
A saveWatch() 0 33 5
A getAllWatches() 0 6 1
A truncateWatches() 0 4 1
B paginate() 0 45 5
A _wrap() 0 16 4
A stats() 0 8 1

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace XHGui\Searcher;
4
5
use Exception;
6
use MongoCursor;
7
use MongoDate;
8
use MongoDb;
9
use MongoId;
10
use XHGui\Db\Mapper;
11
use XHGui\Profile;
12
13
/**
14
 * A Searcher for a MongoDB backend.
15
 */
16
class MongoSearcher implements SearcherInterface
17
{
18
    protected $_collection;
19
20
    protected $_watches;
21
22
    protected $_mapper;
23
24
    public function __construct(MongoDb $db)
25
    {
26
        $this->_collection = $db->results;
0 ignored issues
show
Bug introduced by
The property results does not seem to exist in MongoDB.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
27
        $this->_watches = $db->watches;
0 ignored issues
show
Bug introduced by
The property watches does not seem to exist in MongoDB.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
28
        $this->_mapper = new Mapper();
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function latest()
35
    {
36
        $cursor = $this->_collection->find()
37
            ->sort(['meta.request_date' => -1])
38
            ->limit(1);
39
        $result = $cursor->getNext();
40
41
        return $this->_wrap($result);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->_wrap($result); of type XHGui\Profile|array adds the type array to the return on line 41 which is incompatible with the return type declared by the interface XHGui\Searcher\SearcherInterface::latest of type XHGui\Profile.
Loading history...
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function query($conditions, $limit, $fields = [])
48
    {
49
        $result = $this->_collection->find($conditions, $fields)
50
            ->limit($limit);
51
52
        return iterator_to_array($result);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function get($id)
59
    {
60
        return $this->_wrap($this->_collection->findOne([
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->_wrap($this->_col...> new \MongoId($id)))); of type XHGui\Profile|array adds the type array to the return on line 60 which is incompatible with the return type declared by the interface XHGui\Searcher\SearcherInterface::get of type XHGui\Profile.
Loading history...
61
            '_id' => new MongoId($id),
62
        ]));
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function getForUrl($url, $options, $conditions = [])
69
    {
70
        $conditions = array_merge(
71
            (array)$conditions,
72
            ['simple_url' => $url]
73
        );
74
        $options = array_merge($options, [
75
            'conditions' => $conditions,
76
        ]);
77
78
        return $this->paginate($options);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->paginate($options); (array) is incompatible with the return type declared by the interface XHGui\Searcher\SearcherInterface::getForUrl of type MongoCursor.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function getPercentileForUrl($percentile, $url, $search = [])
85
    {
86
        $result = $this->_mapper->convert([
87
            'conditions' => $search + ['simple_url' => $url],
88
        ]);
89
        $match = $result['conditions'];
90
91
        $col = '$meta.request_date';
92 View Code Duplication
        if (!empty($search['limit']) && $search['limit'][0] === "P") {
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...
93
            $col = '$meta.request_ts';
94
        }
95
96
        $pipeline = [
97
            ['$match' => $match],
98
            [
99
                '$project' => [
100
                    'date' => $col,
101
                    'profile.main()' => 1,
102
                ],
103
            ],
104
            [
105
                '$group' => [
106
                    '_id' => '$date',
107
                    'row_count' => ['$sum' => 1],
108
                    'wall_times' => ['$push' => '$profile.main().wt'],
109
                    'cpu_times' => ['$push' => '$profile.main().cpu'],
110
                    'mu_times' => ['$push' => '$profile.main().mu'],
111
                    'pmu_times' => ['$push' => '$profile.main().pmu'],
112
                ],
113
            ],
114
            [
115
                '$project' => [
116
                    'date' => '$date',
117
                    'row_count' => '$row_count',
118
                    'raw_index' => [
119
                        '$multiply' => [
120
                            '$row_count',
121
                            $percentile / 100,
122
                        ],
123
                    ],
124
                    'wall_times' => '$wall_times',
125
                    'cpu_times' => '$cpu_times',
126
                    'mu_times' => '$mu_times',
127
                    'pmu_times' => '$pmu_times',
128
                ],
129
            ],
130
            ['$sort' => ['_id' => 1]],
131
        ];
132
133
        $results = $this->_collection->aggregate(
134
            $pipeline,
135
            ['cursor' => ['batchSize' => 0]]
136
        );
137
138
        if (empty($results['result'])) {
139
            return [];
140
        }
141
        $keys = [
142
            'wall_times' => 'wt',
143
            'cpu_times' => 'cpu',
144
            'mu_times' => 'mu',
145
            'pmu_times' => 'pmu',
146
        ];
147
        foreach ($results['result'] as &$result) {
148
            $result['date'] = ($result['_id'] instanceof MongoDate) ? date('Y-m-d H:i:s', $result['_id']->sec) : $result['_id'];
149
            unset($result['_id']);
150
            $index = max(round($result['raw_index']) - 1, 0);
151
            foreach ($keys as $key => $out) {
152
                sort($result[$key]);
153
                $result[$out] = $result[$key][$index] ?? null;
154
                unset($result[$key]);
155
            }
156
        }
157
158
        return $results['result'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164
    public function getAvgsForUrl($url, $search = [])
165
    {
166
        $match = ['meta.simple_url' => $url];
167
        if (isset($search['date_start'])) {
168
            $match['meta.request_date']['$gte'] = (string)$search['date_start'];
169
        }
170
        if (isset($search['date_end'])) {
171
            $match['meta.request_date']['$lte'] = (string)$search['date_end'];
172
        }
173
        $results = $this->_collection->aggregate(
174
            [
175
            ['$match' => $match],
176
            [
177
                '$project' => [
178
                    'date' => '$meta.request_date',
179
                    'profile.main()' => 1,
180
                ],
181
            ],
182
            [
183
                '$group' => [
184
                    '_id' => '$date',
185
                    'avg_wt' => ['$avg' => '$profile.main().wt'],
186
                    'avg_cpu' => ['$avg' => '$profile.main().cpu'],
187
                    'avg_mu' => ['$avg' => '$profile.main().mu'],
188
                    'avg_pmu' => ['$avg' => '$profile.main().pmu'],
189
                ],
190
            ],
191
            ['$sort' => ['_id' => 1]],
192
        ],
193
            ['cursor' => ['batchSize' => 0]]
194
        );
195
        if (empty($results['result'])) {
196
            return [];
197
        }
198
        foreach ($results['result'] as $i => $result) {
199
            $results['result'][$i]['date'] = $result['_id'];
200
            unset($results['result'][$i]['_id']);
201
        }
202
203
        return $results['result'];
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209
    public function getAll($options = [])
210
    {
211
        return $this->paginate($options);
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function delete($id)
218
    {
219
        $this->_collection->remove(['_id' => new MongoId($id)], []);
220
    }
221
222
    /**
223
     * {@inheritdoc}
224
     */
225
    public function truncate()
226
    {
227
        return $this->_collection->drop();
228
    }
229
230
    /**
231
     * {@inheritdoc}
232
     */
233
    public function saveWatch(array $data)
234
    {
235
        if (empty($data['name'])) {
236
            return false;
237
        }
238
239
        if (!empty($data['removed']) && isset($data['_id'])) {
240
            $this->_watches->remove(
241
                ['_id' => new MongoId($data['_id'])],
242
                ['w' => 1]
243
            );
244
245
            return true;
246
        }
247
248
        if (empty($data['_id'])) {
249
            $this->_watches->insert(
250
                $data,
251
                ['w' => 1]
252
            );
253
254
            return true;
255
        }
256
257
        $data['_id'] = new MongoId($data['_id']);
258
        $this->_watches->update(
259
            ['_id' => $data['_id']],
260
            $data,
261
            ['w' => 1]
262
        );
263
264
        return true;
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    public function getAllWatches()
271
    {
272
        $cursor = $this->_watches->find();
273
274
        return array_values(iterator_to_array($cursor));
275
    }
276
277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function truncateWatches()
281
    {
282
        $this->_watches->drop();
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288
    private function paginate($options)
289
    {
290
        $opts = $this->_mapper->convert($options);
291
292
        $totalRows = $this->_collection->find(
293
            $opts['conditions'],
294
            ['_id' => 1]
295
        )->count();
296
297
        $totalPages = max(ceil($totalRows / $opts['perPage']), 1);
298
        $page = 1;
299
        if (isset($options['page'])) {
300
            $page = min(max($options['page'], 1), $totalPages);
301
        }
302
303
        $projection = false;
304
        if (isset($options['projection'])) {
305
            if ($options['projection'] === true) {
306
                $projection = ['meta' => 1, 'profile.main()' => 1];
307
            } else {
308
                $projection = $options['projection'];
309
            }
310
        }
311
312
        if ($projection === false) {
313
            $cursor = $this->_collection->find($opts['conditions'])
314
                ->sort($opts['sort'])
315
                ->skip((int)($page - 1) * $opts['perPage'])
316
                ->limit($opts['perPage']);
317
        } else {
318
            $cursor = $this->_collection->find($opts['conditions'], $projection)
319
                ->sort($opts['sort'])
320
                ->skip((int)($page - 1) * $opts['perPage'])
321
                ->limit($opts['perPage']);
322
        }
323
324
        return [
325
            'results' => $this->_wrap($cursor),
326
            'sort' => $opts['sort'],
327
            'direction' => $opts['direction'],
328
            'page' => $page,
329
            'perPage' => $opts['perPage'],
330
            'totalPages' => $totalPages,
331
        ];
332
    }
333
334
    /**
335
     * Converts arrays + MongoCursors into Profile instances.
336
     *
337
     * @param array|MongoCursor $data The data to transform.
338
     * @return Profile|Profile[] The transformed/wrapped results.
339
     */
340
    private function _wrap($data)
341
    {
342
        if ($data === null) {
343
            throw new Exception('No profile data found.');
344
        }
345
346
        if (is_array($data)) {
347
            return new Profile($data);
348
        }
349
        $results = [];
350
        foreach ($data as $row) {
351
            $results[] = new Profile($row);
352
        }
353
354
        return $results;
355
    }
356
357
    /**
358
     * {@inheritdoc}
359
     */
360
    public function stats()
361
    {
362
        return [
363
            'profiles' => 0,
364
            'latest'   => 0,
365
            'bytes'    => 0,
366
        ];
367
    }
368
}
369