UserTrait::getUser()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 16
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 11
nc 8
nop 0
crap 30
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/spark/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/spark
7
 */
8
9
namespace flipbox\spark\models\traits;
10
11
use Craft;
12
use craft\elements\User as UserElement;
13
use flipbox\spark\helpers\ModelHelper;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 1.0.0
18
 */
19
trait UserTrait
20
{
21
22
    /**
23
     * @var int|null
24
     */
25
    private $userId;
26
27
    /**
28
     * @var UserElement|null
29
     */
30
    private $user;
31
32
    /**
33
     * Set associated userId
34
     *
35
     * @param $id
36
     * @return $this
37
     */
38
    public function setUserId(int $id)
39
    {
40
41
        // Has the id changed?
42
        if ($id !== $this->userId) {
43
            // Invalidate existing user
44
            if ($this->user !== null && $this->user->getId() !== $id) {
45
                $this->user = null;
46
            };
47
48
            $this->userId = $id;
49
        }
50
51
        return $this;
52
    }
53
54
    /**
55
     * Get associated userId
56
     *
57
     * @return int|null
58
     */
59
    public function getUserId()
60
    {
61
        return $this->userId;
62
    }
63
64
65
    /**
66
     * Associate a user
67
     *
68
     * @param $user
69
     * @return $this
70
     */
71
    public function setUser($user)
72
    {
73
74
        // Clear cache
75
        $this->user = null;
76
77
        // Find element
78
        if (!$user = $this->findUserElement($user)) {
79
            // Clear property / cache
80
            $this->userId = $this->user = null;
81
        } else {
82
            // Set property
83
            $this->userId = $user->getId();
84
85
            // Set cache
86
            $this->user = $user;
87
        }
88
89
        return $this;
90
    }
91
92
    /**
93
     * @return UserElement|null
94
     */
95
    public function getUser()
96
    {
97
98
        // Check cache
99
        if (is_null($this->user)) {
100
            // Check property
101
            if (!empty($this->userId)) {
102
                // Find element
103
                if ($userElement = Craft::$app->getUsers()->getUserById($this->userId)) {
104
                    // Set
105
                    $this->setUser($userElement);
106
                } else {
107
                    // Clear property (it's invalid)
108
                    $this->userId = null;
109
110
                    // Prevent subsequent look-ups
111
                    $this->user = false;
0 ignored issues
show
Documentation Bug introduced by
It seems like false of type false is incompatible with the declared type object<craft\elements\User>|null of property $user.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
112
                }
113
            } else {
114
                // Prevent subsequent look-ups
115
                $this->user = false;
116
            }
117
        }
118
119
        return !$this->user ? null : $this->user;
120
    }
121
122
    /**
123
     * @param $user
124
     * @return UserElement|null
125
     */
126
    private function findUserElement($user)
127
    {
128
129
        // Element
130
        if ($user instanceof UserElement) {
131
            return $user;
132
133
            // Id
134
        } elseif (is_numeric($user)) {
135
            return Craft::$app->getUsers()->getUserById($user);
136
137
            // Username / Email
138
        } elseif (!is_null($user)) {
139
            return Craft::$app->getUsers()->getUserByUsernameOrEmail($user);
140
        }
141
142
        return null;
143
    }
144
145
    /**
146
     * @return array
147
     */
148
    protected function userRules(): array
149
    {
150
151
        return [
152
            [
153
                [
154
                    'userId'
155
                ],
156
                'number',
157
                'integerOnly' => true
158
            ],
159
            [
160
                [
161
                    'userId',
162
                    'user'
163
                ],
164
                'safe',
165
                'on' => [
166
                    ModelHelper::SCENARIO_DEFAULT
167
                ]
168
            ]
169
        ];
170
    }
171
172
    /**
173
     * @return array
174
     */
175
    protected function userFields(): array
176
    {
177
178
        return [
179
            'userId'
180
        ];
181
    }
182
183
    /**
184
     * @return array
185
     */
186
    protected function userAttributes(): array
187
    {
188
189
        return [
190
            'userId'
191
        ];
192
    }
193
194
    /**
195
     * @return array
196
     */
197
    protected function userAttributeLabels(): array
198
    {
199
200
        return [
201
            'userId' => Craft::t('app', 'User Id')
202
        ];
203
    }
204
}
205