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

UserAttribute::resolveUser()   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\elements\User as UserElement;
13
use craft\records\User as UserRecord;
14
use flipbox\ember\traits\UserMutator;
15
use flipbox\ember\traits\UserRules;
16
use yii\db\ActiveQueryInterface;
17
18
/**
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 1.0.0
21
 *
22
 * @property UserRecord[] $userRecord
23
 */
24
trait UserAttribute
25
{
26
    use ActiveRecord,
27
        UserRules,
28
        UserMutator;
29
30
    /**
31
     * Get associated userId
32
     *
33
     * @return int|null
34
     */
35
    public function getUserId()
36
    {
37
        $id = $this->getAttribute('userId');
38
        if (null === $id && null !== $this->user) {
39
            $id = $this->userId = $this->user->id;
40
        }
41
42
        return $id;
43
    }
44
45
    /**
46
     * @return UserElement|null
47
     */
48
    protected function resolveUser()
49
    {
50
        if ($model = $this->resolveUserFromRelation()) {
51
            return $model;
52
        }
53
54
        return $this->resolveUserFromId();
55
    }
56
57
    /**
58
     * @return UserElement|null
59
     */
60
    private function resolveUserFromRelation()
61
    {
62
        if (false === $this->isRelationPopulated('userRecord')) {
63
            return null;
64
        }
65
66
        /** @var UserRecord $record */
67
        $record = $this->getRelation('userRecord');
68
        if (null === $record) {
69
            return null;
70
        }
71
72
        return Craft::$app->getUsers()->getUserById($record->id);
73
    }
74
    
75
    /**
76
     * Get the associated User
77
     *
78
     * @return ActiveQueryInterface
79
     */
80
    public function getUserRecord(): ActiveQueryInterface
81
    {
82
        return $this->hasOne(
83
            UserRecord::class,
84
            ['userId' => 'id']
85
        );
86
    }
87
}
88