Passed
Push — drop-deprecated ( db0b1f )
by Michael
27:00
created

Comparator::diffColumn()   F

Complexity

Conditions 28
Paths 1296

Size

Total Lines 75
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 28.2853

Importance

Changes 0
Metric Value
eloc 41
dl 0
loc 75
ccs 39
cts 42
cp 0.9286
rs 0
c 0
b 0
f 0
cc 28
nc 1296
nop 2
crap 28.2853

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_unique;
14
use function assert;
15
use function count;
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 1512
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema)
27
    {
28 1512
        $c = new self();
29
30 1512
        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 2692
    public function compare(Schema $fromSchema, Schema $toSchema)
43
    {
44 2692
        $diff             = new SchemaDiff();
45 2692
        $diff->fromSchema = $fromSchema;
46
47 2692
        $foreignKeysToTable = [];
48
49 2692
        foreach ($toSchema->getNamespaces() as $namespace) {
50 648
            if ($fromSchema->hasNamespace($namespace)) {
51 648
                continue;
52
            }
53
54 648
            $diff->newNamespaces[$namespace] = $namespace;
55
        }
56
57 2692
        foreach ($fromSchema->getNamespaces() as $namespace) {
58 648
            if ($toSchema->hasNamespace($namespace)) {
59 648
                continue;
60
            }
61
62 384
            $diff->removedNamespaces[$namespace] = $namespace;
63
        }
64
65 2692
        foreach ($toSchema->getTables() as $table) {
66 2692
            $tableName = $table->getShortestName($toSchema->getName());
67 2692
            if (! $fromSchema->hasTable($tableName)) {
68 1440
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
69
            } else {
70 2692
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
71 2692
                if ($tableDifferences !== false) {
72 2642
                    $diff->changedTables[$tableName] = $tableDifferences;
73
                }
74
            }
75
        }
76
77
        /* Check if there are tables removed */
78 2692
        foreach ($fromSchema->getTables() as $table) {
79 2692
            $tableName = $table->getShortestName($fromSchema->getName());
80
81 2692
            $table = $fromSchema->getTable($tableName);
82 2692
            if (! $toSchema->hasTable($tableName)) {
83 1464
                $diff->removedTables[$tableName] = $table;
84
            }
85
86
            // also remember all foreign keys that point to a specific table
87 2692
            foreach ($table->getForeignKeys() as $foreignKey) {
88 528
                $foreignTable = strtolower($foreignKey->getForeignTableName());
89 528
                if (! isset($foreignKeysToTable[$foreignTable])) {
90 528
                    $foreignKeysToTable[$foreignTable] = [];
91
                }
92 528
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
93
            }
94
        }
95
96 2692
        foreach ($diff->removedTables as $tableName => $table) {
97 1464
            if (! isset($foreignKeysToTable[$tableName])) {
98 1464
                continue;
99
            }
100
101 528
            $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 528
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
106
                // strtolower the table name to make if compatible with getShortestName
107 528
                $localTableName = strtolower($foreignKey->getLocalTableName());
108 528
                if (! isset($diff->changedTables[$localTableName])) {
109
                    continue;
110
                }
111
112 528
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
113 528
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
114
115
                    // We check if the key is from the removed table if not we skip.
116 528
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
117 528
                        continue;
118
                    }
119 528
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
120
                }
121
            }
122
        }
123
124 2692
        foreach ($toSchema->getSequences() as $sequence) {
125 1128
            $sequenceName = $sequence->getShortestName($toSchema->getName());
126 1128
            if (! $fromSchema->hasSequence($sequenceName)) {
127 1128
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
128 1128
                    $diff->newSequences[] = $sequence;
129
                }
130
            } else {
131 984
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
132 720
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
133
                }
134
            }
135
        }
136
137 2692
        foreach ($fromSchema->getSequences() as $sequence) {
138 1152
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
139 576
                continue;
140
            }
141
142 1152
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
143
144 1152
            if ($toSchema->hasSequence($sequenceName)) {
145 984
                continue;
146
            }
147
148 1152
            $diff->removedSequences[] = $sequence;
149
        }
150
151 2692
        return $diff;
152
    }
153
154
    /**
155
     * @param Schema   $schema
156
     * @param Sequence $sequence
157
     *
158
     * @return bool
159
     */
160 1152
    private function isAutoIncrementSequenceInSchema($schema, $sequence)
161
    {
162 1152
        foreach ($schema->getTables() as $table) {
163 576
            if ($sequence->isAutoIncrementsFor($table)) {
164 576
                return true;
165
            }
166
        }
167
168 1152
        return false;
169
    }
