Completed
Pull Request — master (#3588)
by Andrej
19:46
created

Comparator   F

Complexity

Total Complexity 112

Size/Duplication

Total Lines 511
Duplicated Lines 0 %

Test Coverage

Coverage 97.84%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 112
eloc 224
c 1
b 0
f 0
dl 0
loc 511
ccs 227
cts 232
cp 0.9784
rs 2

11 Methods

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

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