Passed
Push — master ( 7ce3f4...5e32cd )
by for
14:35
created

User   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 43
c 2
b 1
f 0
dl 0
loc 187
rs 10
wmc 18

16 Methods

Rating   Name   Duplication   Size   Complexity  
A isPasswordResetTokenValid() 0 9 2
A findByPasswordResetToken() 0 9 2
A validatePassword() 0 3 1
A findIdentity() 0 6 1
A rules() 0 6 1
A fields() 0 19 1
A validateAuthKey() 0 3 1
A removePasswordResetToken() 0 3 1
A tableName() 0 3 1
A behaviors() 0 6 1
A getId() 0 3 1
A generateAuthKey() 0 3 1
A generatePasswordResetToken() 0 3 1
A setPassword() 0 3 1
A getAuthKey() 0 3 1
A findIdentityByAccessToken() 0 4 1
1
<?php
2
3
namespace app\core\models;
4
5
use app\core\types\UserStatus;
6
use Yii;
7
use yii\behaviors\TimestampBehavior;
8
use yii\db\ActiveRecord;
9
use yii\web\IdentityInterface;
10
use yiier\helpers\DateHelper;
11
12
/**
13
 * This is the model class for table "{{%user}}".
14
 *
15
 * @property int $id
16
 * @property string $username
17
 * @property string|null $avatar
18
 * @property string $auth_key
19
 * @property string $password_hash
20
 * @property string|null $password_reset_token
21
 * @property string|null $email
22
 * @property int|null $status 状态:1正常 0冻结
23
 * @property string $base_currency_code
24
 * @property int|null $created_at
25
 * @property int|null $updated_at
26
 *
27
 * @property-write string $password
28
 * @property-read string $authKey
29
 */
30
class User extends ActiveRecord implements IdentityInterface
31
{
32
    /**
33
     * @inheritdoc
34
     */
35
    public static function tableName()
36
    {
37
        return '{{%user}}';
38
    }
39
40
    /**
41
     * @inheritdoc
42
     * @throws \yii\base\InvalidConfigException
43
     */
44
    public function behaviors()
45
    {
46
        return [
47
            [
48
                'class' => TimestampBehavior::class,
49
                'value' => Yii::$app->formatter->asDatetime('now')
50
            ],
51
        ];
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    public function rules()
58
    {
59
        return [
60
            ['status', 'default', 'value' => UserStatus::ACTIVE],
61
            ['status', 'in', 'range' => [UserStatus::ACTIVE, UserStatus::UNACTIVATED]],
62
            [['username'], 'string', 'max' => 60],
63
        ];
64
    }
65
66
    /**
67
     * @inheritdoc
68
     */
69
    public static function findIdentity($id)
70
    {
71
        return static::find()
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::find()->w...TIVE))->limit(1)->one() also could return the type array|yii\db\ActiveRecord which is incompatible with the return type mandated by yii\web\IdentityInterface::findIdentity() of null|yii\web\IdentityInterface.
Loading history...
72
            ->where(['id' => $id, 'status' => UserStatus::ACTIVE])
73
            ->limit(1)
74
            ->one();
75
    }
76
77
78
    /**
79
     * @param mixed $token
80
     * @param null $type
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $type is correct as it would always require null to be passed?
Loading history...
81
     * @return void|IdentityInterface
82
     */
83
    public static function findIdentityByAccessToken($token, $type = null)
84
    {
85
        $userId = (string)$token->getClaim('id');
86
        return self::findIdentity($userId);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::findIdentity($userId) also could return the type array|yii\db\ActiveRecord which is incompatible with the documented return type yii\web\IdentityInterface.
Loading history...
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function getId()
93
    {
94
        return $this->getPrimaryKey();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getPrimaryKey() also could return the type array which is incompatible with the return type mandated by yii\web\IdentityInterface::getId() of integer|string.
Loading history...
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function getAuthKey()
101
    {
102
        return $this->auth_key;
103
    }
104
105
    /**
106
     * @inheritdoc
107
     */
108
    public function validateAuthKey($authKey)
109
    {
110
        return $this->getAuthKey() === $authKey;
111
    }
112
113
    /**
114
     * Validates password
115
     *
116
     * @param string $password password to validate
117
     * @return bool if password provided is valid for current user
118
     */
119
    public function validatePassword($password)
120
    {
121
        return Yii::$app->security->validatePassword($password, $this->password_hash);
122
    }
123
124
    /**
125
     * Generates password hash from password and sets it to the model
126
     *
127
     * @param string $password
128
     * @throws \yii\base\Exception
129
     */
130
    public function setPassword($password)
131
    {
132
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
133
    }
134
135
    /**
136
     * Generates "remember me" authentication key
137
     * @throws \yii\base\Exception
138
     */
139
    public function generateAuthKey()
140
    {
141
        $this->auth_key = Yii::$app->security->generateRandomString();
142
    }
143
144
    /**
145
     * Generates new password reset token
146
     * @throws \yii\base\Exception
147
     */
148
    public function generatePasswordResetToken()
149
    {
150
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
151
    }
152
153
    /**
154
     * Removes password reset token
155
     */
156
    public function removePasswordResetToken()
157
    {
158
        $this->password_reset_token = null;
159
    }
160
161
    /**
162
     * Finds user by password reset token
163
     *
164
     * @param string $token password reset token
165
     * @return User|array|ActiveRecord|null
166
     */
167
    public static function findByPasswordResetToken($token)
168
    {
169
        if (!static::isPasswordResetTokenValid($token)) {
170
            return null;
171
        }
172
173
        return static::find()
174
            ->where(['password_reset_token' => $token, 'status' => [UserStatus::ACTIVE]])
175
            ->one();
176
    }
177
178
    /**
179
     * Finds out if password reset token is valid
180
     *
181
     * @param string $token password reset token
182
     * @return boolean
183
     */
184
    public static function isPasswordResetTokenValid($token)
185
    {
186
        if (empty($token)) {
187
            return false;
188
        }
189
190
        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
191
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
192
        return $timestamp + $expire >= time();
193
    }
194
195
    /**
196
     * @return array
197
     */
198
    public function fields()
199
    {
200
        $fields = parent::fields();
201
        unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);
202
203
        $fields['created_at'] = function (self $model) {
204
            return DateHelper::datetimeToIso8601($model->created_at);
0 ignored issues
show
Bug introduced by
It seems like $model->created_at can also be of type null; however, parameter $dateStr of yiier\helpers\DateHelper::datetimeToIso8601() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

204
            return DateHelper::datetimeToIso8601(/** @scrutinizer ignore-type */ $model->created_at);
Loading history...
205
        };
206
207
        $fields['avatar'] = function (self $model) {
208
            $avatar = md5(strtolower(trim($model->avatar)));
0 ignored issues
show
Bug introduced by
It seems like $model->avatar can also be of type null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

208
            $avatar = md5(strtolower(trim(/** @scrutinizer ignore-type */ $model->avatar)));
Loading history...
209
            return "https://www.gravatar.com/avatar/{$avatar}?s=48";
210
        };
211
212
        $fields['updated_at'] = function (self $model) {
213
            return DateHelper::datetimeToIso8601($model->updated_at);
0 ignored issues
show
Bug introduced by
It seems like $model->updated_at can also be of type null; however, parameter $dateStr of yiier\helpers\DateHelper::datetimeToIso8601() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

213
            return DateHelper::datetimeToIso8601(/** @scrutinizer ignore-type */ $model->updated_at);
Loading history...
214
        };
215
216
        return $fields;
217
    }
218
}
219