PasswordResetRequestForm   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
eloc 30
c 1
b 0
f 1
dl 0
loc 68
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A rules() 0 10 1
A getUser() 0 19 4
A sendEmail() 0 17 2
1
<?php
2
3
namespace modules\users\models;
4
5
use Yii;
6
use yii\base\Model;
7
use modules\users\Module;
8
9
/**
10
 * Class PasswordResetRequestForm
11
 * @package modules\users\models
12
 *
13
 * @property-read bool|User $user
14
 * @property string $email Email
15
 */
16
class PasswordResetRequestForm extends Model
17
{
18
    public $email;
19
20
    /**
21
     * @inheritdoc
22
     * @return array
23
     */
24
    public function rules()
25
    {
26
        return [
27
            ['email', 'trim'],
28
            ['email', 'required'],
29
            ['email', 'email'],
30
            ['email', 'exist',
31
                'targetClass' => User::class,
32
                'filter' => ['status' => User::STATUS_ACTIVE],
33
                'message' => Module::t('module', 'There is no users with this e-mail.'),
34
            ],
35
        ];
36
    }
37
38
    /**
39
     * Sends an email with a link, for resetting the password.
40
     *
41
     * @return bool whether the email was send
42
     */
43
    public function sendEmail()
44
    {
45
46
        if ($user = $this->getUser()) {
47
            return Yii::$app->mailer->compose(
48
                [
49
                    'html' => '@modules/users/mail/passwordResetToken-html',
50
                    'text' => '@modules/users/mail/passwordResetToken-text'
51
                ],
52
                ['user' => $user]
53
            )
54
                ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
55
                ->setTo($this->email)
56
                ->setSubject(Yii::$app->name . ' | ' . Module::t('module', 'Access recovery'))
57
                ->send();
58
        }
59
        return false;
60
    }
61
62
    /**
63
     * @return bool|User
64
     */
65
    private function getUser()
66
    {
67
        /* @var $user User */
68
        $user = User::findOne([
69
            'status' => User::STATUS_ACTIVE,
70
            'email' => $this->email,
71
        ]);
72
73
        if ($user === null) {
74
            return false;
75
        }
76
77
        if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
78
            $user->generatePasswordResetToken();
79
            if (!$user->save()) {
80
                return false;
81
            }
82
        }
83
        return $user;
84
    }
85
}
86