Completed
Push — master ( 59199f...042504 )
by Alexey
02:46
created

BaseUser::getUserFullName()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 8.8571
cc 6
eloc 11
nc 5
nop 0
1
<?php
2
namespace modules\users\models;
3
4
use Yii;
5
use yii\behaviors\TimestampBehavior;
6
use yii\db\ActiveRecord;
7
use yii\web\IdentityInterface;
8
use yii\helpers\ArrayHelper;
9
use yii\helpers\Html;
10
use modules\users\Module;
11
12
/**
13
 * Class BaseUser
14
 * @package modules\users\models
15
 *
16
 * This is the model class for table "{{%user}}".
17
 *
18
 * @property int $id ID
19
 * @property string $username Username
20
 * @property string $auth_key Authorization Key
21
 * @property string $password_hash Hash Password
22
 * @property string $password_reset_token Password Token
23
 * @property string $email_confirm_token Email Confirm Token
24
 * @property string $email Email
25
 * @property int $status Status
26
 * @property int $last_visit Last Visit
27
 * @property int $created_at Created
28
 * @property int $updated_at Updated
29
 * @property string $first_name First Name
30
 * @property string $last_name Last Name
31
 * @property int $registration_type Type Registration
32
 */
33
class BaseUser extends ActiveRecord implements IdentityInterface
34
{
35
    // Status
36
    const STATUS_BLOCKED = 0;
37
    const STATUS_ACTIVE = 1;
38
    const STATUS_WAIT = 2;
39
    const STATUS_DELETED = 3;
40
41
    // Type of registration
42
    const TYPE_REGISTRATION_SYSTEM = 0;
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public static function tableName()
48
    {
49
        return '{{%user}}';
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55
    public function behaviors()
56
    {
57
        return [
58
            'timestamp' => [
59
                'class' => TimestampBehavior::className(),
60
            ],
61
        ];
62
    }
63
64
    /**
65
     * @inheritdoc
66
     */
67
    public function rules()
68
    {
69
        return [
70
            ['username', 'required'],
71
            ['username', 'match', 'pattern' => '#^[\w_-]+$#i'],
72
            ['username', 'unique', 'targetClass' => self::className(), 'message' => Module::t('module', 'This username is already taken.')],
73
            ['username', 'string', 'min' => 2, 'max' => 255],
74
75
            ['email', 'required'],
76
            ['email', 'email'],
77
            ['email', 'unique', 'targetClass' => self::className(), 'message' => Module::t('module', 'This email is already taken.')],
78
            ['email', 'string', 'max' => 255],
79
80
            ['status', 'integer'],
81
            ['status', 'default', 'value' => self::STATUS_WAIT],
82
            ['status', 'in', 'range' => array_keys(self::getStatusesArray())],
83
84
            [['first_name', 'last_name'], 'string', 'max' => 45],
85
            [['registration_type'], 'safe'],
86
        ];
87
    }
88
89
    /**
90
     * @inheritdoc
91
     */
92
    public function attributeLabels()
93
    {
94
        return [
95
            'id' => 'ID',
96
            'created_at' => Module::t('module', 'Created'),
97
            'updated_at' => Module::t('module', 'Updated'),
98
            'last_visit' => Module::t('module', 'Last Visit'),
99
            'username' => Module::t('module', 'Username'),
100
            'email' => Module::t('module', 'Email'),
101
            'auth_key' => Module::t('module', 'Auth Key'),
102
            'status' => Module::t('module', 'Status'),
103
            'first_name' => Module::t('module', 'First Name'),
104
            'last_name' => Module::t('module', 'Last Name'),
105
            'registration_type' => Module::t('module', 'Registration Type'),
106
        ];
107
    }
108
109
    /**
110
     * @inheritdoc
111
     */
112
    public static function findIdentity($id = null)
113
    {
114
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::findOne(a...> self::STATUS_ACTIVE)) also could return the type yii\db\BaseActiveRecord which is incompatible with the return type mandated by yii\web\IdentityInterface::findIdentity() of yii\web\IdentityInterface.
Loading history...
115
    }
116
117
    /**
118
     * @param mixed $token
119
     * @param null $type
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $type is correct as it would always require null to be passed?
Loading history...
120
     * @return null|static|ActiveRecord
121
     */
122
    public static function findIdentityByAccessToken($token = '', $type = null)
123
    {
124
        return static::findOne(['auth_key' => $token, 'status' => self::STATUS_ACTIVE]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::findOne(a...> self::STATUS_ACTIVE)) also could return the type yii\db\BaseActiveRecord which is incompatible with the return type mandated by yii\web\IdentityInterfac...IdentityByAccessToken() of yii\web\IdentityInterface.
Loading history...
125
    }
126
127
    /**
128
     * Finds user by username
129
     *
130
     * @param string $username
131
     * @return static|null|ActiveRecord
132
     */
133
    public static function findByUsername($username = '')
134
    {
135
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
136
    }
137
138
    /**
139
     * Finds user by email
140
     *
141
     * @param string $email
142
     * @return array|null|ActiveRecord
143
     */
144
    public static function findByUsernameEmail($email = '')
145
    {
146
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
147
    }
148
149
    /**
150
     * Finds user by username or email
151
     *
152
     * @param string $string
153
     * @return array|null|ActiveRecord
154
     */
155
    public static function findByUsernameOrEmail($string = '')
156
    {
157
        return static::find()
158
            ->where(['or', ['username' => $string], ['email' => $string]])
159
            ->andWhere(['status' => self::STATUS_ACTIVE])
160
            ->one();
161
    }
162
163
    /**
164
     * Finds user by password reset token
165
     *
166
     * @param string $token password reset token
167
     * @return static|null
168
     */
169
    public static function findByPasswordResetToken($token = '')
170
    {
171
        if (!static::isPasswordResetTokenValid($token)) {
172
            return null;
173
        }
174
        return static::findOne([
175
            'password_reset_token' => $token,
176
            'status' => self::STATUS_ACTIVE,
177
        ]);
178
    }
179
180
    /**
181
     * Finds out if password reset token is valid
182
     *
183
     * @param string $token password reset token
184
     * @return boolean
185
     */
186
    public static function isPasswordResetTokenValid($token = '')
187
    {
188
        if (empty($token)) {
189
            return false;
190
        }
191
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
192
        $parts = explode('_', $token);
193
        $timestamp = (int)end($parts);
194
        return $timestamp + $expire >= time();
195
    }
196
197
    /**
198
     * @inheritdoc
199
     */
200
    public function getId()
201
    {
202
        return $this->getPrimaryKey();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getPrimaryKey() also could return the type array|array<mixed,null|mixed> which is incompatible with the return type mandated by yii\web\IdentityInterface::getId() of integer|string.
Loading history...
203
    }
204
205
    /**
206
     * @inheritdoc
207
     */
208
    public function getAuthKey()
209
    {
210
        return $this->auth_key;
211
    }
212
213
    /**
214
     * @inheritdoc
215
     */
216
    public function validateAuthKey($authKey = '')
217
    {
218
        return $this->getAuthKey() === $authKey;
219
    }
220
221
    /**
222
     * Validates password
223
     *
224
     * @param string $password password to validate
225
     * @return boolean if password provided is valid for current user
226
     */
227
    public function validatePassword($password = '')
228
    {
229
        return Yii::$app->security->validatePassword($password, $this->password_hash);
230
    }
231
232
    /**
233
     * Generates password hash from password and sets it to the model
234
     *
235
     * @param string $password
236
     */
237
    public function setPassword($password = '')
238
    {
239
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
240
    }
241
242
    /**
243
     * Generates "remember me" authentication key
244
     */
245
    public function generateAuthKey()
246
    {
247
        $this->auth_key = Yii::$app->security->generateRandomString();
248
    }
249
250
    /**
251
     * Generates new password reset token
252
     */
253
    public function generatePasswordResetToken()
254
    {
255
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
256
    }
257
258
    /**
259
     * Removes password reset token
260
     */
261
    public function removePasswordResetToken()
262
    {
263
        $this->password_reset_token = null;
264
    }
265
266
    /**
267
     * @param $email_confirm_token
268
     * @return bool|null|static
269
     */
270
    public static function findByEmailConfirmToken($email_confirm_token = '')
271
    {
272
        return static::findOne([
273
            'email_confirm_token' => $email_confirm_token,
274
            'status' => self::STATUS_WAIT
275
        ]);
276
    }
277
278
    /**
279
     * Generates email confirmation token
280
     */
281
    public function generateEmailConfirmToken()
282
    {
283
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
284
    }
285
286
    /**
287
     * Removes email confirmation token
288
     */
289
    public function removeEmailConfirmToken()
290
    {
291
        $this->email_confirm_token = null;
292
    }
293
294
    /**
295
     * @return bool
296
     */
297
    public function isDeleted()
298
    {
299
        return $this->status === self::STATUS_DELETED;
300
    }
301
302
    /**
303
     * Actions before saving
304
     *
305
     * @param bool $insert
306
     * @return bool
307
     */
308
    public function beforeSave($insert)
309
    {
310
        if (parent::beforeSave($insert)) {
311
            if ($insert) {
312
                $this->generateAuthKey();
313
            }
314
            return true;
315
        }
316
        return false;
317
    }
318
319
    /**
320
     * @return array
321
     */
322
    public static function getStatusesArray()
323
    {
324
        return [
325
            self::STATUS_BLOCKED => Module::t('module', 'Blocked'),
326
            self::STATUS_ACTIVE => Module::t('module', 'Active'),
327
            self::STATUS_WAIT => Module::t('module', 'Wait'),
328
            self::STATUS_DELETED => Module::t('module', 'Deleted'),
329
        ];
330
    }
331
332
    /**
333
     * @return mixed
334
     */
335
    public function getStatusName()
336
    {
337
        return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
338
    }
339
340
    /**
341
     * Return <span class="label label-success">Active</span>
342
     * @return string
343
     */
344
    public function getStatusLabelName()
345
    {
346
        $name = ArrayHelper::getValue(self::getLabelsArray(), $this->status);
347
        return Html::tag('span', self::getStatusName(), ['class' => 'label label-' . $name]);
0 ignored issues
show
Bug Best Practice introduced by
The method modules\users\models\BaseUser::getStatusName() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

347
        return Html::tag('span', self::/** @scrutinizer ignore-call */ getStatusName(), ['class' => 'label label-' . $name]);
Loading history...
348
    }
349
350
    /**
351
     * @return array
352
     */
353
    public static function getLabelsArray()
354
    {
355
        return [
356
            self::STATUS_BLOCKED => 'default',
357
            self::STATUS_ACTIVE => 'success',
358
            self::STATUS_WAIT => 'warning',
359
            self::STATUS_DELETED => 'danger',
360
        ];
361
    }
362
363
    /**
364
     * Type of registration
365
     * How the user is created
366
     * If the system registration type is registered by itself,
367
     * if it is created from the admin area,
368
     * then the login type that created the account
369
     *
370
     * @return mixed|string
371
     */
372
    public function getRegistrationType()
373
    {
374
        if ($this->registration_type > 0) {
375
            if (($model = User::findOne($this->registration_type)) !== null) {
376
                return $model->username;
377
            }
378
        }
379
        return $this->getRegistrationTypeName();
380
    }
381
382
    /**
383
     * Returns the registration type string
384
     * @return mixed
385
     */
386
    public function getRegistrationTypeName()
387
    {
388
        return ArrayHelper::getValue(self::getRegistrationTypesArray(), $this->registration_type);
389
    }
390
391
    /**
392
     * Returns an array of log types
393
     * @return array
394
     */
395
    public static function getRegistrationTypesArray()
396
    {
397
        return [
398
            self::TYPE_REGISTRATION_SYSTEM => Module::t('module', 'System'),
399
        ];
400
    }
401
}
402