1
|
|
|
<?php |
2
|
|
|
namespace App\Http\Api\Backend\Model; |
3
|
|
|
|
4
|
|
|
use App\Model\User as BaseUser; |
5
|
|
|
use yii\helpers\ArrayHelper; |
6
|
|
|
use Yii; |
7
|
|
|
|
8
|
|
|
class User extends BaseUser |
9
|
|
|
{ |
10
|
|
|
public $role_names; |
11
|
|
|
|
12
|
|
|
public function rules() |
13
|
|
|
{ |
14
|
|
|
return array_merge(parent::rules(), [ |
15
|
|
|
[['role_names'], 'required'], |
16
|
|
|
['role_names', 'each', 'rule' => ['validateRole']], |
17
|
|
|
]); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function validateRole($attribute) |
21
|
|
|
{ |
22
|
|
|
$roleName = $this->$attribute; |
23
|
|
|
if (!Yii::$app->getAuthManager()->getRole($roleName)) { |
24
|
|
|
$this->addError($attribute, Yii::t('yii', '{attribute} is invalid.', [ |
25
|
|
|
'attribute' => sprintf("%s '%s'", $this->getAttributeLabel($attribute), $roleName) |
26
|
|
|
])); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function afterSave($insert, $changedAttributes) |
31
|
|
|
{ |
32
|
|
|
parent::afterSave($insert, $changedAttributes); |
33
|
|
|
|
34
|
|
|
$this->saveRoles(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private function saveRoles() |
38
|
|
|
{ |
39
|
|
|
if (empty($this->role_names)) { |
40
|
|
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$auth = Yii::$app->getAuthManager(); |
44
|
|
|
// revoke |
45
|
|
|
$auth->revokeAll($this->id); |
46
|
|
|
// assign |
47
|
|
|
foreach ($this->role_names as $name) { |
48
|
|
|
$auth->assign($auth->getRole($name), $this->id); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function extraFields() |
53
|
|
|
{ |
54
|
|
|
return [ |
55
|
|
|
'roles', |
56
|
|
|
'role_names' => 'roleNames', |
57
|
|
|
]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getRoles() |
61
|
|
|
{ |
62
|
|
|
$roles = Yii::$app->getAuthManager()->getRolesByUser($this->id); |
63
|
|
|
return ArrayHelper::getColumn($roles, function ($element) { |
64
|
|
|
return [ |
65
|
|
|
'name' => $element->name, |
66
|
|
|
'description' => $element->description, |
67
|
|
|
]; |
68
|
|
|
}, false); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function getRoleNames() |
72
|
|
|
{ |
73
|
|
|
$roles = Yii::$app->getAuthManager()->getRolesByUser($this->id); |
74
|
|
|
return array_column($roles, 'name'); |
75
|
|
|
} |
76
|
|
|
} |