Completed
Branch feature/pre-split (4f3c6e)
by Anton
03:29
created

BelongsToMorphedSchema::declareTables()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 38
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 4
nop 1
dl 0
loc 38
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\ORM\Schemas\Relations;
9
10
use Spiral\ORM\Exceptions\RelationSchemaException;
11
use Spiral\ORM\ORMInterface;
12
use Spiral\ORM\Record;
13
use Spiral\ORM\Schemas\Relations\Traits\MorphedTrait;
14
use Spiral\ORM\Schemas\Relations\Traits\TypecastTrait;
15
use Spiral\ORM\Schemas\SchemaBuilder;
16
17
/**
18
 * BelongsToMorphed are almost identical to BelongsTo except it parent Record defined by role value
19
 * stored in [morph key] and parent key in [inner key].
20
 *
21
 * You can define BelongsToMorphed relation using syntax for BelongsTo but declaring outer class
22
 * as interface, meaning you should not only declare inversed relation name, but also it's type -
23
 * HAS_ONE or HAS_MANY.
24
 *
25
 * Example: 'parent' => [self::BELONGS_TO_MORPHED => 'Records\CommentableInterface']
26
 *
27
 * Attention, be very careful using morphing relations, you must know what you doing!
28
 * Attention #2, relation like that can not be preloaded!
29
 *
30
 * Example, [Comment can belong to any CommentableInterface record], relation name "parent",
31
 * relation requested to be inversed into HAS_MANY "comments":
32
 * - relation will walk should every record implementing CommentableInterface to collect name and
33
 *   type of outer keys, if outer key is not consistent across records implementing this interface
34
 *   an exception will be raised, let's say that outer key is "id" in every record
35
 * - relation will create inner key "parent_id" in "comments" table (or other table name), nullable
36
 *   by default
37
 * - relation will create "parent_type" morph key in "comments" table, nullable by default
38
 * - relation will create complex index index on columns "parent_id" and "parent_type" in
39
 *   "comments" table if allowed
40
 * - due relation is inversable every record implementing CommentableInterface will receive
41
 *   HAS_MANY relation "comments" pointing to Comment record using record role value
42
 *
43
 * @see BelongsToSchema
44
 */
45
class BelongsToMorphedSchema extends AbstractSchema
46
{
47
    use MorphedTrait, TypecastTrait;
48
49
    /**
50
     * Relation type.
51
     */
52
    const RELATION_TYPE = Record::BELONGS_TO_MORPHED;
53
54
    /**
55
     * Size of string column dedicated to store outer role name. Used in polymorphic relations.
56
     * Even simple relations might include morph key (usually such relations created via inversion
57
     * of polymorphic relation).
58
     *
59
     * @see RecordSchema::getRole()
60
     */
61
    const MORPH_COLUMN_SIZE = 32;
62
63
    /**
64
     * Options needed in runtime.
65
     */
66
    const PACK_OPTIONS = [
67
        Record::INNER_KEY,
68
        Record::OUTER_KEY,
69
        Record::MORPH_KEY,
70
        Record::NULLABLE
71
    ];
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    const OPTIONS_TEMPLATE = [
77
        //By default morphed relations points to PRIMARY KEY
78
        Record::OUTER_KEY      => ORMInterface::R_PRIMARY_KEY,
79
80
        //Inner key will be based on singular name of relation and outer key name
81
        Record::INNER_KEY      => '{relation:singular}_id',
82
83
        //Inner key will be based on singular name of relation and outer key name
84
        Record::MORPH_KEY      => '{relation:singular}_type',
85
86
        //Relation allowed to create indexes in inner table
87
        Record::CREATE_INDEXES => true,
88
89
        //We are going to make all relations nullable by default, so we can add fields to existed
90
        //tables without raising an exceptions
91
        Record::NULLABLE       => true,
92
    ];
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public function declareTables(SchemaBuilder $builder): array
98
    {
99
        $sourceTable = $this->sourceTable($builder);
100
101
        if (!interface_exists($target = $this->definition->getTarget())) {
102
            throw new RelationSchemaException("Morphed relations can only be pointed to an interface");
103
        }
104
105
        $outerKey = $this->findOuter($builder);
106
        if (empty($outerKey)) {
107
            throw new RelationSchemaException("Unable to build morphed relation, no outer record found");
108
        }
109
110
        //Make sure all tables has same outer
111
        $this->verifyOuter($builder, $outerKey);
112
113
        //Column to be used as inner key
114
        $innerKey = $sourceTable->column($this->option(Record::INNER_KEY));
115
116
        //Syncing types
117
        $innerKey->setType($this->resolveType($outerKey));
118
119
        //If nullable
120
        $innerKey->nullable($this->option(Record::NULLABLE));
121
122
        //Morph key is always string
123
        $morphKey = $sourceTable->column($this->option(Record::MORPH_KEY));
124
        $morphKey->string(self::MORPH_COLUMN_SIZE);
125
126
        //Do we need indexes?
127
        if ($this->option(Record::CREATE_INDEXES)) {
128
            //Compound outer key
129
            $sourceTable->index([$innerKey->getName(), $morphKey->getName()]);
130
        }
131
132
        //No constrains to create
133
        return [$sourceTable];
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function packRelation(SchemaBuilder $builder): array
140
    {
141
        $schema = parent::packRelation($builder);
142
        $schema[ORMInterface::R_SCHEMA][Record::OUTER_KEY] = $this->findOuter($builder)->getName();
143
144
        foreach ($this->findTargets($builder) as $outer) {
145
            //Role => model mapping
146
            $schema[ORMInterface::R_SCHEMA][ORMInterface::R_ROLE_NAME][$outer->getRole()] = $outer->getClass();
147
        }
148
149
        return $schema;
150
    }
151
}