Passed
Push — master ( 30294b...1839bf )
by Alexey
02:13
created

User::attributeLabels()   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\ArrayHelper;
7
use modules\users\models\query\UserQuery;
8
use modules\users\traits\ModuleTrait;
9
use modules\users\Module;
10
11
/**
12
 * Class User
13
 * @package modules\users\models
14
 *
15
 * This is the model class extends BaseUser.
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 BaseUser
38
{
39
    use ModuleTrait;
40
41
    public $role;
42
43
    /**
44
     * @inheritdoc
45
     * @return array
46
     */
47
    public function attributeLabels()
48
    {
49
        return ArrayHelper::merge(parent::attributeLabels(), [
50
            'role' => Module::t('module', 'Role'),
51
        ]);
52
    }
53
    /**
54
     * @return object|\yii\db\ActiveQuery
55
     * @throws \yii\base\InvalidConfigException
56
     */
57
    public static function find()
58
    {
59
        return Yii::createObject(UserQuery::class, [get_called_class()]);
60
    }
61
62
    /**
63
     * Finds user by email
64
     *
65
     * @param string $email
66
     * @return static|null
67
     */
68
    public static function findByUsernameEmail($email)
69
    {
70
        return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]);
71
    }
72
73
    /**
74
     * Finds user by username or email
75
     *
76
     * @param string $string
77
     * @return static|null
78
     * @throws \yii\base\InvalidConfigException
79
     */
80
    public static function findByUsernameOrEmail($string)
81
    {
82
        return static::find()
83
            ->where(['or', ['username' => $string], ['email' => $string]])
84
            ->andWhere(['status' => self::STATUS_ACTIVE])
85
            ->one();
86
    }
87
88
    /**
89
     * Generates password hash from password and sets it to the model
90
     *
91
     * @param string $password
92
     * @throws \yii\base\Exception
93
     */
94
    public function setPassword($password)
95
    {
96
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
97
    }
98
99
    /**
100
     * Generates new password reset token
101
     */
102
    public function generatePasswordResetToken()
103
    {
104
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
105
    }
106
107
    /**
108
     * Removes password reset token
109
     */
110
    public function removePasswordResetToken()
111
    {
112
        $this->password_reset_token = null;
113
    }
114
115
    /**
116
     * Removes email confirmation token
117
     */
118
    public function removeEmailConfirmToken()
119
    {
120
        $this->email_confirm_token = null;
121
    }
122
123
    /**
124
     * Finds user by password reset token
125
     *
126
     * @param mixed $token password reset token
127
     * @return static|null
128
     */
129
    public static function findByPasswordResetToken($token)
130
    {
131
        if (!static::isPasswordResetTokenValid($token)) {
132
            return null;
133
        }
134
        return static::findOne([
135
            'password_reset_token' => $token,
136
            'status' => self::STATUS_ACTIVE,
137
        ]);
138
    }
139
140
    /**
141
     * @param mixed $email_confirm_token
142
     * @return bool|null|static
143
     */
144
    public static function findByEmailConfirmToken($email_confirm_token)
145
    {
146
        return static::findOne([
147
            'email_confirm_token' => $email_confirm_token,
148
            'status' => self::STATUS_WAIT
149
        ]);
150
    }
151
152
    /**
153
     * Generates email confirmation token
154
     */
155
    public function generateEmailConfirmToken()
156
    {
157
        $this->email_confirm_token = Yii::$app->security->generateRandomString();
158
    }
159
160
    /**
161
     * Validates password
162
     *
163
     * @param string $password password to validate
164
     * @return bool if password provided is valid for current user
165
     */
166
    public function validatePassword($password)
167
    {
168
        return Yii::$app->security->validatePassword($password, $this->password_hash);
169
    }
170
171
    /**
172
     * Type of registration
173
     * How the user is created
174
     * If the system registration type is registered by itself,
175
     * if it is created from the admin area,
176
     * then the login type that created the account
177
     *
178
     * @return mixed|string
179
     */
180
    public function getRegistrationType()
181
    {
182
        if ($this->registration_type > 0) {
183
            if (($model = User::findOne($this->registration_type)) !== null) {
184
                return $model->username;
185
            }
186
        }
187
        return $this->getRegistrationTypeName();
188
    }
189
190
    /**
191
     * Returns the registration type string
192
     * @return mixed
193
     */
194
    public function getRegistrationTypeName()
195
    {
196
        return ArrayHelper::getValue(self::getRegistrationTypesArray(), $this->registration_type);
197
    }
198
199
    /**
200
     * Returns an array of log types
201
     * @return array
202
     */
203
    public static function getRegistrationTypesArray()
204
    {
205
        return [
206
            self::TYPE_REGISTRATION_SYSTEM => Module::t('module', 'System'),
207
        ];
208
    }
209
210
    /**
211
     * @param string|integer $id
212
     * @return bool
213
     */
214
    public function isSuperAdmin($id = '')
215
    {
216
        $id = $id ? $id : $this->id;
217
        $authManager = Yii::$app->authManager;
218
        $roles = $authManager->getRolesByUser($id);
219
        foreach ($roles as $role) {
220
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN)
221
                return true;
222
        }
223
        return false;
224
    }
225
226
    /**
227
     * @return bool
228
     */
229
    public function isDeleted()
230
    {
231
        return $this->status === self::STATUS_DELETED;
232
    }
233
234
    /**
235
     * Finds out if password reset token is valid
236
     *
237
     * @param mixed $token password reset token
238
     * @return boolean
239
     */
240
    public static function isPasswordResetTokenValid($token)
241
    {
242
        if (empty($token)) {
243
            return false;
244
        }
245
        $expire = Yii::$app->params['users.passwordResetTokenExpire'];
246
        $parts = explode('_', $token);
247
        $timestamp = (int)end($parts);
248
        return $timestamp + $expire >= time();
249
    }
250
251
    /**
252
     * Set Status
253
     * @return int|string
254
     */
255
    public function setStatus()
256
    {
257
        switch ($this->status) {
258
            case self::STATUS_ACTIVE:
259
                $this->status = self::STATUS_BLOCKED;
260
                break;
261
            case self::STATUS_DELETED:
262
                $this->status = self::STATUS_WAIT;
263
                break;
264
            default:
265
                $this->status = self::STATUS_ACTIVE;
266
        }
267
        return $this->status;
268
    }
269
}
270