Passed
Push — drop-deprecated ( db0b1f )
by Michael
27:00
created

Table::addNamedForeignKeyConstraint()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 25
ccs 12
cts 12
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 7
nop 5
crap 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A Table::getForeignKey() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\Schema\Visitor\Visitor;
9
use Doctrine\DBAL\Types\Type;
10
use function array_keys;
11
use function array_merge;
12
use function array_search;
13
use function array_unique;
14
use function in_array;
15
use function is_string;
16
use function preg_match;
17
use function strlen;
18
use function strtolower;
19
use function uksort;
20
21
/**
22
 * Object Representation of a table.
23
 */
24
class Table extends AbstractAsset
25
{
26
    /** @var Column[] */
27
    protected $_columns = [];
28
29
    /** @var Index[] */
30
    private $implicitIndexes = [];
31
32
    /** @var Index[] */
33
    protected $_indexes = [];
34
35
    /** @var string */
36
    protected $_primaryKeyName = false;
37
38
    /** @var UniqueConstraint[] */
39
    protected $_uniqueConstraints = [];
40
41
    /** @var ForeignKeyConstraint[] */
42
    protected $_fkConstraints = [];
43
44
    /** @var mixed[] */
45
    protected $_options = [];
46
47
    /** @var SchemaConfig|null */
48
    protected $_schemaConfig = null;
49
50
    /**
51
     * @param string                 $tableName
52
     * @param Column[]               $columns
53
     * @param Index[]                $indexes
54
     * @param UniqueConstraint[]     $uniqueConstraints
55
     * @param ForeignKeyConstraint[] $fkConstraints
56
     * @param mixed[]                $options
57
     *
58
     * @throws DBALException
59
     */
60 16872
    public function __construct(
61
        $tableName,
62
        array $columns = [],
63
        array $indexes = [],
64
        array $uniqueConstraints = [],
65
        array $fkConstraints = [],
66
        array $options = []
67
    ) {
68 16872
        if (strlen($tableName) === 0) {
69 1536
            throw DBALException::invalidTableName($tableName);
70
        }
71
72 16872
        $this->_setName($tableName);
73
74 16872
        foreach ($columns as $column) {
75 16024
            $this->_addColumn($column);
76
        }
77
78 16872
        foreach ($indexes as $idx) {
79 15993
            $this->_addIndex($idx);
80
        }
81
82 16872
        foreach ($uniqueConstraints as $uniqueConstraint) {
83
            $this->_addUniqueConstraint($uniqueConstraint);
84
        }
85
86 16872
        foreach ($fkConstraints as $fkConstraint) {
87 15234
            $this->_addForeignKeyConstraint($fkConstraint);
88
        }
89
90 16872
        $this->_options = $options;
91 16872
    }
92
93
    /**
94
     * @return void
95
     */
96 16504
    public function setSchemaConfig(SchemaConfig $schemaConfig)
97
    {
98 16504
        $this->_schemaConfig = $schemaConfig;
99 16504
    }
100
101
    /**
102
     * Sets the Primary Key.
103
     *
104
     * @param string[]     $columnNames
105
     * @param string|false $indexName
106
     *
107
     * @return self
108
     */
109 16872
    public function setPrimaryKey(array $columnNames, $indexName = false)
110
    {
111 16872
        $this->_addIndex($this->_createIndex($columnNames, $indexName ?: 'primary', true, true));
112
113 16872
        foreach ($columnNames as $columnName) {
114 16872
            $column = $this->getColumn($columnName);
115 16872
            $column->setNotnull(true);
116
        }
117
118 16872
        return $this;
119
    }
120
121
    /**
122
     * @param mixed[]     $columnNames
123
     * @param string|null $indexName
124
     * @param string[]    $flags
125
     * @param mixed[]     $options
126
     *
127
     * @return self
128
     */
129
    public function addUniqueConstraint(array $columnNames, $indexName = null, array $flags = [], array $options = [])
130
    {
131
        if ($indexName === null) {
132
            $indexName = $this->_generateIdentifierName(
133
                array_merge([$this->getName()], $columnNames),
134
                'uniq',
135
                $this->_getMaxIdentifierLength()
136
            );
137
        }
138
139
        return $this->_addUniqueConstraint($this->_createUniqueConstraint($columnNames, $indexName, $flags, $options));
140
    }
141
142
    /**
143
     * @param string[]    $columnNames
144
     * @param string|null $indexName
145
     * @param string[]    $flags
146
     * @param mixed[]     $options
147
     *
148
     * @return self
149
     */
150 15540
    public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = [])
