Completed
Push — master ( 897398...958eef )
by Anton
02:56 queued 01:16
created

FieldTrait::createField()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 6
nop 3
dl 0
loc 22
rs 9.7666
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\Traits;
11
12
use Cycle\ORM\Relation;
13
use Cycle\Schema\Definition\Entity;
14
use Cycle\Schema\Definition\Field;
15
use Cycle\Schema\Generator\Table\ColumnSchema;
16
use Cycle\Schema\Relation\Util\OptionSchema;
17
18
trait FieldTrait
19
{
20
    /**
21
     * @param Entity $entity
22
     * @param int    $field
23
     * @return bool
24
     */
25
    protected function hasField(Entity $entity, int $field): bool
26
    {
27
        return $entity->getFields()->has($this->getOptions()->get($field));
28
    }
29
30
    /**
31
     * @param Entity $entity
32
     * @param int    $field
33
     * @return Field
34
     */
35
    protected function getField(Entity $entity, int $field): Field
36
    {
37
        return $entity->getFields()->get($this->getOptions()->get($field));
38
    }
39
40
    /**
41
     * @param Entity $target
42
     * @param Field  $source
43
     * @param string $name
44
     */
45
    protected function ensureField(Entity $target, Field $source, string $name)
46
    {
47
        if ($target->getFields()->has($name)) {
48
            // field already exists and defined by the user
49
            return;
50
        }
51
52
        $field = new Field();
53
        $field->setColumn($name);
54
        $field->setTypecast($source->getTypecast());
55
56
        switch ($source->getType()) {
57
            case 'primary':
58
                $field->setType('int');
59
                break;
60
            case 'bigPrimary':
61
                $field->setType('bigint');
62
                break;
63
            default:
64
                $field->setType($source->getType());
65
        }
66
67
        if ($this->getOptions()->get(Relation::NULLABLE)) {
68
            $field->getOptions()->set(ColumnSchema::OPT_NULLABLE, true);
69
        }
70
71
        $target->getFields()->set($name, $field);
72
    }
73
74
    /**
75
     * @return OptionSchema
76
     */
77
    abstract protected function getOptions(): OptionSchema;
78
}