ResetPasswordForm::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 6
c 2
b 0
f 0
dl 0
loc 10
rs 10
cc 4
nc 3
nop 2
1
<?php
2
3
namespace modules\users\models;
4
5
use yii\base\Exception;
6
use yii\base\Model;
7
use yii\base\InvalidArgumentException;
8
use modules\users\Module;
9
10
/**
11
 * Class ResetPasswordForm
12
 * @package modules\users\models\frontend
13
 *
14
 * @property string $password Password
15
 */
16
class ResetPasswordForm extends Model
17
{
18
    public $password;
19
20
    /**
21
     * @var User
22
     */
23
    private $user;
24
25
    /**
26
     * Creates a form model given a token.
27
     *
28
     * @param mixed $token
29
     * @param array $config name-value pairs that will be used to initialize the object properties
30
     * @throws InvalidArgumentException if token is empty or not valid
31
     */
32
    public function __construct($token = '', $config = [])
33
    {
34
        if (empty($token) || !is_string($token)) {
35
            throw new InvalidArgumentException(Module::translate('module', 'Password reset token cannot be blank.'));
36
        }
37
        $this->user = User::findByPasswordResetToken($token);
38
        if (!$this->user) {
39
            throw new InvalidArgumentException(Module::translate('module', 'Wrong password reset token.'));
40
        }
41
        parent::__construct($config);
42
    }
43
44
    /**
45
     * @inheritdoc
46
     * @return array
47
     */
48
    public function rules()
49
    {
50
        return [
51
            ['password', 'required'],
52
            [
53
                'password',
54
                'string',
55
                'min' => User::LENGTH_STRING_PASSWORD_MIN,
56
                'max' => User::LENGTH_STRING_PASSWORD_MAX
57
            ],
58
        ];
59
    }
60
61
    /**
62
     * @inheritdoc
63
     * @return array
64
     */
65
    public function attributeLabels()
66
    {
67
        return [
68
            'password' => Module::translate('module', 'New Password'),
69
        ];
70
    }
71
72
    /**
73
     * Resets password.
74
     *
75
     * @return bool if password was reset.
76
     * @throws Exception
77
     */
78
    public function resetPassword()
79
    {
80
        $user = $this->user;
81
        $user->setPassword($this->password);
82
        $user->removePasswordResetToken();
83
        return $user->save(false);
84
    }
85
}
86