151
    {
152 15540
        if ($indexName === null) {
153 15207
            $indexName = $this->_generateIdentifierName(
154 15207
                array_merge([$this->getName()], $columnNames),
155 15207
                'idx',
156 15207
                $this->_getMaxIdentifierLength()
157
            );
158
        }
159
160 15540
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
161
    }
162
163
    /**
164
     * Drops the primary key from this table.
165
     *
166
     * @return void
167
     */
168 14490
    public function dropPrimaryKey()
169
    {
170 14490
        $this->dropIndex($this->_primaryKeyName);
171 14490
        $this->_primaryKeyName = false;
0 ignored issues
show
Documentation Bug introduced by
The property $_primaryKeyName was declared of type string, but false is of type false. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
172 14490
    }
173
174
    /**
175
     * Drops an index from this table.
176
     *
177
     * @param string $indexName The index name.
178
     *
179
     * @return void
180
     *
181
     * @throws SchemaException If the index does not exist.
182
     */
183 14500
    public function dropIndex($indexName)
184
    {
185 14500
        $indexName = $this->normalizeIdentifier($indexName);
186
187 14500
        if (! $this->hasIndex($indexName)) {
188
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
189
        }
190
191 14500
        unset($this->_indexes[$indexName]);
192 14500
    }
193
194
    /**
195
     * @param string[]    $columnNames
196
     * @param string|null $indexName
197
     * @param mixed[]     $options
198
     *
199
     * @return self
200
     */
201 16429
    public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
202
    {
203 16429
        if ($indexName === null) {
204 16111
            $indexName = $this->_generateIdentifierName(
205 16111
                array_merge([$this->getName()], $columnNames),
206 16111
                'uniq',
207 16111
                $this->_getMaxIdentifierLength()
208
            );
209
        }
210
211 16429
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, true, false, [], $options));
212
    }
213
214
    /**
215
     * Renames an index.
216
     *
217
     * @param string      $oldIndexName The name of the index to rename from.
218
     * @param string|null $newIndexName The name of the index to rename to.
219
     *                                  If null is given, the index name will be auto-generated.
220
     *
221
     * @return self This table instance.
222
     *
223
     * @throws SchemaException If no index exists for the given current name
224
     *                         or if an index with the given new name already exists on this table.
225
     */
226 14292
    public function renameIndex($oldIndexName, $newIndexName = null)
227
    {
228 14292
        $oldIndexName           = $this->normalizeIdentifier($oldIndexName);
229 14292
        $normalizedNewIndexName = $this->normalizeIdentifier($newIndexName);
230
231 14292
        if ($oldIndexName === $normalizedNewIndexName) {
232 432
            return $this;
233
        }
234
235 14292
        if (! $this->hasIndex($oldIndexName)) {
236 360
            throw SchemaException::indexDoesNotExist($oldIndexName, $this->_name);
237
        }
238
239 14292
        if ($this->hasIndex($normalizedNewIndexName)) {
240 336
            throw SchemaException::indexAlreadyExists($normalizedNewIndexName, $this->_name);
241
        }
242
243 14292
        $oldIndex = $this->_indexes[$oldIndexName];
244
245 14292
        if ($oldIndex->isPrimary()) {
246 432
            $this->dropPrimaryKey();
247
248 432
            return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName ?? false);
249
        }
250
251 14292
        unset($this->_indexes[$oldIndexName]);
252
253 14292
        if ($oldIndex->isUnique()) {
254 432
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
255
        }
256
257 14292
        return $this->addIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getFlags(), $oldIndex->getOptions());
258
    }
