ForeignKeys   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 23
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A run() 0 21 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Generator;
6
7
use Cycle\Schema\GeneratorInterface;
8
use Cycle\Schema\Registry;
9
10
final class ForeignKeys implements GeneratorInterface
11
{
12
    public function run(Registry $registry): Registry
13
    {
14
        foreach ($registry as $entity) {
15
            foreach ($entity->getForeignKeys() as $fk) {
16
                $target = $registry->getEntity($fk->getTarget());
17
                $targetSchema = $registry->getTableSchema($target);
18
19
                $pkExists = \array_diff($fk->getOuterColumns(), $targetSchema->getPrimaryKeys()) === [];
20
                if (!$pkExists && !$targetSchema->hasIndex($fk->getOuterColumns())) {
21
                    $targetSchema->index($fk->getOuterColumns())->unique();
22
                }
23
24
                $registry->getTableSchema($entity)
25
                    ->foreignKey($fk->getInnerColumns(), $fk->isCreateIndex())
26
                    ->references($registry->getTable($target), $fk->getOuterColumns())
27
                    ->onUpdate($fk->getAction())
28
                    ->onDelete($fk->getAction());
29
            }
30
        }
31
32
        return $registry;
33
    }
34
}
35