Completed
Push — master ( 3da316...265344 )
by Pavel
02:57
created

User::afterSave()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
rs 9.4285
ccs 8
cts 8
cp 1
cc 2
eloc 7
nc 2
nop 2
crap 2
1
<?php
2
/**
3
 * User model for the module yii2-activeuser
4
 *
5
 * @link https://github.com/inblank/yii2-activeuser
6
 * @copyright Copyright (c) 2016 Pavel Aleksandrov <[email protected]>
7
 * @license http://opensource.org/licenses/MIT
8
 */
9
10
namespace inblank\activeuser\models;
11
12
use inblank\activeuser\traits\CommonTrait;
13
use inblank\image\ImageBehavior;
14
use yii;
15
use yii\db\ActiveRecord;
16
use yii\web\IdentityInterface;
17
18
/**
19
 * This is the model class for table "{{%activeuser_users}}"
20
 *
21
 * Table fields:
22
 * @property integer $id user identifier
23
 * @property integer $status user status. STATUS_ACTIVE, STATUS_BLOCKED, STATUS_CONFIRM, STATUS_RESTORE
24
 * @property string $email user email used as login
25
 * @property string $pass_hash hash of user password
26
 * @property string $name real user name
27
 * @property int $gender user gender. User::MALE, User::FEMALE. If empty, not set
28
 * @property string $birth user birth date
29
 * @property string $avatar user avatar filename
30
 * @property string $access_token user access token for use site API
31
 * @property string $auth_key user key for access by `remember me`
32
 * @property string $token token for registration confirm or restore password
33
 * @property int $token_created_at the time when the token was created
34
 * @property string $registered_at user registration date
35
 *
36
 * By getters:
37
 * @property $statusText user status as text
38
 * @property $genderText user gender as text
39
 *
40
 * Relations:
41
 * @property Profile $profile user profile data
42
 *
43
 * @mixin ImageBehavior
44
 */
