Failed Conditions
Pull Request — develop (#3348)
by Sergei
10:40
created

Comparator::compare()   F

Complexity

Conditions 25
Paths > 20000

Size

Total Lines 110
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 25.0033

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 110
ccs 56
cts 57
cp 0.9825
rs 0
c 0
b 0
f 0
cc 25
nc 25200
nop 2
crap 25.0033

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 strcasecmp;
18
use function strtolower;
19
20
/**
21
 * Compares two Schemas and return an instance of SchemaDiff.
22
 */
23
class Comparator
24
{
25 1655
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
26
    {
27 1655
        $c = new self();
28
29 1655
        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 2867
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
40
    {
41 2867
        $diff             = new SchemaDiff();
42 2867
        $diff->fromSchema = $fromSchema;
43
44 2867
        $foreignKeysToTable = [];
45
46 2867
        foreach ($toSchema->getNamespaces() as $namespace) {
47 704
            if ($fromSchema->hasNamespace($namespace)) {
48 704
                continue;
49
            }
50
51 704
            $diff->newNamespaces[$namespace] = $namespace;
52
        }
53
54 2867
        foreach ($fromSchema->getNamespaces() as $namespace) {
55 704
            if ($toSchema->hasNamespace($namespace)) {
56 704
                continue;
57
            }
58
59 417
            $diff->removedNamespaces[$namespace] = $namespace;
60
        }
61
62 2867
        foreach ($toSchema->getTables() as $table) {
63 2861
            $tableName = $table->getShortestName($toSchema->getName());
64 2861
            if (! $fromSchema->hasTable($tableName)) {
65 1565
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
66
            } else {
67 2859
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
68 2859
                if ($tableDifferences !== false) {
69 2801
                    $diff->changedTables[$tableName] = $tableDifferences;
70
                }
71
            }
72
        }
73
74
        /* Check if there are tables removed */
75 2867
        foreach ($fromSchema->getTables() as $table) {
76 2860
            $tableName = $table->getShortestName($fromSchema->getName());
77
78 2860
            $table = $fromSchema->getTable($tableName);
79 2860
            if (! $toSchema->hasTable($tableName)) {
80 1591
                $diff->removedTables[$tableName] = $table;
81
            }
82
83
            // also remember all foreign keys that point to a specific table
84 2860
            foreach ($table->getForeignKeys() as $foreignKey) {
85 574
                $foreignTable = strtolower($foreignKey->getForeignTableName());
86 574
                if (! isset($foreignKeysToTable[$foreignTable])) {
87 574
                    $foreignKeysToTable[$foreignTable] = [];
88
                }
89 592
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
90
            }
91
        }
92
93 2867
        foreach ($diff->removedTables as $tableName => $table) {
94 1591
            if (! isset($foreignKeysToTable[$tableName])) {
95 1589
                continue;
96
            }
97
98 574
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
99
100
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
101
            // and the removedForeignKeys from changedTables
102 574
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
103
                // strtolower the table name to make if compatible with getShortestName
104 574
                $localTableName = strtolower($foreignKey->getLocalTableName());
105 574
                if (! isset($diff->changedTables[$localTableName])) {
106
                    continue;
107
                }
108
109 574
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
110 574
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
111
112
                    // We check if the key is from the removed table if not we skip.
113 574
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
114 573
                        continue;
115
                    }
116 574
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
117
                }
118
            }
119
        }
120
121 2867
        foreach ($toSchema->getSequences() as $sequence) {
122 1226
            $sequenceName = $sequence->getShortestName($toSchema->getName());
123 1226
            if (! $fromSchema->hasSequence($sequenceName)) {
124 1225
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
125 1225
                    $diff->newSequences[] = $sequence;
126
                }
127
            } else {
128 1068
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
129 784
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
130
                }
131
            }
132
        }
133
134 2867
        foreach ($fromSchema->getSequences() as $sequence) {
135 1252
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
136 625
                continue;
137
            }
138
139 1251
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
140
141 1251
            if ($toSchema->hasSequence($sequenceName)) {
142 1068
                continue;
143
            }
144
145 1250
            $diff->removedSequences[] = $sequence;
146
        }
