LoginForm::validatePassword()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
rs 9.2
cc 4
eloc 5
nc 3
nop 2
1
<?php
2
3
namespace yiicod\auth\models;
4
5
use Yii;
6
use yii\base\Model;
7
use yii\web\User;
8
9
/**
10
 * Login form
11
 */
12
class LoginForm extends Model
13
{
14
    public $username;
15
    public $password;
16
    public $rememberMe = true;
17
18
    private $_user = false;
19
20
    /**
21
     * @inheritdoc
22
     */
23
    public function rules()
24
    {
25
        return [
26
            // username and password are both required
27
            [['username', 'password'], 'required'],
28
            // rememberMe must be a boolean value
29
            ['rememberMe', 'boolean'],
30
            // password is validated by validatePassword()
31
            ['password', 'validatePassword'],
32
        ];
33
    }
34
35
    /**
36
     * Validates the password.
37
     * This method serves as the inline validation for password.
38
     *
39
     * @param string $attribute the attribute currently being validated
40
     * @param array $params the additional name-value pairs given in the rule
41
     */
42
    public function validatePassword($attribute, $params)
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
43
    {
44
        if (!$this->hasErrors()) {
45
            $user = $this->getUser();
46
            if (!$user || !$user->validatePassword($this->password)) {
47
                $this->addError($attribute, 'Incorrect username or password.');
48
            }
49
        }
50
    }
51
52
    /**
53
     * Logs in a user using the provided username and password.
54
     *
55
     * @return bool whether the user is logged in successfully
56
     */
57
    public function login()
58
    {
59
        if ($this->validate()) {
60
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
61
        } else {
62
            return false;
63
        }
64
    }
65
66
    /**
67
     * Finds user by [[username]]
68
     *
69
     * @return User|null
70
     */
71
    public function getUser()
72
    {
73
        if (false === $this->_user) {
74
            $userClass = Yii::$app->get('auth')->modelMap['user']['class'];
75
            $this->_user = $userClass::findByUsername($this->username);
76
        }
77
78
        return $this->_user;
79
    }
80
81
    public function attributeLabels()
82
    {
83
        return \yii\helpers\ArrayHelper::merge(parent::attributeLabels(), [
84
            'username' => 'email',
85
        ]);
86
    }
87
}
88