Passed
Pull Request — master (#3233)
by Sergey
12:25
created

Comparator::compare()   F

Complexity

Conditions 30
Paths > 20000

Size

Total Lines 126
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 66
CRAP Score 30.0029

Importance

Changes 0
Metric Value
eloc 68
dl 0
loc 126
rs 0
c 0
b 0
f 0
ccs 66
cts 67
cp 0.9851
cc 30
nc 302400
nop 2
crap 30.0029

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

272
            if (! $this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
273 297
                continue;
274
            }
275
276 303
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
277 303
            $changes++;
278
        }
279
280 2564
        $this->detectIndexRenamings($tableDifferences);
281
282 2564
        $fromFkeys = $table1->getForeignKeys();
283 2564
        $toFkeys   = $table2->getForeignKeys();
284
285 2564
        foreach ($fromFkeys as $key1 => $constraint1) {
286 251
            foreach ($toFkeys as $key2 => $constraint2) {
287 118
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
288 43
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
289
                } else {
290 75
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
291 38
                        $tableDifferences->changedForeignKeys[] = $constraint2;
292 38
                        $changes++;
293 251
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
294
                    }
295
                }
296
            }
297
        }
298
299 2564
        foreach ($fromFkeys as $constraint1) {
300 170
            $tableDifferences->removedForeignKeys[] = $constraint1;
301 170
            $changes++;
302
        }
303
304 2564
        foreach ($toFkeys as $constraint2) {
305 56
            $tableDifferences->addedForeignKeys[] = $constraint2;
306 56
            $changes++;
307
        }
308
309 2564
        return $changes ? $tableDifferences : false;
310
    }
311
312
    /**
313
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
314
     * however ambiguities between different possibilities should not lead to renaming at all.
315
     *
316
     * @return void
317
     */
318 2564
    private function detectColumnRenamings(TableDiff $tableDifferences)
319
    {
320 2564
        $renameCandidates = [];
321 2564
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
322 588
            foreach ($tableDifferences->removedColumns as $removedColumn) {
323 455
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
324 361
                    continue;
325
                }
326
327 588
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
328
            }
329
        }
330
331 2564
        foreach ($renameCandidates as $candidateColumns) {
332 455
            if (count($candidateColumns) !== 1) {
333 19
                continue;
334
            }
335
336 436
            [$removedColumn, $addedColumn] = $candidateColumns[0];
337 436
            $removedColumnName             = strtolower($removedColumn->getName());
338 436
            $addedColumnName               = strtolower($addedColumn->getName());
339
340 436
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
341 19
                continue;
342
            }
343
344 436
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
345
            unset(
346 436
                $tableDifferences->addedColumns[$addedColumnName],
347 436
                $tableDifferences->removedColumns[$removedColumnName]
348
            );
349
        }
350 2564
    }
351
352
    /**
353
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
354
     * however ambiguities between different possibilities should not lead to renaming at all.
355
     *
356
     * @return void
357
     */
358 2564
    private function detectIndexRenamings(TableDiff $tableDifferences)
359
    {
360 2564
        $renameCandidates = [];
361
362
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
363 2564
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
364 338
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
365 159
                if ($this->diffIndex($addedIndex, $removedIndex)) {
366 84
                    continue;
367
                }
368
369 338
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
370
            }
371
        }
372
373 2564
        foreach ($renameCandidates as $candidateIndexes) {
374
            // If the current rename candidate contains exactly one semantically equal index,
375
            // we can safely rename it.
376
            // Otherwise it is unclear if a rename action is really intended,
377
            // therefore we let those ambiguous indexes be added/dropped.
378 75
            if (count($candidateIndexes) !== 1) {
379 19
                continue;
380
            }
381
382 56
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
383
384 56
            $removedIndexName = strtolower($removedIndex->getName());
385 56
            $addedIndexName   = strtolower($addedIndex->getName());
386
387 56
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
388
                continue;
389
            }
390
391 56
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
392
            unset(
393 56
                $tableDifferences->addedIndexes[$addedIndexName],
394 56
                $tableDifferences->removedIndexes[$removedIndexName]
395
            );
396
        }
397 2564
    }
398
399
    /**
400
     * @return bool
401
     */
402 175
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
403
    {
404 175
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
405 37
            return true;
406
        }
407
408 138
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
409
            return true;
410
        }
411
412 138
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
413 19
            return true;
414
        }
415
416 119
        if ($key1->onUpdate() !== $key2->onUpdate()) {
417 19
            return true;
418
        }
419
420 100
        return $key1->onDelete() !== $key2->onDelete();
421
    }
422
423
    /**
424
     * Returns the difference between the fields $field1 and $field2.
425
     *
426
     * If there are differences this method returns $field2, otherwise the
427
     * boolean false.
428
     *
429
     * @return string[]
430
     */
431 2887
    public function diffColumn(Column $column1, Column $column2)
432
    {
433 2887
        $properties1 = $column1->toArray();
434 2887
        $properties2 = $column2->toArray();
435
436 2887
        $changedProperties = [];
437
438 2887
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
439 2887
            if ($properties1[$property] === $properties2[$property]) {
440 2887
                continue;
441
            }
442
443 350
            $changedProperties[] = $property;
444
        }
445
446
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
447 2887
        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

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