Completed
Push — develop ( 9af24d...90e507 )
by Nate
11:21
created

FieldAttribute::resolveFieldFromRelation()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 11
cp 0
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/domains/license
6
 * @link       https://www.flipboxfactory.com/software/domains/
7
 */
8
9
namespace flipbox\domains\records\traits;
10
11
use Craft;
12
use craft\base\FieldInterface;
13
use craft\records\Field as FieldRecord;
14
use flipbox\ember\records\traits\ActiveRecord;
15
use yii\db\ActiveQueryInterface;
16
17
/**
18
 * @author Flipbox Factory <[email protected]>
19
 * @since 1.0.0
20
 */
21
trait FieldAttribute
22
{
23
    use ActiveRecord,
24
        FieldRules,
25
        FieldMutator;
26
27
    /**
28
     * Get associated fieldId
29
     *
30
     * @return int|null
31
     */
32
    public function getFieldId()
33
    {
34
        $id = $this->getAttribute('fieldId');
35
        if (null === $id && null !== $this->field) {
36
            $id = $this->fieldId = $this->field->id;
37
        }
38
39
        return $id;
40
    }
41
42
    /**
43
     * @return FieldInterface|null
44
     */
45
    protected function resolveField()
46
    {
47
        if ($model = $this->resolveFieldFromRelation()) {
48
            return $model;
49
        }
50
51
        return $this->resolveFieldFromId();
52
    }
53
54
    /**
55
     * @return FieldInterface|null
56
     */
57
    private function resolveFieldFromRelation()
58
    {
59
        if (false === $this->isRelationPopulated('fieldRecord')) {
60
            return null;
61
        }
62
63
        /** @var FieldRecord $record */
64
        $record = $this->getRelation('fieldRecord');
65
        if (null === $record) {
66
            return null;
67
        }
68
69
        return Craft::$app->getFields()->getFieldById($record->id);
70
    }
71
72
    /**
73
     * Get the associated Field
74
     *
75
     * @return ActiveQueryInterface
76
     */
77
    public function getFieldRecord()
78
    {
79
        return $this->hasOne(
80
            FieldRecord::class,
81
            ['fieldId' => 'id']
82
        );
83
    }
84
}
85