147
148 2867
        return $diff;
149
    }
150
151 1254
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
152
    {
153 1254
        foreach ($schema->getTables() as $table) {
154 626
            if ($sequence->isAutoIncrementsFor($table)) {
155 626
                return true;
156
            }
157
        }
158
159 1252
        return false;
160
    }
161
162 1953
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
163
    {
164 1953
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
165 1276
            return true;
166
        }
167
168 1952
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
169
    }
170
171
    /**
172
     * Returns the difference between the tables $table1 and $table2.
173
     *
174
     * If there are no differences this method returns the boolean false.
175
     *
176
     * @return TableDiff|false
177
     */
178 3798
    public function diffTable(Table $table1, Table $table2)
179
    {
180 3798
        $changes                     = 0;
181 3798
        $tableDifferences            = new TableDiff($table1->getName());
182 3798
        $tableDifferences->fromTable = $table1;
183
184 3798
        $table1Columns = $table1->getColumns();
185 3798
        $table2Columns = $table2->getColumns();
186
187
        /* See if all the fields in table 1 exist in table 2 */
188 3798
        foreach ($table2Columns as $columnName => $column) {
189 3793
            if ($table1->hasColumn($columnName)) {
190 3777
                continue;
191
            }
192
193 3635
            $tableDifferences->addedColumns[$columnName] = $column;
194 3635
            $changes++;
195
        }
196
        /* See if there are any removed fields in table 2 */
197 3798
        foreach ($table1Columns as $columnName => $column) {
198
            // See if column is removed in table 2.
199 3793
            if (! $table2->hasColumn($columnName)) {
200 3451
                $tableDifferences->removedColumns[$columnName] = $column;
201 3451
                $changes++;
202 3451
                continue;
203
            }
204
205
            // See if column has changed properties in table 2.
206 3777
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
207
208 3777
            if (empty($changedProperties)) {
209 3753
                continue;
210
            }
211
212 3583
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
213 3583
            $columnDiff->fromColumn                               = $column;
214 3583
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
215 3583
            $changes++;
216
        }
217
218 3798
        $this->detectColumnRenamings($tableDifferences);
219
220 3798
        $table1Indexes = $table1->getIndexes();
221 3798
        $table2Indexes = $table2->getIndexes();
222
223
        /* See if all the indexes in table 1 exist in table 2 */
224 3798
        foreach ($table2Indexes as $indexName => $index) {
225 3673
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
226 3654
                continue;
227
            }
228
229 3580
            $tableDifferences->addedIndexes[$indexName] = $index;
230 3580
            $changes++;
231
        }
232
        /* See if there are any removed indexes in table 2 */
233 3798
        foreach ($table1Indexes as $indexName => $index) {
234
            // See if index is removed in table 2.
235 3669
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
236 3669
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
237
            ) {
238 3550
                $tableDifferences->removedIndexes[$indexName] = $index;
239 3550
                $changes++;
240 3550
                continue;
241
            }
242
243
            // See if index has changed in table 2.
244 3654
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
245 3654
            assert($table2Index instanceof Index);
246
247 3654
            if (! $this->diffIndex($index, $table2Index)) {
248 3606
                continue;
249
            }
250
251 3620
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
252 3620
            $changes++;
253
        }
254
255 3798
        $this->detectIndexRenamings($tableDifferences);
256
257 3798
        $fromFkeys = $table1->getForeignKeys();
258 3798
        $toFkeys   = $table2->getForeignKeys();
259
260 3798
        foreach ($fromFkeys as $key1 => $constraint1) {
261 3367
            foreach ($toFkeys as $key2 => $constraint2) {
262 3276
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
263 3243
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
264
                } else {
265 3274
                    $name1 = $constraint1->getName();
266 3274
                    $name2 = $constraint2->getName();
267
268 3274
                    if ($name1 !== null && $name2 !== null && strcasecmp($name1, $name2) === 0) {
269 1146
                        $tableDifferences->changedForeignKeys[] = $constraint2;
270 1146
                        $changes++;
271 1155
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
272
                    }
273
                }
274
            }
275
        }
