Passed
Pull Request — 2.x (#66)
by Maxim
15:09
created

Embedded::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Relation;
6
7
use Cycle\ORM\Relation;
8
use Cycle\Schema\Exception\FieldException\EmbeddedPrimaryKeyException;
9
use Cycle\Schema\Registry;
10
use Cycle\Schema\Relation\Traits\ForeignKeyTrait;
11
12
final class Embedded extends RelationSchema
13
{
14
    use ForeignKeyTrait;
15
16
    // internal relation type
17
    protected const RELATION_TYPE = Relation::EMBEDDED;
18
19
    // relation schema options
20
    protected const RELATION_SCHEMA = [
21
        Relation::LOAD => Relation::LOAD_EAGER,
22
        self::EMBEDDED_PREFIX => '',
23
    ];
24
25
    /**
26
     * @param Registry $registry
27
     */
28 56
    public function compute(Registry $registry): void
29
    {
30 56
        $source = $registry->getEntity($this->source);
31 56
        $target = $registry->getEntity($this->target);
32
33
        $targetRole = $target->getRole();
34 56
        $sourceRole = $source->getRole();
35 56
        \assert($targetRole !== null && $sourceRole !== null);
36
37
        // each embedded entity must isolated
38 56
        $target = clone $target;
39 56
        $target->setRole($sourceRole . ':' . $targetRole . ':' . $this->name);
40
        $targetRole = $target->getRole();
41
        \assert($targetRole !== null);
42 56
43
        // embedded entity must point to the same table as parent entity
44 56
        $registry->register($target);
45
        $registry->linkTable($target, $registry->getDatabase($source), $registry->getTable($source));
46 56
47 56
        // isolated
48
        $this->target = $targetRole;
49
50 56
        $prefix = $this->getOptions()->get(self::EMBEDDED_PREFIX);
51 56
        assert(\is_string($prefix));
52
        foreach ($target->getFields() as $field) {
53 48
            /** @var non-empty-string $columnName */
54 8
            $columnName = $prefix . $field->getColumn();
55
            $field->setColumn($columnName);
56 40
        }
57
58
        foreach ($source->getFields() as $name => $field) {
59
            if ($field->isPrimary()) {
60 48
                // sync primary keys
61 40
                if ($target->getFields()->has($name)) {
62
                    throw new EmbeddedPrimaryKeyException($target, $name);
63
                }
64
                $target->getFields()->set($name, $field);
65
            }
66 16
        }
67
68
        parent::compute($registry);
69 16
    }
70
71
    /**
72
     * @param Registry $registry
73
     */
74
    public function render(Registry $registry): void
75
    {
76
        // relation does not require any column rendering besides actual tables
77
    }
78
}
79