Completed
Push — master ( 21b574...bdc881 )
by Andrii
07:23
created

src/models/LoginForm.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * HiSite Yii2 base project.
4
 *
5
 * @link      https://github.com/hiqdev/hisite
6
 * @package   hisite
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hisite\models;
12
13
use Yii;
14
use yii\base\Model;
15
16
/**
17
 * LoginForm is the model behind the login form.
18
 *
19
 * @property User|null $user This property is read-only
20
 */
21
class LoginForm extends Model
22
{
23
    public $username;
24
    public $password;
25
    public $rememberMe = true;
26
27
    private $_user = false;
28
29
    /**
30
     * @return array the validation rules
31
     */
32
    public function rules()
33
    {
34
        return [
35
            // username and password are both required
36
            [['username', 'password'], 'required'],
37
            // rememberMe must be a boolean value
38
            ['rememberMe', 'boolean'],
39
            // password is validated by validatePassword()
40
            ['password', 'validatePassword'],
41
        ];
42
    }
43
44
    /**
45
     * Validates the password.
46
     * This method serves as the inline validation for password.
47
     *
48
     * @param string $attribute the attribute currently being validated
49
     * @param array $params the additional name-value pairs given in the rule
50
     */
51
    public function validatePassword($attribute, $params)
0 ignored issues
show
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...
52
    {
53
        if (!$this->hasErrors()) {
54
            $user = $this->getUser();
55
56
            if (!$user || !$user->validatePassword($this->password)) {
57
                $this->addError($attribute, 'Incorrect username or password.');
58
            }
59
        }
60
    }
61
62
    /**
63
     * Logs in a user using the provided username and password.
64
     * @return boolean whether the user is logged in successfully
65
     */
66
    public function login()
67
    {
68
        if ($this->validate()) {
69
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
70
        }
71
72
        return false;
73
    }
74
75
    /**
76
     * Finds user by [[username]].
77
     *
78
     * @return User|null
79
     */
80
    public function getUser()
81
    {
82
        if ($this->_user === false) {
83
            $this->_user = User::findByUsername($this->username);
84
        }
85
86
        return $this->_user;
87
    }
88
}
89