Passed
Push — master ( 40d7bb...2ec62b )
by Alexey
02:41
created

User::beforeDelete()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 11
c 0
b 0
f 0
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
namespace modules\users\models;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
use yii\helpers\Html;
8
use modules\users\models\query\UserQuery;
9
use modules\users\Module;
10
11
/**
12
 * Class User
13
 * @package modules\users\models
14
 *
15
 * @property array statusesArray Array statuses
16
 * @property string userFullName Full user name
17
 * @property int|string registrationType Type registered
18
 * @property int $registration_type Type Registration
19
 * @property string statusLabelName Status name in label
20
 * @property string statusName Status name
21
 */
22
class User extends IdentityUser
23
{
24
    const LENGTH_STRING_PASSWORD_MIN = 6;
25
    const LENGTH_STRING_PASSWORD_MAX = 16;
26
27
    const SCENARIO_ADMIN_CREATE = 'adminCreate';
28
    const SCENARIO_ADMIN_UPDATE = 'adminUpdate';
29
    const SCENARIO_ADMIN_PASSWORD_UPDATE = 'adminPasswordUpdate';
30
    const SCENARIO_PROFILE_UPDATE = 'profileUpdate';
31
    const SCENARIO_PASSWORD_UPDATE = 'passwordUpdate';
32
    const SCENARIO_PROFILE_DELETE = 'profileDelete';
33
34
    /**
35
     * @var string
36
     */
37
    public $currentPassword;
38
39
    /**
40
     * @var string
41
     */
42
    public $newPassword;
43
44
    /**
45
     * @var string
46
     */
47
    public $newPasswordRepeat;
48
49
    /**
50
     * @return array
51
     */
52
    public function rules()
53
    {
54
        return ArrayHelper::merge(parent::rules(), [
55
            ['status', 'integer'],
56
            ['status', 'default', 'value' => self::STATUS_WAIT],
57
            ['status', 'in', 'range' => array_keys(self::getStatusesArray())],
58
59
            [['newPassword', 'newPasswordRepeat'], 'required', 'on' => [self::SCENARIO_ADMIN_CREATE, self::SCENARIO_PASSWORD_UPDATE, self::SCENARIO_ADMIN_PASSWORD_UPDATE]],
60
            ['newPassword', 'string', 'min' => self::LENGTH_STRING_PASSWORD_MIN],
61
            ['newPasswordRepeat', 'compare', 'compareAttribute' => 'newPassword'],
62
            ['currentPassword', 'validateCurrentPassword', 'skipOnEmpty' => false, 'skipOnError' => false],
63
        ]);
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    public function scenarios()
70
    {
71
        $scenarios = parent::scenarios();
72
        $scenarios[self::SCENARIO_ADMIN_CREATE] = ['avatar', 'username', 'email', 'status', 'newPassword', 'newPasswordRepeat', 'registration_type', 'first_name', 'last_name'];
73
        $scenarios[self::SCENARIO_ADMIN_UPDATE] = ['username', 'email', 'status', 'first_name', 'last_name', 'newPassword', 'newPasswordRepeat'];
74
        $scenarios[self::SCENARIO_ADMIN_PASSWORD_UPDATE] = ['newPassword', 'newPasswordRepeat'];
75
        $scenarios[self::SCENARIO_PASSWORD_UPDATE] = ['currentPassword', 'newPassword', 'newPasswordRepeat'];
76
        $scenarios[self::SCENARIO_PROFILE_UPDATE] = ['username', 'email', 'first_name', 'last_name'];
77
        $scenarios[self::SCENARIO_PROFILE_DELETE] = ['status'];
78
        $scenarios['default'] = ['username', 'email', 'first_name', 'last_name', 'password_hash', 'status', 'auth_key', 'email_confirm_token'];
79
        return $scenarios;
80
    }
81
82
    /**
83
     * @return array
84
     */
85
    public function attributeLabels()
86
    {
87
        return ArrayHelper::merge(parent::attributeLabels(), [
88
            'userRoleName' => Module::t('module', 'Role'),
89
            'currentPassword' => Module::t('module', 'Current Password'),
90
            'newPassword' => Module::t('module', 'New Password'),
91
            'newPasswordRepeat' => Module::t('module', 'Repeat Password'),
92
        ]);
93
    }
94
95
    /**
96
     * Type of registration
97
     * How the user is created
98
     * If the system registration type is registered by itself,
99
     * if it is created from the admin area,
100
     * then the login type that created the account
101
     *
102
     * @return mixed|string
103
     */
104
    public function getRegistrationType()
105
    {
106
        if ($this->registration_type > 0) {
107
            if (($model = User::findOne($this->registration_type)) !== null) {
108
                return $model->username;
109
            }
110
        }
111
        return $this->getRegistrationTypeName();
112
    }
113
114
    /**
115
     * Returns the registration type string
116
     * @return mixed
117
     */
118
    public function getRegistrationTypeName()
119
    {
120
        return ArrayHelper::getValue(self::getRegistrationTypesArray(), $this->registration_type);
121
    }
122
123
    /**
124
     * Returns an array of log types
125
     * @return array
126
     */
127
    public static function getRegistrationTypesArray()
128
    {
129
        return [
130
            self::TYPE_REGISTRATION_SYSTEM => Module::t('module', 'System'),
131
        ];
132
    }
133
134
    /**
135
     * @param string $attribute
136
     */
137
    public function validateCurrentPassword($attribute)
138
    {
139
        if (!empty($this->newPassword) && !empty($this->newPasswordRepeat) && !$this->hasErrors()) {
140
            $this->processValidatePassword($attribute);
141
        } else {
142
            $this->addError($attribute, Module::t('module', 'Not all fields are filled in correctly.'));
143
        }
144
    }
145
146
    /**
147
     * @param string $attribute
148
     */
149
    protected function processValidatePassword($attribute)
150
    {
151
        if ($attribute) {
152
            if (!$this->validatePassword($this->$attribute))
153
                $this->addError($attribute, Module::t('module', 'Incorrect current password.'));
154
        } else {
155
            $this->addError($attribute, Module::t('module', 'Enter your current password.'));
156
        }
157
    }
158
159
    /**
160
     * @return array
161
     */
162
    public static function getStatusesArray()
163
    {
164
        return [
165
            self::STATUS_BLOCKED => Module::t('module', 'Blocked'),
166
            self::STATUS_ACTIVE => Module::t('module', 'Active'),
167
            self::STATUS_WAIT => Module::t('module', 'Wait'),
168
            self::STATUS_DELETED => Module::t('module', 'Deleted'),
169
        ];
170
    }
171
172
    /**
173
     * Set Status
174
     * @return int|string
175
     */
176
    public function setStatus()
177
    {
178
        switch ($this->status) {
179
            case self::STATUS_ACTIVE:
180
                $this->status = self::STATUS_BLOCKED;
181
                break;
182
            case self::STATUS_DELETED:
183
                $this->status = self::STATUS_WAIT;
184
                break;
185
            default:
186
                $this->status = self::STATUS_ACTIVE;
187
        }
188
        return $this->status;
189
    }
190
191
    /**
192
     * @param integer|string $id
193
     * @return bool
194
     */
195
    public function isSuperAdmin($id = '')
196
    {
197
        $id = $id ? $id : $this->id;
198
        $authManager = Yii::$app->authManager;
199
        $roles = $authManager->getRolesByUser($id);
200
        foreach ($roles as $role) {
201
            if ($role->name == \modules\rbac\models\Role::ROLE_SUPER_ADMIN)
202
                return true;
203
        }
204
        return false;
205
    }
206
207
    /**
208
     * @return bool
209
     */
210
    public function isDeleted()
211
    {
212
        return $this->status === self::STATUS_DELETED;
213
    }
214
215
    /**
216
     * @return mixed
217
     */
218
    public function getStatusName()
219
    {
220
        return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
221
    }
222
223
    /**
224
     * Return <span class="label label-success">Active</span>
225
     * @return string
226
     */
227
    public function getStatusLabelName()
228
    {
229
        $name = ArrayHelper::getValue(self::getLabelsArray(), $this->status);
230
        return Html::tag('span', $this->getStatusName(), ['class' => 'label label-' . $name]);
231
    }
232
233
    /**
234
     * @return array
235
     */
236
    public static function getLabelsArray()
237
    {
238
        return [
239
            self::STATUS_BLOCKED => 'default',
240
            self::STATUS_ACTIVE => 'success',
241
            self::STATUS_WAIT => 'warning',
242
            self::STATUS_DELETED => 'danger',
243
        ];
244
    }
245
246
    /**
247
     * @return object|\yii\db\ActiveQuery
248
     * @throws \yii\base\InvalidConfigException
249
     */
250
    public static function find()
251
    {
252
        return Yii::createObject(UserQuery::class, [get_called_class()]);
253
    }
254
255
    /**
256
     * Actions before saving
257
     *
258
     * @param bool $insert
259
     * @return bool
260
     */
261
    /**
262
     * Actions before saving
263
     *
264
     * @param bool $insert
265
     * @return bool
266
     * @throws \yii\base\Exception
267
     */
268
    public function beforeSave($insert)
269
    {
270
        if (parent::beforeSave($insert)) {
271
            if ($insert) {
272
                $this->generateAuthKey();
273
            }
274
            if (!empty($this->newPassword)) {
275
                $this->setPassword($this->newPassword);
276
            }
277
            return true;
278
        }
279
        return false;
280
    }
281
282
    /**
283
     * @return bool
284
     */
285
    public function beforeDelete()
286
    {
287
        if (!parent::beforeDelete()) {
288
            return false;
289
        }
290
291
        $authManager = Yii::$app->getAuthManager();
292
        if ($authManager->getRolesByUser($this->id)) {
293
            $authManager->revokeAll($this->id);
294
        }
295
        return true;
296
    }
297
}
298