AssignController::beforeAction()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace modules\rbac\controllers;
4
5
use Yii;
6
use modules\rbac\models\Assignment;
7
use yii\data\ArrayDataProvider;
8
use yii\web\Controller;
9
use yii\filters\VerbFilter;
10
use yii\filters\AccessControl;
11
use yii\base\InvalidConfigException;
12
use yii\web\NotFoundHttpException;
13
use modules\rbac\Module;
14
15
/**
16
 * Class AssignController
17
 * @package modules\rbac\controllers
18
 */
19
class AssignController extends Controller
20
{
21
    /** @var $p_user object */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $p_user at position 0 could not be parsed: Unknown type name '$p_user' at position 0 in $p_user.
Loading history...
22
    private $p_user = null;
23
24
    /**
25
     * @param \yii\base\Action $action
26
     * @return bool
27
     * @throws InvalidConfigException
28
     * @throws \yii\web\BadRequestHttpException
29
     */
30
    public function beforeAction($action)
31
    {
32
        if (empty(Yii::$app->controller->module->params['userClass'])) {
33
            throw new InvalidConfigException(Module::t(
34
                'module',
35
                'You must specify the User class in the module settings.'
36
            ));
37
        }
38
        $this->p_user = new Yii::$app->controller->module->params['userClass']();
39
        return parent::beforeAction($action);
40
    }
41
42
    /**
43
     * @inheritdoc
44
     * @return array
45
     */
46
    public function behaviors()
47
    {
48
        return [
49
            'access' => [
50
                'class' => AccessControl::class,
51
                'rules' => [
52
                    [
53
                        'allow' => true,
54
                        'roles' => ['managerRbac'],
55
                    ],
56
                ],
57
            ],
58
            'verbs' => [
59
                'class' => VerbFilter::class,
60
                'actions' => [
61
                    'revoke' => ['POST'],
62
                ],
63
            ],
64
        ];
65
    }
66
67
    /**
68
     * @return mixed
69
     */
70
    public function actionIndex()
71
    {
72
        $assignModel = new Assignment();
73
        $users = $this->p_user->find()->all();
74
        $dataProvider = new ArrayDataProvider([
75
            'allModels' => $users,
76
            'sort' => [
77
                'attributes' => ['username', 'role'],
78
            ],
79
            'pagination' => [
80
                'pageSize' => 25,
81
            ],
82
        ]);
83
        return $this->render('index', [
84
            'dataProvider' => $dataProvider,
85
            'assignModel' => $assignModel,
86
        ]);
87
    }
88
89
    /**
90
     * @param string|int $id
91
     * @return mixed
92
     * @throws NotFoundHttpException
93
     */
94
    public function actionView($id)
95
    {
96
        $assignModel = new Assignment();
97
        return $this->render('view', [
98
            'model' => $this->findModel($id),
99
            'assignModel' => $assignModel,
100
        ]);
101
    }
102
103
    /**
104
     * @param string|int $id
105
     * @return string|\yii\web\Response
106
     * @throws NotFoundHttpException
107
     * @throws \Exception
108
     */
109
    public function actionUpdate($id)
110
    {
111
        $model = new Assignment([
112
            'user' => $this->findModel($id)
113
        ]);
114
        if ($model->load(Yii::$app->request->post())) {
115
            $auth = Yii::$app->authManager;
116
            $role = $auth->getRole($model->role);
117
            // отвязываем роли если есть
118
            if ($auth->getRolesByUser($model->user->id)) {
119
                $auth->revokeAll($model->user->id);
120
            }
121
            // Привязываем новую роль
122
            if ($auth->assign($role, $model->user->id)) {
123
                return $this->redirect(['view', 'id' => $model->user->id]);
124
            }
125
        }
126
        $model->role = $model->getRoleUser($id);
127
        return $this->render('update', [
128
            'model' => $model,
129
        ]);
130
    }
131
132
    /**
133
     * @param string|int $id
134
     * @return \yii\web\Response
135
     * @throws NotFoundHttpException
136
     */
137
    public function actionRevoke($id)
138
    {
139
        /** @var \modules\users\models\User $model */
140
        $model = $this->findModel($id);
141
        $auth = Yii::$app->authManager;
142
        if ($auth->getRolesByUser($model->id)) {
143
            if ($auth->revokeAll($model->id)) {
144
                Yii::$app->session->setFlash('success', Module::t(
0 ignored issues
show
Bug introduced by
The method setFlash() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

144
                Yii::$app->session->/** @scrutinizer ignore-call */ 
145
                                    setFlash('success', Module::t(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
145
                    'module',
146
                    'User "{:username}" successfully unassigned.',
147
                    [':username' => $model->username]
148
                ));
149
            } else {
150
                Yii::$app->session->setFlash('error', Module::t('module', 'Error!'));
151
            }
152
        } else {
153
            Yii::$app->session->setFlash('warning', Module::t(
154
                'module',
155
                'User "{:username}" is not attached to any role!',
156
                [':username' => $model->username]
157
            ));
158
        }
159
        return $this->redirect(['index']);
160
    }
161
162
    /**
163
     * Finds the User model based on its primary key value.
164
     * If the model is not found, a 404 HTTP exception will be thrown.
165
     * @param string|int $id
166
     * @return null|\modules\users\models\User the loaded model
167
     * @throws NotFoundHttpException if the model cannot be found
168
     */
169
    protected function findModel($id)
170
    {
171
        $userModel = $this->p_user;
172
        if (($model = $userModel->findOne($id)) !== null) {
173
            return $model;
174
        } else {
175
            throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
176
        }
177
    }
178
}
179