Completed
Push — master ( c064eb...85769a )
by Igor
03:38
created

User::getStatusDescription()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
rs 9.6666
cc 3
eloc 6
nc 3
nop 0
crap 3.0416
1
<?php
2
3
namespace app\models;
4
5
use Yii;
6
use yii\base\NotSupportedException;
7
use yii\db\ActiveRecord;
8
use yii\web\IdentityInterface;
9
use yii\behaviors\TimestampBehavior;
10
use app\models\UserProfile;
11
use app\models\UserProvider;
12
use app\models\query\UserQuery;
13
14
/**
15
 * This is the model class for table "user".
16
 *
17
 * @property integer $id
18
 * @property string $username
19
 * @property string $email
20
 * @property string $password
21
 * @property string $password_reset_token
22
 * @property string $email_confirm_token
23
 * @property string $auth_key
24
 * @property string $date_confirm
25
 * @property string $date_create
26
 * @property string $date_update
27
 * @property string $date_login
28
 * @property integer $ip
29
 * @property string $role
30
 * @property integer $status
31
 */
32
class User extends \yii\db\ActiveRecord implements IdentityInterface
33
{
34
    const STATUS_DELETED = 0;
35
    const STATUS_ACTIVE  = 1;
36
    const STATUS_BLOCKED = 2;
37
38
    const ROLE_SUPERUSER = 'SuperUser';
39
40
    /**
41
     * @var string
42
     */
43
    public $passwordNew;
44
45
    /**
46
     * @inheritdoc
47
     */
48 115
    public static function tableName()
49
    {
50 115
        return 'user';
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56 82
    public function attributeLabels()
57
    {
58
        return [
59 82
            'id' => Yii::t('app', 'ID'),
60 82
            'username' => Yii::t('app', 'Username'),
61 82
            'email' => Yii::t('app', 'Email'),
62 82
            'password' => Yii::t('app', 'Password'),
63 82
            'date_create' => Yii::t('app', 'Date create'),
64 82
            'date_update' => Yii::t('app', 'Date update'),
65 82
            'date_login' => Yii::t('app', 'Last login'),
66 82
            'ip' => Yii::t('app', 'IP'),
67 82
            'role' => Yii::t('app', 'Role'),
68 82
            'status' => Yii::t('app', 'Status'),
69
70 82
            'passwordNew' => Yii::t('app', 'New password'),
71
        ];
72
    }
73
74
    /**
75
     * @inheritdoc
76
     */
77 105
    public function behaviors()
78
    {
79
        return [
80
            [
81 105
                'class' => TimestampBehavior::class,
82 105
                'createdAtAttribute' => 'date_create',
83 105
                'updatedAtAttribute' => 'date_update',
84 105
                'value' => new \yii\db\Expression('NOW()'),
85
            ],
86
        ];
87
    }
88
89
    /**
90
     * @inheritdoc
91
     * @codeCoverageIgnore
92
     */
93
    public function events()
94
    {
95
        return [
96
            ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
97
        ];
98
    }
99
100 11
    public function transactions()
101
    {
102
        return [
103 11
            'create' => self::OP_ALL,
104 11
            'update' => self::OP_ALL,
105 11
            'delete' => self::OP_ALL,
106
        ];
107
    }
108
109
    /**
110
     * @return \yii\db\ActiveQuery
111
     */
112 11
    public function getProfile()
113
    {
114 11
        return $this->hasOne(UserProfile::class, ['user_id' => 'id']);
115
    }
116
117
    /**
118
     * @param array $attributes
119
     */
120 3
    public function setProfile($attributes = [])
121
    {
122 3
        return $this->populateRelation('profile', new UserProfile($attributes));
123
    }
124
125
    /**
126
     * @return \yii\db\ActiveQuery
127
     */
128 12
    public function getProviders()
129
    {
130 12
        return $this->hasMany(UserProvider::class, ['user_id' => 'id']);
131
    }
132
133
    /**
134
     * @param array $attributes
135
     */
136
    public function setProviders($attributes = [])
137
    {
138
        return $this->populateRelation('providers', [new UserProvider($attributes)]);
139
    }
140
141
    /**
142
     * @return \yii\db\ActiveQuery
143
     */
144 6
    public function getRoles()
145
    {
146 6
        return $this->hasOne(AuthItem::class, ['name' => 'role']);
147
    }
148
149
    /**
150
     * @inheritdoc
151
     * @return UserQuery
152
     */
153 84
    public static function find()
154
    {
155 84
        return new UserQuery(get_called_class());
156
    }
157
158
    /**
159
     * @inheritdoc
160
     */
161 11
    public function beforeSave($insert)
162
    {
163 11
        if (parent::beforeSave($insert)) {
164 11
            if ($insert) {
165 3
                $this->generateAuthKey();
166 3
                if (!Yii::$app instanceof \yii\console\Application) {
167 3
                    $this->ip = ip2long(Yii::$app->request->getUserIP());
168
                }
169
170 3
                if ($this->profile === null) {
171
                    $this->setProfile();
172
                }
173
            }
174
175 11
            if (!empty($this->passwordNew)) {
176 1
                $this->setPassword($this->passwordNew);
177
            }
178
179 11
            return true;
180
        } // @codeCoverageIgnore
181
182
        return false; // @codeCoverageIgnore
183
    }
184
185
    /**
186
     * @inheritdoc
187
     * @property \app\models\UserProfile $profile
188
     * @property \app\models\UserProvider $providers
189
     */
190 11
    public function afterSave($insert, $changedAttributes)
191
    {
192 11
        parent::afterSave($insert, $changedAttributes);
193
194 11
        if ($this->profile !== null) {
195 8
            $this->link('profile', $this->profile);
196
        }
197
198 11
        if ($this->providers !== null && count($this->providers)) {
199
            foreach ($this->providers as $provider) {
200
                if ($provider) {
201
                    $this->link('providers', $provider);
202
                }
203
            }
204
        }
205 11
    }
206
207
    /**
208
     * @inheritdoc
209
     * @param boolean $runValidation
210
     * @param array $attributeNames
211
     * @return boolean
212
     */
213
    public function save($runValidation = true, $attributeNames = null)
214
    {
215 11
        return $this->getDb()->transaction(function () use ($runValidation, $attributeNames) {
216 11
            return parent::save($runValidation, $attributeNames);
217 11
        });
218
    }
219
220
    /**
221
     * Get all statuses
222
     *
223
     * @param string[]
224
     */
225 6
    public static function getStatuses(): array
226
    {
227
        return [
228 6
            self::STATUS_DELETED => Yii::t('app', 'Deleted'),
229 6
            self::STATUS_BLOCKED => Yii::t('app', 'Locked'),
230 6
            self::STATUS_ACTIVE  => Yii::t('app', 'Active'),
231
        ];
232
    }
233
234
    /**
235
     * Get statuse name
236
     *
237
     * @return string
238
     */
239 6
    public function getStatusName(): string
240
    {
241 6
        $statuses = self::getStatuses();
242 6
        return isset($statuses[$this->status]) ? $statuses[$this->status] : '';
243
    }
244
245
    /**
246
     * Is it deleted?
247
     *
248
     * @param bool
249
     */
250
    public function isDeleted(): bool
251
    {
252
        return $this->status == self::STATUS_DELETED;
253
    }
254
255
    /**
256
     * Is it blocked?
257
     *
258
     * @param bool
259
     */
260 6
    public function isBlocked(): bool
261
    {
262 6
        return $this->status == self::STATUS_BLOCKED;
263
    }
264
265
    /**
266
     * Is it active?
267
     *
268
     * @param bool
269
     */
270 34
    public function isActive(): bool
271
    {
272 34
        return $this->status == self::STATUS_ACTIVE;
273
    }
274
275
    /**
276
     * Is it confirmed?
277
     *
278
     * @param bool
279
     */
280 11
    public function isConfirmed(): bool
281
    {
282 11
        return strtotime($this->date_confirm) > 0;
283
    }
284
285
    /**
286
     * Is SuperUser?
287
     *
288
     * @return bool
289
     */
290 19
    public function isSuperUser(): bool
291
    {
292 19
        return $this->role === self::ROLE_SUPERUSER;
293
    }
294
295
    /**
296
     * Set confirmed
297
     */
298 2
    public function setConfirmed(): void
299
    {
300 2
        $this->email_confirm_token = null;
301 2
        $this->date_confirm = new \yii\db\Expression('NOW()');
302 2
    }
303
304
    /**
305
     * Get status description
306
     *
307
     * @return string
308
     */
309 8
    public function getStatusDescription(): string
310
    {
311 8
        if ($this->status == self::STATUS_BLOCKED) {
312 4
            return Yii::t('app', 'Your account has been suspended');
313 4
        } elseif ($this->status == self::STATUS_DELETED) {
314 4
            return Yii::t('app', 'Your account has been deleted');
315
        }
316
        return Yii::t('app', 'Your account is activated');
317
    }
318
319
    /**
320
     * @inheritdoc
321
     */
322 32
    public function getId()
323
    {
324 32
        return $this->id;
325
    }
326
327
    /**
328
     * @inheritdoc
329
     */
330
    public function getAuthKey()
331
    {
332
        return $this->auth_key;
333
    }
334
335
    /**
336
     * @inheritdoc
337
     */
338
    public function validateAuthKey($authKey)
339
    {
340
        return $this->getAuthKey() === $authKey;
341
    }
342
343
    /**
344
     * Generates "remember me" authentication key
345
     */
346 3
    public function generateAuthKey()
347
    {
348 3
        $this->auth_key = Yii::$app->security->generateRandomString();
349 3
    }
350
351
    /**
352
     * Validates password
353
     *
354
     * @param string $password password to validate
355
     * @return boolean if password provided is valid for current user
356
     */
357 22
    public function validatePassword(string $password): bool
358
    {
359 22
        if (empty($this->password)) {
360
            return false;
361
        }
362
363 22
        return Yii::$app->security->validatePassword($password, $this->password);
364
    }
365
366
    /**
367
     * Set a new password
368
     *
369
     * @param string $password
370
     */
371 6
    public function setPassword(string $password): void
372
    {
373 6
        $this->password = Yii::$app->security->generatePasswordHash($password);
374 6
    }
375
376
    /**
377
     * Set new password reset token
378
     *
379
     * @param string $token
380
     */
381 1
    public function setPasswordResetToken(string $token): void
382
    {
383 1
        $this->password_reset_token = $token;
384 1
    }
385
386
    /**
387
     * Removes password reset token
388
     */
389 2
    public function removePasswordResetToken(): void
390
    {
391 2
        $this->password_reset_token = null;
392 2
    }
393
394
    /**
395
     * Set new confirm email token
396
     *
397
     * @param string $token
398
     */
399 4
    public function setEmailConfirmToken(string $token): void
400
    {
401 4
        $this->email_confirm_token = $token;
402 4
        $this->date_confirm = null;
403 4
    }
404
405
    /**
406
     * @inheritdoc
407
     */
408 24
    public static function findIdentity($id)
409
    {
410 24
        return static::findOne([$id]);
411
    }
412
413
    /**
414
     * @inheritdoc
415
     */
416
    public static function findIdentityByAccessToken($token, $type = null)
417
    {
418
        throw new NotSupportedException('findIdentityByAccessToken is not implemented.');
419
    }
420
421
    /**
422
     * Update date login
423
     */
424 12
    public function updateDateLogin(): void
425
    {
426 12
        $this->updateAttributes([
427 12
            'date_login' => new \yii\db\Expression('NOW()'),
428 12
            'ip' => ip2long(Yii::$app->request->getUserIP())
429
        ]);
430 12
    }
431
432
    /**
433
     * @return bool
434
     */
435
    public function beforeDelete()
436
    {
437
        Yii::$app->authManager->revokeAll($this->id);
438
439
        if ($this->profile !== null) {
440
            $this->profile->delete();
441
        }
442
443
        return true;
444
    }
445
}
446