Completed
Pull Request — develop (#3515)
by Sergei
20:18
created

Comparator   F

Complexity

Total Complexity 111

Size/Duplication

Total Lines 507
Duplicated Lines 0 %

Test Coverage

Coverage 97.83%

Importance

Changes 0
Metric Value
wmc 111
eloc 222
dl 0
loc 507
ccs 225
cts 230
cp 0.9783
rs 2
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A diffSequence() 0 7 2
B detectIndexRenamings() 0 37 7
F diffColumn() 0 82 29
F diffTable() 0 107 24
F compare() 0 110 25
A isAutoIncrementSequenceInSchema() 0 9 3
A compareSchemas() 0 5 1
A diffForeignKey() 0 19 5
A isALegacyJsonComparison() 0 8 6
A diffIndex() 0 3 2
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
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\Types;
8
use function array_intersect_key;
9
use function array_key_exists;
10
use function array_keys;
11
use function array_map;
12
use function array_merge;
13
use function array_shift;
14
use function array_unique;
15
use function assert;
16
use function count;
17
use function strtolower;
18
19
/**
20
 * Compares two Schemas and return an instance of SchemaDiff.
21
 */
22
class Comparator
23
{
24
    /**
25
     * @return SchemaDiff
26
     */
27 1529
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
28
    {
29 1529
        $c = new self();
30
31 1529
        return $c->compare($fromSchema, $toSchema);
32
    }
33
34
    /**
35
     * Returns a SchemaDiff object containing the differences between the schemas $fromSchema and $toSchema.
36
     *
37
     * The returned differences are returned in such a way that they contain the
38
     * operations to change the schema stored in $fromSchema to the schema that is
39
     * stored in $toSchema.
40
     *
41
     * @return SchemaDiff
42
     */
43 2744
    public function compare(Schema $fromSchema, Schema $toSchema)
44
    {
45 2744
        $diff             = new SchemaDiff();
46 2744
        $diff->fromSchema = $fromSchema;
47
48 2744
        $foreignKeysToTable = [];
49
50 2744
        foreach ($toSchema->getNamespaces() as $namespace) {
51 650
            if ($fromSchema->hasNamespace($namespace)) {
52 650
                continue;
53
            }
54
55 650
            $diff->newNamespaces[$namespace] = $namespace;
56
        }
57
58 2744
        foreach ($fromSchema->getNamespaces() as $namespace) {
59 650
            if ($toSchema->hasNamespace($namespace)) {
60 650
                continue;
61
            }
62
63 385
            $diff->removedNamespaces[$namespace] = $namespace;
64
        }
65
66 2744
        foreach ($toSchema->getTables() as $table) {
67 2738
            $tableName = $table->getShortestName($toSchema->getName());
68 2738
            if (! $fromSchema->hasTable($tableName)) {
69 1445
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
70
            } else {
71 2736
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
72 2736
                if ($tableDifferences !== false) {
73 2688
                    $diff->changedTables[$tableName] = $tableDifferences;
74
                }
75
            }
76
        }
77
78
        /* Check if there are tables removed */
79 2744
        foreach ($fromSchema->getTables() as $table) {
80 2737
            $tableName = $table->getShortestName($fromSchema->getName());
81
82 2737
            $table = $fromSchema->getTable($tableName);
83 2737
            if (! $toSchema->hasTable($tableName)) {
84 1469
                $diff->removedTables[$tableName] = $table;
85
            }
86
87
            // also remember all foreign keys that point to a specific table
88 2737
            foreach ($table->getForeignKeys() as $foreignKey) {
89 530
                $foreignTable = strtolower($foreignKey->getForeignTableName());
90 530
                if (! isset($foreignKeysToTable[$foreignTable])) {
91 530
                    $foreignKeysToTable[$foreignTable] = [];
92
                }
93 548
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
94
            }
95
        }
96
97 2744
        foreach ($diff->removedTables as $tableName => $table) {
98 1469
            if (! isset($foreignKeysToTable[$tableName])) {
99 1467
                continue;
100
            }
101
102 530
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
103
104
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
105
            // and the removedForeignKeys from changedTables
106 530
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
107
                // strtolower the table name to make if compatible with getShortestName
108 530
                $localTableName = strtolower($foreignKey->getLocalTableName());
109 530
                if (! isset($diff->changedTables[$localTableName])) {
110
                    continue;
111
                }
112
113 530
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
114 530
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
115
116
                    // We check if the key is from the removed table if not we skip.
117 530
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
118 529
                        continue;
119
                    }
120 530
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
121
                }
122
            }
123
        }