259
260
    /**
261
     * Checks if an index begins in the order of the given columns.
262
     *
263
     * @param string[] $columnNames
264
     *
265
     * @return bool
266
     */
267 14483
    public function columnsAreIndexed(array $columnNames)
268
    {
269 14483
        foreach ($this->getIndexes() as $index) {
270
            /** @var $index Index */
271 14483
            if ($index->spansColumns($columnNames)) {
272 14483
                return true;
273
            }
274
        }
275
276
        return false;
277
    }
278
279
    /**
280
     * @param string  $columnName
281
     * @param string  $typeName
282
     * @param mixed[] $options
283
     *
284
     * @return Column
285
     */
286 16872
    public function addColumn($columnName, $typeName, array $options = [])
287
    {
288 16872
        $column = new Column($columnName, Type::getType($typeName), $options);
289
290 16872
        $this->_addColumn($column);
291
292 16872
        return $column;
293
    }
294
295
    /**
296
     * Change Column Details.
297
     *
298
     * @param string  $columnName
299
     * @param mixed[] $options
300
     *
301
     * @return self
302
     */
303 14723
    public function changeColumn($columnName, array $options)
304
    {
305 14723
        $column = $this->getColumn($columnName);
306
307 14723
        $column->setOptions($options);
308
309 14723
        return $this;
310
    }
311
312
    /**
313
     * Drops a Column from the Table.
314
     *
315
     * @param string $columnName
316
     *
317
     * @return self
318
     */
319 1416
    public function dropColumn($columnName)
320
    {
321 1416
        $columnName = $this->normalizeIdentifier($columnName);
322
323 1416
        unset($this->_columns[$columnName]);
324
325 1416
        return $this;
326
    }
327
328
    /**
329
     * Adds a foreign key constraint.
330
     *
331
     * Name is inferred from the local columns.
332
     *
333
     * @param Table|string $foreignTable       Table schema instance or table name
334
     * @param string[]     $localColumnNames
335
     * @param string[]     $foreignColumnNames
336
     * @param mixed[]      $options
337
     * @param string|null  $name
338
     *
339
     * @return self
340
     */
341 16434
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $name = null)
342
    {
343 16434
        if (! $name) {
344 16434
            $name = $this->_generateIdentifierName(
345 16434
                array_merge((array) $this->getName(), $localColumnNames),
346 16434
                'fk',
347 16434
                $this->_getMaxIdentifierLength()
348
            );
349
        }
350
351 16434
        if ($foreignTable instanceof Table) {
352 16077
            foreach ($foreignColumnNames as $columnName) {
353 16077
                if (! $foreignTable->hasColumn($columnName)) {
354 984
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
355
                }
356
            }
357
        }
358
359 16434
        foreach ($localColumnNames as $columnName) {
360 16434
            if (! $this->hasColumn($columnName)) {
361 1008
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
362
            }
363
        }
364
365 16434
        $constraint = new ForeignKeyConstraint(
366 15807
            $localColumnNames,
367
            $foreignTable,
368
            $foreignColumnNames,
369
            $name,
370 627
            $options
371
        );
372
373 16434
        return $this->_addForeignKeyConstraint($constraint);
374
    }
375
376
    /**
377
     * @param string $name
378
     * @param mixed  $value
379
     *
380
     * @return self
381
     */
382 14636
    public function addOption($name, $value)
383
    {
384 14636
        $this->_options[$name] = $value;
385
386 14636
        return $this;
387
    }
388
389
    /**
390
     * Returns whether this table has a foreign key constraint with the given name.
391
     *
392
     * @param string $constraintName
393
     *
394
     * @return bool
395
     */
396 14287
    public function hasForeignKey($constraintName)
397
    {
398 14287
        $constraintName = $this->normalizeIdentifier($constraintName);
399
400 14287
        return isset($this->_fkConstraints[$constraintName]);
401
    }
402
403
    /**
404
     * Returns the foreign key constraint with the given name.
405
     *
406
     * @param string $constraintName The constraint name.
407
     *
408
     * @return ForeignKeyConstraint
409
     *
410
     * @throws SchemaException If the foreign key does not exist.
411
     */
