Completed
Push — master ( 1a9812...b70610 )
by Sergei
19s queued 14s
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 459
    public static function compareSchemas(Schema $fromSchema, Schema $toSchema) : SchemaDiff
25
    {
26 459
        $c = new self();
27
28 459
        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 763
    public function compare(Schema $fromSchema, Schema $toSchema) : SchemaDiff
39
    {
40 763
        $diff             = new SchemaDiff();
41 763
        $diff->fromSchema = $fromSchema;
42
43 763
        $foreignKeysToTable = [];
44
45 763
        foreach ($toSchema->getNamespaces() as $namespace) {
46 54
            if ($fromSchema->hasNamespace($namespace)) {
47 54
                continue;
48
            }
49
50 54
            $diff->newNamespaces[$namespace] = $namespace;
51
        }
52
53 763
        foreach ($fromSchema->getNamespaces() as $namespace) {
54 54
            if ($toSchema->hasNamespace($namespace)) {
55 54
                continue;
56
            }
57
58 27
            $diff->removedNamespaces[$namespace] = $namespace;
59
        }
60
61 763
        foreach ($toSchema->getTables() as $table) {
62 601
            $tableName = $table->getShortestName($toSchema->getName());
63 601
            if (! $fromSchema->hasTable($tableName)) {
64 135
                $diff->newTables[$tableName] = $toSchema->getTable($tableName);
65
            } else {
66 547
                $tableDifferences = $this->diffTable($fromSchema->getTable($tableName), $toSchema->getTable($tableName));
67 547
                if ($tableDifferences !== null) {
68 304
                    $diff->changedTables[$tableName] = $tableDifferences;
69
                }
70
            }
71
        }
72
73
        /* Check if there are tables removed */
74 763
        foreach ($fromSchema->getTables() as $table) {
75 574
            $tableName = $table->getShortestName($fromSchema->getName());
76
77 574
            $table = $fromSchema->getTable($tableName);
78 574
            if (! $toSchema->hasTable($tableName)) {
79 135
                $diff->removedTables[$tableName] = $table;
80
            }
81
82
            // also remember all foreign keys that point to a specific table
83 574
            foreach ($table->getForeignKeys() as $foreignKey) {
84 54
                $foreignTable = strtolower($foreignKey->getForeignTableName());
85 54
                if (! isset($foreignKeysToTable[$foreignTable])) {
86 54
                    $foreignKeysToTable[$foreignTable] = [];
87
                }
88 54
                $foreignKeysToTable[$foreignTable][] = $foreignKey;
89
            }
90
        }
91
92 763
        foreach ($diff->removedTables as $tableName => $table) {
93 135
            if (! isset($foreignKeysToTable[$tableName])) {
94 81
                continue;
95
            }
96
97 54
            $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 54
            foreach ($foreignKeysToTable[$tableName] as $foreignKey) {
102
                // strtolower the table name to make if compatible with getShortestName
103 54
                $localTableName = strtolower($foreignKey->getLocalTableName());
104 54
                if (! isset($diff->changedTables[$localTableName])) {
105
                    continue;
106
                }
107
108 54
                foreach ($diff->changedTables[$localTableName]->removedForeignKeys as $key => $removedForeignKey) {
109 54
                    assert($removedForeignKey instanceof ForeignKeyConstraint);
110
111
                    // We check if the key is from the removed table if not we skip.
112 54
                    if ($tableName !== strtolower($removedForeignKey->getForeignTableName())) {
113 27
                        continue;
114
                    }
115 54
                    unset($diff->changedTables[$localTableName]->removedForeignKeys[$key]);
116
                }
117
            }
118
        }
119
120 763
        foreach ($toSchema->getSequences() as $sequence) {
121 108
            $sequenceName = $sequence->getShortestName($toSchema->getName());
122 108
            if (! $fromSchema->hasSequence($sequenceName)) {
123 81
                if (! $this->isAutoIncrementSequenceInSchema($fromSchema, $sequence)) {
124 81
                    $diff->newSequences[] = $sequence;
125
                }
126
            } else {
127 54
                if ($this->diffSequence($sequence, $fromSchema->getSequence($sequenceName))) {
128 27
                    $diff->changedSequences[] = $toSchema->getSequence($sequenceName);
129
                }
130
            }
131
        }
132
133 763
        foreach ($fromSchema->getSequences() as $sequence) {
134 108
            if ($this->isAutoIncrementSequenceInSchema($toSchema, $sequence)) {
135 27
                continue;
136
            }
137
138 81
            $sequenceName = $sequence->getShortestName($fromSchema->getName());
139
140 81
            if ($toSchema->hasSequence($sequenceName)) {
141 54
                continue;
142
            }
143
144 54
            $diff->removedSequences[] = $sequence;
145
        }
146
147 763
        return $diff;
148
    }
149
150 162
    private function isAutoIncrementSequenceInSchema(Schema $schema, Sequence $sequence) : bool
151
    {
152 162
        foreach ($schema->getTables() as $table) {
153 54
            if ($sequence->isAutoIncrementsFor($table)) {
154 54
                return true;
155
            }
156
        }
157
158 108
        return false;
159
    }
160
161 90
    public function diffSequence(Sequence $sequence1, Sequence $sequence2) : bool
162
    {
163 90
        if ($sequence1->getAllocationSize() !== $sequence2->getAllocationSize()) {
164 54
            return true;
165
        }
166
167 63
        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 2967
    public function diffTable(Table $table1, Table $table2) : ?TableDiff
176
    {
177 2967
        $changes                     = 0;
178 2967
        $tableDifferences            = new TableDiff($table1->getName());
179 2967
        $tableDifferences->fromTable = $table1;
180
181 2967
        $table1Columns = $table1->getColumns();
182 2967
        $table2Columns = $table2->getColumns();
183
184
        /* See if all the fields in table 1 exist in table 2 */
185 2967
        foreach ($table2Columns as $columnName => $column) {
186 2832
            if ($table1->hasColumn($columnName)) {
187 2481
                continue;
188
            }
189
190 637
            $tableDifferences->addedColumns[$columnName] = $column;
191 637
            $changes++;
192
        }
193
        /* See if there are any removed fields in table 2 */
194 2967
        foreach ($table1Columns as $columnName => $column) {
195
            // See if column is removed in table 2.
196 2832
            if (! $table2->hasColumn($columnName)) {
197 539
                $tableDifferences->removedColumns[$columnName] = $column;
198 539
                $changes++;
199 539
                continue;
200
            }
201
202
            // See if column has changed properties in table 2.
203 2481
            $changedProperties = $this->diffColumn($column, $table2->getColumn($columnName));
204
205 2481
            if (empty($changedProperties)) {
206 1869
                continue;
207
            }
208
209 857
            $columnDiff                                           = new ColumnDiff($column->getName(), $table2->getColumn($columnName), $changedProperties);
210 857
            $columnDiff->fromColumn                               = $column;
211 857
            $tableDifferences->changedColumns[$column->getName()] = $columnDiff;
212 857
            $changes++;
213
        }
214
215 2967
        $this->detectColumnRenamings($tableDifferences);
216
217 2967
        $table1Indexes = $table1->getIndexes();
218 2967
        $table2Indexes = $table2->getIndexes();
219
220
        /* See if all the indexes in table 1 exist in table 2 */
221 2967
        foreach ($table2Indexes as $indexName => $index) {
222 1231
            if (($index->isPrimary() && $table1->hasPrimaryKey()) || $table1->hasIndex($indexName)) {
223 739
                continue;
224
            }
225
226 492
            $tableDifferences->addedIndexes[$indexName] = $index;
227 492
            $changes++;
228
        }
229
        /* See if there are any removed indexes in table 2 */
230 2967
        foreach ($table1Indexes as $indexName => $index) {
231
            // See if index is removed in table 2.
232 1150
            if (($index->isPrimary() && ! $table2->hasPrimaryKey()) ||
233 1150
                ! $index->isPrimary() && ! $table2->hasIndex($indexName)
234
            ) {
235 465
                $tableDifferences->removedIndexes[$indexName] = $index;
236 465
                $changes++;
237 465
                continue;
238
            }
239
240
            // See if index has changed in table 2.
241 739
            $table2Index = $index->isPrimary() ? $table2->getPrimaryKey() : $table2->getIndex($indexName);
242 739
            assert($table2Index instanceof Index);
243
244 739
            if (! $this->diffIndex($index, $table2Index)) {
245 334
                continue;
246
            }
247
248 448
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
249 448
            $changes++;
250
        }
251
252 2967
        $this->detectIndexRenamings($tableDifferences);
253
254 2967
        $fromFkeys = $table1->getForeignKeys();
255 2967
        $toFkeys   = $table2->getForeignKeys();
256
257 2967
        foreach ($fromFkeys as $key1 => $constraint1) {
258 273
            foreach ($toFkeys as $key2 => $constraint2) {
259 165
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
260 58
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
261
                } else {
262 107
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
263 54
                        $tableDifferences->changedForeignKeys[] = $constraint2;
264 54
                        $changes++;
265 54
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
266
                    }
267
                }
268
            }
269
        }
270
271 2967
        foreach ($fromFkeys as $constraint1) {
272 161
            $tableDifferences->removedForeignKeys[] = $constraint1;
273 161
            $changes++;
274
        }
275
276 2967
        foreach ($toFkeys as $constraint2) {
277 80
            $tableDifferences->addedForeignKeys[] = $constraint2;
278 80
            $changes++;
279
        }
280
281 2967
        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 2967
    private function detectColumnRenamings(TableDiff $tableDifferences) : void
289
    {
290 2967
        $renameCandidates = [];
291 2967
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
292 637
            foreach ($tableDifferences->removedColumns as $removedColumn) {
293 431
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
294 297
                    continue;
295
                }
296
297 431
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
298
            }
299
        }
