Completed
Push — master ( 7f79d0...1c7523 )
by Sergei
25:19 queued 22:43
created

Comparator   F

Complexity

Total Complexity 111

Size/Duplication

Total Lines 506
Duplicated Lines 0 %

Test Coverage

Coverage 97.82%

Importance

Changes 0
Metric Value
wmc 111
eloc 221
dl 0
loc 506
rs 2
c 0
b 0
f 0
ccs 224
cts 229
cp 0.9782

11 Methods

Rating   Name   Duplication   Size   Complexity  
A diffSequence() 0 7 2
A compareSchemas() 0 5 1
A isALegacyJsonComparison() 0 8 6
A diffIndex() 0 3 2
B detectIndexRenamings() 0 37 7
F diffColumn() 0 82 29
F diffTable() 0 106 24
F compare() 0 110 25
A isAutoIncrementSequenceInSchema() 0 9 3
A diffForeignKey() 0 19 5
B detectColumnRenamings() 0 30 7

How to fix   Complexity   

Complex Class

Complex classes like Comparator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Comparator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Types;
6
use function array_intersect_key;
7
use function array_key_exists;
8
use function array_keys;
9
use function array_map;
10
use function array_merge;
11
use function array_shift;
12
use function array_unique;
13
use function assert;
14
use function count;
15
use function strtolower;
16
17
/**
18
 * Compares two Schemas and return an instance of SchemaDiff.
19
 */
20
class Comparator
21
{
22
    /**
23
     * @return SchemaDiff
24
     */
25 459
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
26
    {
27 459
        $c = new self();
28
29 459
        return $c->compare($fromSchema, $toSchema);
30
    }
31
32
    /**
33
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
34
     *
35
     * The returned differences are returned in such a way that they contain the
36
     * operations to change the schema stored in $fromSchema to the schema that is
37
     * stored in $toSchema.
38
     *
39
     * @return SchemaDiff
40
     */
41 757
    public function compare(Schema $fromSchema, Schema $toSchema)
42
    {
43 757
        $diff             = new SchemaDiff();
44 757
        $diff->fromSchema = $fromSchema;
45
46 757
        $foreignKeysToTable = [];
47
48 757
        foreach ($toSchema->getNamespaces() as $namespace) {
49 54
            if ($fromSchema->hasNamespace($namespace)) {
50 54
                continue;
51
            }
52
53 54
            $diff->newNamespaces[$namespace] = $namespace;
54
        }
55
56 757
        foreach ($fromSchema->getNamespaces() as $namespace) {
57 54
            if ($toSchema->hasNamespace($namespace)) {
58 54
                continue;
59
            }
60
61 27
            $diff->removedNamespaces[$namespace] = $namespace;
62
        }
63
64 757
        foreach ($toSchema->getTables() as $table) {
65 595
            $tableName = $table->getShortestName($toSchema->getName());
66 595
            if (! $fromSchema->hasTable($tableName)) {
67 135
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
68
            } else {
69 541
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
70 541
                if ($tableDifferences !== false) {
71 320
                    $diff->changedTables[$tableName] = $tableDifferences;
72
                }
73
            }
74
        }
75
76
        /* Check if there are tables removed */
77 757
        foreach ($fromSchema->getTables() as $table) {
78 568
            $tableName = $table->getShortestName($fromSchema->getName());
79
80 568
            $table = $fromSchema->getTable($tableName);
81 568
            if (! $toSchema->hasTable($tableName)) {
82 135
                $diff->removedTables[$tableName] = $table;
83
            }
84
85
            // also remember all foreign keys that point to a specific table
86 568
            foreach ($table->getForeignKeys() as $foreignKey) {
87 54
                $foreignTable = strtolower($foreignKey->getForeignTableName());
88 54
                if (! isset($foreignKeysToTable[$foreignTable])) {
89 54
                    $foreignKeysToTable[$foreignTable] = [];
90
                }
91 90
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
92
            }
93
        }
94
95 757
        foreach ($diff->removedTables as $tableName => $table) {
96 135
            if (! isset($foreignKeysToTable[$tableName])) {
97 81
                continue;
98
            }
99
100 54
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
101
102
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
103
            // and the removedForeignKeys from changedTables
104 54
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
105
                // strtolower the table name to make if compatible with getShortestName
106 54
                $localTableName = strtolower($foreignKey->getLocalTableName());
107 54
                if (! isset($diff->changedTables[$localTableName])) {
108
                    continue;
109
                }
110
111 54
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
112 54
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
113
114
                    // We check if the key is from the removed table if not we skip.
115 54
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
116 27
                        continue;
117
                    }
118 54
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
119
                }
120
            }