45
class User extends ActiveRecord implements yii\web\IdentityInterface
46
{
47
    use CommonTrait;
48
49
    /** Male gender */
50
    const MALE = 1;
51
    /** Female gender */
52
    const FEMALE = 2;
53
54
    /** Active user status */
55
    const STATUS_ACTIVE = 1;
56
    /** Blocked user status */
57
    const STATUS_BLOCKED = 2;
58
    /** User await email confirmation status */
59
    const STATUS_CONFIRM = 3;
60
    /** User await access restore status */
61
    const STATUS_RESTORE = 4;
62
63
    // TODO where store password between data enter and confirmation email? Password must be send with congratulation email
64
    /** @var string password field on registration on restore */
65
    public $password;
66
67
    /**
68
     * @inheritdoc
69
     */
70 15
    public static function tableName()
71
    {
72 15
        return '{{%activeuser_users}}';
73
    }
74
75
    /**
76
     * @inheritdoc
77
     * @return UserQuery the active query used by this AR class.
78
     */
79 14
    public static function find()
80
    {
81 14
        $queryClass = self::di('UserQuery');
82 14
        return new $queryClass(get_called_class());
83
    }
84
85
    /**
86
     * Finds an identity by the given ID.
87
     * @param string|integer $id the ID to be looked for
88
     * @return IdentityInterface the identity object that matches the given ID.
89
     * Null should be returned if such an identity cannot be found
90
     * or the identity is not in an active state (disabled, deleted, etc.)
91
     */
92 2
    public static function findIdentity($id)
93
    {
94 2
        return static::findOne($id);
95
    }
96
97
    /**
98
     * Find user by token
99
     * @param string $token for search
100
     * @return null|static
101
     */
102 3
    public static function findByToken($token)
103
    {
104 3
        return empty($token) ? null : static::findOne(['token' => $token]);
105
    }
106
107
    /**
108
     * Finds an identity by the given token.
109
     * @param mixed $token the token to be looked for
110
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
111
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
112
     * @return IdentityInterface the identity object that matches the given token.
113
     * Null should be returned if such an identity cannot be found
114
     * or the identity is not in an active state (disabled, deleted, etc.)
115
     */
116 1
    public static function findIdentityByAccessToken($token, $type = null)
117
    {
118 1
        if (empty($token)) {
119 1
            return null;
120
        }
121 1
        return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
122
    }
123
124
    /**
125
     * Confirm user registration
126
     * @return bool return false if cannot confirm.
127
     * If in errors list has key `error`, that user already confirmed
128
     * If in errors list has key `token`, that confirm token was expired
129
     */
130 3
    public function confirm()
131
    {
132 3
        if ($this->isConfirmed()) {
133 1
            $this->addError('error', Yii::t('activeuser_general', 'User already confirmed'));
134 1
            return false;
135
        }
136 3
        if ($this->isConfirmTokenExpired()) {
137 1
            $this->addError('token', Yii::t('activeuser_general', 'You token was expired'));
138 1
            return false;
139
        }
140 3
        $this->updateAttributes([
141 3
            'token' => null,
142 3
            'token_created_at' => 0,
143 3
            'status' => self::STATUS_ACTIVE,
144
        ]);
145 3
        $this->module->sendMessage('register', [
146 3
            'user' => $this,
147
        ]);
148 3
        return true;
149
    }
150
151
    /**
152
     * Check that user was confirmed
153
     * @return bool
154
     */
155 6
    public function isConfirmed()
156
    {
157 6
        return $this->status !== self::STATUS_CONFIRM;
158
    }
159
160
    /**
161
     * Checks that the token was expired
162
     * @param int $timeToExpire time
163
     * @return bool
164
     */
165 3
    public function isTokenExpired($timeToExpire)
166
    {
167 3
        return $this->token_created_at + $timeToExpire < time();
168
    }
169
170
    /**
171
     * Checks that the confirmation token was expired
172
     * @return bool
173
     */
174 3
    public function isConfirmTokenExpired()
175
    {
176 3
        return $this->isTokenExpired($this->getModule()->confirmationTime);
177
    }
178
179
    /**
180
     * Checks that the restore token was expired
181
     * @return bool
182
     */
183 1
    public function isRestoreTokenExpired()
184
    {
185 1
        return $this->isTokenExpired($this->getModule()->restoreTime);
186
    }
187
188
    /**
189
     * @inheritdoc
190
     */
191 10
    public function rules()
192
    {
193
        // todo check password length
194
        return [
195 10
            [['email', 'password'], 'required'],
196
            ['email', 'unique'],
197
            ['email', 'string', 'max' => 200],
198
            ['email', 'email'],
199
            ['name', 'string', 'max' => 200],
200
            ['name', function () {
201 10
                if (in_array('name', $this->module->registrationFields) && empty($this->name)) {
202 2
                    $this->addError('name', Yii::t('activeuser_general', 'Name cannot be blank.'));
203
                }
204 10
            }, 'skipOnEmpty' => false],
205 10
            ['status', 'in', 'range' => [
206 10
                self::STATUS_ACTIVE,
207 10
                self::STATUS_BLOCKED,
208 10
                self::STATUS_CONFIRM,
209 10
                self::STATUS_RESTORE,
210
            ]],
211
            ['status', 'default', 'value' => function () {
212 9
                return $this->module->enableConfirmation ? self::STATUS_CONFIRM : self::STATUS_ACTIVE;
213 10
            }],
214 10
            ['gender', 'in', 'range' => [
215 10
                0,
216 10
                self::MALE,
217 10
                self::FEMALE,
218
            ]],
219
            ['birth', 'date', 'format' => 'php:Y-m-d', 'skipOnEmpty' => true,],
220
            ['token_created_at', 'integer'],
221
            ['registered_at', 'date', 'format' => 'php:Y-m-d H:i:s'],
222 10
            ['registered_at', 'default', 'value' => function () {
223 10
                return date('Y-m-d H:i:s');
224 10
            }],
225
            // rules below for prevent nullable value of attributes
226
            [['name', 'avatar'], 'default', 'value' => ''],
227
            [['gender', 'token_created_at'], 'default', 'value' => 0],
228
        ];
229
    }
230
231
    /**
232
     * @inheritdoc
233
     */
234 1
    public function attributeLabels()
235
    {
236
        return [
237 1
            'id' => 'ID',
238 1
            'status' => Yii::t('activeuser_general', 'Status'),
239 1
            'email' => Yii::t('activeuser_general', 'Email'),
240 1
            'password' => Yii::t('activeuser_general', 'Password'),
241 1
            'pass_hash' => Yii::t('activeuser_general', 'Password hash'),
242 1
            'name' => Yii::t('activeuser_general', 'Name'),
243 1
            'gender' => Yii::t('activeuser_general', 'Gender'),
244 1
            'birth' => Yii::t('activeuser_general', 'Birth'),
245 1
            'avatar' => Yii::t('activeuser_general', 'Avatar'),
246 1
            'access_token' => Yii::t('activeuser_general', 'Access token'),
247 1
            'auth_key' => Yii::t('activeuser_general', 'Auth key'),
248 1
            'token' => Yii::t('activeuser_general', 'Token'),
249 1
            'token_created_at' => Yii::t('activeuser_general', 'Token created'),
250 1
            'registered_at' => Yii::t('activeuser_general', 'Registered'),
251
        ];
252
    }
253
254
    /**
255
     * Get user profile
256
     * @return yii\db\ActiveQuery
257
     */
258 1
    public function getProfile()
259
    {
260 1
        return $this->hasOne(self::di('Profile'), ['user_id' => 'id']);
261
    }
262
263
    /**
264
     * @inheritdoc
265
     */
266 10
    public function beforeSave($insert)
267
    {
268 10
        if (!parent::beforeSave($insert)) {
269 1
            return false;
270
        }
271 9
        if ($this->getIsNewRecord() && !empty($this->password)) {
272 9
            $this->pass_hash = Yii::$app->getSecurity()->generatePasswordHash($this->password);
273
        }
274 9
        return true;
275
    }
276
277
    /**
278
     * @inheritdoc
279
     */
280 9
    public function afterSave($insert, $changedAttributes)
281
    {
282 9
        if ($insert) {
283
            // add profile for new user
284 9
            Yii::createObject([
285 9
                'class' => self::di('Profile'),
286 9
                'user_id' => $this->id,
287 9
            ])->save();
288
        }
289 9
        parent::afterSave($insert, $changedAttributes);
290 9
    }
291
292
    /**
293
     * @inheritdoc
294
     */
295 10
    public function transactions()
296
    {
297
        return [
298 10
            self::SCENARIO_DEFAULT => self::OP_INSERT,
299
        ];
300
    }
301
302
    /**
303
     * Returns an ID that can uniquely identify a user identity.
304
     * @return string|integer an ID that uniquely identifies a user identity.
305
     */
306 2
    public function getId()
307
    {
308 2
        return $this->id;
309
    }
310
311
    /**
312
     * Validates the given auth key.
313
     *
314
     * This is required if [[User::enableAutoLogin]] is enabled.
315
     * @param string $authKey the given auth key
316
     * @return boolean whether the given auth key is valid.
317
     * @see getAuthKey()
318
     */
319 1
    public function validateAuthKey($authKey)
320
    {
321 1
        $userAuthKey = $this->getAuthKey();
322 1
        return $this->status === self::STATUS_ACTIVE && !empty($userAuthKey) && $userAuthKey === $authKey;
323
    }
324
325
    /**
326
     * Returns a key that can be used to check the validity of a given identity ID.
327
     *
328
     * The key should be unique for each individual user, and should be persistent
329
     * so that it can be used to check the validity of the user identity.
330
     *
331
     * The space of such keys should be big enough to defeat potential identity attacks.
332
     *
333
     * This is required if [[User::enableAutoLogin]] is enabled.
334
     * @return string a key that is used to check the validity of a given identity ID.
335
     * @see validateAuthKey()
336
     */
337 1
    public function getAuthKey()
338
    {
339 1
        return $this->auth_key;
340
    }
341
342
    /**
343
     * Check active user
344
     * @return bool
345
     */
346 2
    public function isActive()
347
    {
348 2
        return $this->status === self::STATUS_ACTIVE;
349
    }
350
351
    /**
352
     * User creation
353
     * For create the user you always must set attributes `email`, `password` and `name`
354
     * @param bool $sendEmail whether to send email about registration
355
     * @return bool
356
     */
357 1
    public function create($sendEmail = false)
358
    {
359 1
        $oldRegisterFields = $this->module->registrationFields;
360 1
        $this->module->registrationFields = ['password', 'name'];
361 1 View Code Duplication
        if ($this->getIsNewRecord() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
362 1
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
363
        }
364 1
        $generatedPassword = false;
365 1
        if (empty($this->password)) {
366
            // password autogenerate
367 1
            $generatedPassword = true;
368 1
            $this->password = $this->generatePassword();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->generatePassword() can also be of type array. However, the property $password is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
369
        }
370 1
        $this->status = self::STATUS_ACTIVE;
371 1
        $isCreated = $this->save();
372 1
        $this->module->registrationFields = $oldRegisterFields;
373 1
        if (!$isCreated) {
374 1
            if ($generatedPassword) {
375
                $this->password = null;
376
            }
377 1
            return false;
378
        }
379 1
        if ($sendEmail) {
380
            // send email with registration congratulation
381 1
            $this->module->sendMessage('register', [
382 1
                'user' => $this,
383
            ]);
384
        }
385 1
        return true;
386
    }
387
388
    /**
389
     * User registration
390
     * @return bool
391
     */
392 8
    public function register()
393
    {
394 8 View Code Duplication
        if ($this->getIsNewRecord() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
395 1
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
396
        }
397 8
        if (!$this->module->enableRegistration) {
398 1
            $this->addError('registration', Yii::t('activeuser_general', 'Registration is not available'));
399 1
            return false;
400
        }
401 8
        if (!in_array('password', $this->module->registrationFields)) {
402
            // password autogenerate
403 6
            $this->password = $this->generatePassword();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->generatePassword() can also be of type array. However, the property $password is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
404
        }
405 8
        if (!$this->save()) {
406 1
            return false;
407
        }
408 8
        if ($this->module->enableConfirmation) {
409 8
            $this->generateToken();
410
            // send email with confirm link
411 8
            $this->module->sendMessage('confirm', [
412 8
                'user' => $this,
413
            ]);
414 1
        } elseif ($this->module->enableRegistrationEmail) {
415
            // send email with registration congratulation
416 1
            $this->module->sendMessage('register', [
417 1
                'user' => $this,
418
            ]);
419
        }
420 8
        return true;
421
    }
422
423
    /**
424
     * Password generator
425
     * @return mixed
426
     */
427 7
    public function generatePassword()
428
    {
429 7
        return (new \PWGen())->generate();
430
    }
431
432
    /**
433
     * Generate special hash
434
     * @return string
435
     */
436 8
    public function generateToken()
437
    {
438 8
        $this->updateAttributes([
439 8
            'token' => Yii::$app->security->generateRandomString(40),
440 8
            'token_created_at' => time(),
441
        ]);
442 8
        return $this->token;
443
    }
444
445
    /**
446
     * Start password restore procedure
447
     * @return bool
448
     */
449 1
    public function restore()
450
    {
451 1
        if (!$this->module->enablePasswordRestore) {
452 1
            $this->addError('error', Yii::t('activeuser_general', 'Password restore by email is disabled'));
453 1
            return false;
454
        }
455 1
        if ($this->isBlocked() || !$this->isConfirmed()) {
456 1
            $this->addError('error', Yii::t('activeuser_general', 'You cannot start restore procedure'));
457 1
            return false;
458
        }
459 1
        $this->generateToken();
460 1
        $this->updateAttributes([
461 1
            'status' => self::STATUS_RESTORE,
462
        ]);
463 1
        $this->module->sendMessage('restore', [
464 1
            'user' => $this,
465
        ]);
466 1
        return true;
467
    }
468
469
    /**
470
     * Check blocked user
471
     * @return bool
472
     */
473 4
    public function isBlocked()
474
    {
475 4
        return $this->status === self::STATUS_BLOCKED;
476
    }
477
478
    /**
479
     * Block user
480
     * @param bool $sendMail whether to send confirmation email about blocking.
481
     * If null, use global setting Module::$enableBlockingEmail
482
     * @return bool return false if user already blocked or not confirmed
483
     */
484 1 View Code Duplication
    public function block($sendMail = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
485
    {
486 1
        if ($this->isBlocked() || !$this->isConfirmed()) {
487 1
            return false;
488
        }
489 1
        if ($sendMail === null) {
490 1
            $sendMail = $this->module->enableBlockingEmail;
491
        }
492 1
        $this->updateAttributes([
493 1
            'status' => self::STATUS_BLOCKED
494
        ]);
495 1
        if ($sendMail) {
496 1
            $this->module->sendMessage('block', [
497 1
                'user' => $this,
498
            ]);
499
        }
500 1
        return true;
501
    }
502
503
    /**
504
     * Unblock user
505
     * @param bool $sendMail whether to send confirmation email about unblocking.
506
     * If null, use global setting Module::$enableUnblockingEmail
507
     * @return bool return false if user not blocked
508
     */
509 1 View Code Duplication
    public function unblock($sendMail = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
510
    {
511 1
        if (!$this->isBlocked()) {
512 1
            return false;
513
        }
514 1
        if ($sendMail === null) {
515 1
            $sendMail = $this->module->enableBlockingEmail;
516
        }
517 1
        $this->updateAttributes([
518 1
            'status' => self::STATUS_ACTIVE
519
        ]);
520 1
        if ($sendMail) {
521 1
            $this->module->sendMessage('unblock', [
522 1
                'user' => $this,
523
            ]);
524
        }
525 1
        return true;
526
    }
527
528
    /**
529
     * Change the user password
530
     * @return bool
531
     */
532 1
    public function changePassword()
533
    {
534 1
        if (!$this->isRestore()) {
535 1
            $this->addError('error', Yii::t('activeuser_general', 'User not request restore procedure'));
536 1
            return false;
537
        }
538 1
        if ($this->isRestoreTokenExpired()) {
539 1
            $this->addError('token', Yii::t('activeuser_general', 'You token was expired'));
540 1
            return false;
541
        }
542 1
        if (empty($this->password) && !$this->module->generatePassOnRestore) {
543 1
            $this->addError('password', Yii::t('activeuser_general', 'Password cannot be blank'));
544 1
            return false;
545
        }
546 1
        $this->status = self::STATUS_ACTIVE;
547 1
        $this->newPassword();
548 1
        return true;
549
    }
550
551
    /**
552
     * Set new password
553
     * @param bool $sendEmail whether to send email about password change
554
     * @throws yii\base\Exception
555
     * @throws yii\base\InvalidConfigException
556
     */
557 1
    public function newPassword($sendEmail = null)
558
    {
559 1
        if (empty($this->password)) {
560 1
            $this->password = $this->generatePassword();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->generatePassword() can also be of type array. However, the property $password is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
561
        }
562 1
        $this->updateAttributes([
563 1
            'pass_hash' => Yii::$app->getSecurity()->generatePasswordHash($this->password),
564
            'token' => null,
565 1
            'token_created_at' => 0,
566 1
            'status' => $this->status,
567
        ]);
568 1
        if ($sendEmail === null) {
569 1
            $sendEmail = $this->getModule()->enableNewPasswordEmail;
570
        }
571 1
        if ($sendEmail) {
572 1
            $this->module->sendMessage('passchanged', [
573 1
                'user' => $this,
574
            ]);
575
        }
576 1
    }
577
578
    /**
579
     * Check that user request restore
580
     * @return bool
581
     */
582 2
    public function isRestore()
583
    {
584 2
        return $this->status === self::STATUS_RESTORE;
585
    }
586
587
    /**
588
     * Get user status as text
589
     * @param string $status status value. If not set, get from model
590
     * @return null|string
591
     */
592
    public function getStatusText($status = null)
593
    {
594
        if ($status === null) {
595
            $status = $this->status;
596
        }
597
        switch ($status) {
598
            case self::STATUS_ACTIVE:
599
                $statusText = 'Active';
600
                break;
601
            case self::STATUS_BLOCKED:
602
                $statusText = 'Blocked';
603
                break;
604
            case self::STATUS_CONFIRM:
605
                $statusText = 'Confirm';
606
                break;
607
            case self::STATUS_RESTORE:
608
                $statusText = 'Restore';
609
                break;
610
            default:
611
                return null;
612
        }
613
        return Yii::t('activeuser_general', $statusText);
614
    }
615
616
    /**
617
     * Get status list as array
618
     * @return array
619
     */
620
    public function statusesList()
621
    {
622
        return [
623
            self::STATUS_ACTIVE => $this->getStatusText(self::STATUS_ACTIVE),
624
            self::STATUS_BLOCKED => $this->getStatusText(self::STATUS_BLOCKED),
625
            self::STATUS_CONFIRM => $this->getStatusText(self::STATUS_CONFIRM),
626
            self::STATUS_RESTORE => $this->getStatusText(self::STATUS_RESTORE),
627
        ];
628
    }
629
630
    /**
631
     * Get user gender as text
632
     * @param int $gender gender value. If not set, get from model
633
     * @return null|string
634
     */
635
    public function getGenderText($gender = null)
636
    {
637
        if ($gender === null) {
638
            $gender = $this->gender;
639
        }
640
        switch ($gender) {
641
            case self::MALE:
642
                $genderText = 'Men';
643
                break;
644
            case self::FEMALE:
645
                $genderText = 'Women';
646
                break;
647
            default:
648
                return null;
649
        }
650
        return Yii::t('activeuser_general', $genderText);
651
    }
652
653
    /**
654
     * Get gender list as array
655
     * @return array
656
     */
657
    public function gendersList()
658
    {
659
        return [
660
            self::MALE => $this->getGenderText(self::MALE),
661
            self::FEMALE => $this->getGenderText(self::FEMALE),
662
        ];
663
    }
664
665
    /**
666
     * Resend confirmation message
667
     */
668
    public function resend()
669
    {
670
        if ($this->getModule()->enableConfirmation && !$this->getIsNewRecord() && $this->status === self::STATUS_CONFIRM) {
671
            $this->generateToken();
672
            $this->getModule()->sendMessage('confirm', [
673
                'user' => $this,
674
            ]);
675
        }
676
    }
677
678
    /**
679
     * @inheritdoc
680
     */
681 14
    public function behaviors()
682
    {
683
        return [
684
            [
685 14
                'class' => ImageBehavior::className(),
686 14
                'imageAttribute' => 'avatar',
687 14
                'imageSize' => 150,
688 14
                'imageResizeStrategy' => ImageBehavior::CROP,
689
            ]
690
        ];
691
    }
692
}
693