Passed
Push — master ( f7a351...988e81 )
by Alexey
03:10
created

AssignController::actionIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
eloc 11
nc 1
nop 0
cc 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 $user object */
22
    private $_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('module', 'You must specify the User class in the module settings.'));
34
        }
35
        $this->_user = new Yii::$app->controller->module->params['userClass']();
36
        return parent::beforeAction($action);
37
    }
38
39
    /**
40
     * @inheritdoc
41
     * @return array
42
     */
43
    public function behaviors()
44
    {
45
        return [
46
            'access' => [
47
                'class' => AccessControl::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

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

47
                'class' => /** @scrutinizer ignore-deprecated */ AccessControl::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
48
                'rules' => [
49
                    [
50
                        'allow' => true,
51
                        'roles' => ['managerRbac'],
52
                    ],
53
                ],
54
            ],
55
            'verbs' => [
56
                'class' => VerbFilter::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

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

56
                'class' => /** @scrutinizer ignore-deprecated */ VerbFilter::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
57
                'actions' => [
58
                    'revoke' => ['POST'],
59
                ],
60
            ],
61
        ];
62
    }
63
64
    /**
65
     * @return mixed
66
     */
67
    public function actionIndex()
68
    {
69
        $assignModel = new Assignment();
70
        $users = $this->_user->find()->all();
71
        $dataProvider = new ArrayDataProvider([
72
            'allModels' => $users,
73
            'sort' => [
74
                'attributes' => ['username', 'role'],
75
            ],
76
            'pagination' => [
77
                'pageSize' => 25,
78
            ],
79
        ]);
80
        return $this->render('index', [
81
            'dataProvider' => $dataProvider,
82
            'assignModel' => $assignModel,
83
        ]);
84
    }
85
86
    /**
87
     * @param string|int $id
88
     * @return mixed
89
     * @throws NotFoundHttpException
90
     */
91
    public function actionView($id)
92
    {
93
        $assignModel = new Assignment();
94
        return $this->render('view', [
95
            'model' => $this->findModel($id),
96
            'assignModel' => $assignModel,
97
        ]);
98
    }
99
100
    /**
101
     * @param string|int $id
102
     * @return string|\yii\web\Response
103
     * @throws NotFoundHttpException
104
     * @throws \Exception
105
     */
106
    public function actionUpdate($id)
107
    {
108
        $model = new Assignment([
109
            'user' => $this->findModel($id)
110
        ]);
111
        if ($model->load(Yii::$app->request->post())) {
112
            $auth = Yii::$app->authManager;
113
            $role = $auth->getRole($model->role);
114
            // отвязываем роли если есть
115
            if ($auth->getRolesByUser($model->user->id)) {
116
                $auth->revokeAll($model->user->id);
117
            }
118
            // Привязываем новую роль
119
            if ($auth->assign($role, $model->user->id)) {
120
                return $this->redirect(['view', 'id' => $model->user->id]);
121
            }
122
        }
123
        $model->role = $model->getRoleUser($id);
124
        return $this->render('update', [
125
            'model' => $model,
126
        ]);
127
    }
128
129
    /**
130
     * @param string|int $id
131
     * @return \yii\web\Response
132
     * @throws NotFoundHttpException
133
     */
134
    public function actionRevoke($id)
135
    {
136
        /** @var \modules\users\models\User $model */
137
        $model = $this->findModel($id);
138
        $auth = Yii::$app->authManager;
139
        if ($auth->getRolesByUser($model->id)) {
140
            if ($auth->revokeAll($model->id)) {
141
                Yii::$app->session->setFlash('success', Module::t('module', 'User "{:username}" successfully unassigned.', [':username' => $model->username]));
142
            } else {
143
                Yii::$app->session->setFlash('error', Module::t('module', 'Error!'));
144
            }
145
        } else {
146
            Yii::$app->session->setFlash('warning', Module::t('module', 'User "{:username}" is not attached to any role!', [':username' => $model->username]));
147
        }
148
        return $this->redirect(['index']);
149
    }
150
151
    /**
152
     * Finds the User model based on its primary key value.
153
     * If the model is not found, a 404 HTTP exception will be thrown.
154
     * @param string|int $id
155
     * @return null|\modules\users\models\User the loaded model
156
     * @throws NotFoundHttpException if the model cannot be found
157
     */
158
    protected function findModel($id)
159
    {
160
        $userModel = $this->_user;
161
        if (($model = $userModel->findOne($id)) !== null) {
162
            return $model;
163
        } else {
164
            throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
165
        }
166
    }
167
}
168