Passed
Push — master ( b9a837...4518ef )
by Anton
01:49
created

FieldTrait::getField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
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\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 createField(Entity $target, Field $source, string $name)
46
    {
47
        $field = new Field();
48
        $field->setColumn($name);
49
        $field->setTypecast($source->getTypecast());
50
51
        switch ($source->getType()) {
52
            case 'primary':
53
                $field->setType('int');
54
                break;
55
            case 'bigPrimary':
56
                $field->setType('bigint');
57
                break;
58
            default:
59
                $field->setType($source->getType());
60
        }
61
62
        if ($this->getOptions()->get(Relation::NULLABLE)) {
63
            $field->getOptions()->set(ColumnSchema::OPT_NULLABLE, true);
64
        }
65
66
        $target->getFields()->set($name, $field);
67
    }
68
69
    /**
70
     * @return OptionSchema
71
     */
72
    abstract protected function getOptions(): OptionSchema;
73
}