412 312
    public function getForeignKey($constraintName)
413
    {
414 312
        $constraintName = $this->normalizeIdentifier($constraintName);
415
416 312
        if (! $this->hasForeignKey($constraintName)) {
417
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
418
        }
419
420 312
        return $this->_fkConstraints[$constraintName];
421
    }
422
423
    /**
424
     * Removes the foreign key constraint with the given name.
425
     *
426
     * @param string $constraintName The constraint name.
427
     *
428
     * @return void
429
     *
430
     * @throws SchemaException
431
     */
432 312
    public function removeForeignKey($constraintName)
433
    {
434 312
        $constraintName = $this->normalizeIdentifier($constraintName);
435
436 312
        if (! $this->hasForeignKey($constraintName)) {
437
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
438
        }
439
440 312
        unset($this->_fkConstraints[$constraintName]);
441 312
    }
442
443
    /**
444
     * Returns whether this table has a unique constraint with the given name.
445
     *
446
     * @param string $constraintName
447
     *
448
     * @return bool
449
     */
450
    public function hasUniqueConstraint($constraintName)
451
    {
452
        $constraintName = $this->normalizeIdentifier($constraintName);
453
454
        return isset($this->_uniqueConstraints[$constraintName]);
455
    }
456
457
    /**
458
     * Returns the unique constraint with the given name.
459
     *
460
     * @param string $constraintName The constraint name.
461
     *
462
     * @return UniqueConstraint
463
     *
464
     * @throws SchemaException If the foreign key does not exist.
465
     */
466
    public function getUniqueConstraint($constraintName)
467
    {
468
        $constraintName = $this->normalizeIdentifier($constraintName);
469
470
        if (! $this->hasUniqueConstraint($constraintName)) {
471
            throw SchemaException::uniqueConstraintDoesNotExist($constraintName, $this->_name);
472
        }
473
474
        return $this->_uniqueConstraints[$constraintName];
475
    }
476
477
    /**
478
     * Removes the unique constraint with the given name.
479
     *
480
     * @param string $constraintName The constraint name.
481
     *
482
     * @return void
483
     *
484
     * @throws SchemaException
485
     */
486
    public function removeUniqueConstraint($constraintName)
487
    {
488
        $constraintName = $this->normalizeIdentifier($constraintName);
489
490
        if (! $this->hasUniqueConstraint($constraintName)) {
491
            throw SchemaException::uniqueConstraintDoesNotExist($constraintName, $this->_name);
492
        }
493
494
        unset($this->_uniqueConstraints[$constraintName]);
495
    }
496
497
    /**
498
     * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
499
     *
500
     * @return Column[]
501
     */
502 16872
    public function getColumns()
503
    {
504 16872
        $columns = $this->_columns;
505 16872
        $pkCols  = [];
506 16872
        $fkCols  = [];
507
508 16872
        $primaryKey = $this->getPrimaryKey();
509
510 16872
        if ($primaryKey !== null) {
511 16872
            $pkCols = $primaryKey->getColumns();
512
        }
513
514 16872
        foreach ($this->getForeignKeys() as $fk) {
515
            /** @var ForeignKeyConstraint $fk */
516 16511
            $fkCols = array_merge($fkCols, $fk->getColumns());
517
        }
518
519 16872
        $colNames = array_unique(array_merge($pkCols, $fkCols, array_keys($columns)));
520
521
        uksort($columns, static function ($a, $b) use ($colNames) {
522 16872
            return array_search($a, $colNames) >= array_search($b, $colNames);
523 16872
        });
524
525 16872
        return $columns;
526
    }
527
528
    /**
529
     * Returns whether this table has a Column with the given name.
530
     *
531
     * @param string $columnName The column name.
532
     *
533
     * @return bool
534
     */
535 16872
    public function hasColumn($columnName)
536
    {
537 16872
        $columnName = $this->normalizeIdentifier($columnName);
538
539 16872
        return isset($this->_columns[$columnName]);
540
    }
