Completed
Pull Request — master (#1510)
by
unknown
07:26
created

MongoDbAdapter::getVersionLog()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Phinx\Db\Adapter;
4
5
use MongoDB\Client;
6
use MongoDB\Collection;
7
use MongoDB\Database;
8
use Phinx\Db\Action\AddIndex;
9
use Phinx\Db\Action\DropIndex;
10
use Phinx\Db\Action\DropTable;
11
use Phinx\Db\Adapter\AdapterInterface as PhinxAdapter;
12
use Phinx\Db\Table\Column;
13
use Phinx\Db\Table\Table;
14
use Phinx\Migration\MigrationInterface;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Output\OutputInterface;
17
18
class MongoDbAdapter implements PhinxAdapter
19
{
20
21
    protected $collectionName = 'phinx_migration';
22
23
    /** @var InputInterface $consoleInput */
24
    protected $consoleInput;
25
26
    /** @var OutputInterface $consoleOutput */
27
    protected $consoleOutput;
28
29
    /** @var Client $mongoClient */
30
    protected $mongoClient;
31
32
    /** @var Database $database */
33
    protected $database;
34
35
    /** @var Collection $collection */
36
    protected $collection;
37
38
    /** @var string $databaseName */
39
    protected $databaseName;
40
41
    /** @var string $uri */
42
    protected $uri;
43
44
    protected $session;
45
46
    protected $options = [
47
        'table_prefix' => ''
48
    ];
49
50
    public function __construct(array $options)
51
    {
52
        $this->collectionName = $options['default_migration_table'];
53
        $this->databaseName = $options['name'];
54
        $this->uri = $options['uri'];
55
        $this->options = $options;
56
        $this->connect();
57
    }
58
59
    /**
60
     * @return array
61
     */
62
    public function getVersions()
63
    {
64
        return array_keys($this->getVersionLog());
65
    }
66
67
    /**
68
     * @return array
69
     */
70
    public function getVersionLog()
71
    {
72
        $result = [];
73
        $rows = $this->getMigrationCollection()->find();
74
        foreach ($rows as $row) {
75
            $result[$row['version']] = $row;
76
        }
77
        return $result;
78
    }
79
80
    /**
81
     * @param array $options
82
     * @return $this|PhinxAdapter
83
     */
84
    public function setOptions(array $options)
85
    {
86
        return $this;
87
    }
88
89
    /**
90
     * @return array
91
     */
92
    public function getOptions()
93
    {
94
        return $this->options;
95
    }
96
97
    public function hasOption($name)
98
    {
99
        return true;
100
    }
101
102
    /**
103
     * @param string $name
104
     * @return mixed|null
105
     */
106
    public function getOption($name)
107
    {
108
        if (isset($this->options[$name])) {
109
            return $this->options[$name];
110
        }
111
        return null;
112
    }
113
114
    /**
115
     * @param InputInterface $input
116
     * @return $this|PhinxAdapter
117
     */
118
    public function setInput(InputInterface $input)
119
    {
120
        $this->consoleInput = $input;
121
        return $this;
122
    }
123
124
    /**
125
     * @return InputInterface
126
     */
127
    public function getInput()
128
    {
129
        return $this->consoleInput;
130
    }
131
132
    /**
133
     * @param OutputInterface $output
134
     * @return PhinxAdapter
135
     */
136
    public function setOutput(OutputInterface $output)
137
    {
138
        $this->consoleOutput = $output;
139
        return $this;
140
    }
141
142
    public function getOutput()
143
    {
144
        return $this->consoleOutput;
145
    }
146
147
    /**
148
     * @param MigrationInterface $migration
149
     * @param string $direction
150
     * @param int $startTime
151
     * @param int $endTime
152
     * @return $this|PhinxAdapter
153
     */
154
    public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime)
155
    {
156
        if (strcasecmp($direction, MigrationInterface::UP) === 0) {
157
            $this->getMigrationCollection()->insertOne([
158
                'name' => $migration->getName(),
159
                'start_time' => $startTime,
160
                'end_time' => $endTime,
161
                'version' => $migration->getVersion(),
162
                'breakpoint' => false
163
            ]);
164
        } else {
165
            $this->getMigrationCollection()->deleteOne([
166
                'version' => $migration->getVersion()
167
            ]);
168
        }
169
        return $this;
170
    }
171
172
    /**
173
     * @param MigrationInterface $migration
174
     * @return $this|PhinxAdapter
175
     */
176
    public function toggleBreakpoint(MigrationInterface $migration)
177
    {
178
        return $this;
179
    }
180
181
    public function resetAllBreakpoints()
182
    {
183
        throw new \InvalidArgumentException("Not implemented");
184
    }
185
186
    /**
187
     * @return bool
188
     */
189
    public function hasSchemaTable()
190
    {
191
        return true;
192
    }
193
194
    public function createSchemaTable()
195
    {
196
        throw new \InvalidArgumentException("Not implemented");
197
    }
198
199
    public function getAdapterType()
200
    {
201
        return null;
202
    }
203
204
    public function connect()
205
    {
206
        $this->mongoClient = new Client($this->uri);
207
        $this->database = $this->mongoClient->selectDatabase($this->databaseName);
208
        $this->collection = $this->database->selectCollection($this->collectionName);
209
    }
210
211
    public function disconnect()
212
    {
213
        throw new \InvalidArgumentException("Not implemented");
214
    }
215
216
    public function hasTransactions()
217
    {
218
        return false;
219
    }
220
221
    public function beginTransaction()
222
    {
223
        throw new \InvalidArgumentException("Not implemented");
224
    }
225
226
    public function commitTransaction()
227
    {
228
        throw new \InvalidArgumentException("Not implemented");
229
    }
230
231
    public function rollbackTransaction()
232
    {
233
        throw new \InvalidArgumentException("Not implemented");
234
    }
235
236
    public function execute($sql)
237
    {
238
        throw new \InvalidArgumentException("Don't know how to execute");
239
    }
240
241
    public function executeActions(Table $table, array $actions)
242
    {
243
        foreach ($actions as $action) {
244
            if ($action instanceof AddIndex) {
245
                $columns = $action->getIndex()->getColumns();
246
                $options = [];
247
                $indexName = $action->getIndex()->getName();
248
                if (!empty($indexName)) {
249
                    $options['name'] = $indexName;
250
                }
251
                $type = $action->getIndex()->getType();
252
                if ($type == 'unique') {
253
                    $options['unique'] = true;
254
                }
255
                $this->getDatabase()
256
                    ->selectCollection($action->getTable()->getName())
257
                    ->createIndex($columns, $options);
258
            } elseif ($action instanceof DropIndex) {
259
                $indexName = $action->getIndex()->getName();
260
                if (!empty($indexName)) {
261
                    $this->getDatabase()->selectCollection($action->getTable()->getName())
262
                        ->dropIndex($indexName);
263
                }
264
            } elseif ($action instanceof DropTable) {
265
                $this->getDatabase()
266
                    ->dropCollection($action->getTable()->getName());
267
            } else {
268
                throw new \InvalidArgumentException(
269
                    sprintf("Don't know how to execute action: '%s'", get_class($action))
270
                );
271
            }
272
        }
273
    }
274
275
    public function getQueryBuilder()
276
    {
277
        return null;
278
    }
279
280
    public function query($sql)
281
    {
282
        throw new \InvalidArgumentException("Not implemented");
283
    }
284
285
    public function fetchRow($sql)
286
    {
287
        throw new \InvalidArgumentException("Not implemented");
288
    }
289
290
    public function fetchAll($sql)
291
    {
292
        throw new \InvalidArgumentException("Not implemented");
293
    }
294
295
    /**
296
     * @param Table $table
297
     * @param array $row
298
     */
299
    public function insert(Table $table, $row)
300
    {
301
        $this->getDatabase()->selectCollection($table->getName())->insertOne($row);
302
    }
303
304
    /**
305
     * @param Table $table
306
     * @param array $rows
307
     */
308
    public function bulkinsert(Table $table, $rows)
309
    {
310
        $this->getDatabase()->selectCollection($table->getName())->insertMany($rows);
311
    }
312
313
    /**
314
     * @param string $tableName
315
     * @return mixed|string
316
     */
317
    public function quoteTableName($tableName)
318
    {
319
        return str_replace('.', '`.`', $this->quoteColumnName($tableName));
320
    }
321
322
    /**
323
     * @param string $columnName
324
     * @return string
325
     */
326
    public function quoteColumnName($columnName)
327
    {
328
        return '`' . str_replace('`', '``', $columnName) . '`';
329
    }
330
331
    /**
332
     * @param string $tableName
333
     * @return bool
334
     */
335
    public function hasTable($tableName)
336
    {
337
        return true;
338
    }
339
340
    /**
341
     * @param Table $table
342
     * @param array $columns
343
     * @param array $indexes
344
     */
345
    public function createTable(Table $table, array $columns = [], array $indexes = [])
346
    {
347
    }
348
349
    /**
350
     * @param string $tableName
351
     */
352
    public function truncateTable($tableName)
353
    {
354
        $this->getDatabase()->dropCollection($tableName);
355
    }
356
357
    /**
358
     * @param string $tableName
359
     * @return array|Column[]
360
     */
361
    public function getColumns($tableName)
362
    {
363
        return [];
364
    }
365
366
    /**
367
     * @param string $tableName
368
     * @param string $columnName
369
     * @return bool
370
     */
371
    public function hasColumn($tableName, $columnName)
372
    {
373
        return true;
374
    }
375
376
    /**
377
     * @param string $tableName
378
     * @param mixed $columns
379
     * @return bool|void
380
     */
381
    public function hasIndex($tableName, $columns)
382
    {
383
        $indexes = $this->getDatabase()->selectCollection($tableName)->listIndexes();
384
        $this->hasValues($indexes, $columns);
0 ignored issues
show
Unused Code introduced by
The call to the method Phinx\Db\Adapter\MongoDbAdapter::hasValues() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
385
    }
386
387
    /**
388
     * @param string $tableName
389
     * @param string $indexName
390
     * @return bool
391
     */
392
    public function hasIndexByName($tableName, $indexName)
393
    {
394
        $indexes = $this->getDatabase()->selectCollection($tableName)->listIndexes();
395
        return $this->hasValue($indexes, $indexName);
396
    }
397
398
    /**
399
     * @param string $tableName
400
     * @param string[] $columns
401
     * @param null $constraint
402
     * @return bool
403
     */
404
    public function hasPrimaryKey($tableName, $columns, $constraint = null)
405
    {
406
        return true;
407
    }
408
409
    /**
410
     * @param string $tableName
411
     * @param string[] $columns
412
     * @param null $constraint
413
     * @return bool
414
     */
415
    public function hasForeignKey($tableName, $columns, $constraint = null)
416
    {
417
        return false;
418
    }
419
420
    /**
421
     * @return array
422
     */
423
    public function getColumnTypes()
424
    {
425
        return [
426
            self::PHINX_TYPE_BIG_INTEGER,
427
            self::PHINX_TYPE_BOOLEAN,
428
            self::PHINX_TYPE_INTEGER,
429
            self::PHINX_TYPE_STRING,
430
            self::PHINX_TYPE_FLOAT
431
        ];
432
    }
433
434
    /**
435
     * @param Column $column
436
     * @return bool
437
     */
438
    public function isValidColumnType(Column $column)
439
    {
440
        return true;
441
    }
442
443
    /**
444
     * @param string $type
445
     * @param null $limit
446
     * @return array|string[]
447
     */
448
    public function getSqlType($type, $limit = null)
449
    {
450
        return [];
451
    }
452
453
    /**
454
     * @param string $name
455
     * @param array $options
456
     */
457
    public function createDatabase($name, $options = [])
458
    {
459
    }
460
461
    /**
462
     * @param string $name
463
     * @return bool
464
     */
465
    public function hasDatabase($name)
466
    {
467
        return true;
468
    }
469
470
    /**
471
     * @param string $name
472
     */
473
    public function dropDatabase($name)
474
    {
475
        $this->mongoClient->dropDatabase($name);
476
    }
477
478
    public function createSchema($schemaName = 'public')
479
    {
480
        throw new \InvalidArgumentException("Not implemented");
481
    }
482
483
    /**
484
     * @param string $schemaName
485
     */
486
    public function dropSchema($schemaName)
487
    {
488
        $this->getDatabase()->dropCollection($schemaName);
489
    }
490
491
    public function castToBool($value)
492
    {
493
        throw new \InvalidArgumentException("Not implemented");
494
    }
495
496
    protected function getMigrationCollection()
497
    {
498
        return $this->collection;
499
    }
500
501
    /**
502
     * @return Database
503
     */
504
    protected function getDatabase()
505
    {
506
        return $this->database;
507
    }
508
509
    /**
510
     * @param \Iterator $iterator
511
     * @param $value
512
     * @return bool
513
     */
514
    protected function hasValue(\Iterator $iterator, $value)
515
    {
516
        foreach ($iterator as $iteration) {
517
            if ($iteration == $value) {
518
                return true;
519
            }
520
        }
521
        return false;
522
    }
523
524
    /**
525
     * @param \Iterator $iterator
526
     * @param $values
527
     * @return bool
528
     */
529
    protected function hasValues(\Iterator $iterator, $values)
530
    {
531
        foreach ($iterator as $iteration) {
532
            if ($this->hasValue($iteration, $values)) {
533
                return true;
534
            }
535
        }
536
        return false;
537
    }
538
539
    /**
540
     * @return Client|\PDO
541
     */
542
    public function getConnection()
543
    {
544
        return $this->mongoClient;
545
    }
546
}
547