PasswordResetRequestForm::sendEmail()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 9.2088
c 0
b 0
f 0
cc 5
nc 6
nop 0
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', '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', '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', 'An error occurred while saving user'));
73
            }
74
        }
75
76
        $sent = Yii::$app->mailer
77
            ->compose('passwordResetToken', ['user' => $user])
78
            ->setTo($user->email)
79
            ->setSubject(Yii::t('app', 'Password Reset'))
80
            ->send();
81
82
        if (!$sent) {
83
            throw new UserException(Yii::t('app', 'An error occurred while sending a message to reset password'));
84
        }
85
    }
86
}
87