541
542
    /**
543
     * Returns the Column with the given name.
544
     *
545
     * @param string $columnName The column name.
546
     *
547
     * @return Column
548
     *
549
     * @throws SchemaException If the column does not exist.
550
     */
551 16872
    public function getColumn($columnName)
552
    {
553 16872
        $columnName = $this->normalizeIdentifier($columnName);
554
555 16872
        if (! $this->hasColumn($columnName)) {
556 1392
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
557
        }
558
559 16872
        return $this->_columns[$columnName];
560
    }
561
562
    /**
563
     * Returns the primary key.
564
     *
565
     * @return Index|null The primary key, or null if this Table has no primary key.
566
     */
567 16872
    public function getPrimaryKey()
568
    {
569 16872
        return $this->hasPrimaryKey()
570 16872
            ? $this->getIndex($this->_primaryKeyName)
571 16872
            : null;
572
    }
573
574
    /**
575
     * Returns the primary key columns.
576
     *
577
     * @return string[]
578
     *
579
     * @throws DBALException
580
     */
581 14490
    public function getPrimaryKeyColumns()
582
    {
583 14490
        $primaryKey = $this->getPrimaryKey();
584
585 14490
        if ($primaryKey === null) {
586
            throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
587
        }
588
589 14490
        return $primaryKey->getColumns();
590
    }
591
592
    /**
593
     * Returns whether this table has a primary key.
594
     *
595
     * @return bool
596
     */
597 16872
    public function hasPrimaryKey()
598
    {
599 16872
        return $this->_primaryKeyName && $this->hasIndex($this->_primaryKeyName);
600
    }
601
602
    /**
603
     * Returns whether this table has an Index with the given name.
604
     *
605
     * @param string $indexName The index name.
606
     *
607
     * @return bool
608
     */
609 16872
    public function hasIndex($indexName)
610
    {
611 16872
        $indexName = $this->normalizeIdentifier($indexName);
612
613 16872
        return isset($this->_indexes[$indexName]);
614
    }
615
616
    /**
617
     * Returns the Index with the given name.
618
     *
619
     * @param string $indexName The index name.
620
     *
621
     * @return Index
622
     *
623
     * @throws SchemaException If the index does not exist.
624
     */
625 16872
    public function getIndex($indexName)
626
    {
627 16872
        $indexName = $this->normalizeIdentifier($indexName);
628
629 16872
        if (! $this->hasIndex($indexName)) {
630 1272
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
631
        }
632
633 16872
        return $this->_indexes[$indexName];
634
    }
635
636
    /**
637
     * @return Index[]
638
     */
639 16872
    public function getIndexes()
640
    {
641 16872
        return $this->_indexes;
642
    }
643
644
    /**
645
     * Returns the unique constraints.
646
     *
647
     * @return UniqueConstraint[]
648
     */
649 16872
    public function getUniqueConstraints()
650
    {
651 16872
        return $this->_uniqueConstraints;
652
    }
653
654
    /**
655
     * Returns the foreign key constraints.
656
     *
657
     * @return ForeignKeyConstraint[]
658
     */
659 16872
    public function getForeignKeys()
660
    {
661 16872
        return $this->_fkConstraints;
662
    }
663
664
    /**
665
     * @param string $name
666
     *
667
     * @return bool
668
     */
669 14530
    public function hasOption($name)
670
    {
671 14530
        return isset($this->_options[$name]);
672
    }
673
674
    /**
675
     * @param string $name
676
     *
677
     * @return mixed
678
     */
679 14162
    public function getOption($name)
680
    {
681 14162
        return $this->_options[$name];
682
    }
683
684
    /**
685
     * @return mixed[]
686
     */
687 16872
    public function getOptions()
688
    {
689 16872
        return $this->_options;
690
    }
691
692
    /**
693
     * @return void
694
     */
695 16334
    public function visit(Visitor $visitor)
696
    {
697 16334
        $visitor->acceptTable($this);
698
699 16334
        foreach ($this->getColumns() as $column) {
700 16334
            $visitor->acceptColumn($this, $column);
701
        }
702
703 16334
        foreach ($this->getIndexes() as $index) {
704 14797
            $visitor->acceptIndex($this, $index);
705
        }
706
707 16334
        foreach ($this->getForeignKeys() as $constraint) {
708 144
            $visitor->acceptForeignKey($this, $constraint);
709
        }
710 16334
    }
