Completed
Pull Request — master (#3355)
by Sergei
52:31 queued 41:00
created

Comparator::diffColumn()   F

Complexity

Conditions 29
Paths 2592

Size

Total Lines 82
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 29.0736

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 82
ccs 43
cts 45
cp 0.9556
rs 0
c 0
b 0
f 0
cc 29
nc 2592
nop 2
crap 29.0736

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

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

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