Passed
Push — 2.9 ( 2c6848...66f281 )
by Sergei
21:20 queued 10s
created

Comparator::diffColumn()   F

Complexity

Conditions 30
Paths 5184

Size

Total Lines 86
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 30.0695

Importance

Changes 0
Metric Value
eloc 46
dl 0
loc 86
rs 0
c 0
b 0
f 0
ccs 45
cts 47
cp 0.9574
cc 30
nc 5184
nop 2
crap 30.0695

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

255
            if (! $this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
256 418
                continue;
257
            }
258
259 431
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
260 431
            $changes++;
261
        }
262
263 3701
        $this->detectIndexRenamings($tableDifferences);
264
265 3701
        $fromFkeys = $table1->getForeignKeys();
266 3701
        $toFkeys   = $table2->getForeignKeys();
267
268 3701
        foreach ($fromFkeys as $key1 => $constraint1) {
269 356
            foreach ($toFkeys as $key2 => $constraint2) {
270 167
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
271 60
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
272
                } else {
273 107
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
274 54
                        $tableDifferences->changedForeignKeys[] = $constraint2;
275 54
                        $changes++;
276 76
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
277
                    }
278
                }
279
            }
280
        }
281
282 3701
        foreach ($fromFkeys as $constraint1) {
283 242
            $tableDifferences->removedForeignKeys[] = $constraint1;
284 242
            $changes++;
285
        }
286
287 3701
        foreach ($toFkeys as $constraint2) {
288 80
            $tableDifferences->addedForeignKeys[] = $constraint2;
289 80
            $changes++;
290
        }
291
292 3701
        return $changes ? $tableDifferences : false;
293
    }
294
295
    /**
296
     * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
297
     * however ambiguities between different possibilities should not lead to renaming at all.
298
     *
299
     * @return void
300
     */
301 3701
    private function detectColumnRenamings(TableDiff $tableDifferences)
302
    {
303 3701
        $renameCandidates = [];
304 3701
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
305 836
            foreach ($tableDifferences->removedColumns as $removedColumn) {
306 647
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
307 513
                    continue;
308
                }
309
310 661
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
311
            }
312
        }
313
314 3701
        foreach ($renameCandidates as $candidateColumns) {
315 647
            if (count($candidateColumns) !== 1) {
316 27
                continue;
317
            }
318
319 620
            [$removedColumn, $addedColumn] = $candidateColumns[0];
320 620
            $removedColumnName             = strtolower($removedColumn->getName());
321 620
            $addedColumnName               = strtolower($addedColumn->getName());
322
323 620
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
324 27
                continue;
325
            }
326
327 620
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
328
            unset(
329 620
                $tableDifferences->addedColumns[$addedColumnName],
330 620
                $tableDifferences->removedColumns[$removedColumnName]
331
            );
332
        }
333 3701
    }
334
335
    /**
336
     * Try to find indexes that only changed their name, rename operations maybe cheaper than add/drop
337
     * however ambiguities between different possibilities should not lead to renaming at all.
338
     *
339
     * @return void
340
     */
341 3701
    private function detectIndexRenamings(TableDiff $tableDifferences)
342
    {
343 3701
        $renameCandidates = [];
344
345
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
346 3701
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
347 486
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
348 229
                if ($this->diffIndex($addedIndex, $removedIndex)) {
349 122
                    continue;
350
                }
351
352 133
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
353
            }
354
        }
355
356 3701
        foreach ($renameCandidates as $candidateIndexes) {
357
            // If the current rename candidate contains exactly one semantically equal index,
358
            // we can safely rename it.
359
            // Otherwise it is unclear if a rename action is really intended,
360
            // therefore we let those ambiguous indexes be added/dropped.
361 107
            if (count($candidateIndexes) !== 1) {
362 27
                continue;
363
            }
364
365 80
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
366
367 80
            $removedIndexName = strtolower($removedIndex->getName());
368 80
            $addedIndexName   = strtolower($addedIndex->getName());
369
370 80
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
371
                continue;
372
            }
373
374 80
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
375
            unset(
376 80
                $tableDifferences->addedIndexes[$addedIndexName],
377 80
                $tableDifferences->removedIndexes[$removedIndexName]
378
            );
379
        }
380 3701
    }
381
382
    /**
383
     * @return bool
384
     */
385 248
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
386
    {
387 248
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
388 53
            return true;
389
        }
390
391 195
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
392
            return true;
393
        }
394
395 195
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
396 27
            return true;
397
        }
398
399 168
        if ($key1->onUpdate() !== $key2->onUpdate()) {
400 27
            return true;
401
        }
402
403 141
        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 4214
    public function diffColumn(Column $column1, Column $column2)
415
    {
416 4214
        $properties1 = $column1->toArray();
417 4214
        $properties2 = $column2->toArray();
418
419 4214
        $changedProperties = [];
420
421 4214
        if (get_class($properties1['type']) !== get_class($properties2['type'])) {
422 418
            $changedProperties[] = 'type';
423
        }
424
425 4214
        foreach (['notnull', 'unsigned', 'autoincrement'] as $property) {
426 4214
            if ($properties1[$property] === $properties2[$property]) {
427 4214
                continue;
428
            }
429
430 95
            $changedProperties[] = $property;
431
        }
432
433
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
434 4214
        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

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