121
        }
122
123 757
        foreach ($toSchema->getSequences() as $sequence) {
124 108
            $sequenceName = $sequence->getShortestName($toSchema->getName());
125 108
            if (! $fromSchema->hasSequence($sequenceName)) {
126 81
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
127 81
                    $diff->newSequences[] = $sequence;
128
                }
129
            } else {
130 54
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
131 33
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
132
                }
133
            }
134
        }
135
136 757
        foreach ($fromSchema->getSequences() as $sequence) {
137 108
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
138 27
                continue;
139
            }
140
141 81
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
142
143 81
            if ($toSchema->hasSequence($sequenceName)) {
144 54
                continue;
145
            }
146
147 54
            $diff->removedSequences[] = $sequence;
148
        }
149
150 757
        return $diff;
151
    }
152
153
    /**
154
     * @param Schema   $schema
155
     * @param Sequence $sequence
156
     *
157
     * @return bool
158
     */
159 162
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
160
    {
161 162
        foreach ($schema->getTables() as $table) {
162 54
            if ($sequence->isAutoIncrementsFor($table)) {
163 54
                return true;
164
            }
165
        }
166
167 108
        return false;
168
    }
169
170
    /**
171
     * @return bool
172
     */
173 92
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
174
    {
175 92
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
176 54
            return true;
177
        }
178
179 65
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
180
    }
181
182
    /**
183
     * Returns the difference between the tables $table1 and $table2.
184
     *
185
     * If there are no differences this method returns the boolean false.
186
     *
187
     * @return TableDiff|false
188
     */
189 3743
    public function diffTable(Table $table1, Table $table2)
190
    {
191 3743
        $changes                     = 0;
192 3743
        $tableDifferences            = new TableDiff($table1->getName());
193 3743
        $tableDifferences->fromTable = $table1;
194
195 3743
        $table1Columns = $table1->getColumns();
196 3743
        $table2Columns = $table2->getColumns();
197
198
        /* See if all the fields in table 1 exist in table 2 */
199 3743
        foreach ($table2Columns as $columnName => $column) {
200 3608
            if ($table1->hasColumn($columnName)) {
201 3041
                continue;
202
            }
203
204 850
            $tableDifferences->addedColumns[$columnName] = $column;
205 850
            $changes++;
206
        }
207
        /* See if there are any removed fields in table 2 */
208 3743
        foreach ($table1Columns as $columnName => $column) {
209
            // See if column is removed in table 2.
210 3608
            if (! $table2->hasColumn($columnName)) {
211 836
                $tableDifferences->removedColumns[$columnName] = $column;
212 836
                $changes++;
213 836
                continue;
214
            }
215
216
            // See if column has changed properties in table 2.
217 3041
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
218
219 3041
            if (empty($changedProperties)) {
220 2057
                continue;
221
            }
222
223 1310
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
224 1310
            $columnDiff->fromColumn                               = $column;
225 1310
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
226 1310
            $changes++;
227
        }
228
229 3743
        $this->detectColumnRenamings($tableDifferences);
230
231 3743
        $table1Indexes = $table1->getIndexes();
232 3743
        $table2Indexes = $table2->getIndexes();
233
234
        /* See if all the indexes in table 1 exist in table 2 */
235 3743
        foreach ($table2Indexes as $indexName => $index) {
236 1323
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
237 837
                continue;
238
            }
239
240 486
            $tableDifferences->addedIndexes[$indexName] = $index;
241 486
            $changes++;
242
        }
243
        /* See if there are any removed indexes in table 2 */
244 3743
        foreach ($table1Indexes as $indexName => $index) {
245
            // See if index is removed in table 2.
246 1242
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
247 1242
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
248
            ) {
249 540
                $tableDifferences->removedIndexes[$indexName] = $index;
250 540
                $changes++;
251 540
                continue;
252
            }