300
301 2967
        foreach ($renameCandidates as $candidateColumns) {
302 431
            if (count($candidateColumns) !== 1) {
303 27
                continue;
304
            }
305
306 404
            [$removedColumn, $addedColumn] = $candidateColumns[0];
307 404
            $removedColumnName             = strtolower($removedColumn->getName());
308 404
            $addedColumnName               = strtolower($addedColumn->getName());
309
310 404
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
311 27
                continue;
312
            }
313
314 404
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
315
            unset(
316 404
                $tableDifferences->addedColumns[$addedColumnName],
317 404
                $tableDifferences->removedColumns[$removedColumnName]
318
            );
319
        }
320 2967
    }
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 2967
    private function detectIndexRenamings(TableDiff $tableDifferences) : void
327
    {
328 2967
        $renameCandidates = [];
329
330
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
331 2967
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
332 492
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
333 232
                if ($this->diffIndex($addedIndex, $removedIndex)) {
334 125
                    continue;
335
                }
336
337 107
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
338
            }
339
        }
340
341 2967
        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 107
            if (count($candidateIndexes) !== 1) {
347 27
                continue;
348
            }
349
350 80
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
351
352 80
            $removedIndexName = strtolower($removedIndex->getName());
353 80
            $addedIndexName   = strtolower($addedIndex->getName());
