Completed
Pull Request — master (#3772)
by Christoph
51:54
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_unique;
14
use function assert;
15
use function count;
16
use function get_class;
17
use function strtolower;
18
19
/**
20
 * Compares two Schemas and return an instance of SchemaDiff.
21
 */
22
class Comparator
23
{
24 1408
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
25
    {
26 1408
        $c = new self();
27
28 1408
        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 2418
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
39
    {
40 2418
        $diff             = new SchemaDiff();
41 2418
        $diff->fromSchema = $fromSchema;
42
43 2418
        $foreignKeysToTable = [];
44
45 2418
        foreach ($toSchema->getNamespaces() as $namespace) {
46 489
            if ($fromSchema->hasNamespace($namespace)) {
47 489
                continue;
48
            }
49
50 489
            $diff->newNamespaces[$namespace] = $namespace;
51
        }
52
53 2418
        foreach ($fromSchema->getNamespaces() as $namespace) {
54 489
            if ($toSchema->hasNamespace($namespace)) {
55 489
                continue;
56
            }
57
58 233
            $diff->removedNamespaces[$namespace] = $namespace;
59
        }
60
61 2418
        foreach ($toSchema->getTables() as $table) {
62 2400
            $tableName = $table->getShortestName($toSchema->getName());
63 2400
            if (! $fromSchema->hasTable($tableName)) {
64 1303
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
65
            } else {
66 2394
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
67 2394
                if ($tableDifferences !== null) {
68 2317
                    $diff->changedTables[$tableName] = $tableDifferences;
69
                }
70
            }
71
        }
72
73
        /* Check if there are tables removed */
74 2418
        foreach ($fromSchema->getTables() as $table) {
75 2397
            $tableName = $table->getShortestName($fromSchema->getName());
76
77 2397
            $table = $fromSchema->getTable($tableName);
78 2397
            if (! $toSchema->hasTable($tableName)) {
79 1326
                $diff->removedTables[$tableName] = $table;
80
            }
81
82
            // also remember all foreign keys that point to a specific table
83 2397
            foreach ($table->getForeignKeys() as $foreignKey) {
84 374
                $foreignTable = strtolower($foreignKey->getForeignTableName());
85 374
                if (! isset($foreignKeysToTable[$foreignTable])) {
86 374
                    $foreignKeysToTable[$foreignTable] = [];
87
                }
88 374
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
89
            }
90
        }
91
92 2418
        foreach ($diff->removedTables as $tableName => $table) {
93 1326
            if (! isset($foreignKeysToTable[$tableName])) {
94 1320
                continue;
95
            }
96
97 374
            $diff->orphanedForeignKeys = array_merge($diff->orphanedForeignKeys, $foreignKeysToTable[$tableName]);
98
99
            // deleting duplicated foreign keys present on both on the orphanedForeignKey
100
            // and the removedForeignKeys from changedTables
101 374
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
102
                // strtolower the table name to make if compatible with getShortestName
103 374
                $localTableName = strtolower($foreignKey->getLocalTableName());
104 374
                if (! isset($diff->changedTables[$localTableName])) {
105
                    continue;
106
                }
107
108 374
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
109 374
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
110
111
                    // We check if the key is from the removed table if not we skip.
112 374
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
113 371
                        continue;
114
                    }
115 374
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
116
                }
117
            }
118
        }
119
120 2418
        foreach ($toSchema->getSequences() as $sequence) {
121 955
            $sequenceName = $sequence->getShortestName($toSchema->getName());
122 955
            if (! $fromSchema->hasSequence($sequenceName)) {
123 952
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
124 952
                    $diff->newSequences[] = $sequence;
125
                }
126
            } else {
127 811
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
128 555
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
129
                }
130
            }
131
        }
132
133 2418
        foreach ($fromSchema->getSequences() as $sequence) {
134 978
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
135 417
                continue;
136
            }
137
138 975
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
139
140 975
            if ($toSchema->hasSequence($sequenceName)) {
141 811
                continue;
142
            }
143
144 972
            $diff->removedSequences[] = $sequence;
145
        }
146
147 2418
        return $diff;
148
    }
149
150 984
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
151
    {
152 984
        foreach ($schema->getTables() as $table) {
153 420
            if ($sequence->isAutoIncrementsFor($table)) {
154 420
                return true;
155
            }
156
        }
157
158 978
        return false;
159
    }
160
161 1496
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
162
    {
163 1496
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
164 995
            return true;
165
        }
166
167 1493
        return $sequence1->getInitialValue() !== $sequence2->getInitialValue();
168
    }
169
170
    /**
171
     * Returns the difference between the tables $table1 and $table2.
172
     *
173
     * If there are no differences this method returns the boolean false.
174
     */
175 3371
    public function diffTable(Table $table1, Table $table2) : ?TableDiff
