Completed
Push — master ( d0bd4d...b4b0fd )
by Igor
23:04
created

PasswordResetRequestForm   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 7
dl 0
loc 68
c 0
b 0
f 0
ccs 22
cts 24
cp 0.9167
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A attributeLabels() 0 6 1
B sendEmail() 0 27 5
A rules() 0 13 1
1
<?php
2
3
namespace app\models\forms;
4
5
use Yii;
6
use yii\base\Exception;
7
use yii\base\UserException;
8
use app\models\entity\User;
9
use app\services\Tokenizer;
10
11
class PasswordResetRequestForm extends \yii\base\Model
12
{
13
    /**
14
     * @var string
15
     */
16
    public $email;
17
18
    /**
19
     * @inheritdoc
20
     */
21 14
    public function rules()
22
    {
23
        return [
24 14
            ['email', 'filter', 'filter' => 'trim'],
25
            ['email', 'required'],
26
            ['email', 'email'],
27 14
            ['email', 'exist',
28 14
                'targetClass' => '\app\models\entity\User',
29
                'filter' => ['status' => User::STATUS_ACTIVE],
30 14
                'message' => Yii::t('app.msg', 'There is no user with such email')
31
            ],
32
        ];
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38 12
    public function attributeLabels()
39
    {
40
        return [
41 12
            'email' => Yii::t('app', 'Email'),
42
        ];
43
    }
44
45
    /**
46
     * Sends an email with a link, for resetting the password
47
     *
48
     * @throws Exception
49
     * @throws UserException
50
     */
51 6
    public function sendEmail(): void
52
    {
53
        /* @var $user User */
54 6
        $user = User::find()->email($this->email)->one();
55 6
        if (!$user) {
56 3
            throw new UserException(Yii::t('app.msg', 'User not found'));
57
        }
58
59 3
        $tokenizer = new Tokenizer();
60 3
        if (!$tokenizer->validate($user->password_reset_token)) {
61 1
            $user->setPasswordResetToken($tokenizer->generate());
62 1
            if (!$user->save()) {
63
                throw new Exception(Yii::t('app.msg', 'An error occurred while saving user'));
64
            }
65
        }
66
67 3
        $sent = Yii::$app->notify->sendMessage(
68 3
            $user->email,
69 3
            Yii::t('app', 'Password Reset'),
70 3
            'passwordResetToken',
71 3
            ['user' => $user]
72
        );
73
74 3
        if (!$sent) {
75
            throw new UserException(Yii::t('app.msg', 'An error occurred while sending a message to reset password'));
76
        }
77 3
    }
78
}
79