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

255
            if (! $this->diffIndex($index, /** @scrutinizer ignore-type */ $table2Index)) {
Loading history...
256 374
                continue;
257
            }
258
259 383
            $tableDifferences->changedIndexes[$indexName] = $table2Index;
260 383
            $changes++;
261
        }
262
263 3267
        $this->detectIndexRenamings($tableDifferences);
264
265 3267
        $fromFkeys = $table1->getForeignKeys();
266 3267
        $toFkeys   = $table2->getForeignKeys();
267
268 3267
        foreach ($fromFkeys as $key1 => $constraint1) {
269 317
            foreach ($toFkeys as $key2 => $constraint2) {
270 149
                if ($this->diffForeignKey($constraint1, $constraint2) === false) {
271 54
                    unset($fromFkeys[$key1], $toFkeys[$key2]);
272
                } else {
273 95
                    if (strtolower($constraint1->getName()) === strtolower($constraint2->getName())) {
274 48
                        $tableDifferences->changedForeignKeys[] = $constraint2;
275 48
                        $changes++;
276 317
                        unset($fromFkeys[$key1], $toFkeys[$key2]);
277
                    }
278
                }
279
            }
280
        }
281
282 3267
        foreach ($fromFkeys as $constraint1) {
283 215
            $tableDifferences->removedForeignKeys[] = $constraint1;
284 215
            $changes++;
285
        }
286
287 3267
        foreach ($toFkeys as $constraint2) {
288 71
            $tableDifferences->addedForeignKeys[] = $constraint2;
289 71
            $changes++;
290
        }
291
292 3267
        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 3267
    private function detectColumnRenamings(TableDiff $tableDifferences)
302
    {
303 3267
        $renameCandidates = [];
304 3267
        foreach ($tableDifferences->addedColumns as $addedColumnName => $addedColumn) {
305 743
            foreach ($tableDifferences->removedColumns as $removedColumn) {
306 575
                if (count($this->diffColumn($addedColumn, $removedColumn)) !== 0) {
307 456
                    continue;
308
                }
309
310 743
                $renameCandidates[$addedColumn->getName()][] = [$removedColumn, $addedColumn, $addedColumnName];
311
            }
312
        }
313
314 3267
        foreach ($renameCandidates as $candidateColumns) {
315 575
            if (count($candidateColumns) !== 1) {
316 24
                continue;
317
            }
318
319 551
            [$removedColumn, $addedColumn] = $candidateColumns[0];
320 551
            $removedColumnName             = strtolower($removedColumn->getName());
321 551
            $addedColumnName               = strtolower($addedColumn->getName());
322
323 551
            if (isset($tableDifferences->renamedColumns[$removedColumnName])) {
324 24
                continue;
325
            }
326
327 551
            $tableDifferences->renamedColumns[$removedColumnName] = $addedColumn;
328
            unset(
329 551
                $tableDifferences->addedColumns[$addedColumnName],
330 551
                $tableDifferences->removedColumns[$removedColumnName]
331
            );
332
        }
333 3267
    }
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 3267
    private function detectIndexRenamings(TableDiff $tableDifferences)
342
    {
343 3267
        $renameCandidates = [];
344
345
        // Gather possible rename candidates by comparing each added and removed index based on semantics.
346 3267
        foreach ($tableDifferences->addedIndexes as $addedIndexName => $addedIndex) {
347 431
            foreach ($tableDifferences->removedIndexes as $removedIndex) {
348 203
                if ($this->diffIndex($addedIndex, $removedIndex)) {
349 108
                    continue;
350
                }
351
352 431
                $renameCandidates[$addedIndex->getName()][] = [$removedIndex, $addedIndex, $addedIndexName];
353
            }
354
        }
355
356 3267
        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 95
            if (count($candidateIndexes) !== 1) {
362 24
                continue;
363
            }
364
365 71
            [$removedIndex, $addedIndex] = $candidateIndexes[0];
366
367 71
            $removedIndexName = strtolower($removedIndex->getName());
368 71
            $addedIndexName   = strtolower($addedIndex->getName());
369
370 71
            if (isset($tableDifferences->renamedIndexes[$removedIndexName])) {
371
                continue;
372
            }
373
374 71
            $tableDifferences->renamedIndexes[$removedIndexName] = $addedIndex;
375
            unset(
376 71
                $tableDifferences->addedIndexes[$addedIndexName],
377 71
                $tableDifferences->removedIndexes[$removedIndexName]
378
            );
379
        }
380 3267
    }
381
382
    /**
383
     * @return bool
384
     */
385 221
    public function diffForeignKey(ForeignKeyConstraint $key1, ForeignKeyConstraint $key2)
386
    {
387 221
        if (array_map('strtolower', $key1->getUnquotedLocalColumns()) !== array_map('strtolower', $key2->getUnquotedLocalColumns())) {
388 47
            return true;
389
        }
390
391 174
        if (array_map('strtolower', $key1->getUnquotedForeignColumns()) !== array_map('strtolower', $key2->getUnquotedForeignColumns())) {
392
            return true;
393
        }
394
395 174
        if ($key1->getUnqualifiedForeignTableName() !== $key2->getUnqualifiedForeignTableName()) {
396 24
            return true;
397
        }
398
399 150
        if ($key1->onUpdate() !== $key2->onUpdate()) {
400 24
            return true;
401
        }
402
403 126
        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 3675
    public function diffColumn(Column $column1, Column $column2)
415
    {
416 3675
        $properties1 = $column1->toArray();
417 3675
        $properties2 = $column2->toArray();
418
419 3675
        $changedProperties = [];
420
421 3675
        foreach (['type', 'notnull', 'unsigned', 'autoincrement'] as $property) {
422 3675
            if ($properties1[$property] === $properties2[$property]) {
423 3675
                continue;
424
            }
425
426 436
            $changedProperties[] = $property;
427
        }
428
429
        // This is a very nasty hack to make comparator work with the legacy json_array type, which should be killed in v3
430 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

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