Passed
Push — master ( 032773...bdea76 )
by Alexey
02:15
created

User::getRegistrationTypesArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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
     * Finds user by username
183
     *
184
     * @param string $username
185
     * @return static|null|yii\db\ActiveRecord
186
     */
187
    public static function findByUsername($username)
188
    {
189
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
190
    }
191
192
    /**
193
     * Generates "remember me" authentication key
194
     */
195
    public function generateAuthKey()
196
    {
197
        $this->auth_key = Yii::$app->security->generateRandomString();
198
    }
199
200
    /**
201
     * Generates email confirmation token
202
     */
203
    public function generateEmailConfirmToken()
204
    {
205
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
206
    }
207
208
    /**
209
     * Validates password
210
     *
211
     * @param string $password password to validate
212
     * @return bool if password provided is valid for current user
213
     */
214
    public function validatePassword($password)
215
    {
216
        return Yii::$app->security->validatePassword($password, $this->password_hash);
217
    }
218
219
    /**
220
     * @param string|integer $id
221
     * @return bool
222
     */
223
    public function isSuperAdmin($id = '')
224
    {
225
        $id = $id ? $id : $this->id;
226
        $authManager = Yii::$app->authManager;
227
        $roles = $authManager->getRolesByUser($id);
228
        foreach ($roles as $role) {
229
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN)
230
                return true;
231
        }
232
        return false;
233
    }
234
235
    /**
236
     * @return bool
237
     */
238
    public function isDeleted()
239
    {
240
        return $this->status === self::STATUS_DELETED;
241
    }
242
243
    /**
244
     * Finds out if password reset token is valid
245
     *
246
     * @param mixed $token password reset token
247
     * @return boolean
248
     */
249
    public static function isPasswordResetTokenValid($token)
250
    {
251
        if (empty($token)) {
252
            return false;
253
        }
254
        $expire = Yii::$app->params['users.passwordResetTokenExpire'];
255
        $parts = explode('_', $token);
256
        $timestamp = (int)end($parts);
257
        return $timestamp + $expire >= time();
258
    }
259
260
    /**
261
     * Set Status
262
     * @return int|string
263
     */
264
    public function setStatus()
265
    {
266
        switch ($this->status) {
267
            case self::STATUS_ACTIVE:
268
                $this->status = self::STATUS_BLOCKED;
269
                break;
270
            case self::STATUS_DELETED:
271
                $this->status = self::STATUS_WAIT;
272
                break;
273
            default:
274
                $this->status = self::STATUS_ACTIVE;
275
        }
276
        return $this->status;
277
    }
278
}
279