ForeignKeyTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 52.94%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 48
ccs 9
cts 17
cp 0.5294
rs 10
c 3
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createForeignCompositeKey() 0 18 2
A createForeignKey() 0 16 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Relation\Traits;
6
7
use Cycle\Schema\Definition\Entity;
8
use Cycle\Schema\Definition\Field;
9
use Cycle\Schema\Definition\Map\FieldMap;
10
use Cycle\Schema\Registry;
11
use Cycle\Schema\Relation\OptionSchema;
12
use Cycle\Schema\Relation\RelationSchema;
13
14
trait ForeignKeyTrait
15
{
16
    /**
17
     * Create foreign key between two entities. Only when both entities are located in a same database.
18
     */
19
    final protected function createForeignKey(
20
        Registry $registry,
21
        Entity $source,
22
        Entity $target,
23
        Field $innerField,
24
        Field $outerField,
25
        bool $indexCreate = true,
26
    ): void {
27
        if ($registry->getDatabase($source) !== $registry->getDatabase($target)) {
28
            return;
29
        }
30
31
        $outerFields = (new FieldMap())->set($outerField->getColumn(), $outerField);
32
        $innerFields = (new FieldMap())->set($innerField->getColumn(), $innerField);
33
34
        $this->createForeignCompositeKey($registry, $source, $target, $outerFields, $innerFields, $indexCreate);
35
    }
36
37
    /**
38
     * Create foreign key between two entities with composite fields. Only when both entities are located
39
     * in a same database.
40 136
     */
41
    final protected function createForeignCompositeKey(
42
        Registry $registry,
43
        Entity $source,
44
        Entity $target,
45
        FieldMap $innerFields,
46
        FieldMap $outerFields,
47 136
        bool $indexCreate = true,
48
    ): void {
49
        if ($registry->getDatabase($source) !== $registry->getDatabase($target)) {
50
            return;
51 136
        }
52 136
53 136
        $fkAction = $this->getOptions()->get(RelationSchema::FK_ACTION);
54 136
        $registry->getTableSchema($target)
55 136
            ->foreignKey($outerFields->getColumnNames(), $indexCreate)
56 136
            ->references($registry->getTable($source), $innerFields->getColumnNames())
57 136
            ->onUpdate($fkAction)
58
            ->onDelete($this->getOptions()->get(RelationSchema::FK_ON_DELETE) ?? $fkAction);
59
    }
60
61
    abstract protected function getOptions(): OptionSchema;
62
}
63