Completed
Push — master ( 5b873e...d824de )
by Alexey
02:27
created

Role::getRolesByRole()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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