711
712
    /**
713
     * Clone of a Table triggers a deep clone of all affected assets.
714
     *
715
     * @return void
716
     */
717 15697
    public function __clone()
718
    {
719 15697
        foreach ($this->_columns as $k => $column) {
720 15697
            $this->_columns[$k] = clone $column;
721
        }
722
723 15697
        foreach ($this->_indexes as $k => $index) {
724 15697
            $this->_indexes[$k] = clone $index;
725
        }
726
727 15697
        foreach ($this->_fkConstraints as $k => $fk) {
728 14768
            $this->_fkConstraints[$k] = clone $fk;
729 14768
            $this->_fkConstraints[$k]->setLocalTable($this);
730
        }
731 15697
    }
732
733
    /**
734
     * @return int
735
     */
736 16557
    protected function _getMaxIdentifierLength()
737
    {
738 16557
        return $this->_schemaConfig instanceof SchemaConfig
739 16417
            ? $this->_schemaConfig->getMaxIdentifierLength()
740 16557
            : 63;
741
    }
742
743
    /**
744
     * @return void
745
     *
746
     * @throws SchemaException
747
     */
748 16872
    protected function _addColumn(Column $column)
749
    {
750 16872
        $columnName = $column->getName();
751 16872
        $columnName = $this->normalizeIdentifier($columnName);
752
753 16872
        if (isset($this->_columns[$columnName])) {
754 1368
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
755
        }
756
757 16872
        $this->_columns[$columnName] = $column;
758 16872
    }
759
760
    /**
761
     * Adds an index to the table.
762
     *
763
     * @return self
764
     *
765
     * @throws SchemaException
766
     */
767 16872
    protected function _addIndex(Index $indexCandidate)
768
    {
769 16872
        $indexName               = $indexCandidate->getName();
770 16872
        $indexName               = $this->normalizeIdentifier($indexName);
771 16872
        $replacedImplicitIndexes = [];
772
773 16872
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
774 13234
            if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
775 13234
                continue;
776
            }
777
778 696
            $replacedImplicitIndexes[] = $name;
779
        }
780
781 16872
        if ((isset($this->_indexes[$indexName]) && ! in_array($indexName, $replacedImplicitIndexes, true)) ||
782 16872
            ($this->_primaryKeyName !== false && $indexCandidate->isPrimary())
783
        ) {
784 1248
            throw SchemaException::indexAlreadyExists($indexName, $this->_name);
785
        }
786
787 16872
        foreach ($replacedImplicitIndexes as $name) {
788 696
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
789
        }
790
791 16872
        if ($indexCandidate->isPrimary()) {
792 16872
            $this->_primaryKeyName = $indexName;
793
        }
794
795 16872
        $this->_indexes[$indexName] = $indexCandidate;
796
797 16872
        return $this;
798
    }
799
800
    /**
801
     * @return self
802
     */
803
    protected function _addUniqueConstraint(UniqueConstraint $constraint)
804
    {
805
        $name = strlen($constraint->getName())
806
            ? $constraint->getName()
807
            : $this->_generateIdentifierName(
808
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
0 ignored issues
show
Bug introduced by
The method getLocalColumns() does not exist on Doctrine\DBAL\Schema\UniqueConstraint. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

808
                array_merge((array) $this->getName(), $constraint->/** @scrutinizer ignore-call */ getLocalColumns()),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
809
                'fk',
810
                $this->_getMaxIdentifierLength()
811
            );
812
813
        $name = $this->normalizeIdentifier($name);
814
815
        $this->_uniqueConstraints[$name] = $constraint;
816
817
        // If there is already an index that fulfills this requirements drop the request. In the case of __construct
818
        // calling this method during hydration from schema-details all the explicitly added indexes lead to duplicates.
819
        // This creates computation overhead in this case, however no duplicate indexes are ever added (column based).
820
        $indexName = $this->_generateIdentifierName(
821
            array_merge([$this->getName()], $constraint->getColumns()),
822
            'idx',
823
            $this->_getMaxIdentifierLength()
824
        );
825
826
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, true, false);
827
828
        foreach ($this->_indexes as $existingIndex) {
829
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
830
                return $this;
831
            }
