PasswordResetRequestForm::sendEmail()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 29
ccs 0
cts 25
cp 0
rs 9.6666
cc 4
nc 4
nop 0
crap 20
1
<?php
2
namespace App\Http\Form;
3
4
use App\Model\User;
5
use Yii;
6
use yii\base\Model;
7
8
/**
9
 * Password reset request form
10
 */
11
class PasswordResetRequestForm extends Model
12
{
13
    public $email;
14
15
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function rules()
20
    {
21
        return [
22
            ['email', 'trim'],
23
            ['email', 'required'],
24
            ['email', 'email'],
25
            ['email', 'exist',
26
                'targetClass' => User::class,
27
                'filter' => ['status' => User::STATUS_ACTIVE],
28
                'message' => 'There is no user with this email address.'
29
            ],
30
        ];
31
    }
32
33
    /**
34
     * Sends an email with a link, for resetting the password.
35
     *
36
     * @return bool whether the email was send
37
     */
38
    public function sendEmail()
39
    {
40
        /* @var $user User */
41
        $user = User::findOne([
42
            'status' => User::STATUS_ACTIVE,
43
            'email' => $this->email,
44
        ]);
45
46
        if (!$user) {
0 ignored issues
show
introduced by
$user is of type App\Model\User, thus it always evaluated to true.
Loading history...
47
            return false;
48
        }
49
        
50
        if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
51
            $user->generatePasswordResetToken();
52
            if (!$user->save()) {
53
                return false;
54
            }
55
        }
56
57
        return Yii::$app
58
            ->mailer
59
            ->compose(
60
                ['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
61
                ['user' => $user]
62
            )
63
            ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
64
            ->setTo($this->email)
65
            ->setSubject('Password reset for ' . Yii::$app->name)
66
            ->send();
67
    }
68
}
69