253
254
            // See if index has changed in table 2.
255 837
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
256
257 837
            if (! $this->diffIndex($index, $table2Index)) {
0 ignored issues
show
Bug introduced by
It seems like $table2Index can also be of type null; however, parameter $index2 of Doctrine\DBAL\Schema\Comparator::diffIndex() does only seem to accept Doctrine\DBAL\Schema\Index, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

257
            if (! $this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
258 432
                continue;
259
            }
260
261 445
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
262 445
            $changes++;
263
        }
264
265 3743
        $this->detectIndexRenamings($tableDifferences);
266
267 3743
        $fromFkeys = $table1->getForeignKeys();
268 3743
        $toFkeys   = $table2->getForeignKeys();
269
270 3743
        foreach ($fromFkeys as $key1 => $constraint1) {
271 356
            foreach ($toFkeys as $key2 => $constraint2) {
272 167
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
273 60
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
274
                } else {
275 107
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
276 54
                        $tableDifferences->changedForeignKeys[] = $constraint2;
277 54
                        $changes++;
278 76
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
279
                    }
280
                }
281
            }
282
        }
283
284 3743
        foreach ($fromFkeys as $constraint1) {
285 242
            $tableDifferences->removedForeignKeys[] = $constraint1;
286 242
            $changes++;
287
        }
288
289 3743
        foreach ($toFkeys as $constraint2) {
290 80
            $tableDifferences->addedForeignKeys[] = $constraint2;
291 80
            $changes++;
292
        }
293
294 3743
        return $changes ? $tableDifferences : false;
295
    }
296
297
    /**
298
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
299
     * however ambiguities between different possibilities should not lead to renaming at all.
300
     *
301
     * @return void
302
     */
303 3743
    private function detectColumnRenamings(TableDiff $tableDifferences)
304
    {
305 3743
        $renameCandidates = [];
306 3743
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
307 850
            foreach ($tableDifferences->removedColumns as $removedColumn) {
308 647
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
309 513
                    continue;
310
                }
311
312 661
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
313
            }
314
        }
315
316 3743
        foreach ($renameCandidates as $candidateColumns) {
317 647
            if (count($candidateColumns) !== 1) {
318 27
                continue;
319
            }
320
321 620
            [$removedColumn, $addedColumn] = $candidateColumns[0];
322 620
            $removedColumnName             = strtolower($removedColumn->getName());
323 620
            $addedColumnName               = strtolower($addedColumn->getName());
324
325 620
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
326 27
                continue;
327
            }
328
329 620
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
330
            unset(
331 620
                $tableDifferences->addedColumns[$addedColumnName],
332 620
                $tableDifferences->removedColumns[$removedColumnName]
333
            );
334
        }
335 3743
    }
336
337
    /**
338
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
339
     * however ambiguities between different possibilities should not lead to renaming at all.
340
     *
341
     * @return void
342
     */
343 3743
    private function detectIndexRenamings(TableDiff $tableDifferences)
344
    {
345 3743
        $renameCandidates = [];
346
347
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
348 3743
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
349 486
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
350 229
                if ($this->diffIndex($addedIndex, $removedIndex)) {
351 122
                    continue;
352
                }
353
354 133
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
355
            }
356
        }
357
358 3743
        foreach ($renameCandidates as $candidateIndexes) {
359
            // If the current rename candidate contains exactly one semantically equal index,
360
            // we can safely rename it.
361
            // Otherwise it is unclear if a rename action is really intended,
362
            // therefore we let those ambiguous indexes be added/dropped.
363 107
            if (count($candidateIndexes) !== 1) {
364 27
                continue;
365
            }
366
367 80
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
368
369 80
            $removedIndexName = strtolower($removedIndex->getName());
370 80
            $addedIndexName   = strtolower($addedIndex->getName());
371
372 80
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
373
                continue;
374
            }
375
376 80
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
377
            unset(
378 80
                $tableDifferences->addedIndexes[$addedIndexName],
379 80
                $tableDifferences->removedIndexes[$removedIndexName]
380
            );
381
        }
382 3743
    }
383
384
    /**
385
     * @return bool
386
     */
387 248
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
388
    {
389 248
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
390 53
            return true;
391
        }
392
393 195
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
394
            return true;
395
        }