176
    {
177 3371
        $changes                     = 0;
178 3371
        $tableDifferences            = new TableDiff($table1->getName());
179 3371
        $tableDifferences->fromTable = $table1;
180
181 3371
        $table1Columns = $table1->getColumns();
182 3371
        $table2Columns = $table2->getColumns();
183
184
        /* See if all the fields in table 1 exist in table 2 */
185 3371
        foreach ($table2Columns as $columnName => $column) {
186 3356
            if ($table1->hasColumn($columnName)) {
187 3317
                continue;
188
            }
189
190 3042
            $tableDifferences->addedColumns[$columnName] = $column;
191 3042
            $changes++;
192
        }
193
        /* See if there are any removed fields in table 2 */
194 3371
        foreach ($table1Columns as $columnName => $column) {
195
            // See if column is removed in table 2.
196 3356
            if (! $table2->hasColumn($columnName)) {
197 2877
                $tableDifferences->removedColumns[$columnName] = $column;
198 2877
                $changes++;
199 2877
                continue;
200
            }
201
202
            // See if column has changed properties in table 2.
203 3317
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
204
205 3317
            if (empty($changedProperties)) {
206 3257
                continue;
207
            }
208
209 3048
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
210 3048
            $columnDiff->fromColumn                               = $column;
211 3048
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
212 3048
            $changes++;
213
        }
214
215 3371
        $this->detectColumnRenamings($tableDifferences);
216
217 3371
        $table1Indexes = $table1->getIndexes();
218 3371
        $table2Indexes = $table2->getIndexes();
219
220
        /* See if all the indexes in table 1 exist in table 2 */
221 3371
        foreach ($table2Indexes as $indexName => $index) {
222 3159
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
223 3108
                continue;
224
            }
225
226 2975
            $tableDifferences->addedIndexes[$indexName] = $index;
227 2975
            $changes++;
228
        }
229
        /* See if there are any removed indexes in table 2 */
230 3371
        foreach ($table1Indexes as $indexName => $index) {
231
            // See if index is removed in table 2.
232 3150
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
233 3150
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
234
            ) {
235 2957
                $tableDifferences->removedIndexes[$indexName] = $index;
236 2957
                $changes++;
237 2957
                continue;
238
            }
239
240
            // See if index has changed in table 2.
241 3108
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
242 3108
            assert($table2Index instanceof Index);
243
244 3108
            if (! $this->diffIndex($index, $table2Index)) {
245 3063
                continue;
246
            }
247
248 3015
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
249 3015
            $changes++;
250
        }
251
252 3371
        $this->detectIndexRenamings($tableDifferences);
253
254 3371
        $fromFkeys = $table1->getForeignKeys();
255 3371
        $toFkeys   = $table2->getForeignKeys();
256
257 3371
        foreach ($fromFkeys as $key1 => $constraint1) {
258 2800
            foreach ($toFkeys as $key2 => $constraint2) {
259 2712
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
260 2672
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
261
                } else {
262 2681
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
263 880
                        $tableDifferences->changedForeignKeys[] = $constraint2;
264 880
                        $changes++;
265 880
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
266
                    }
267
                }
268
            }
269
        }
270
271 3371
        foreach ($fromFkeys as $constraint1) {
272 2763
            $tableDifferences->removedForeignKeys[] = $constraint1;
273 2763
            $changes++;
274
        }
275
276 3371
        foreach ($toFkeys as $constraint2) {
277 2682
            $tableDifferences->addedForeignKeys[] = $constraint2;
278 2682
            $changes++;
279
        }
280
281 3371
        return $changes ? $tableDifferences : null;
282
    }
283
284
    /**
285
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
286
     * however ambiguities between different possibilities should not lead to renaming at all.
287
     */
288 3371
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
289
    {
290 3371
        $renameCandidates = [];
291 3371
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
292 3042
            foreach ($tableDifferences->removedColumns as $removedColumn) {
293 2865
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
294 2609
                    continue;
295
                }
296
297 2865
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
298
            }
299
        }
300
301 3371
        foreach ($renameCandidates as $candidateColumns) {
302 2865
            if (count($candidateColumns) !== 1) {
303 647
                continue;
304
            }
305
306 2862
            [$removedColumn, $addedColumn] = $candidateColumns[0];
307 2862
            $removedColumnName             = strtolower($removedColumn->getName());
308 2862
            $addedColumnName               = strtolower($addedColumn->getName());
309
310 2862
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
311 1107
                continue;
312
            }
313
314 2862
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
315
            unset(
316 2862
                $tableDifferences->addedColumns[$addedColumnName],
317 2862
                $tableDifferences->removedColumns[$removedColumnName]
318
            );
319
        }
320 3371
    }
321
322
    /**
323
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
324
     * however ambiguities between different possibilities should not lead to renaming at all.
325
     */
