Passed
Push — master ( 4cb0ab...7d85ff )
by Anton
01:43
created

HasMany::compute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
namespace Cycle\Schema\Relation;
11
12
use Cycle\ORM\Relation;
13
use Cycle\Schema\Registry;
14
use Cycle\Schema\Relation\Traits\FieldTrait;
15
use Cycle\Schema\Relation\Traits\ForeignKeyTrait;
16
17
class HasMany extends RelationSchema
18
{
19
    use FieldTrait, ForeignKeyTrait;
20
21
    // internal relation type
22
    protected const RELATION_TYPE = Relation::HAS_MANY;
23
24
    // relation schema options
25
    protected const RELATION_SCHEMA = [
26
        // save with parent
27
        Relation::CASCADE              => true,
28
29
        // use outer entity constrain by default
30
        Relation::CONSTRAIN            => true,
31
32
        // not nullable by default
33
        Relation::NULLABLE             => false,
34
35
        // link to parent entity primary key by default
36
        Relation::INNER_KEY            => '{source:primaryKey}',
37
38
        // default field name for inner key
39
        Relation::OUTER_KEY            => '{source:role}_{innerKey}',
40
41
        // rendering options
42
        RelationSchema::INDEX_CREATE   => true,
43
        RelationSchema::FK_CREATE      => true,
44
        RelationSchema::FK_ACTION      => 'CASCADE',
45
        RelationSchema::BIND_INTERFACE => false
46
    ];
47
48
    /**
49
     * @param Registry $registry
50
     */
51
    public function compute(Registry $registry)
52
    {
53
        parent::compute($registry);
54
55
        $source = $registry->getEntity($this->source);
56
        $target = $registry->getEntity($this->target);
57
58
        // create target outer field
59
        $this->ensureField(
60
            $target,
61
            $this->options->get(Relation::OUTER_KEY),
62
            $this->getField($source, Relation::INNER_KEY)
63
        );
64
    }
65
66
    /**
67
     * @param Registry $registry
68
     */
69
    public function render(Registry $registry)
70
    {
71
        $source = $registry->getEntity($this->source);
72
        $target = $registry->getEntity($this->target);
73
74
        $innerField = $this->getField($source, Relation::INNER_KEY);
75
        $outerField = $this->getField($target, Relation::OUTER_KEY);
76
77
        $table = $registry->getTableSchema($target);
78
79
        if ($this->options->get(self::INDEX_CREATE)) {
80
            $table->index([$outerField->getColumn()]);
81
        }
82
83
        if ($this->options->get(self::FK_CREATE)) {
84
            $this->createForeignKey($registry, $source, $target, $innerField, $outerField);
85
        }
86
    }
87
}