396
397 195
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
398 27
            return true;
399
        }
400
401 168
        if ($key1->onUpdate() !== $key2->onUpdate()) {
402 27
            return true;
403
        }
404
405 141
        return $key1->onDelete() !== $key2->onDelete();
406
    }
407
408
    /**
409
     * Returns the difference between the fields $field1 and $field2.
410
     *
411
     * If there are differences this method returns $field2, otherwise the
412
     * boolean false.
413
     *
414
     * @return string[]
415
     */
416 4202
    public function diffColumn(Column $column1, Column $column2)
417
    {
418 4202
        $properties1 = $column1->toArray();
419 4202
        $properties2 = $column2->toArray();
420
421 4202
        $changedProperties = [];
422
423 4202
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
424 4202
            if ($properties1[$property] === $properties2[$property]) {
425 4202
                continue;
426
            }
427
428 489
            $changedProperties[] = $property;
429
        }
430
431
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
432 4202
        if ($this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\Schema\Com...ALegacyJsonComparison() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

432
        if (/** @scrutinizer ignore-deprecated */ $this->isALegacyJsonComparison($properties1['type'], $properties2['type'])) {
Loading history...
433 49
            array_shift($changedProperties);
434
435 49
            $changedProperties[] = 'comment';
436
        }
437
438
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
439
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
440 4202
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
441 4202
            || $properties1['default'] != $properties2['default']) {
442 118
            $changedProperties[] = 'default';
443
        }
444
445 4202
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
446 4202
            $properties1['type'] instanceof Types\BinaryType
447
        ) {
448
            // check if value of length is set at all, default value assumed otherwise.
449 866
            $length1 = $properties1['length'] ?: 255;
450 866
            $length2 = $properties2['length'] ?: 255;
451 866
            if ($length1 !== $length2) {
452 407
                $changedProperties[] = 'length';
453
            }
454
455 866
            if ($properties1['fixed'] !== $properties2['fixed']) {
456 866
                $changedProperties[] = 'fixed';
457
            }
458 3702
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
459 52
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
460
                $changedProperties[] = 'precision';
461
            }
462 52
            if ($properties1['scale'] !== $properties2['scale']) {
463
                $changedProperties[] = 'scale';
464
            }
465
        }
466
467
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
468 4202
        if ($properties1['comment'] !== $properties2['comment'] &&
469 4202
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
470 4202
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
471
        ) {
472 1269
            $changedProperties[] = 'comment';
473
        }
474
475 4202
        $customOptions1 = $column1->getCustomSchemaOptions();
476 4202
        $customOptions2 = $column2->getCustomSchemaOptions();
477
478 4202
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
479 54
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
480 27
                $changedProperties[] = $key;
481 54
            } elseif ($properties1[$key] !== $properties2[$key]) {
482 4
                $changedProperties[] = $key;
483
            }
484
        }
485
486 4202
        $platformOptions1 = $column1->getPlatformOptions();
487 4202
        $platformOptions2 = $column2->getPlatformOptions();
488
489 4202
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
490 96
            if ($properties1[$key] === $properties2[$key]) {
491 68
                continue;
492
            }
493
494 55
            $changedProperties[] = $key;
495
        }
496
497 4202
        return array_unique($changedProperties);
498
    }
499
500
    /**
501
     * TODO: kill with fire on v3.0
502
     *
503
     * @deprecated
504
     */
505 4202
    private function isALegacyJsonComparison(Types\Type $one, Types\Type $other) : bool
506
    {
507 4202
        if (! $one instanceof Types\JsonType || ! $other instanceof Types\JsonType) {
508 4115
            return false;
509
        }
510
511 87
        return ( ! $one instanceof Types\JsonArrayType && $other instanceof Types\JsonArrayType)
512 87
            || ( ! $other instanceof Types\JsonArrayType && $one instanceof Types\JsonArrayType);
513
    }
514
515
    /**
516
     * Finds the difference between the indexes $index1 and $index2.
517
     *
518
     * Compares $index1 with $index2 and returns $index2 if there are any
519
     * differences or false in case there are no differences.
520
     *
521
     * @return bool
522
     */
523 1066
    public function diffIndex(Index $index1, Index $index2)
524
    {
525 1066
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
526
    }
527
}
528