Completed
Push — master ( 6f54d6...ffe8b5 )
by CodexShaper
05:45
created

MongoDB::getCollectionNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 6
rs 10
1
<?php
2
3
namespace CodexShaper\DBM\Database\Drivers;
4
5
use CodexShaper\DBM\Database\Drivers\MongoDB\Index;
6
use CodexShaper\DBM\Models\CollectionField;
7
use CodexShaper\DBM\Models\DBM_Collection;
8
use CodexShaper\DBM\Traits\MongoConnection;
9
use Illuminate\Support\Facades\DB;
10
11
class MongoDB
12
{
13
    use MongoConnection;
14
15
    /**
16
     * Run MongoDB command.
17
     *
18
     * @return  \MongoDB\Driver\Cursor
19
     */
20
    public function command(array $command)
21
    {
22
        return static::getMongoClient()->{$this->admin}->command($command);
23
    }
24
    /**
25
     * Rename collection.
26
     *
27
     * @param   string  $fromNs
28
     * @param   string  $toNs
29
     *
30
     * @return  \MongoDB\Driver\Cursor
31
     */
32
    public function renameCollection($fromNs, $toNs)
33
    {
34
        return $this->command(['renameCollection' => $fromNs, 'to' => $toNs]);
35
    }
36
    /**
37
     * Rename fields.
38
     *
39
     * @param   string  $collectionName
40
     * @param   array   $fields
41
     *
42
     * @return  void
43
     */
44
    public function renameFields($collectionName, $fields)
45
    {
46
        $rename = [];
47
        foreach ($fields as $oldName => $newName) {
48
            $rename[$oldName] = $newName;
49
        }
50
        $update = [
51
            '$rename' => $rename,
52
        ];
53
54
        $this->selectCollection($collectionName)->updateMany([], $update, ['upsert' => true]);
55
    }
56
    /**
57
     * Get the MongoDB database object.
58
     *
59
     * @return  \MongoDB\Database
60
     */
61
    public function getDB()
62
    {
63
        return DB::connection()->getMongoDB();
64
    }
65
    /**
66
     * Get the MongoDB collection namespace.
67
     *
68
     * @param   string  $databaseName
69
     * @param   string  $collectionName
70
     * @return string
71
     */
72
    public function getNamespace($databaseName, $collectionName)
73
    {
74
        return $databaseName.'.'.$collectionName;
75
    }
76
    /**
77
     * Get the all collections.
78
     *
79
     * @return  \MongoDB\Model\CollectionInfoIterator
80
     */
81
    public function getCollections()
82
    {
83
        return $this->getDB()->listCollections();
84
    }
85
    /**
86
     * Get the all collections name.
87
     *
88
     * @return  array
89
     */
90
    public function getCollectionNames()
91
    {
92
        $collections = $this->getCollections();
93
        $collectionNames = [];
94
        foreach ($collections as $key => $collection) {
95
            $collectionNames[] = $collection->getName();
96
        }
97
98
        return $collectionNames;
99
    }
100
    /**
101
     * Check MongoDB collection.
102
     *
103
     * @param   string $collectionName
104
     *
105
     * @return  bool
106
     */
107
    public function hasCollection($collectionName)
108
    {
109
        return (in_array($collectionName, $this->getCollectionNames())) ? true : false;
110
    }
111
    /**
112
     * Create MongoDB colelction.
113
     *
114
     * @param   string $collectionName
115
     *
116
     * @return  array|object Command result document
117
     */
118
    public function createCollection($collectionName)
119
    {
120
        return $this->getDB()->createCollection($collectionName);
121
    }
122
    /**
123
     * Get MongoDB colelction.
124
     *
125
     * @param   string $collectionName
126
     *
127
     * @return  array
128
     */
129
    public function getCollection($collectionName)
130
    {
131
        return [
132
            'name'           => $collectionName,
133
            'oldName'        => $collectionName,
134
            'columns'        => $this->getColumns($collectionName),
135
            'indexes'        => Index::getIndexes($this->selectCollection($collectionName)),
136
            'foreignKeys'    => [],
137
            'primaryKeyName' => ['_id'],
138
            'options'        => [],
139
        ];
140
    }
141
    /**
142
     * Update MongoDB colelction.
143
     *
144
     * @param   array $collection
145
     *
146
     * @return  bool
147
     */
148
    public function updateCollection($collection)
149
    {
150
151
        $newName = $collection['name'];
152
        $oldName = $collection['oldName'];
153
        $collectionName = $oldName;
154
        $connection = config('database.default');
155
        $database = config('database.connections.'.$connection.'.database');
156
        $fromNs = $this->getNamespace($database, $oldName);
157
        $toNs = $this->getNamespace($database, $newName);
158
159
        if ($newName != $oldName) {
160
            $this->renameCollection($fromNs, $toNs);
161
            $collectionName = $newName;
162
        }
163
164
        $this->setFields($collectionName, $this->getColumns($collectionName));
165
        Index::setIndexes($this->selectCollection($collectionName), $collection['indexes']);
166
167
        return true;
168
169
    }
170
    /**
171
     * Rename MongoDB colelction columns.
172
     *
173
     * @param   string $collectionName
174
     * @param   array $fields
175
     *
176
     * @return  void
177
     */
178
    public function renameColumns($collectionName, $fields)
179
    {
180
        $collection = $this->selectCollection($collectionName);
181
        $renames = [];
182
        foreach ($fields as $field) {
183
            if ($field->oldName != '') {
184
                if ($field->oldName != $field->name) {
185
                    $renames[$field->oldName] = $field->name;
186
                }
187
188
            }
189
        }
190
        $update = [];
191
        if ($field->oldName != '') {
192
            $update['$rename'] = $renames;
193
            $collection->updateMany([], $update, ['upsert' => true]);
194
            $dbmCollection = DBM_Collection::where('name', $collectionName)->first();
195
            foreach ($renames as $oldName => $newName) {
196
                $collection_field = CollectionField::where([
197
                    'dbm_collection_id' => $dbmCollection->_id,
198
                    'old_name'          => $oldName,
199
                ])->first();
200
                $collection_field->old_name = $newName;
201
                $collection_field->update();
202
            }
203
        }
204
    }
205
    /**
206
     * Add MongoDB colelction columns.
207
     *
208
     * @param   string $collectionName
209
     *
210
     * @return  void
211
     */
212
    public function addColumns($collectionName)
213
    {
214
        $collection = $this->selectCollection($collectionName);
215
        $newFields = $this->getColumnsName($collectionName);
216
        $update = [];
217
218
        if ($collection->count() > 0) {
219
            foreach ($newFields as $newField) {
220
                $cursor = $collection->find();
221
                $iterator = iterator_to_array($cursor);
222
223
                foreach ($iterator as $document) {
224
                    $columnNames = [];
225
                    $id = '';
226
                    foreach ($document as $columnName => $columnValue) {
227
                        if (is_object($columnValue)) {
228
                            foreach ($columnValue as $key => $value) {
229
                                if ($columnName == '_id') {
230
                                    $id = $value;
231
                                }
232
                            }
233
                        }
234
                        $columnNames[] = $columnName;
235
                    }
236
237
                    if ($id != '' && ! in_array($newField, $columnNames)) {
238
                        $update['$set'] = [$newField => ''];
239
                        $collection->updateOne(
240
                            ['_id' => new \MongoDB\BSON\ObjectID($id)],
241
                            $update,
242
                            ['upsert' => true]
243
                        );
244
                    }
245
                }
246
            }
247
248
        }
249
    }
250
    /**
251
     * Remove MongoDB colelction columns.
252
     *
253
     * @param   string $collectionName
254
     *
255
     * @return  void
256
     */
257
    public function removeColumns($collectionName)
258
    {
259
        $collection = $this->selectCollection($collectionName);
260
        $newFields = $this->getColumnsName($collectionName);
261
        $columns = $this->getCollectionColumns($collectionName);
262
        $update = [];
263
        $unsets = [];
264
265
        foreach ($columns as $column) {
266
            if (! in_array($column, $newFields)) {
267
                $unsets[$column] = '';
268
        }
269
270
        if (count($unsets) > 0) {
271
            $update['$unset'] = $unsets;
272
            $collection->updateMany([], $update, ['upsert' => true]);
273
        }
274
    }
275
    /**
276
     * Set MongoDB colelction fields.
277
     *
278
     * @param   string $collectionName
279
     * @param   array $fields
280
     *
281
     * @return  void
282
     */
283
    public function setFields($collectionName, $fields)
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_PUBLIC on line 283 at column 4
Loading history...
284
    {
285
        /*
286
         * Rename Columns
287
         */
288
        $this->renameColumns($collectionName, $fields);
289
290
        /*
291
         * Add Columns
292
         */
293
        $this->addColumns($collectionName);
294
        /*
295
         * Remove Columns
296
         */
297
        $this->removeColumns($collectionName);
298
        return true;
299
    }
300
    /**
301
     * Drop MongoDB colelction.
302
     *
303
     * @param   string $collectionName
304
     *
305
     * @return  void
306
     */
307
    public function dropCollection($collectionName)
308
    {
309
        $this->getDB()->dropCollection($collectionName);
310
    }
311
    /**
312
     * Select MongoDB colelction.
313
     *
314
     * @param   string $collectionName
315
     *
316
     * @return  \MongoDB\Collection
317
     */
318
    public function selectCollection($collectionName)
319
    {
320
        return $this->getDB()->selectCollection($collectionName);
321
    }
322
    /**
323
     * Get MongoDB colelction columns.
324
     *
325
     * @param   string $collectionName
326
     *
327
     * @return  array
328
     */
329
    public function getCollectionColumns($collectionName)
330
    {
331
        $cursor = $this->selectCollection($collectionName)->find();
332
        $iterator = iterator_to_array($cursor);
333
        $columnNames = [];
334
335
        foreach ($iterator as $document) {
336
            foreach ($document as $columnName => $columnValue) {
337
                $columnNames[] = $columnName;
338
            }
339
        }
340
341
        return array_values(array_unique($columnNames));
342
    }
343
    /**
344
     * Get MongoDB columns.
345
     *
346
     * @param   string $collectionName
347
     *
348
     * @return  array
349
     */
350
    public function getColumns($collectionName)
351
    {
352
        $columns = [];
353
354
        if ($collection = DBM_Collection::where('name', $collectionName)->first()) {
355
356
            $fields = $collection->fields;
357
            foreach ($fields as $field) {
358
                $columns[] = (object) [
359
                    'name'          => $field->name,
360
                    'oldName'       => $field->old_name,
361
                    'type'          => [
362
                        'name' => $field->type,
363
                    ],
364
                    'autoincrement' => false,
365
                    'default'       => null,
366
                    'length'        => null,
367
                ];
368
            }
369
        } else {
370
            $fields = $this->getCollectionColumns($collectionName);
371
            foreach ($fields as $field) {
372
                $columns[] = (object) [
373
                    'name'          => $field,
374
                    'oldName'       => $field,
375
                    'type'          => [
376
                        'name' => '',
377
                    ],
378
                    'autoincrement' => false,
379
                    'default'       => null,
380
                    'length'        => null,
381
                ];
382
            }
383
        }
384
385
        return $columns;
386
    }
387
    /**
388
     * Get colelction ColumnsName.
389
     *
390
     * @param   string $collectionName
391
     *
392
     * @return  array
393
     */
394
    public function getColumnsName($collectionName)
395
    {
396
        return DBM_Collection::where('name', $collectionName)->first()->fields->pluck('name')->toArray();
397
    }
398
399
}
400