170
171
    /**
172
     * @return bool
173
     */
174 1782
    public function diffSequence(Sequence $sequence1, Sequence $sequence2)
175
    {
176 1782
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
177 1176
            return true;
178
        }
179
180 1782
        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 3498
    public function diffTable(Table $table1, Table $table2)
191
    {
192 3498
        $changes                     = 0;
193 3498
        $tableDifferences            = new TableDiff($table1->getName());
194 3498
        $tableDifferences->fromTable = $table1;
195
196 3498
        $table1Columns = $table1->getColumns();
197 3498
        $table2Columns = $table2->getColumns();
198
199
        /* See if all the fields in table 1 exist in table 2 */
200 3498
        foreach ($table2Columns as $columnName => $column) {
201 3498
            if ($table1->hasColumn($columnName)) {
202 3498
                continue;
203
            }
204
205 3411
            $tableDifferences->addedColumns[$columnName] = $column;
206 3411
            $changes++;
207
        }
208
        /* See if there are any removed fields in table 2 */
209 3498
        foreach ($table1Columns as $columnName => $column) {
210
            // See if column is removed in table 2.
211 3498
            if (! $table2->hasColumn($columnName)) {
212 3229
                $tableDifferences->removedColumns[$columnName] = $column;
213 3229
                $changes++;
214 3229
                continue;
215
            }
216
217
            // See if column has changed properties in table 2.
218 3498
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
219
220 3498
            if (empty($changedProperties)) {
221 3498
                continue;
222
            }
223
224 3371
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
225 3371
            $columnDiff->fromColumn                               = $column;
226 3371
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
227 3371
            $changes++;
228
        }
229
230 3498
        $this->detectColumnRenamings($tableDifferences);
231
232 3498
        $table1Indexes = $table1->getIndexes();
233 3498
        $table2Indexes = $table2->getIndexes();
234
235
        /* See if all the indexes in table 1 exist in table 2 */
236 3498
        foreach ($table2Indexes as $indexName => $index) {
237 3460
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
238 3460
                continue;
239
            }
240
241 3359
            $tableDifferences->addedIndexes[$indexName] = $index;
242 3359
            $changes++;
243
        }
244
        /* See if there are any removed indexes in table 2 */
245 3498
        foreach ($table1Indexes as $indexName => $index) {
246
            // See if index is removed in table 2.
247 3460
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
248 3460
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
249
            ) {
250 3330
                $tableDifferences->removedIndexes[$indexName] = $index;
251 3330
                $changes++;
252 3330
                continue;
253
            }
254
255
            // See if index has changed in table 2.
256 3460
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
257 3460
            assert($table2Index instanceof Index);
258
259 3460
            if (! $this->diffIndex($index, $table2Index)) {
260 3460
                continue;
261
            }
262
263 3408
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
264 3408
            $changes++;
265
        }
266
267 3498
        $this->detectIndexRenamings($tableDifferences);
268
269 3498
        $fromFkeys = $table1->getForeignKeys();
270 3498
        $toFkeys   = $table2->getForeignKeys();
271
272 3498
        foreach ($fromFkeys as $key1 => $constraint1) {
273 3223
            foreach ($toFkeys as $key2 => $constraint2) {
274 3180
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
275 3157
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
276
                } else {
277 3150
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
278 1056
                        $tableDifferences->changedForeignKeys[] = $constraint2;
279 1056
                        $changes++;
280 1056
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
281
                    }
282
                }
283
            }
284
        }
285
286 3498
        foreach ($fromFkeys as $constraint1) {
287 3193
            $tableDifferences->removedForeignKeys[] = $constraint1;
288 3193
            $changes++;
289
        }
290
291 3498
        foreach ($toFkeys as $constraint2) {
292 3152
            $tableDifferences->addedForeignKeys[] = $constraint2;
293 3152
            $changes++;
294
        }
295
296 3498
        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 3498
    private function detectColumnRenamings(TableDiff $tableDifferences)
306
    {
307 3498
        $renameCandidates = [];
308 3498
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
309 3411
            foreach ($tableDifferences->removedColumns as $removedColumn) {
310 3229
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
311 2952
                    continue;
312
                }
313
314 3229
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
315
            }
316
        }
317
318 3498
        foreach ($renameCandidates as $candidateColumns) {
319 3229
            if (count($candidateColumns) !== 1) {
320 816
                continue;
321
            }
322
323 3229
            [$removedColumn, $addedColumn] = $candidateColumns[0];
324 3229
            $removedColumnName             = strtolower($removedColumn->getName());
325 3229
            $addedColumnName               = strtolower($addedColumn->getName());
326
327 3229
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
328 1296
                continue;
329
            }
