Completed
Pull Request — develop (#3518)
by Michael
105:06 queued 40:05
created

Table::addNamedForeignKeyConstraint()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 25
ccs 14
cts 14
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 17654
     * @throws DBALException
59
     */
60
    public function __construct(
61
        $tableName,
62
        array $columns = [],
63
        array $indexes = [],
64
        array $uniqueConstraints = [],
65
        array $fkConstraints = [],
66 17654
        array $options = []
67 1561
    ) {
68
        if (strlen($tableName) === 0) {
69
            throw DBALException::invalidTableName($tableName);
70 17653
        }
71
72 17653
        $this->_setName($tableName);
73 16192
74
        foreach ($columns as $column) {
75
            $this->_addColumn($column);
76 17652
        }
77 16119
78
        foreach ($indexes as $idx) {
79
            $this->_addIndex($idx);
80 17650
        }
81
82
        foreach ($uniqueConstraints as $uniqueConstraint) {
83
            $this->_addUniqueConstraint($uniqueConstraint);
84 17650
        }
85 15348
86
        foreach ($fkConstraints as $fkConstraint) {
87
            $this->_addForeignKeyConstraint($fkConstraint);
88 17650
        }
89 17650
90
        $this->_options = $options;
91
    }
92
93
    /**
94 16674
     * @return void
95
     */
96 16674
    public function setSchemaConfig(SchemaConfig $schemaConfig)
97 16674
    {
98
        $this->_schemaConfig = $schemaConfig;
99
    }
100
101
    /**
102
     * Sets the Primary Key.
103
     *
104
     * @param string[]     $columnNames
105
     * @param string|false $indexName
106
     *
107 17254
     * @return self
108
     */
109 17254
    public function setPrimaryKey(array $columnNames, $indexName = false)
110
    {
111 17254
        $this->_addIndex($this->_createIndex($columnNames, $indexName ?: 'primary', true, true));
112 17254
113 17254
        foreach ($columnNames as $columnName) {
114
            $column = $this->getColumn($columnName);
115
            $column->setNotnull(true);
116 17254
        }
117
118
        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 15724
     * @return self
149
     */
150 15724
    public function addIndex(array $columnNames, $indexName = null, array $flags = [], array $options = [])
151 15322
    {
152 15322
        if ($indexName === null) {
153 15322
            $indexName = $this->_generateIdentifierName(
154 15322
                array_merge([$this->getName()], $columnNames),
155
                'idx',
156
                $this->_getMaxIdentifierLength()
157
            );
158 15724
        }
159
160
        return $this->_addIndex($this->_createIndex($columnNames, $indexName, false, false, $flags, $options));
161
    }
162
163
    /**
164
     * Drops the primary key from this table.
165
     *
166 14581
     * @return void
167
     */
168 14581
    public function dropPrimaryKey()
169 14581
    {
170 14581
        $this->dropIndex($this->_primaryKeyName);
171
        $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
    }
173
174
    /**
175
     * Drops an index from this table.
176
     *
177
     * @param string $indexName The index name.
178
     *
179
     * @return void
180
     *
181 14604
     * @throws SchemaException If the index does not exist.
182
     */
183 14604
    public function dropIndex($indexName)
184
    {
185 14604
        $indexName = $this->normalizeIdentifier($indexName);
186
187
        if (! $this->hasIndex($indexName)) {
188
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
189 14604
        }
190 14604
191
        unset($this->_indexes[$indexName]);
192
    }
193
194
    /**
195
     * @param string[]    $columnNames
196
     * @param string|null $indexName
197
     * @param mixed[]     $options
198
     *
199 16559
     * @return self
200
     */
201 16559
    public function addUniqueIndex(array $columnNames, $indexName = null, array $options = [])
202 16227
    {
203 16227
        if ($indexName === null) {
204 16227
            $indexName = $this->_generateIdentifierName(
205 16227
                array_merge([$this->getName()], $columnNames),
206
                'uniq',
207
                $this->_getMaxIdentifierLength()
208
            );
209 16559
        }
210
211
        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 14401
     *                         or if an index with the given new name already exists on this table.
225
     */
226 14401
    public function renameIndex($oldIndexName, $newIndexName = null)
227 14401
    {
228
        $oldIndexName           = $this->normalizeIdentifier($oldIndexName);
229 14401
        $normalizedNewIndexName = $this->normalizeIdentifier($newIndexName);
230 441
231
        if ($oldIndexName === $normalizedNewIndexName) {
232
            return $this;
233 14401
        }
234 361
235
        if (! $this->hasIndex($oldIndexName)) {
236
            throw SchemaException::indexDoesNotExist($oldIndexName, $this->_name);
237 14400
        }
238 337
239
        if ($this->hasIndex($normalizedNewIndexName)) {
240
            throw SchemaException::indexAlreadyExists($normalizedNewIndexName, $this->_name);
241 14399
        }
242
243 14399
        $oldIndex = $this->_indexes[$oldIndexName];
244 433
245
        if ($oldIndex->isPrimary()) {
246 433
            $this->dropPrimaryKey();
247
248
            return $this->setPrimaryKey($oldIndex->getColumns(), $newIndexName ?? false);
249 14399
        }
250
251 14399
        unset($this->_indexes[$oldIndexName]);
252 434
253
        if ($oldIndex->isUnique()) {
254
            return $this->addUniqueIndex($oldIndex->getColumns(), $newIndexName, $oldIndex->getOptions());
255 14398
        }
256
257
        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 14581
     * @return bool
266
     */
267 14581
    public function columnsAreIndexed(array $columnNames)
268
    {
269 14581
        foreach ($this->getIndexes() as $index) {
270 14581
            /** @var $index Index */
271
            if ($index->spansColumns($columnNames)) {
272
                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 17534
     * @return Column
285
     */
286 17534
    public function addColumn($columnName, $typeName, array $options = [])
287
    {
288 17534
        $column = new Column($columnName, Type::getType($typeName), $options);
289
290 17534
        $this->_addColumn($column);
291
292
        return $column;
293
    }
294
295
    /**
296
     * Change Column Details.
297
     *
298
     * @param string  $columnName
299
     * @param mixed[] $options
300
     *
301
     * @return self
302
     */
303
    public function changeColumn($columnName, array $options)
304
    {
305
        $column = $this->getColumn($columnName);
306
307
        $column->setOptions($options);
308
309
        return $this;
310
    }
311
312
    /**
313
     * Drops a Column from the Table.
314
     *
315
     * @param string $columnName
316
     *
317
     * @return self
318
     */
319
    public function dropColumn($columnName)
320 14833
    {
321
        $columnName = $this->normalizeIdentifier($columnName);
322 14833
323
        unset($this->_columns[$columnName]);
324 14833
325
        return $this;
326 14833
    }
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 1449
     * @param mixed[]      $options
337
     * @param string|null  $name
338 1449
     *
339
     * @return self
340 1449
     */
341
    public function addForeignKeyConstraint($foreignTable, array $localColumnNames, array $foreignColumnNames, array $options = [], $name = null)
342 1449
    {
343
        if (! $name) {
344
            $name = $this->_generateIdentifierName(
345
                array_merge((array) $this->getName(), $localColumnNames),
346
                'fk',
347
                $this->_getMaxIdentifierLength()
348
            );
349
        }
350
351
        if ($foreignTable instanceof Table) {
352
            foreach ($foreignColumnNames as $columnName) {
353
                if (! $foreignTable->hasColumn($columnName)) {
354
                    throw SchemaException::columnDoesNotExist($columnName, $foreignTable->getName());
355
                }
356
            }
357
        }
358 16626
359
        foreach ($localColumnNames as $columnName) {
360 16626
            if (! $this->hasColumn($columnName)) {
361 16580
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
362 16580
            }
363 16580
        }
364 16580
365
        $constraint = new ForeignKeyConstraint(
366
            $localColumnNames,
367
            $foreignTable,
368 16626
            $foreignColumnNames,
369
            $name,
370
            $options
371
        );
372
373
        return $this->_addForeignKeyConstraint($constraint);
374
    }
375
376
    /**
377
     * @param string $name
378
     * @param mixed  $value
379
     *
380
     * @return self
381
     */
382
    public function addOption($name, $value)
383
    {
384
        $this->_options[$name] = $value;
385 10316
386
        return $this;
387 10316
    }
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
    public function hasForeignKey($constraintName)
397
    {
398
        $constraintName = $this->normalizeIdentifier($constraintName);
399
400
        return isset($this->_fkConstraints[$constraintName]);
401
    }
402
403
    /**
404
     * Returns the foreign key constraint with the given name.
405 16627
     *
406
     * @param string $constraintName The constraint name.
407 16627
     *
408 16220
     * @return ForeignKeyConstraint
409 16220
     *
410 1054
     * @throws SchemaException If the foreign key does not exist.
411
     */
412
    public function getForeignKey($constraintName)
413
    {
414
        $constraintName = $this->normalizeIdentifier($constraintName);
415 16626
416 16626
        if (! $this->hasForeignKey($constraintName)) {
417 1122
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
418
        }
419
420
        return $this->_fkConstraints[$constraintName];
421 16625
    }
422 15999
423 89
    /**
424 89
     * Removes the foreign key constraint with the given name.
425 89
     *
426 715
     * @param string $constraintName The constraint name.
427
     *
428
     * @return void
429 16625
     *
430
     * @throws SchemaException
431
     */
432
    public function removeForeignKey($constraintName)
433
    {
434
        $constraintName = $this->normalizeIdentifier($constraintName);
435
436
        if (! $this->hasForeignKey($constraintName)) {
437
            throw SchemaException::foreignKeyDoesNotExist($constraintName, $this->_name);
438 14737
        }
439
440 14737
        unset($this->_fkConstraints[$constraintName]);
441
    }
442 14737
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 14394
        $constraintName = $this->normalizeIdentifier($constraintName);
453
454 14394
        return isset($this->_uniqueConstraints[$constraintName]);
455
    }
456 14394
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 321
        $constraintName = $this->normalizeIdentifier($constraintName);
469
470 321
        if (! $this->hasUniqueConstraint($constraintName)) {
471
            throw SchemaException::uniqueConstraintDoesNotExist($constraintName, $this->_name);
472 321
        }
473
474
        return $this->_uniqueConstraints[$constraintName];
475
    }
476 321
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 322
        $constraintName = $this->normalizeIdentifier($constraintName);
489
490 322
        if (! $this->hasUniqueConstraint($constraintName)) {
491
            throw SchemaException::uniqueConstraintDoesNotExist($constraintName, $this->_name);
492 322
        }
493
494
        unset($this->_uniqueConstraints[$constraintName]);
495
    }
496 322
497 322
    /**
498
     * Returns ordered list of columns (primary keys are first, then foreign keys, then the rest)
499
     *
500
     * @return Column[]
501
     */
502
    public function getColumns()
503
    {
504
        $columns = $this->_columns;
505
        $pkCols  = [];
506
        $fkCols  = [];
507
508
        $primaryKey = $this->getPrimaryKey();
509
510
        if ($primaryKey !== null) {
511
            $pkCols = $primaryKey->getColumns();
512
        }
513
514
        foreach ($this->getForeignKeys() as $fk) {
515
            /** @var ForeignKeyConstraint $fk */
516
            $fkCols = array_merge($fkCols, $fk->getColumns());
517
        }
518
519
        $colNames = array_unique(array_merge($pkCols, $fkCols, array_keys($columns)));
520
521
        uksort($columns, static function ($a, $b) use ($colNames) {
522
            return array_search($a, $colNames) >= array_search($b, $colNames);
523
        });
524
525
        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
    public function hasColumn($columnName)
536
    {
537
        $columnName = $this->normalizeIdentifier($columnName);
538
539
        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
    public function getColumn($columnName)
552
    {
553
        $columnName = $this->normalizeIdentifier($columnName);
554
555
        if (! $this->hasColumn($columnName)) {
556
            throw SchemaException::columnDoesNotExist($columnName, $this->_name);
557
        }
558 17411
559
        return $this->_columns[$columnName];
560 17411
    }
561 17411
562 17411
    /**
563
     * Returns the primary key.
564 17411
     *
565
     * @return Index|null The primary key, or null if this Table has no primary key.
566 17411
     */
567 17173
    public function getPrimaryKey()
568
    {
569
        return $this->hasPrimaryKey()
570 17411
            ? $this->getIndex($this->_primaryKeyName)
571
            : null;
572 16658
    }
573
574
    /**
575 17411
     * Returns the primary key columns.
576
     *
577
     * @return string[]
578 17250
     *
579 17411
     * @throws DBALException
580
     */
581 17411
    public function getPrimaryKeyColumns()
582
    {
583
        $primaryKey = $this->getPrimaryKey();
584
585
        if ($primaryKey === null) {
586
            throw new DBALException('Table ' . $this->getName() . ' has no primary key.');
587
        }
588
589
        return $primaryKey->getColumns();
590
    }
591 17438
592
    /**
593 17438
     * Returns whether this table has a primary key.
594
     *
595 17438
     * @return bool
596
     */
597
    public function hasPrimaryKey()
598
    {
599
        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 17334
     * @return bool
608
     */
609 17334
    public function hasIndex($indexName)
610
    {
611 17334
        $indexName = $this->normalizeIdentifier($indexName);
612 1417
613
        return isset($this->_indexes[$indexName]);
614
    }
615 17333
616
    /**
617
     * Returns the Index with the given name.
618
     *
619
     * @param string $indexName The index name.
620
     *
621
     * @return Index
622
     *
623 17416
     * @throws SchemaException If the index does not exist.
624
     */
625 17416
    public function getIndex($indexName)
626 17178
    {
627 17416
        $indexName = $this->normalizeIdentifier($indexName);
628
629
        if (! $this->hasIndex($indexName)) {
630
            throw SchemaException::indexDoesNotExist($indexName, $this->_name);
631
        }
632
633
        return $this->_indexes[$indexName];
634
    }
635
636
    /**
637 14576
     * @return Index[]
638
     */
639 14576
    public function getIndexes()
640
    {
641 14576
        return $this->_indexes;
642
    }
643
644
    /**
645 14576
     * Returns the unique constraints.
646
     *
647
     * @return UniqueConstraint[]
648
     */
649
    public function getUniqueConstraints()
650
    {
651
        return $this->_uniqueConstraints;
652
    }
653 17419
654
    /**
655 17419
     * Returns the foreign key constraints.
656
     *
657
     * @return ForeignKeyConstraint[]
658
     */
659
    public function getForeignKeys()
660
    {
661
        return $this->_fkConstraints;
662
    }
663
664
    /**
665 17230
     * @param string $name
666
     *
667 17230
     * @return bool
668
     */
669 17230
    public function hasOption($name)
670
    {
671
        return isset($this->_options[$name]);
672
    }
673
674
    /**
675
     * @param string $name
676
     *
677
     * @return mixed
678
     */
679
    public function getOption($name)
680
    {
681 17208
        return $this->_options[$name];
682
    }
683 17208
684
    /**
685 17208
     * @return mixed[]
686 1297
     */
687
    public function getOptions()
688
    {
689 17207
        return $this->_options;
690
    }
691
692
    /**
693
     * @return void
694
     */
695 17398
    public function visit(Visitor $visitor)
696
    {
697 17398
        $visitor->acceptTable($this);
698
699
        foreach ($this->getColumns() as $column) {
700
            $visitor->acceptColumn($this, $column);
701
        }
702
703
        foreach ($this->getIndexes() as $index) {
704
            $visitor->acceptIndex($this, $index);
705 17287
        }
706
707 17287
        foreach ($this->getForeignKeys() as $constraint) {
708
            $visitor->acceptForeignKey($this, $constraint);
709
        }
710
    }
711
712
    /**
713
     * Clone of a Table triggers a deep clone of all affected assets.
714
     *
715 17429
     * @return void
716
     */
717 17429
    public function __clone()
718
    {
719
        foreach ($this->_columns as $k => $column) {
720
            $this->_columns[$k] = clone $column;
721
        }
722
723
        foreach ($this->_indexes as $k => $index) {
724
            $this->_indexes[$k] = clone $index;
725 14676
        }
726
727 14676
        foreach ($this->_fkConstraints as $k => $fk) {
728
            $this->_fkConstraints[$k] = clone $fk;
729
            $this->_fkConstraints[$k]->setLocalTable($this);
730
        }
731
    }
732
733
    /**
734
     * @return int
735 14240
     */
736
    protected function _getMaxIdentifierLength()
737 14240
    {
738
        return $this->_schemaConfig instanceof SchemaConfig
739
            ? $this->_schemaConfig->getMaxIdentifierLength()
740
            : 63;
741
    }
742
743 17301
    /**
744
     * @return void
745 17301
     *
746
     * @throws SchemaException
747
     */
748
    protected function _addColumn(Column $column)
749
    {
750
        $columnName = $column->getName();
751 16453
        $columnName = $this->normalizeIdentifier($columnName);
752
753 16453
        if (isset($this->_columns[$columnName])) {
754
            throw SchemaException::columnAlreadyExists($this->getName(), $columnName);
755 16453
        }
756 16450
757
        $this->_columns[$columnName] = $column;
758
    }
759 16453
760 14908
    /**
761
     * Adds an index to the table.
762
     *
763 16453
     * @return self
764 148
     *
765
     * @throws SchemaException
766 16453
     */
767
    protected function _addIndex(Index $indexCandidate)
768
    {
769
        $indexName               = $indexCandidate->getName();
770
        $indexName               = $this->normalizeIdentifier($indexName);
771
        $replacedImplicitIndexes = [];
772
773 15841
        foreach ($this->implicitIndexes as $name => $implicitIndex) {
774
            if (! $implicitIndex->isFullfilledBy($indexCandidate) || ! isset($this->_indexes[$name])) {
775 15841
                continue;
776 15840
            }
777
778
            $replacedImplicitIndexes[] = $name;
779 15841
        }
780 15829
781
        if ((isset($this->_indexes[$indexName]) && ! in_array($indexName, $replacedImplicitIndexes, true)) ||
782
            ($this->_primaryKeyName !== false && $indexCandidate->isPrimary())
783 15841
        ) {
784 14872
            throw SchemaException::indexAlreadyExists($indexName, $this->_name);
785 14872
        }
786
787 15841
        foreach ($replacedImplicitIndexes as $name) {
788
            unset($this->_indexes[$name], $this->implicitIndexes[$name]);
789
        }
790
791
        if ($indexCandidate->isPrimary()) {
792 16791
            $this->_primaryKeyName = $indexName;
793
        }
794 16791
795 16530
        $this->_indexes[$indexName] = $indexCandidate;
796 16791
797
        return $this;
798
    }
799
800
    /**
801
     * @return self
802
     */
803
    protected function _addUniqueConstraint(UniqueConstraint $constraint)
804 17563
    {
805
        $name = strlen($constraint->getName())
806 17563
            ? $constraint->getName()
807 17563
            : $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 17563
                'fk',
810 1393
                $this->_getMaxIdentifierLength()
811
            );
812
813 17563
        $name = $this->normalizeIdentifier($name);
814 17563
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 17378
            $this->_getMaxIdentifierLength()
824
        );
825 17378
826 17378
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, true, false);
827 17378
828
        foreach ($this->_indexes as $existingIndex) {
829 17378
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
830 13311
                return $this;
831 13307
            }
832
        }
833
834 724
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
835
836
        return $this;
837 17378
    }
838 17378
839
    /**
840 1274
     * @return self
841
     */
842
    protected function _addForeignKeyConstraint(ForeignKeyConstraint $constraint)
843 17378
    {
844 724
        $constraint->setLocalTable($this);
845
846
        $name = strlen($constraint->getName())
847 17378
            ? $constraint->getName()
848 17256
            : $this->_generateIdentifierName(
849
                array_merge((array) $this->getName(), $constraint->getLocalColumns()),
850
                'fk',
851 17378
                $this->_getMaxIdentifierLength()
852
            );
853 17378
854
        $name = $this->normalizeIdentifier($name);
855
856
        $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
        $indexName = $this->_generateIdentifierName(
863
            array_merge([$this->getName()], $constraint->getColumns()),
864
            'idx',
865
            $this->_getMaxIdentifierLength()
866
        );
867
868
        $indexCandidate = $this->_createIndex($constraint->getColumns(), $indexName, false, false);
869
870
        foreach ($this->_indexes as $existingIndex) {
871
            if ($indexCandidate->isFullfilledBy($existingIndex)) {
872
                return $this;
873
            }
874
        }
875
876
        $this->_addIndex($indexCandidate);
877
        $this->implicitIndexes[$this->normalizeIdentifier($indexName)] = $indexCandidate;
878
879
        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
    private function normalizeIdentifier($identifier)
892
    {
893
        if ($identifier === null) {
894
            return '';
895
        }
896
897
        return $this->trimQuotes(strtolower($identifier));
898 16708
    }
899
900 16708
    /**
901
     * @param mixed[] $columns
902 16708
     * @param string  $indexName
903 16629
     * @param mixed[] $flags
904 1795
     * @param mixed[] $options
905 1795
     *
906 1795
     * @return UniqueConstraint
907 16708
     *
908
     * @throws SchemaException
909
     */
910 16708
    private function _createUniqueConstraint(array $columns, $indexName, array $flags = [], array $options = [])
911
    {
912 16708
        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 16708
                $columnName = $index;
919 16708
            } else {
920 16708
                $columnName = $value;
921 16708
            }
922
923
            if (! $this->hasColumn($columnName)) {
924 16708
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
925
            }
926 16708
        }
927 16682
928 15326
        return new UniqueConstraint($indexName, $columns, $flags, $options);
929
    }
930
931
    /**
932 16684
     * @param mixed[]  $columns
933 16684
     * @param string   $indexName
934
     * @param bool     $isUnique
935 16684
     * @param bool     $isPrimary
936
     * @param string[] $flags
937
     * @param mixed[]  $options
938
     *
939
     * @return Index
940
     *
941
     * @throws SchemaException
942
     */
943
    private function _createIndex(array $columns, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
944
    {
945
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
946
            throw SchemaException::indexNameInvalid($indexName);
947 17567
        }
948
949 17567
        foreach ($columns as $index => $value) {
950 433
            if (is_string($index)) {
951
                $columnName = $index;
952
            } else {
953 17567
                $columnName = $value;
954
            }
955
956
            if (! $this->hasColumn($columnName)) {
957
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
958
            }
959
        }
960
961
        return new Index($indexName, $columns, $isUnique, $isPrimary, $flags, $options);
962
    }
963
}
964