Role::getRoleChild()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace modules\rbac\models;
4
5
use Yii;
6
use yii\base\Model;
7
use modules\rbac\traits\ModuleTrait;
8
use modules\rbac\Module;
9
use yii\rbac\Item;
10
11
/**
12
 * Class Role
13
 * @package modules\rbac\models
14
 *
15
 * @property-read \yii\rbac\Role[] $roleChild
16
 * @property-read array $roleChildArray
17
 * @property-read Item[] $children
18
 * @property-read array $rolePermissions
19
 * @property-read array|string[] $rolesArray
20
 * @property-read array $roleItemsArray
21
 * @property-read \yii\rbac\Role[] $roles
22
 */
23
class Role extends Model
24
{
25
    use ModuleTrait;
26
27
    // константы ролей
28
    const ROLE_SUPER_ADMIN = 'super_admin';
29
    const ROLE_SUPER_ADMIN_DESCRIPTION = 'Super Administrator';
30
31
    const ROLE_ADMIN = 'admin';
32
    const ROLE_ADMIN_DESCRIPTION = 'Administrator';
33
34
    const ROLE_MANAGER = 'manager';
35
    const ROLE_MANAGER_DESCRIPTION = 'Manager';
36
37
    const ROLE_EDITOR = 'editor';
38
    const ROLE_EDITOR_DESCRIPTION = 'Editor';
39
40
    const ROLE_DEFAULT = 'user';
41
    const ROLE_DEFAULT_DESCRIPTION = 'User';
42
43
    // сценарии
44
    const SCENARIO_CREATE = 'create';
45
    const SCENARIO_UPDATE = 'update';
46
47
    public $name;
48
    public $description;
49
    public $isNewRecord = false;
50
51
    /** @var  array $rolesByRole Наследуемые роли */
52
    public $rolesByRole;
53
    /** @var  array $itemsRoles Доступные роли */
54
    public $itemsRoles;
55
56
    /** @var  array $permissionsByRole Установленные разрешения для роли */
57
    public $permissionsByRole;
58
    /** @var array $itemsPermissions Разрешения */
59
    public $itemsPermissions;
60
61
    /**
62
     * @inheritdoc
63
     * @return array
64
     */
65
    public function rules()
66
    {
67
        return [
68
            ['name', 'required', 'on' => self::SCENARIO_CREATE],
69
            ['name', 'string', 'max' => 64, 'on' => self::SCENARIO_CREATE],
70
            [
71
                'name',
72
                'match',
73
                'pattern' => '#^[\w_-]+$#i',
74
                'message' => Module::t(
75
                    'module',
76
                    'It is allowed to use the Latin alphabet, numbers, dashes and underscores.(A-z,0-1,-,_)'
77
                ),
78
                'on' => self::SCENARIO_CREATE
79
            ],
80
            [
81
                'name',
82
                'validateUniqueName',
83
                'skipOnEmpty' => false,
84
                'skipOnError' => false,
85
                'on' => [self::SCENARIO_CREATE]
86
            ],
87
88
            [['description'], 'string'],
89
            [
90
                ['rolesByRole', 'itemsRoles', 'permissionsByRole', 'itemsPermissions'],
91
                'required',
92
                'message' => Module::t(
93
                    'module',
94
                    'You must select in the field «{attribute}».'
95
                ),
96
                'on' => self::SCENARIO_UPDATE
97
            ],
98
        ];
99
    }
100
101
    /**
102
     * @param string $attribute
103
     */
104
    public function validateUniqueName($attribute)
105
    {
106
        if (!$attribute) {
107
            $this->addError($attribute, Module::t('module', 'Enter name role.'));
108
        }
109
        if (!$this->hasErrors()) {
110
            $this->processCheckRoleName($attribute);
111
        }
112
    }
113
114
    /**
115
     * @param string $attribute
116
     * @return mixed
117
     */
118
    public function processCheckRoleName($attribute)
119
    {
120
        if (!empty($this->name)) {
121
            $auth = Yii::$app->authManager;
122
            if ($auth->getRole($this->name)) {
123
                $this->addError($attribute, Module::t('module', 'This name is already taken.'));
124
            }
125
        }
126
        return $attribute;
127
    }
128
129
    /**
130
     * @return array
131
     */
132
    public function scenarios()
133
    {
134
        $scenarios = parent::scenarios();
135
        $scenarios[self::SCENARIO_CREATE] = ['name', 'description'];
136
        $scenarios[self::SCENARIO_UPDATE] = [
137
            'name', 'description', 'rolesByRole', 'itemsRoles', 'permissionsByRole', 'itemsPermissions'
138
        ];
139
        return $scenarios;
140
    }
141
142
    /**
143
     * @inheritdoc
144
     * @return array
145
     */
146
    public function attributeLabels()
147
    {
148
        return [
149
            'name' => Module::t('module', 'Name'),
150
            'description' => Module::t('module', 'Description'),
151
            'rolesByRole' => Module::t('module', 'Roles by role'),
152
            'itemsRoles' => Module::t('module', 'Items roles'),
153
            'permissionsByRole' => Module::t('module', 'Permissions by role'),
154
            'itemsPermissions' => Module::t('module', 'Items permissions'),
155
        ];
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    public function getRolesArray()
162
    {
163
        return [
164
            self::ROLE_SUPER_ADMIN => self::ROLE_SUPER_ADMIN_DESCRIPTION,
165
            self::ROLE_ADMIN => self::ROLE_ADMIN_DESCRIPTION,
166
            self::ROLE_MANAGER => self::ROLE_MANAGER_DESCRIPTION,
167
            self::ROLE_EDITOR => self::ROLE_EDITOR_DESCRIPTION,
168
            self::ROLE_DEFAULT => self::ROLE_DEFAULT_DESCRIPTION,
169
        ];
170
    }
171
172
    /**
173
     * Возвращает установленные разрешения для роли
174
     * @return array
175
     */
176
    public function getPermissionsByRole()
177
    {
178
        $auth = Yii::$app->authManager;
179
        $perm = $auth->getPermissionsByRole($this->name);
180
        $arr = [];
181
        foreach ($perm as $value) {
182
            if ($value->name != $this->name) {
183
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
184
            }
185
        }
186
        return $arr;
187
    }
188
189
    /**
190
     * Возвращает все разрешения
191
     * @return array
192
     */
193
    public function getItemsPermissions()
194
    {
195
        $auth = Yii::$app->authManager;
196
        $perm = $auth->getPermissions();
197
        $arr = [];
198
        foreach ($perm as $value) {
199
            if ($value->name != $this->name) {
200
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
201
            }
202
        }
203
        $permByRole = $this->getPermissionsByRole();
204
        return array_diff($arr, $permByRole);
205
    }
206
207
    /**
208
     * Возвращает дочерние роли
209
     * @return array
210
     */
211
    public function getRolesByRole()
212
    {
213
        $auth = Yii::$app->authManager;
214
        $roles = $auth->getChildRoles($this->name);
215
        $arr = [];
216
        foreach ($roles as $value) {
217
            if ($value->name != $this->name) {
218
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
219
            }
220
        }
221
        return $arr;
222
    }
223
224
    /**
225
     * Возвращает все роли
226
     * @return array
227
     */
228
    public function getItemsRoles()
229
    {
230
        $auth = Yii::$app->authManager;
231
        $roles = $auth->getRoles();
232
        $arr = [];
233
        foreach ($roles as $value) {
234
            if ($value->name != $this->name) {
235
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
236
            }
237
        }
238
        $rolesByRole = $this->getRolesByRole();
239
        return array_diff($arr, $rolesByRole);
240
    }
241
242
    /**
243
     * @return \yii\rbac\Role[]
244
     */
245
    public function getRoleChild()
246
    {
247
        $auth = Yii::$app->authManager;
248
        return $auth->getChildRoles($this->name);
249
    }
250
251
    /**
252
     * Возвращает массив дочерних ролей
253
     * @return array
254
     */
255
    public function getRoleChildArray()
256
    {
257
        $roles = $this->getRoleChild();
258
        $arr = [];
259
        foreach ($roles as $value) {
260
            if ($value->name != $this->name) {
261
                $arr[$value->name] = $value->description;
262
            }
263
        }
264
        return $arr;
265
    }
266
267
    /**
268
     * Получаем все роли
269
     * @return \yii\rbac\Role[]
270
     */
271
    public function getRoles()
272
    {
273
        $auth = Yii::$app->authManager;
274
        return $auth->getRoles();
275
    }
276
277
    /**
278
     * Возвращает массив ролей
279
     * @return array
280
     */
281
    public function getRoleItemsArray()
282
    {
283
        $roles = $this->getRoles();
284
        $arr = [];
285
        foreach ($roles as $value) {
286
            if ($value->name != $this->name) {
287
                $arr[$value->name] = $value->description;
288
            }
289
        }
290
        return $arr;
291
    }
292
293
    /**
294
     *
295
     * @return array
296
     */
297
    public function getRolePermissions()
298
    {
299
        $auth = Yii::$app->authManager;
300
        $children = $auth->getChildren($this->name);
301
        $perm = [];
302
        foreach ($children as $key => $child) {
303
            if ($child->type == 2) {
304
                $perm[$key] = $child;
305
            }
306
        }
307
        return $perm;
308
    }
309
310
    /**
311
     * Все дети
312
     * @return Item[]
313
     */
314
    public function getChildren()
315
    {
316
        $auth = Yii::$app->authManager;
317
        return $auth->getChildren($this->name);
318
    }
319
}
320