Completed
Push — master ( 9618b4...df349c )
by Anton
12:53 queued 05:50
created

FieldTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 19
dl 0
loc 50
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A ensureField() 0 27 5
A getField() 0 3 1
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\Traits;
11
12
use Cycle\ORM\Relation;
13
use Cycle\Schema\Definition\Entity;
14
use Cycle\Schema\Definition\Field;
15
use Cycle\Schema\Relation\OptionSchema;
16
use Cycle\Schema\Table\ColumnSchema;
17
18
trait FieldTrait
19
{
20
    /**
21
     * @param Entity $entity
22
     * @param int    $field
23
     * @return Field
24
     */
25
    protected function getField(Entity $entity, int $field): Field
26
    {
27
        return $entity->getFields()->get($this->getOptions()->get($field));
28
    }
29
30
    /**
31
     * @param Entity $target
32
     * @param string $name
33
     * @param Field  $outer
34
     */
35
    protected function ensureField(Entity $target, string $name, Field $outer)
36
    {
37
        if ($target->getFields()->has($name)) {
38
            // field already exists and defined by the user
39
            return;
40
        }
41
42
        $field = new Field();
43
        $field->setColumn($name);
44
        $field->setTypecast($outer->getTypecast());
45
46
        switch ($outer->getType()) {
47
            case 'primary':
48
                $field->setType('int');
49
                break;
50
            case 'bigPrimary':
51
                $field->setType('bigint');
52
                break;
53
            default:
54
                $field->setType($outer->getType());
55
        }
56
57
        if ($this->getOptions()->get(Relation::NULLABLE)) {
58
            $field->getOptions()->set(ColumnSchema::OPT_NULLABLE, true);
59
        }
60
61
        $target->getFields()->set($name, $field);
62
    }
63
64
    /**
65
     * @return OptionSchema
66
     */
67
    abstract protected function getOptions(): OptionSchema;
68
}