Passed
Push — master ( 2e0752...8a3ec8 )
by Mehmet
03:05
created

MongoDB::find()   C

Complexity

Conditions 13
Paths 52

Size

Total Lines 54
Code Lines 40

Duplication

Lines 12
Ratio 22.22 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 12
loc 54
rs 6.7593
cc 13
eloc 40
nc 52
nop 7

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 Soupmix;
4
/*
5
MongoDB Adapter
6
*/
7
Use MongoDB as MongoDBLib;
8
9
class MongoDB implements Base
10
{
11
    public $conn = null;
12
13
    private $dbName = null;
14
15
    public $db = null;
16
17
    public function __construct($config)
18
    {
19
        $this->dbName = $config['db_name'];
20
        $this->connect($config);
21
    }
22
23
    public function connect($config)
24
    {
25
        $this->conn = new MongoDBLib\Client($config['connection_string'], $config['options']);
26
        $this->db = $this->conn->{$this->dbName};
27
    }
28
29
    public function create($collection, $config)
30
    {
31
        return $this->db->createCollection($collection);
32
    }
33
34
    public function drop($collection, $config)
35
    {
36
        return $this->db->dropCollection($collection);
37
    }
38
39
    public function truncate($collection, $config)
40
    {
41
        $this->db->dropCollection($collection);
42
43
        return $this->db->createCollection($collection);
44
    }
45
46
    public function createIndexes($collection, $indexes)
47
    {
48
        $collection = $this->db->selectCollection($collection);
49
50
        return $collection->createIndexes($indexes);
51
    }
52
53
    public function insert($collection, $values)
54
    {
55
        $collection = $this->db->selectCollection($collection);
56
        $result = $collection->insertOne($values);
57
        $docId = $result->getInsertedId();
58
        if (is_object($docId)) {
59
            return (string) $docId;
60
        }
61
        return null;
62
        
63
    }
64
65
    public function get($collection, $docId)
66
    {
67
        $collection = $this->db->selectCollection($collection);
68
69
        $options = [
70
            'typeMap' => ['root' => 'array', 'document' => 'array'],
71
        ];
72
73
        if (gettype($docId) == "array") {
74
75
            $idList = [];
76
            foreach ($docId as $itemId){
77
                $idList[]=['_id'=>new MongoDBLib\BSON\ObjectID($itemId)];
78
            }
79
80
            //$filter = ['_id' => new MongoDBLib\BSON\ObjectID($docId)];
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
            // {'$or':[{"_id":ObjectId("574d5b38a102fd10905a9183")}, {'_id':ObjectId("574d5b38a102fd10905a9182")}]}
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
82
            $filter = ['$or'=>$idList];
83
            $cursor = $collection->find($filter, $options);
84
            $iterator = new \IteratorIterator($cursor);
85
            $iterator->rewind();
86
            $results=[];
87 View Code Duplication
            while ($doc = $iterator->current()) {
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...
88
                if (isset($doc['_id'])) {
89
                    $doc['id'] = (string) $doc['_id'];
90
                    unset($doc['_id']);
91
                }
92
                $results[$doc['id']] = $doc;
93
                $iterator->next();
94
            }
95
            return $results;
96
        } else {
97
            $filter = ['_id' => new MongoDBLib\BSON\ObjectID($docId)];
98
            $result = $collection->findOne($filter, $options);
99
            if ($result!==null) {
100
                $result['id'] = (string) $result['_id'];
101
                unset($result['_id']);
102
            }
103
104
        }
105
106
        return $result;
107
    }
108
109
    public function update($collection, $filters, $values)
110
    {
111
        $collection = $this->db->selectCollection($collection);
112 View Code Duplication
        if (isset($filters['id'])) {
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...
113
            $filters['_id'] = new MongoDBLib\BSON\ObjectID($filters['id']);
114
            unset($filters['id']);
115
        }
116
        $query_filters = [];
117
        if ($filters != null) {
118
            $query_filters = ['$and' => self::buildFilter($filters)];
119
        }
120
        $values_set = ['$set' => $values];
121
122
        $result = $collection->updateMany($query_filters, $values_set);
123
124
        return $result->getModifiedCount();
125
    }
126
127
    public function delete($collection, $filter)
128
    {
129
        $collection = $this->db->selectCollection($collection);
130
        $filter = self::buildFilter($filter)[0];
131
        if (isset($filter['id'])) {
132
            $filter['_id'] = new MongoDBLib\BSON\ObjectID($filter['id']);
133
            unset($filter['id']);
134
        }
135
        $result = $collection->deleteMany($filter);
136
137
        return $result->getDeletedCount();
138
    }
139
140
    public function find($collection, $filters, $fields = null, $sort = null, $start = 0, $limit = 25, $debug = false)
141
    {
142
        $collection = $this->db->selectCollection($collection);
143 View Code Duplication
        if (isset($filters['id'])) {
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...
144
            $filters['_id'] = new MongoDBLib\BSON\ObjectID($filters['id']);
145
            unset($filters['id']);
146
        }
147
        $query_filters = [];
148
        if ($filters != null) {
149
            $query_filters = ['$and' => self::buildFilter($filters)];
150
        }
151
        $count = $collection->count($query_filters);
152
        if ($count > 0) {
153
            $results = [];
154
            $options = [
155
                'limit' => (int) $limit,
156
                'skip' => (int) $start,
157
                'typeMap' => ['root' => 'array', 'document' => 'array'],
158
            ];
159
            if ($fields!==null) {
160
                $projection = [];
161
                foreach ($fields as $field) {
162
                    if ($field=='id') {
163
                        $field = '_id';
164
                    }
165
                    $projection[$field] = true;
166
                }
167
                $options['projection'] = $projection;
168
            }
169
            if ($sort!==null) {
170
                foreach ($sort as $sort_key => $sort_dir) {
171
                    $sort[$sort_key] = ($sort_dir=='desc') ? -1 : 1;
172
                    if ($sort_key=='id') {
173
                        $sort['_id'] = $sort[$sort_key];
174
                        unset($sort['id']);
175
                    }
176
                }
177
                $options['sort'] = $sort;
178
            }
179
            $cursor = $collection->find($query_filters, $options);
180
            $iterator = new \IteratorIterator($cursor);
181
            $iterator->rewind();
182 View Code Duplication
            while ($doc = $iterator->current()) {
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...
183
                if (isset($doc['_id'])) {
184
                    $doc['id'] = (string) $doc['_id'];
185
                    unset($doc['_id']);
186
                }
187
                $results[] = $doc;
188
                $iterator->next();
189
            }
190
            return ['total' => $count, 'data' => $results];
191
        }
192
        return ['total' => 0, 'data' => null];
193
    }
194
195
    public function query($query)
196
    {
197
        // reserved
198
    }
199
200
    public static function buildFilter($filter)
201
    {
202
        $filters = [];
203
        foreach ($filter as $key => $value) {
204
            if (strpos($key, '__')!==false) {
205
                preg_match('/__(.*?)$/i', $key, $matches);
206
                $operator = $matches[1];
207
                switch ($operator) {
208
                    case '!in':
209
                        $operator = 'nin';
210
                        break;
211
                    case 'not':
212
                        $operator = 'ne';
213
                        break;
214
                    case 'wildcard':
215
                        $operator = 'regex';
216
                        $value = str_replace(array('?'), array('.'), $value);
217
                        break;
218
                    case 'prefix':
219
                        $operator = 'regex';
220
                        $value = $value.'*';
221
                        break;
222
                }
223
                $key = str_replace($matches[0], '', $key);
224
                $filters[] = [$key => ['$'.$operator => $value]];
225
            } elseif (strpos($key, '__')===false && is_array($value)) {
226
                $filters[]['$or'] = self::buildFilter($value);
227
            } else {
228
                $filters[][$key] = $value;
229
            }
230
        }
231
232
        return $filters;
233
    }
234
}
235