Completed
Push — master ( 80a78a...a3bfc4 )
by Alexey
02:29
created

PermissionsController   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 220
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 26
dl 0
loc 220
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A actionAddPermissions() 0 21 4
A actionView() 0 9 1
A actionDelete() 0 10 2
A actionIndex() 0 14 1
A actionUpdate() 0 18 3
A actionRemovePermissions() 0 15 3
A behaviors() 0 16 1
A actionCreate() 0 17 4
A detectLoop() 0 12 4
A actionAjaxValidateForm() 0 10 3
1
<?php
2
3
namespace modules\rbac\controllers\backend;
4
5
use Yii;
6
use yii\data\ArrayDataProvider;
7
use yii\web\Controller;
8
use yii\filters\VerbFilter;
9
use yii\filters\AccessControl;
10
use yii\web\BadRequestHttpException;
11
use yii\widgets\ActiveForm;
12
use modules\rbac\models\Permission;
13
use modules\rbac\Module;
14
15
/**
16
 * Class PermissionsController
17
 * @package modules\rbac\controllers\backend
18
 */
19
class PermissionsController extends Controller
20
{
21
    /**
22
     * @inheritdoc
23
     * @return array
24
     */
25
    public function behaviors()
26
    {
27
        return [
28
            'access' => [
29
                'class' => AccessControl::className(),
30
                'rules' => [
31
                    [
32
                        'allow' => true,
33
                        'roles' => ['managerRbac'],
34
                    ],
35
                ],
36
            ],
37
            'verbs' => [
38
                'class' => VerbFilter::className(),
39
                'actions' => [
40
                    'delete' => ['POST']
41
                ],
42
            ],
43
        ];
44
    }
45
46
    /**
47
     * Lists all Permission models.
48
     * @return mixed
49
     */
50
    public function actionIndex()
51
    {
52
        $auth = Yii::$app->authManager;
53
        $dataProvider = new ArrayDataProvider([
54
            'allModels' => $auth->getPermissions(),
55
            'sort' => [
56
                'attributes' => ['name', 'description', 'ruleName'],
57
            ],
58
            'pagination' => [
59
                'pageSize' => 15,
60
            ],
61
        ]);
62
        return $this->render('index', [
63
            'dataProvider' => $dataProvider,
64
        ]);
65
    }
66
67
    /**
68
     * Displays a single Permission model.
69
     * @param string|int $id
70
     * @return mixed
71
     */
72
    public function actionView($id)
73
    {
74
        $auth = Yii::$app->authManager;
75
        $permission = $auth->getPermission($id);
76
77
        $model = new Permission(['name' => $permission->name]);
78
        return $this->render('view', [
79
            'permission' => $permission,
80
            'model' => $model,
81
        ]);
82
    }
83
84
    /**
85
     * Creates Permission a new Permission model.
86
     * If creation is successful, the browser will be redirected to the 'view' page.
87
     * @return string|\yii\web\Response
88
     * @throws \Exception
89
     */
90
    public function actionCreate()
91
    {
92
        $model = new Permission(['scenario' => Permission::SCENARIO_CREATE]);
93
        $model->isNewRecord = true;
94
95
        if ($model->load(Yii::$app->request->post())) {
96
            if ($model->validate()) {
97
                $auth = Yii::$app->authManager;
98
                $perm = $auth->createPermission($model->name);
99
                $perm->description = $model->description;
100
                if ($auth->add($perm)) {
101
                    return $this->redirect(['view', 'id' => $model->name]);
102
                }
103
            }
104
        }
105
        return $this->render('create', [
106
            'model' => $model,
107
        ]);
108
    }
109
110
    /**
111
     * @return array|bool
112
     */
113
    public function actionAjaxValidateForm()
114
    {
115
        $model = new Permission(['scenario' => Permission::SCENARIO_CREATE]);
116
        $model->isNewRecord = true;
117
118
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
119
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
120
            return ActiveForm::validate($model);
121
        }
122
        return false;
123
    }
124
125
    /**
126
     * Updates an existing Permission model.
127
     * If update is successful, the browser will be redirected to the 'view' page.
128
     * @param string|int $id
129
     * @return string|\yii\web\Response
130
     * @throws \Exception
131
     */
