Completed
Push — master ( 69ca06...8af5d6 )
by Nate
03:36
created

ElementAttribute::resolveElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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