354
355 80
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
356
                continue;
357
            }
358
359 80
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
360
            unset(
361 80
                $tableDifferences->addedIndexes[$addedIndexName],
362 80
                $tableDifferences->removedIndexes[$removedIndexName]
363
            );
364
        }
365 2967
    }
366
367 246
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2) : bool
368
    {
369 246
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
370 53
            return true;
371
        }
372
373 193
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
374
            return true;
375
        }
376
377 193
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
378 27
            return true;
379
        }
380
381 166
        if ($key1->onUpdate() !== $key2->onUpdate()) {
382 27
            return true;
383
        }
384
385 139
        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 3480
    public function diffColumn(Column $column1, Column $column2) : array
397
    {
398 3480
        $properties1 = $column1->toArray();
399 3480
        $properties2 = $column2->toArray();
400
401 3480
        $changedProperties = [];
402
403 3480
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
404 203
            $changedProperties[] = 'type';
405
        }
406
407 3480
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
408 3480
            if ($properties1[$property] === $properties2[$property]) {
409 3480
                continue;
410
            }
411
412 69
            $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 3480
        if (($properties1['default'] === null) !== ($properties2['default'] === null)
418 3480
            || $properties1['default'] != $properties2['default']) {
419 121
            $changedProperties[] = 'default';
420
        }
421
422 3480
        if (($properties1['type'] instanceof Types\StringType && ! $properties1['type'] instanceof Types\GuidType) ||
423 3480
            $properties1['type'] instanceof Types\BinaryType
424
        ) {
425 692
            if ((isset($properties1['length']) !== isset($properties2['length']))
426 665
                || (isset($properties1['length']) && isset($properties2['length'])
427 692
                    && $properties1['length'] !== $properties2['length'])
428
            ) {
429 245
                $changedProperties[] = 'length';
430
            }
431
432 692
            if ($properties1['fixed'] !== $properties2['fixed']) {
433 692
                $changedProperties[] = 'fixed';
434
            }
435 3058
        } elseif ($properties1['type'] instanceof Types\DecimalType) {
436 52
            if (($properties1['precision'] ?: 10) !== ($properties2['precision'] ?: 10)) {
437
                $changedProperties[] = 'precision';
438
            }
439 52
            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 3480
        if ($properties1['comment'] !== $properties2['comment'] &&
446 3480
            ! ($properties1['comment'] === null && $properties2['comment'] === '') &&
447 3480
            ! ($properties2['comment'] === null && $properties1['comment'] === '')
448
        ) {
449 891
            $changedProperties[] = 'comment';
450
        }
451
452 3480
        $customOptions1 = $column1->getCustomSchemaOptions();
453 3480
        $customOptions2 = $column2->getCustomSchemaOptions();
454
455 3480
        foreach (array_merge(array_keys($customOptions1), array_keys($customOptions2)) as $key) {
456 54
            if (! array_key_exists($key, $properties1) || ! array_key_exists($key, $properties2)) {
457 27
                $changedProperties[] = $key;
458 54
            } elseif ($properties1[$key] !== $properties2[$key]) {
459
                $changedProperties[] = $key;
460
            }
461
        }
462
463 3480
        $platformOptions1 = $column1->getPlatformOptions();
464 3480
        $platformOptions2 = $column2->getPlatformOptions();
465
466 3480
        foreach (array_keys(array_intersect_key($platformOptions1, $platformOptions2)) as $key) {
467 105
            if ($properties1[$key] === $properties2[$key]) {
468 71
                continue;
469
            }
470
471 61
            $changedProperties[] = $key;
472
        }
473
474 3480
        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 971
    public function diffIndex(Index $index1, Index $index2) : bool
484
    {
485 971
        return ! ($index1->isFullfilledBy($index2) && $index2->isFullfilledBy($index1));
486
    }
487
}
488