132
    public function actionUpdate($id)
133
    {
134
        $auth = Yii::$app->authManager;
135
        $perm = $auth->getPermission($id);
136
137
        $model = new Permission([
138
            'scenario' => Permission::SCENARIO_UPDATE,
139
            'name' => $perm->name,
140
            'description' => $perm->description,
141
        ]);
142
        if ($model->load(Yii::$app->request->post())) {
143
            $perm->description = $model->description;
144
            if ($auth->update($id, $perm)) {
145
                return $this->redirect(['view', 'id' => $id]);
146
            }
147
        }
148
        return $this->render('update', [
149
            'model' => $model,
150
        ]);
151
    }
152
153
    /**
154
     * Привязываем разрешение
155
     * @return array|\yii\web\Response
156
     * @throws BadRequestHttpException
157
     * @throws \Exception
158
     */
159
    public function actionAddPermissions()
160
    {
161
        $model = new Permission([
162
            'scenario' => Permission::SCENARIO_UPDATE,
163
        ]);
164
        if ($model->load(Yii::$app->request->post())) {
165
            $auth = Yii::$app->authManager;
166
            $permission = $auth->getPermission($model->name);
167
            foreach ($model->permissionItems as $perm) {
168
                $add = $auth->getPermission($perm);
169
                // Проверяем, не является добовляемое разрешение родителем?
170
                $result = $this->detectLoop($permission, $add);
171
                if (!$result) {
172
                    $auth->addChild($permission, $add);
173
                } else {
174
                    Yii::$app->session->setFlash('error', Module::t('module', 'The permission of the "{:parent}" is the parent of the "{:permission}"!', [':parent' => $add->name, ':permission' => $permission->name]));
175
                }
176
            }
177
            return $this->redirect(['update', 'id' => $model->name, '#' => 'assign-container-permissions']);
178
        }
179
        throw new BadRequestHttpException(Module::t('module', 'Not a valid request to the method!'));
180
    }
181
182
    /**
183
     * Отвязываем разрешение
184
     * @return array|\yii\web\Response
185
     * @throws BadRequestHttpException
186
     */
187
    public function actionRemovePermissions()
188
    {
189
        $model = new Permission([
190
            'scenario' => Permission::SCENARIO_UPDATE,
191
        ]);
192
        if ($model->load(Yii::$app->request->post())) {
193
            $auth = Yii::$app->authManager;
194
            $permission = $auth->getPermission($model->name);
195
            foreach ($model->permissions as $perm) {
196
                $remove = $auth->getPermission($perm);
197
                $auth->removeChild($permission, $remove);
198
            }
199
            return $this->redirect(['update', 'id' => $model->name, '#' => 'assign-container-permissions']);
200
        }
201
        throw new BadRequestHttpException(Module::t('module', 'Not a valid request to the method!'));
202
    }
203
204
    /**
205
     * Deletes an existing Permission model.
206
     * If deletion is successful, the browser will be redirected to the 'index' page.
207
     * @param string|int $id
208
     * @return \yii\web\Response
209
     */
210
    public function actionDelete($id)
211
    {
212
        $auth = Yii::$app->authManager;
213
        $perm = $auth->getPermission($id);
214
        if ($auth->remove($perm)) {
215
            Yii::$app->session->setFlash('success', Module::t('module', 'The permission "{:name}" have been successfully deleted.', [':name' => $perm->name]));
216
        } else {
217
            Yii::$app->session->setFlash('error', Module::t('module', 'Error!'));
218
        }
219
        return $this->redirect(['index']);
220
    }
221
222
    /**
223
     * @param object $parent
224
     * @param object $child
225
     * @return bool
226
     */
227
    protected function detectLoop($parent, $child)
228
    {
229
        $auth = Yii::$app->authManager;
230
        if ($child->name === $parent->name) {
231
            return true;
232
        }
233
        foreach ($auth->getChildren($child->name) as $grandchild) {
234
            if ($this->detectLoop($parent, $grandchild)) {
235
                return true;
236
            }
237
        }
238
        return false;
239
    }
240
}
241