Passed
Push — master ( c21c1f...04db2a )
by Wilmer
01:51
created

PasswordResetRequestForm::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace app\basic\forms;
4
5
use app\basic\models\UserModels;
6
use yii\base\Application;
7
use yii\base\Model;
8
use yii\mail\MailerInterface;
9
10
/**
11
 * PasswordResetRequestForm is the model behind the password reset request form Web Application Basic.
12
 **/
13
class PasswordResetRequestForm extends Model
14
{
15
    public $email;
16
17
    private $_user;
18
    
19
    protected $app;
20
21
    /**
22
     * __construct
23
     *
24
     * @param Application $app
25
     **/
26
    public function __construct(Application $app)
27
    {
28
        $this->app = $app;
29
    }
30
    
31
	/**
32
     * rules
33
     *
34
	 * @return array the validation rules.
35
	 **/
36
	public function rules()
37
	{
38
		return [
39
			['email', 'trim'],
40
			['email', 'required'],
41
			['email', 'email'],
42
			['email', 'exist',
43
				'targetClass' => UserModels::class,
44
				'filter' => ['status' => UserModels::STATUS_ACTIVE],
45
				'message' => $this->app->t('basic', 'There is no user with this email address.'),
46
			],
47
		];
48
	}
49
50
	/**
51
	 * atributeLabels
52
	 * Translate Atribute Labels.
53
     *
54
	 * @return array customized attribute labels.
55
	 **/
56
	public function attributeLabels()
57
	{
58
		return [
59
			'email' => $this->app->t('basic', 'Email'),
60
		];
61
	}
62
63
	/**
64
     * sendEmail
65
	 * Sends an email with a link, for resetting the password.
66
	 *
67
	 * @return bool whether the email was send.
68
	 **/
69
	public function sendEmail(MailerInterface $mailer)
70
	{
71
		$this->_user = UserModels::findOne([
72
			'status' => UserModels::STATUS_ACTIVE,
73
			'email' => $this->email,
74
		]);
75
76
		if (!$this->_user) {
77
			return false;
78
		}
79
80
		if (!UserModels::isPasswordResetTokenValid($this->_user->password_reset_token)) {
81
			$this->_user->generatePasswordResetToken();
82
			if (!$this->_user->save()) {
83
				return false;
84
			}
85
		}
86
87
        return $mailer->compose(
88
			['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
89
			['user' => $this->_user]
90
		)
91
		->setFrom([$this->app->params['adminEmail'] => $this->app->name . ' robot'])
92
		->setTo($this->email)
93
		->setSubject('Password reset for ' . $this->app->name)
94
		->send();
95
	}
96
}
97