Completed
Push — master ( a45c22...e4b600 )
by Mehmet
04:00
created

MongoDB::mergeFilters()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 8
nc 3
nop 2
1
<?php
2
3
namespace Soupmix;
4
/*
5
MongoDB Adapter
6
*/
7
8
9
class MongoDB implements Base
10
{
11
    public $conn = null;
12
13
    private $dbName = null;
14
15
    public $database = 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 \MongoDB\Client($config['connection_string'], $config['options']);
26
        $this->database = $this->conn->{$this->dbName};
27
    }
28
29
    public function create($collection)
30
    {
31
        return $this->database->createCollection($collection);
32
    }
33
34
    public function drop($collection)
35
    {
36
        return $this->database->dropCollection($collection);
37
    }
38
39
    public function truncate($collection)
40
    {
41
        $this->database->dropCollection($collection);
42
        return $this->database->createCollection($collection);
43
    }
44
45
    public function createIndexes($collection, $indexes)
46
    {
47
        $collection = $this->database->selectCollection($collection);
48
        return $collection->createIndexes($indexes);
49
    }
50
51
    public function insert($collection, $values)
52
    {
53
        $collection = $this->database->selectCollection($collection);
54
        $result = $collection->insertOne($values);
55
        $docId = $result->getInsertedId();
56
        if (is_object($docId)) {
57
            return (string) $docId;
58
        }
59
        return null;
60
        
61
    }
62
63
    public function get($collection, $docId)
64
    {
65
        $collection = $this->database->selectCollection($collection);
66
        if (gettype($docId) == "array") {
67
            return $this->multiGet($collection, $docId);
68
        }
69
        return $this->singleGet($collection, $docId);
70
    }
71
72
    private function singleGet($collection, $docId)
73
    {
74
        $options = [
75
            'typeMap' => ['root' => 'array', 'document' => 'array'],
76
        ];
77
        $filter = ['_id' => new \MongoDB\BSON\ObjectID($docId)];
78
        $result = $collection->findOne($filter, $options);
79
        if ($result!==null) {
80
            $result['id'] = (string) $result['_id'];
81
            unset($result['_id']);
82
        }
83
        return $result;
84
    }
85
86
    private function multiGet($collection, $docIds)
87
    {
88
        $options = [
89
            'typeMap' => ['root' => 'array', 'document' => 'array'],
90
        ];
91
        $idList = [];
92
        foreach ($docIds as $itemId) {
93
            $idList[]=['_id'=>new \MongoDB\BSON\ObjectID($itemId)];
94
        }
95
        $filter = ['$or'=>$idList];
96
        $cursor = $collection->find($filter, $options);
97
        $iterator = new \IteratorIterator($cursor);
98
        $iterator->rewind();
99
        $results=[];
100 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...
101
            if (isset($doc['_id'])) {
102
                $doc['id'] = (string) $doc['_id'];
103
                unset($doc['_id']);
104
            }
105
            $results[$doc['id']] = $doc;
106
            $iterator->next();
107
        }
108
        return $results;
109
    }
110
111
    public function update($collection, $filters, $values)
112
    {
113
        $collection = $this->database->selectCollection($collection);
114 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...
115
            $filters['_id'] = new \MongoDB\BSON\ObjectID($filters['id']);
116
            unset($filters['id']);
117
        }
118
        $query_filters = [];
119
        if ($filters != null) {
120
            $query_filters = ['$and' => self::buildFilter($filters)];
121
        }
122
        $values_set = ['$set' => $values];
123
        try{
124
            $result = $collection->updateMany($query_filters, $values_set);
125
126
        } catch (\Exception $e){
127
            throw new \Exception($e->getMessage());
128
        }
129
130
131
        return $result->getModifiedCount();
132
    }
133
134
    public function delete($collection, $filter)
135
    {
136
        $collection = $this->database->selectCollection($collection);
137
        $filter = self::buildFilter($filter)[0];
138
139
        if (isset($filter['id'])) {
140
            $filter['_id'] = new \MongoDB\BSON\ObjectID($filter['id']);
141
            unset($filter['id']);
142
        }
143
        $result = $collection->deleteMany($filter);
144
145
        return $result->getDeletedCount();
146
    }
147
148
    public function find($collection, $filters, $fields = null, $sort = null, $start = 0, $limit = 25, $debug = false)
149
    {
150
        $collection = $this->database->selectCollection($collection);
151 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...
152
            $filters['_id'] = new \MongoDB\BSON\ObjectID($filters['id']);
153
            unset($filters['id']);
154
        }
