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

AuthItemForm::rules()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
dl 0
loc 15
c 0
b 0
f 0
ccs 4
cts 6
cp 0.6667
rs 9.4285
cc 2
eloc 9
nc 1
nop 0
crap 2.1481
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;
9
10
class AuthItemForm extends \yii\base\Model
11
{
12
    /**
13
     * @var string
14
     */
15
    public $name;
16
    /**
17
     * @var string
18
     */
19
    public $description;
20
    /**
21
     * @var array
22
     */
23
    public $roles;
24
    /**
25
     * @var array
26
     */
27
    public $permissions;
28
    /**
29
     * @var int
30
     */
31
    public $created_at;
32
    /**
33
     * @var int
34
     */
35
    public $updated_at;
36
    /**
37
     * @var \app\models\entity\AuthItem
38
     */
39
    private $model;
40
41
   /**
42
    * @return array the validation rules.
43
    */
44 2
    public function rules()
45
    {
46
        return [
47 2
            [['name', 'description'], 'required'],
48
            [['roles', 'permissions'], 'safe'],
49
50 2
            ['name', 'unique', 'targetClass' => AuthItem::class, 'filter' => function ($query) {
51
                if (!$this->model()->isNewRecord) {
52
                    $query->andWhere(['not', ['name' => $this->model()->name]]);
53
                }
54 2
            }],
55
            ['name', 'string', 'max' => 64],
56
            ['name', 'match', 'pattern' => '/^[a-z]\w*$/i'],
57
        ];
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63 2
    public function attributeLabels()
64
    {
65
        return [
66 2
            'name'        => Yii::t('app', 'Name'),
67 2
            'description' => Yii::t('app', 'Description'),
68 2
            'roles'       => Yii::t('app', 'Inherit role'),
69 2
            'permissions' => Yii::t('app', 'Permissions'),
70
        ];
71
    }
72
73
    /**
74
     * Set model
75
     *
76
     * @param AuthItem $model
77
     */
78 1
    public function setModel(AuthItem $model): void
79
    {
80 1
        $this->model = $model;
81
82 1
        $this->name = $model->name;
83 1
        $this->description = $model->description;
84 1
        $this->created_at = $model->created_at;
85 1
        $this->updated_at = $model->updated_at;
86
87 1
        $permissions = Yii::$app->authManager->getPermissionsByRole($this->name);
88 1
        $this->permissions = ArrayHelper::index($permissions, 'name', []);
89 1
        $this->permissions = array_keys($this->permissions);
90
91 1
        $roles = Yii::$app->authManager->getChildren($this->name);
92 1
        $this->roles = ArrayHelper::index($roles, 'name', []);
93 1
        $this->roles = array_keys($this->roles);
94 1
    }
95
96
    /**
97
     * Get model
98
     *
99
     * @return AuthItem
100
     */
101 2
    public function model(): AuthItem
102
    {
103 2
        if ($this->model === null) {
104 1
            $this->model = new AuthItem();
105
        }
106
107 2
        return $this->model;
108
    }
109
110
    /**
111
     * Save auth item
112
     *
113
     * @throws Exception
114
     * @return AuthItem
115
     */
116
    public function save(): AuthItem
117
    {
118
        $model = $this->model();
119
120
        $model->name = $this->name;
121
        $model->description = $this->description;
122
        $model->type = \yii\rbac\Item::TYPE_ROLE;
123
124
        if (!$model->save()) {
125
            throw new Exception(Yii::t('app.msg', 'An error occurred while saving authItem'));
126
        }
127
128
        if (!$model->isSuperUser()) {
129
            $this->assignRolesAndPermissions();
130
        }
131
132
        return $model;
133
    }
134
135 2
    public function permissionsList(): array
136
    {
137 2
        $list = Yii::$app->authManager->getPermissions();
138 2
        return ArrayHelper::map($list, 'name', function ($row) {
139 2
            return Yii::t('app', $row->description);
140 2
        });
141
    }
142
143 2
    public function rolesList(): array
144
    {
145 2
        $list = Yii::$app->authManager->getRoles();
146 2
        unset($list[$this->model->name]);
147
148 2
        return ArrayHelper::map($list, 'name', 'description');
149
    }
150
151
    private function assignRolesAndPermissions(): void
152
    {
153
        $auth = Yii::$app->authManager;
154
155
        $role = $auth->getRole($this->model->name);
156
        $roles = $auth->getRoles();
157
        $permissions = $auth->getPermissions();
158
159
        $auth->removeChildren($role);
160
161
        if (is_array($this->roles)) {
162
            foreach ($this->roles as $r) {
163
                $auth->addChild($role, $roles[$r]);
164
            }
165
        }
166
167
        if (is_array($this->permissions)) {
168
            $currPermissions = ArrayHelper::index(
169
                $auth->getPermissionsByRole($this->model->name),
170
                'name',
171
                []
172
            );
173
            foreach ($this->permissions as $permission) {
174
                if (!array_key_exists($permission, $currPermissions)) {
175
                    $auth->addChild($role, $permissions[$permission]);
176
                }
177
            }
178
        }
179
    }
180
}
181