Completed
Push — master ( d0bd4d...b4b0fd )
by Igor
23:04
created

UserForm::rules()   B

Complexity

Conditions 3
Paths 1

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.4326

Importance

Changes 0
Metric Value
dl 0
loc 38
c 0
b 0
f 0
ccs 7
cts 11
cp 0.6364
rs 8.8571
cc 3
eloc 25
nc 1
nop 0
crap 3.4326
1
<?php
2
3
namespace app\modules\admin\models\forms;
4
5
use Yii;
6
use yii\base\Exception;
7
use yii\helpers\ArrayHelper;
8
use app\models\entity\{AuthItem, User};
9
10
class UserForm extends \yii\base\Model
11
{
12
    /**
13
     * @var int
14
     */
15
    public $id;
16
    /**
17
     * @var string
18
     */
19
    public $username;
20
    /**
21
     * @var string
22
     */
23
    public $email;
24
    /**
25
     * @var string
26
     */
27
    public $date_create;
28
    /**
29
     * @var string
30
     */
31
    public $date_update;
32
    /**
33
     * @var string
34
     */
35
    public $date_login;
36
    /**
37
     * @var int
38
     */
39
    public $ip;
40
    /**
41
     * @var string
42
     */
43
    public $role_name;
44
    /**
45
     * @var int
46
     */
47
    public $status;
48
    /**
49
     * @var string
50
     */
51
    public $passwordNew;
52
    /**
53
     * @var \app\models\entity\User
54
     */
55
    private $model;
56
57
   /**
58
    * @return array the validation rules.
59
    */
60 2
    public function rules()
61
    {
62
        return [
63 2
            ['username', 'string', 'min' => 3, 'max' => 40],
64
            ['username', 'match', 'pattern' => '/^[a-zA-Z0-9_-]+$/'],
65 2
            ['username', 'unique', 'targetClass' => User::class, 'filter' => function ($query) {
66
                if (!$this->model()->isNewRecord) {
67
                    $query->andWhere(['not', ['id' => $this->model()->id]]);
68
                }
69 2
            }],
70
            ['username', 'default', 'value' => null],
71
72
            ['email', 'email'],
73
            ['email', 'required'],
74
            ['email', 'string', 'max' => 255],
75 2
            ['email', 'unique', 'targetClass' => User::class, 'filter' => function ($query) {
76
                if (!$this->model()->isNewRecord) {
77
                    $query->andWhere(['not', ['id' => $this->model()->id]]);
78
                }
79 2
            }],
80
            ['email', 'default', 'value' => null],
81
82
            ['role_name', 'string'],
83
            [
84
                'role_name',
85
                'exist',
86
                'targetClass' => AuthItem::class,
87
                'targetAttribute' => ['role_name' => 'name'],
88
                'filter' => ['type' => \yii\rbac\Item::TYPE_ROLE]
89
            ],
90
91
            ['status', 'integer'],
92
            ['status', 'default', 'value' => User::STATUS_ACTIVE],
93 2
            ['status', 'in', 'range' => array_keys(User::getStatuses())],
94
95
            ['passwordNew', 'string', 'min' => 6],
96
        ];
97
    }
98
99
    /**
100
     * @inheritdoc
101
     */
102 2
    public function attributeLabels()
103
    {
104
        return [
105 2
            'id' => Yii::t('app', 'ID'),
106 2
            'username' => Yii::t('app', 'Username'),
107 2
            'email' => Yii::t('app', 'Email'),
108 2
            'password' => Yii::t('app', 'Password'),
109 2
            'date_create' => Yii::t('app', 'Date create'),
110 2
            'date_update' => Yii::t('app', 'Date update'),
111 2
            'date_login' => Yii::t('app', 'Last login'),
112 2
            'ip' => Yii::t('app', 'IP'),
113 2
            'role_name' => Yii::t('app', 'Role'),
114 2
            'status' => Yii::t('app', 'Status'),
115
116 2
            'passwordNew' => Yii::t('app', 'New password'),
117
        ];
118
    }
119
120
    /**
121
     * @inheritdoc
122
     * @codeCoverageIgnore
123
     */
124
    public function attributeHints()
125
    {
126
        return [
127
            'username' => Yii::t('app', 'Only letters, numbers, symbols _ and -'),
128
            'passwordNew' => Yii::t('app', 'Set a new password')
129
        ];
130
    }
131
132
    /**
133
     * Set model
134
     *
135
     * @param User $model
136
     */
137 1
    public function setModel(User $model): void
138
    {
139 1
        $this->model = $model;
140
141 1
        $this->id = $model->id;
142 1
        $this->username = $model->username;
143 1
        $this->email = $model->email;
144 1
        $this->date_create = $model->date_create;
145 1
        $this->date_update = $model->date_update;
146 1
        $this->date_login = $model->date_login;
147 1
        $this->ip = $model->id;
148 1
        $this->role_name = $model->role_name;
149 1
        $this->status = $model->status;
150 1
    }
151
152
    /**
153
     * Get model
154
     *
155
     * @return User
156
     */
157 2
    public function model(): User
158
    {
159 2
        if ($this->model === null) {
160 1
            $this->model = new User();
161
        }
162
163 2
        return $this->model;
164
    }
165
166
    /**
167
     * Save user
168
     *
169
     * @throws Exception
170
     * @return User
171
     */
172
    public function save(): User
173
    {
174
        $model = $this->model();
175
176
        $model->id = $this->id;
177
        $model->username = $this->username;
178
        $model->email = $this->email;
179
        $model->date_create = $this->date_create;
180
        $model->date_update = $this->date_update;
181
        $model->date_login = $this->date_login;
182
        $model->ip = $this->id;
183
        $model->role_name = $this->role_name;
184
        $model->status = $this->status;
185
        $model->passwordNew = $this->passwordNew;
186
187
        if ($model->isNewRecord) {
188
            $model->setConfirmed();
189
        }
190
191
        if (!$model->save()) {
192
            throw new Exception(Yii::t('app.msg', 'An error occurred while saving user'));
193
        }
194
195
        $this->id = $model->id;
196
197
        $this->assignUserToRole($model->id, $model->role_name);
198
199
        return $model;
200
    }
201
202 2
    public function statusesList(): array
203
    {
204 2
        return $this->model()->getStatuses();
205
    }
206
207 2
    public function rolesList(): array
208
    {
209 2
        $list = Yii::$app->authManager->getRoles();
210 2
        return ArrayHelper::map($list, 'name', 'description');
211
    }
212
213
    private function assignUserToRole(int $userId, string $roleName = ''): void
214
    {
215
        $auth = Yii::$app->authManager;
216
        $auth->revokeAll($userId);
217
218
        if (!empty($roleName)) {
219
            $role = $auth->getRole($roleName);
220
            if ($role) {
221
                $auth->assign($role, $userId);
222
            }
223
        }
224
    }
225
}
226