330
331 3229
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
332
            unset(
333 3229
                $tableDifferences->addedColumns[$addedColumnName],
334 3229
                $tableDifferences->removedColumns[$removedColumnName]
335
            );
336
        }
337 3498
    }
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 3498
    private function detectIndexRenamings(TableDiff $tableDifferences)
346
    {
347 3498
        $renameCandidates = [];
348
349
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
350 3498
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
351 3359
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
352 3330
                if ($this->diffIndex($addedIndex, $removedIndex)) {
353 3202
                    continue;
354
                }
355
356 3122
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
357
            }
358
        }
359
360 3498
        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 3122
            if (count($candidateIndexes) !== 1) {
366 768
                continue;
367
            }
368
369 3122
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
370
371 3122
            $removedIndexName = strtolower($removedIndex->getName());
372 3122
            $addedIndexName   = strtolower($addedIndex->getName());
373
374 3122
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
375
                continue;
376
            }
377
378 3122
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
379
            unset(
380 3122
                $tableDifferences->addedIndexes[$addedIndexName],
381 3122
                $tableDifferences->removedIndexes[$removedIndexName]
382
            );
383
        }
384 3498
    }
385
386
    /**
387
     * @return bool
388
     */
389 3180
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
390
    {
391 3180
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
392 3110
            return true;
393
        }
394
395 3163
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
396
            return true;
397
        }
398
399 3163
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
400 1032
            return true;
401
        }
402
403 3163
        if ($key1->onUpdate() !== $key2->onUpdate()) {
404 1056
            return true;
405
        }
406
407 3157
        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 3498
    public function diffColumn(Column $column1, Column $column2)
419
    {
420 3498
        $properties1 = $column1->toArray();
421 3498
        $properties2 = $column2->toArray();
422
423 3498
        $changedProperties = [];
424
425 3498
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
426 3498
            if ($properties1[$property] === $properties2[$property]) {
427 3498
                continue;
428
            }
429
430 2468
            $changedProperties[] = $property;
431
        }
432
433
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
434
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
435 3498
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
436 3498
            || $properties1['default'] != $properties2['default']) {
437 3272
            $changedProperties[] = 'default';
438
        }
439
440 3498
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
441 3498
            $properties1['type'] instanceof Types\BinaryType
442
        ) {
443
            // check if value of length is set at all, default value assumed otherwise.
444 3454
            $length1 = $properties1['length'] ?: 255;
445 3454
            $length2 = $properties2['length'] ?: 255;
446 3454
            if ($length1 !== $length2) {
447 2712
                $changedProperties[] = 'length';
448
            }
449
450 3454
            if ($properties1['fixed'] !== $properties2['fixed']) {
451 3454
                $changedProperties[] = 'fixed';
452
            }
453 3498
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
454 3262
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
455
                $changedProperties[] = 'precision';
456
            }
457 3262
            if ($properties1['scale'] !== $properties2['scale']) {
458
                $changedProperties[] = 'scale';
459
            }
460
        }
461
462
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
463 3498
        if ($properties1['comment'] !== $properties2['comment'] &&
464 3498
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
465 3498
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
466
        ) {
467 3168
            $changedProperties[] = 'comment';
468
        }
469
470 3498
        $customOptions1 = $column1->getCustomSchemaOptions();
471 3498
        $customOptions2 = $column2->getCustomSchemaOptions();
472
473 3498
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
474 1320
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
475 1320
                $changedProperties[] = $key;
476 1320
            } elseif ($properties1[$key] !== $properties2[$key]) {
477
                $changedProperties[] = $key;
478
            }
479
        }
480
481 3498
        $platformOptions1 = $column1->getPlatformOptions();
482 3498
        $platformOptions2 = $column2->getPlatformOptions();
483
484 3498
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
485 2242
            if ($properties1[$key] === $properties2[$key]) {
486 2242
                continue;
487
            }
488
489 2134
            $changedProperties[] = $key;
490
        }
491
492 3498
        return array_unique($changedProperties);
493
    }
494
495
    /**
496
     * Finds the difference between the indexes $index1 and $index2.
497
     *
498
     * Compares $index1 with $index2 and returns $index2 if there are any
499
     * differences or false in case there are no differences.
500
     *
501
     * @return bool
502
     */
503 3460
    public function diffIndex(Index $index1, Index $index2)
504
    {
505 3460
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
506
    }
507
}
508