832
        }
833
834
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
835
836
        return $this;
837
    }
838
839
    /**
840
     * @return self
841
     */
842 16511
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
843
    {
844 16511
        $constraint->setLocalTable($this);
845
846 16511
        $name = strlen($constraint->getName())
847 16434
            ? $constraint->getName()
848 1769
            : $this->_generateIdentifierName(
849 1769
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
850 1769
                'fk',
851 16511
                $this->_getMaxIdentifierLength()
852
            );
853
854 16511
        $name = $this->normalizeIdentifier($name);
855
856 16511
        $this->_fkConstraints[$name] = $constraint;
857
858
        // add an explicit index on the foreign key columns.
859
        // If there is already an index that fulfills this requirements drop the request. In the case of __construct
860
        // calling this method during hydration from schema-details all the explicitly added indexes lead to duplicates.
861
        // This creates computation overhead in this case, however no duplicate indexes are ever added (column based).
862 16511
        $indexName = $this->_generateIdentifierName(
863 16511
            array_merge([$this->getName()], $constraint->getColumns()),
864 16511
            'idx',
865 16511
            $this->_getMaxIdentifierLength()
866
        );
867
868 16511
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);
869
870 16511
        foreach ($this->_indexes as $existingIndex) {
871 16511
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
872 15157
                return $this;
873
            }
874
        }
875
876 16511
        $this->_addIndex($indexCandidate);
877 16511
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
878
879 16511
        return $this;
880
    }
881
882
    /**
883
     * Normalizes a given identifier.
884
     *
885
     * Trims quotes and lowercases the given identifier.
886
     *
887
     * @param string|null $identifier The identifier to normalize.
888
     *
889
     * @return string The normalized identifier.
890
     */
891 16872
    private function normalizeIdentifier($identifier)
892
    {
893 16872
        if ($identifier === null) {
894 432
            return '';
895
        }
896
897 16872
        return $this->trimQuotes(strtolower($identifier));
898
    }
899
900
    /**
901
     * @param mixed[] $columns
902
     * @param string  $indexName
903
     * @param mixed[] $flags
904
     * @param mixed[] $options
905
     *
906
     * @return UniqueConstraint
907
     *
908
     * @throws SchemaException
909
     */
910
    private function _createUniqueConstraint(array $columns, $indexName, array $flags = [], array $options = [])
911
    {
912
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
913
            throw SchemaException::indexNameInvalid($indexName);
914
        }
915
916
        foreach ($columns as $index => $value) {
917
            if (is_string($index)) {
918
                $columnName = $index;
919
            } else {
920
                $columnName = $value;
921
            }
922
923
            if (! $this->hasColumn($columnName)) {
924
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
925
            }
926
        }
927
928
        return new UniqueConstraint($indexName, $columns, $flags, $options);
929
    }
930
931
    /**
932
     * @param mixed[]  $columns
933
     * @param string   $indexName
934
     * @param bool     $isUnique
935
     * @param bool     $isPrimary
936
     * @param string[] $flags
937
     * @param mixed[]  $options
938
     *
939
     * @return Index
940
     *
941
     * @throws SchemaException
942
     */
943 16872
    private function _createIndex(array $columns, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
944
    {
945 16872
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
946 1080
            throw SchemaException::indexNameInvalid($indexName);
947
        }
948
949 16872
        foreach ($columns as $index => $value) {
950 16872
            if (is_string($index)) {
951
                $columnName = $index;
952
            } else {
953 16872
                $columnName = $value;
954
            }
955
956 16872
            if (! $this->hasColumn($columnName)) {
957 1056
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
958
            }
959
        }
960
961 16872
        return new Index($indexName, $columns, $isUnique, $isPrimary, $flags, $options);
962
    }
963
}
964