124
125 2744
        foreach ($toSchema->getSequences() as $sequence) {
126 1132
            $sequenceName = $sequence->getShortestName($toSchema->getName());
127 1132
            if (! $fromSchema->hasSequence($sequenceName)) {
128 1131
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
129 1131
                    $diff->newSequences[] = $sequence;
130
                }
131
            } else {
132 986
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
133 724
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
134
                }
135
            }
136
        }
137
138 2744
        foreach ($fromSchema->getSequences() as $sequence) {
139 1156
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
140 577
                continue;
141
            }
142
143 1155
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
144
145 1155
            if ($toSchema->hasSequence($sequenceName)) {
146 986
                continue;
147
            }
148
149 1154
            $diff->removedSequences[] = $sequence;
150
        }
151
152 2744
        return $diff;
153
    }
154
155
    /**
156
     * @param Schema   $schema
157
     * @param Sequence $sequence
158
     *
159
     * @return bool
160
     */
161 1158
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
162
    {
163 1158
        foreach ($schema->getTables() as $table) {
164 578
            if ($sequence->isAutoIncrementsFor($table)) {
165 578
                return true;
166
            }
167
        }
168
169 1156
        return false;
170
    }
171
172
    /**
173
     * @return bool
174
     */
175 1786
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
176
    {
177 1786
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
178 1178
            return true;
179
        }
180
181 1785
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
182
    }
183
184
    /**
185
     * Returns the difference between the tables $table1 and $table2.
186
     *
187
     * If there are no differences this method returns the boolean false.
188
     *
189
     * @return TableDiff|false
190
     */
191 3665
    public function diffTable(Table $table1, Table $table2)
192
    {
193 3665
        $changes                     = 0;
194 3665
        $tableDifferences            = new TableDiff($table1->getName());
195 3665
        $tableDifferences->fromTable = $table1;
196
197 3665
        $table1Columns = $table1->getColumns();
198 3665
        $table2Columns = $table2->getColumns();
199
200
        /* See if all the fields in table 1 exist in table 2 */
201 3665
        foreach ($table2Columns as $columnName => $column) {
202 3660
            if ($table1->hasColumn($columnName)) {
203 3645
                continue;
204
            }
205
206 3489
            $tableDifferences->addedColumns[$columnName] = $column;
207 3489
            $changes++;
208
        }
209
        /* See if there are any removed fields in table 2 */
210 3665
        foreach ($table1Columns as $columnName => $column) {
211
            // See if column is removed in table 2.
212 3660
            if (! $table2->hasColumn($columnName)) {
213 3305
                $tableDifferences->removedColumns[$columnName] = $column;
214 3305
                $changes++;
215 3305
                continue;
216
            }
217
218
            // See if column has changed properties in table 2.
219 3645
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
220
221 3645
            if (empty($changedProperties)) {
222 3621
                continue;
223
            }
224
225 3462
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
226 3462
            $columnDiff->fromColumn                               = $column;
227 3462
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
228 3462
            $changes++;
229
        }
230
231 3665
        $this->detectColumnRenamings($tableDifferences);
232
233 3665
        $table1Indexes = $table1->getIndexes();
234 3665
        $table2Indexes = $table2->getIndexes();
235
236
        /* See if all the indexes in table 1 exist in table 2 */
237 3665
        foreach ($table2Indexes as $indexName => $index) {
238 3560
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
239 3543
                continue;
240
            }
241
242 3429
            $tableDifferences->addedIndexes[$indexName] = $index;
243 3429
            $changes++;
244
        }
245
        /* See if there are any removed indexes in table 2 */
246 3665
        foreach ($table1Indexes as $indexName => $index) {
247
            // See if index is removed in table 2.
248 3557
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
249 3557
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
250
            ) {
251 3400
                $tableDifferences->removedIndexes[$indexName] = $index;
252 3400
                $changes++;
253 3400
                continue;
254
            }
255
256
            // See if index has changed in table 2.
257 3543
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
258 3543
            assert($table2Index instanceof Index);
259
260 3543
            if (! $this->diffIndex($index, $table2Index)) {
261 3528
                continue;
262
            }
263
264 3477
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
265 3477
            $changes++;
266
        }
267
268 3665
        $this->detectIndexRenamings($tableDifferences);
269
270 3665
        $fromFkeys = $table1->getForeignKeys();
271 3665
        $toFkeys   = $table2->getForeignKeys();