155
        $query_filters = [];
156
        if ($filters != null) {
157
            $query_filters = ['$and' => self::buildFilter($filters)];
158
        }
159
        if($debug){
160
            return ['filters'=>$query_filters, 'start'=>$start, 'limit'=>$limit];
161
        }
162
        $count = $collection->count($query_filters);
163
164
        if($debug){
165
            return ['filters'=>$query_filters, 'start'=>$start, 'limit'=>$limit,'sort'=>$sort];
166
        }
167
        if ($count > 0) {
168
            $results = [];
169
            $options = [
170
                'limit' => (int) $limit,
171
                'skip' => (int) $start,
172
                'typeMap' => ['root' => 'array', 'document' => 'array'],
173
            ];
174
            if ($fields!==null) {
175
                $projection = [];
176
                foreach ($fields as $field) {
177
                    if ($field=='id') {
178
                        $field = '_id';
179
                    }
180
                    $projection[$field] = true;
181
                }
182
                $options['projection'] = $projection;
183
            }
184
            if ($sort!==null) {
185
                foreach ($sort as $sort_key => $sort_dir) {
186
                    $sort[$sort_key] = ($sort_dir=='desc') ? -1 : 1;
187
                    if ($sort_key=='id') {
188
                        $sort['_id'] = $sort[$sort_key];
189
                        unset($sort['id']);
190
                    }
191
                }
192
                $options['sort'] = $sort;
193
            }
194
195
            $cursor = $collection->find($query_filters, $options);
196
            $iterator = new \IteratorIterator($cursor);
197
            $iterator->rewind();
198 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...
199
                if (isset($doc['_id'])) {
200
                    $doc['id'] = (string) $doc['_id'];
201
                    unset($doc['_id']);
202
                }
203
                $results[] = $doc;
204
                $iterator->next();
205
            }
206
            return ['total' => $count, 'data' => $results];
207
        }
208
        return ['total' => 0, 'data' => null];
209
    }
210
211
    public function query($query)
212
    {
213
        // reserved
214
    }
215
216
    public static function buildFilter($filter)
217
    {
218
        $filters = [];
219
        foreach ($filter as $key => $value) {
220
            
221
            if (strpos($key, '__')!==false) {
222
                $filters[] = self::buildFilterForKeys($key, $value);
223
                //$filters = self::mergeFilters($filters, $tmpFilters);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
224
            } elseif (strpos($key, '__') === false && is_array($value)) {
225
                $filters[]['$or'] = self::buildFilterForOr($value);
226
            } else {
227
                $filters[][$key] = $value;
228
            }
229
        }
230
        return $filters;
231
    }
232
233
    public static function buildFilterForOr($orValues)
234
    {
235
        $filters = [];
236
        foreach ($orValues as $filter) {
237
            $subKey = array_keys($filter)[0];
238
            $subValue = $filter[$subKey];
239
            if (strpos($subKey, '__')!==false) {
240
                $filters[] = self::buildFilterForKeys($subKey, $subValue);
241
               // $filters = self::mergeFilters($filters, $tmpFilters);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
242
            } else {
243
                $filters[][$subKey] = $subValue;
244
            }
245
        }
246
        return $filters;
247
    }
248
249
    private static function mergeFilters ($filters, $tmpFilters){
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
250
251
        foreach ($tmpFilters as $fKey => $fVals) {
252
            if (isset($filters[$fKey])) {
253
                foreach ($fVals as $fVal) {
254
                    $filters[$fKey][] = $fVal;
255
                }
256
            } else {
257
                $filters[$fKey] = $fVals;
258
            }
259
        }
260
        return $filters;
261
    }
262
263
    private static function buildFilterForKeys($key, $value)
264
    {
265
        preg_match('/__(.*?)$/i', $key, $matches);
266
        $operator = $matches[1];
267
        switch ($operator) {
268
            case '!in':
269
                $operator = 'nin';
270
                break;
271
            case 'not':
272
                $operator = 'ne';
273
                break;
274
            case 'wildcard':
275
                $operator = 'regex';
276
                $value = str_replace(array('?'), array('.'), $value);
277
                break;
278
            case 'prefix':
279
                $operator = 'regex';
280
                $value = $value.'*';
281
                break;
282
        }
283
        $key = str_replace($matches[0], '', $key);
284
        $filters= [$key => ['$'.$operator => $value]];
285
        return $filters;
286
    }
287
288
}
289