Role::afterSave()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
1
<?php
2
namespace App\Http\Api\Backend\Model;
3
4
use Yii;
5
use yii\rbac\Item;
6
use yii\validators\ExistValidator;
7
8
class Role extends AuthItem
9
{
10
    public $permission_names;
11
12
    public function rules()
13
    {
14
        return array_merge([
15
            ['type', 'default', 'value' => Item::TYPE_ROLE],
16
            ['type', 'in', 'range' => [Item::TYPE_ROLE]],
17
            ['permission_names', 'required'],
18
            [
19
                'permission_names', 'each',
20
                'rule' => ['exist', 'targetClass' => AuthItem::class, 'targetAttribute' => 'name', 'filter' => ['type' => Item::TYPE_PERMISSION]],
21
            ],
22
        ], parent::rules());
23
    }
24
25
    public function afterSave($insert, $changeAttributes)
26
    {
27
        parent::afterSave($insert, $changeAttributes);
28
        $this->savePermissions();
29
    }
30
31
    private function savePermissions()
32
    {
33
        if (empty($this->permission_names)) {
34
            return;
35
        }
36
37
        $auth = Yii::$app->getAuthManager();
38
        $role = $auth->getRole($this->name);
39
        $auth->removeChildren($role);
40
        foreach ($this->permission_names as $permissionName) {
41
            $auth->addChild($role, $auth->getPermission($permissionName));
42
        }
43
    }
44
    
45
    public function extraFields()
46
    {
47
        return [
48
            'permission_names' => 'permissionNames',
49
        ];
50
    }
51
52
    public function getPermissionNames(): array
53
    {
54
        $permissions = Yii::$app->getAuthManager()->getPermissionsByRole($this->name);
55
        return array_column($permissions, 'name');
56
    }
57
}
58