276
277 3798
        foreach ($fromFkeys as $constraint1) {
278 3363
            $tableDifferences->removedForeignKeys[] = $constraint1;
279 3363
            $changes++;
280
        }
281
282 3798
        foreach ($toFkeys as $constraint2) {
283 3277
            $tableDifferences->addedForeignKeys[] = $constraint2;
284 3277
            $changes++;
285
        }
286
287 3798
        return $changes ? $tableDifferences : false;
288
    }
289
290
    /**
291
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
292
     * however ambiguities between different possibilities should not lead to renaming at all.
293
     */
294 3798
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
295
    {
296 3798
        $renameCandidates = [];
297 3798
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
298 3635
            foreach ($tableDifferences->removedColumns as $removedColumn) {
299 3446
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
300 3211
                    continue;
301
                }
302
303 3453
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
304
            }
305
        }
306
307 3798
        foreach ($renameCandidates as $candidateColumns) {
308 3446
            if (count($candidateColumns) !== 1) {
309 885
                continue;
310
            }
311
312 3445
            [$removedColumn, $addedColumn] = $candidateColumns[0];
313 3445
            $removedColumnName             = strtolower($removedColumn->getName());
314 3445
            $addedColumnName               = strtolower($addedColumn->getName());
315
316 3445
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
317 1405
                continue;
318
            }
319
320 3445
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
321
            unset(
322 3445
                $tableDifferences->addedColumns[$addedColumnName],
323 3445
                $tableDifferences->removedColumns[$removedColumnName]
324
            );
325
        }
326 3798
    }
327
328
    /**
329
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
330
     * however ambiguities between different possibilities should not lead to renaming at all.
331
     */
332 3798
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
333
    {
334 3798
        $renameCandidates = [];
335
336
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
337 3798
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
338 3580
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
339 3541
                if ($this->diffIndex($addedIndex, $removedIndex)) {
340 3470
                    continue;
341
                }
342
343 3260
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
344
            }
345
        }
346
347 3798
        foreach ($renameCandidates as $candidateIndexes) {
348
            // If the current rename candidate contains exactly one semantically equal index,
349
            // we can safely rename it.
350
            // Otherwise it is unclear if a rename action is really intended,
351
            // therefore we let those ambiguous indexes be added/dropped.
352 3247
            if (count($candidateIndexes) !== 1) {
353 833
                continue;
354
            }
355
356 3246
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
357
358 3246
            $removedIndexName = $removedIndex->getName();
359
360 3246
            if ($removedIndexName === null) {
361
                continue;
362
            }
363
364 3246
            $addedIndexName = $addedIndex->getName();
365
366 3246
            if ($addedIndexName === null) {
367
                continue;
368
            }
369
370 3246
            $removedIndexName = strtolower($removedIndexName);
371 3246
            $addedIndexName   = strtolower($addedIndexName);
372
373 3246
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
374
                continue;
375
            }
376
377 3246
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
378
            unset(
379 3246
                $tableDifferences->addedIndexes[$addedIndexName],
380 3246
                $tableDifferences->removedIndexes[$removedIndexName]
381
            );
382
        }
383 3798
    }
384
385 3279
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
386
    {
387 3279
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
388 3192
            return true;
389
        }
390
391 3260
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
392
            return true;
393
        }
394
395 3260
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
396 1119
            return true;
397
        }
398
399 3259
        if ($key1->onUpdate() !== $key2->onUpdate()) {
400 1145
            return true;
401
        }
402
403 3246
        return $key1->onDelete() !== $key2->onDelete();
404
    }
405
406
    /**
407
     * Returns the difference between the fields $field1 and $field2.
408
     *
409
     * If there are differences this method returns $field2, otherwise the
410
     * boolean false.
411
     *
412
     * @return string[]
413
     */
414 3815
    public function diffColumn(Column $column1, Column $column2) : array
415
    {
416 3815
        $properties1 = $column1->toArray();
417 3815
        $properties2 = $column2->toArray();
418
419 3815
        $changedProperties = [];
420
421 3815
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
422 3815
            if ($properties1[$property] === $properties2[$property]) {
423 3815
                continue;
424
            }
425
426 3260
            $changedProperties[] = $property;
427
        }
428
429
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
430 3815
        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

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