Completed
Push — master ( c3cfbd...a5cba6 )
by Igor
01:40
created

PasswordResetRequestForm::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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