272
273 3665
        foreach ($fromFkeys as $key1 => $constraint1) {
274 3287
            foreach ($toFkeys as $key2 => $constraint2) {
275 3239
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
276 3212
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
277
                } else {
278 3207
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
279 1058
                        $tableDifferences->changedForeignKeys[] = $constraint2;
280 1058
                        $changes++;
281 1067
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
282
                    }
283
                }
284
            }
285
        }
286
287 3665
        foreach ($fromFkeys as $constraint1) {
288 3253
            $tableDifferences->removedForeignKeys[] = $constraint1;
289 3253
            $changes++;
290
        }
291
292 3665
        foreach ($toFkeys as $constraint2) {
293 3208
            $tableDifferences->addedForeignKeys[] = $constraint2;
294 3208
            $changes++;
295
        }
296
297 3665
        return $changes ? $tableDifferences : false;
298
    }
299
300
    /**
301
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
302
     * however ambiguities between different possibilities should not lead to renaming at all.
303
     *
304
     * @return void
305
     */
306 3665
    private function detectColumnRenamings(TableDiff $tableDifferences)
307
    {
308 3665
        $renameCandidates = [];
309 3665
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
310 3489
            foreach ($tableDifferences->removedColumns as $removedColumn) {
311 3300
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
312 2965
                    continue;
313
                }
314
315 3307
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
316
            }
317
        }
318
319 3665
        foreach ($renameCandidates as $candidateColumns) {
320 3300
            if (count($candidateColumns) !== 1) {
321 817
                continue;
322
            }
323
324 3299
            [$removedColumn, $addedColumn] = $candidateColumns[0];
325 3299
            $removedColumnName             = strtolower($removedColumn->getName());
326 3299
            $addedColumnName               = strtolower($addedColumn->getName());
327
328 3299
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
329 1297
                continue;
330
            }
331
332 3299
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
333
            unset(
334 3299
                $tableDifferences->addedColumns[$addedColumnName],
335 3299
                $tableDifferences->removedColumns[$removedColumnName]
336
            );
337
        }
338 3665
    }
339
340
    /**
341
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
342
     * however ambiguities between different possibilities should not lead to renaming at all.
343
     *
344
     * @return void
345
     */
346 3665
    private function detectIndexRenamings(TableDiff $tableDifferences)
347
    {
348 3665
        $renameCandidates = [];
349
350
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
351 3665
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
352 3429
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
353 3391
                if ($this->diffIndex($addedIndex, $removedIndex)) {
354 3231
                    continue;
355
                }
356
357 3192
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
358
            }
359
        }
360
361 3665
        foreach ($renameCandidates as $candidateIndexes) {
362
            // If the current rename candidate contains exactly one semantically equal index,
363
            // we can safely rename it.
364
            // Otherwise it is unclear if a rename action is really intended,
365
            // therefore we let those ambiguous indexes be added/dropped.
366 3179
            if (count($candidateIndexes) !== 1) {
367 769
                continue;
368
            }
369
370 3178
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
371
372 3178
            $removedIndexName = strtolower($removedIndex->getName());
373 3178
            $addedIndexName   = strtolower($addedIndex->getName());
374
375 3178
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
376
                continue;
377
            }
378
379 3178
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
380
            unset(
381 3178
                $tableDifferences->addedIndexes[$addedIndexName],
382 3178
                $tableDifferences->removedIndexes[$removedIndexName]
383
            );
384
        }
385 3665
    }
386
387
    /**
388
     * @return bool
389
     */
390 3242
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
391
    {
392 3242
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
393 3165
            return true;
394
        }
395
396 3223
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
397
            return true;
398
        }
399
400 3223
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
401 1033
            return true;
402
        }
403
404 3222
        if ($key1->onUpdate() !== $key2->onUpdate()) {
405 1057
            return true;
406
        }
407
408 3215
        return $key1->onDelete() !== $key2->onDelete();
409
    }
410
411
    /**
412
     * Returns the difference between the fields $field1 and $field2.
413
     *
414
     * If there are differences this method returns $field2, otherwise the
415
     * boolean false.
416
     *
417
     * @return string[]
418
     */
419 3682
    public function diffColumn(Column $column1, Column $column2)
420
    {
421 3682
        $properties1 = $column1->toArray();
422 3682
        $properties2 = $column2->toArray();
423
424 3682
        $changedProperties = [];
425
426 3682
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
427 3682
            if ($properties1[$property] === $properties2[$property]) {
428 3682
                continue;
429
            }
430
431 3163
            $changedProperties[] = $property;
432
        }
433
434
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
435 3682
        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

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