Passed
Push — master ( 1c6c78...fefe57 )
by Alexey
02:20
created

User::getStatusLabelName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace modules\users\models;
4
5
use Yii;
6
use yii\helpers\Html;
7
use yii\helpers\ArrayHelper;
8
use modules\users\models\query\UserQuery;
9
use modules\users\Module;
10
11
/**
12
 * Class User
13
 * @package modules\users\models
14
 *
15
 * This is the model class extends IdentityUser.
16
 *
17
 * @property int $id ID
18
 * @property string $username Username
19
 * @property string $auth_key Authorization Key
20
 * @property string $password_hash Hash Password
21
 * @property string $password_reset_token Password Token
22
 * @property string $email_confirm_token Email Confirm Token
23
 * @property string $email Email
24
 * @property int|string $status Status
25
 * @property int $last_visit Last Visit
26
 * @property int $created_at Created
27
 * @property int $updated_at Updated
28
 * @property string $first_name First Name
29
 * @property string $last_name Last Name
30
 * @property int|string $registration_type Type Registration
31
 * @property string statusLabelName Status name in label
32
 * @property array statusesArray Array statuses
33
 * @property string statusName Name status
34
 * @property int|string registrationType Type registered
35
 * @property string $role User Role Name
36
 */
37
class User extends IdentityUser
38
{
39
    public $role;
40
41
    /**
42
     * @return mixed
43
     */
44
    public function getStatusName()
45
    {
46
        return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
47
    }
48
49
    /**
50
     * Return <span class="label label-success">Active</span>
51
     * @return string
52
     */
53
    public function getStatusLabelName()
54
    {
55
        $name = ArrayHelper::getValue(self::getLabelsArray(), $this->status);
56
        return Html::tag('span', $this->getStatusName(), ['class' => 'label label-' . $name]);
57
    }
58
59
    /**
60
     * @return array
61
     */
62
    public static function getLabelsArray()
63
    {
64
        return [
65
            self::STATUS_BLOCKED => 'default',
66
            self::STATUS_ACTIVE => 'success',
67
            self::STATUS_WAIT => 'warning',
68
            self::STATUS_DELETED => 'danger',
69
        ];
70
    }
71
72
    /**
73
     * @inheritdoc
74
     * @return array
75
     */
76
    public function attributeLabels()
77
    {
78
        return ArrayHelper::merge(parent::attributeLabels(), [
79
            'role' => Module::t('module', 'Role'),
80
        ]);
81
    }
82
    /**
83
     * @return object|\yii\db\ActiveQuery
84
     * @throws \yii\base\InvalidConfigException
85
     */
86
    public static function find()
87
    {
88
        return Yii::createObject(UserQuery::class, [get_called_class()]);
89
    }
90
91
    /**
92
     * Finds user by email
93
     *
94
     * @param string $email
95
     * @return static|null
96
     */
97
    public static function findByUsernameEmail($email)
98
    {
99
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
100
    }
101
102
    /**
103
     * Finds user by username or email
104
     *
105
     * @param string $string
106
     * @return static|null
107
     * @throws \yii\base\InvalidConfigException
108
     */
109
    public static function findByUsernameOrEmail($string)
110
    {
111
        return static::find()
112
            ->where(['or', ['username' => $string], ['email' => $string]])
113
            ->andWhere(['status' => self::STATUS_ACTIVE])
114
            ->one();
115
    }
116
117
    /**
118
     * Generates password hash from password and sets it to the model
119
     *
120
     * @param string $password
121
     * @throws \yii\base\Exception
122
     */
123
    public function setPassword($password)
124
    {
125
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
126
    }
127
128
    /**
129
     * Generates new password reset token
130
     */
131
    public function generatePasswordResetToken()
132
    {
133
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
134
    }
135
136
    /**
137
     * Removes password reset token
138
     */
139
    public function removePasswordResetToken()
140
    {
141
        $this->password_reset_token = null;
142
    }
143
144
    /**
145
     * Removes email confirmation token
146
     */
147
    public function removeEmailConfirmToken()
148
    {
149
        $this->email_confirm_token = null;
150
    }
151
152
    /**
153
     * Finds user by password reset token
154
     *
155
     * @param mixed $token password reset token
156
     * @return static|null
157
     */
158
    public static function findByPasswordResetToken($token)
159
    {
160
        if (!static::isPasswordResetTokenValid($token)) {
161
            return null;
162
        }
163
        return static::findOne([
164
            'password_reset_token' => $token,
165
            'status' => self::STATUS_ACTIVE,
166
        ]);
167
    }
168
169
    /**
170
     * @param mixed $email_confirm_token
171
     * @return bool|null|static
172
     */
173
    public static function findByEmailConfirmToken($email_confirm_token)
174
    {
175
        return static::findOne([
176
            'email_confirm_token' => $email_confirm_token,
177
            'status' => self::STATUS_WAIT
178
        ]);
179
    }
180
181
    /**
182
     * Generates email confirmation token
183
     */
184
    public function generateEmailConfirmToken()
185
    {
186
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
187
    }
188
189
    /**
190
     * Validates password
191
     *
192
     * @param string $password password to validate
193
     * @return bool if password provided is valid for current user
194
     */
195
    public function validatePassword($password)
196
    {
197
        return Yii::$app->security->validatePassword($password, $this->password_hash);
198
    }
199
200
    /**
201
     * Type of registration
202
     * How the user is created
203
     * If the system registration type is registered by itself,
204
     * if it is created from the admin area,
205
     * then the login type that created the account
206
     *
207
     * @return mixed|string
208
     */
209
    public function getRegistrationType()
210
    {
211
        if ($this->registration_type > 0) {
212
            if (($model = User::findOne($this->registration_type)) !== null) {
213
                return $model->username;
214
            }
215
        }
216
        return $this->getRegistrationTypeName();
217
    }
218
219
    /**
220
     * Returns the registration type string
221
     * @return mixed
222
     */
223
    public function getRegistrationTypeName()
224
    {
225
        return ArrayHelper::getValue(self::getRegistrationTypesArray(), $this->registration_type);
226
    }
227
228
    /**
229
     * Returns an array of log types
230
     * @return array
231
     */
232
    public static function getRegistrationTypesArray()
233
    {
234
        return [
235
            self::TYPE_REGISTRATION_SYSTEM => Module::t('module', 'System'),
236
        ];
237
    }
238
239
    /**
240
     * @param string|integer $id
241
     * @return bool
242
     */
243
    public function isSuperAdmin($id = '')
244
    {
245
        $id = $id ? $id : $this->id;
246
        $authManager = Yii::$app->authManager;
247
        $roles = $authManager->getRolesByUser($id);
248
        foreach ($roles as $role) {
249
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN)
250
                return true;
251
        }
252
        return false;
253
    }
254
255
    /**
256
     * @return bool
257
     */
258
    public function isDeleted()
259
    {
260
        return $this->status === self::STATUS_DELETED;
261
    }
262
263
    /**
264
     * Finds out if password reset token is valid
265
     *
266
     * @param mixed $token password reset token
267
     * @return boolean
268
     */
269
    public static function isPasswordResetTokenValid($token)
270
    {
271
        if (empty($token)) {
272
            return false;
273
        }
274
        $expire = Yii::$app->params['users.passwordResetTokenExpire'];
275
        $parts = explode('_', $token);
276
        $timestamp = (int)end($parts);
277
        return $timestamp + $expire >= time();
278
    }
279
280
    /**
281
     * Set Status
282
     * @return int|string
283
     */
284
    public function setStatus()
285
    {
286
        switch ($this->status) {
287
            case self::STATUS_ACTIVE:
288
                $this->status = self::STATUS_BLOCKED;
289
                break;
290
            case self::STATUS_DELETED:
291
                $this->status = self::STATUS_WAIT;
292
                break;
293
            default:
294
                $this->status = self::STATUS_ACTIVE;
295
        }
296
        return $this->status;
297
    }
298
}
299