326 3371
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
327
    {
328 3371
        $renameCandidates = [];
329
330
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
331 3371
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
332 2975
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
333 2933
                if ($this->diffIndex($addedIndex, $removedIndex)) {
334 2807
                    continue;
335
                }
336
337 2650
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
338
            }
339
        }
340
341 3371
        foreach ($renameCandidates as $candidateIndexes) {
342
            // If the current rename candidate contains exactly one semantically equal index,
343
            // we can safely rename it.
344
            // Otherwise it is unclear if a rename action is really intended,
345
            // therefore we let those ambiguous indexes be added/dropped.
346 2650
            if (count($candidateIndexes) !== 1) {
347 601
                continue;
348
            }
349
350 2647
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
351
352 2647
            $removedIndexName = strtolower($removedIndex->getName());
353 2647
            $addedIndexName   = strtolower($addedIndex->getName());
354
355 2647
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
356
                continue;
357
            }
358
359 2647
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
360
            unset(
361 2647
                $tableDifferences->addedIndexes[$addedIndexName],
362 2647
                $tableDifferences->removedIndexes[$removedIndexName]
363
            );
364
        }
365 3371
    }
366
367 2721
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
368
    {
369 2721
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
370 2607
            return true;
371
        }
372
373 2699
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
374
            return true;
375
        }
376
377 2699
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
378 854
            return true;
379
        }
380
381 2696
        if ($key1->onUpdate() !== $key2->onUpdate()) {
382 877
            return true;
383
        }
384
385 2681
        return $key1->onDelete() !== $key2->onDelete();
386
    }
387
388
    /**
389
     * Returns the difference between the fields $field1 and $field2.
390
     *
391
     * If there are differences this method returns $field2, otherwise the
392
     * boolean false.
393
     *
394
     * @return array<int, string>
395
     */
396 3428
    public function diffColumn(Column $column1, Column $column2) : array
397
    {
398 3428
        $properties1 = $column1->toArray();
399 3428
        $properties2 = $column2->toArray();
400
401 3428
        $changedProperties = [];
402
403 3428
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
404 2119
            $changedProperties[] = 'type';
405
        }
406
407 3428
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
408 3428
            if ($properties1[$property] === $properties2[$property]) {
409 3428
                continue;
410
            }
411
412 1810
            $changedProperties[] = $property;
413
        }
414
415
        // Null values need to be checked additionally as they tell whether to create or drop a default value.
416
        // null != 0, null != false, null != '' etc. This affects platform's table alteration SQL generation.
417 3428
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
418 3428
            || $properties1['default'] != $properties2['default']) {
419 2874
            $changedProperties[] = 'default';
420
        }
421
422 3428
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
423 3428
            $properties1['type'] instanceof Types\BinaryType
424
        ) {
425 3090
            if ((isset($properties1['length']) !== isset($properties2['length']))
426 3087
                || (isset($properties1['length']) && isset($properties2['length'])
427 3090
                    && $properties1['length'] !== $properties2['length'])
428
            ) {
429 2583
                $changedProperties[] = 'length';
430
            }
431
432 3090
            if ($properties1['fixed'] !== $properties2['fixed']) {
433 3090
                $changedProperties[] = 'fixed';
434
            }
435 3383
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
436 2858
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
437
                $changedProperties[] = 'precision';
438
            }
439 2858
            if ($properties1['scale'] !== $properties2['scale']) {
440
                $changedProperties[] = 'scale';
441
            }
442
        }
443
444
        // A null value and an empty string are actually equal for a comment so they should not trigger a change.
445 3428
        if ($properties1['comment'] !== $properties2['comment'] &&
446 3428
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
447 3428
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
448
        ) {
449 2866
            $changedProperties[] = 'comment';
450
        }
451
452 3428
        $customOptions1 = $column1->getCustomSchemaOptions();
453 3428
        $customOptions2 = $column2->getCustomSchemaOptions();
454
455 3428
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
456 1133
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
457 1130
                $changedProperties[] = $key;
458 1133
            } elseif ($properties1[$key] !== $properties2[$key]) {
459
                $changedProperties[] = $key;
460
            }
461
        }
462
463 3428
        $platformOptions1 = $column1->getPlatformOptions();
464 3428
        $platformOptions2 = $column2->getPlatformOptions();
465
466 3428
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
467 1873
            if ($properties1[$key] === $properties2[$key]) {
468 1873
                continue;
469
            }
470
471 1783
            $changedProperties[] = $key;
472
        }
473
474 3428
        return array_unique($changedProperties);
475
    }
476
477
    /**
478
     * Finds the difference between the indexes $index1 and $index2.
479
     *
480
     * Compares $index1 with $index2 and returns $index2 if there are any
481
     * differences or false in case there are no differences.
482
     */
483 3132
    public function diffIndex(Index $index1, Index $index2) : bool
484
    {
485 3132
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
486
    }
487
}
488