Completed
Push — master ( ae08e3...aed614 )
by Alexey
03:06
created

UserController::findModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace modules\admin\controllers;
4
5
use Yii;
6
use modules\admin\models\User;
7
use modules\admin\models\search\UserSearch;
8
use yii\web\Controller;
9
use yii\web\NotFoundHttpException;
10
use yii\filters\VerbFilter;
11
use yii\filters\AccessControl;
12
use yii\web\Response;
13
14
/**
15
 * UserController implements the CRUD actions for User model.
16
 */
17
class UserController extends Controller
18
{
19
    /** @var  string|bool $jsFile */
20
    protected $jsFile;
21
22
    /**
23
     * @inheritdoc
24
     */
25
    public function behaviors()
26
    {
27
        return [
28
            'access' => [
29
                'class' => AccessControl::class,
30
                'rules' => [
31
                    [
32
                        'allow' => true,
33
                        'roles' => ['@'],
34
                    ],
35
                ],
36
            ],
37
            'verbs' => [
38
                'class' => VerbFilter::class,
39
                'actions' => [
40
                    'delete' => ['POST'],
41
                ],
42
            ],
43
        ];
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function init()
50
    {
51
        parent::init();
52
        $this->processRegisterJs();
53
    }
54
55
    /**
56
     * Publish and register the required JS file
57
     */
58
    protected function processRegisterJs()
59
    {
60
        $this->jsFile = '@modules/users/views/ajax/ajax.js';
61
        $assetManager = Yii::$app->assetManager;
62
        $assetManager->publish($this->jsFile);
63
        $url = $assetManager->getPublishedUrl($this->jsFile);
64
        $this->view->registerJsFile($url,
65
            ['depends' => 'yii\web\JqueryAsset',] // depends
66
        );
67
    }
68
69
    /**
70
     * Lists all User models.
71
     * @return mixed
72
     */
73
    public function actionIndex()
74
    {
75
        $searchModel = new UserSearch();
76
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
77
78
        return $this->render('index', [
79
            'searchModel' => $searchModel,
80
            'dataProvider' => $dataProvider,
81
        ]);
82
    }
83
84
    /**
85
     * Displays a single User model.
86
     * @param integer $id
87
     * @return mixed
88
     * @throws NotFoundHttpException if the model cannot be found
89
     */
90
    public function actionView($id)
91
    {
92
        return $this->render('view', [
93
            'model' => $this->findModel($id),
94
        ]);
95
    }
96
97
    /**
98
     * Creates a new User model.
99
     * If creation is successful, the browser will be redirected to the 'view' page.
100
     * @return mixed
101
     */
102
    public function actionCreate()
103
    {
104
        $model = new User();
105
        $model->scenario = $model::SCENARIO_ADMIN_CREATE;
106
107
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
108
            return $this->redirect(['view', 'id' => $model->id]);
109
        }
110
111
        return $this->render('create', [
112
            'model' => $model,
113
        ]);
114
    }
115
116
    /**
117
     * Updates an existing User model.
118
     * If update is successful, the browser will be redirected to the 'view' page.
119
     * @param integer $id
120
     * @return mixed
121
     * @throws NotFoundHttpException if the model cannot be found
122
     */
123
    public function actionUpdate($id)
124
    {
125
        $model = $this->findModel($id);
126
127
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
128
            return $this->redirect(['view', 'id' => $model->id]);
129
        }
130
131
        return $this->render('update', [
132
            'model' => $model,
133
        ]);
134
    }
135
136
    /**
137
     * Deletes an existing User model.
138
     * If deletion is successful, the browser will be redirected to the 'index' page.
139
     * @param integer $id
140
     * @return Response
141
     * @throws NotFoundHttpException
142
     * @throws \Exception
143
     * @throws \Throwable
144
     * @throws \yii\db\StaleObjectException
145
     */
146
    public function actionDelete($id)
147
    {
148
        $model = $this->findModel($id);
149
        if (!$model->isSuperAdmin())
150
            $model->delete();
151
152
        return $this->redirect(['index']);
153
    }
154
155
    /**
156
     * Action Generate new auth key
157
     * @param int|string $id
158
     * @return array|Response
159
     * @throws NotFoundHttpException
160
     */
161
    public function actionGenerateAuthKey($id)
162
    {
163
        $model = $this->processGenerateAuthKey($id);
164
        if (Yii::$app->request->isAjax) {
165
            Yii::$app->response->format = Response::FORMAT_JSON;
166
            return [
167
                'body' => $this->renderAjax('_auth_key', ['model' => $model]),
168
                'success' => true,
169
            ];
170
        }
171
        return $this->redirect(['index']);
172
    }
173
174
    /**
175
     * Generate new auth key
176
     * @param int|string $id
177
     * @return User
178
     * @throws NotFoundHttpException
179
     */
180
    private function processGenerateAuthKey($id)
181
    {
182
        $model = $this->findModel($id);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type string; however, parameter $id of modules\admin\controller...Controller::findModel() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

182
        $model = $this->findModel(/** @scrutinizer ignore-type */ $id);
Loading history...
183
        $model->generateAuthKey();
184
        $model->save();
185
        return $model;
186
    }
187
188
    /**
189
     * Change Status
190
     * @param int|string $id
191
     * @return array|\yii\web\Response
192
     * @throws NotFoundHttpException
193
     */
194
    public function actionStatus($id)
195
    {
196
        if ($model = $this->processChangeStatus($id)) {
197
            if (Yii::$app->request->isAjax) {
198
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
199
                return [
200
                    'body' => $model->getStatusLabelName(),
201
                    'success' => true,
202
                ];
203
            }
204
        }
205
        return $this->redirect(['index']);
206
    }
207
208
    /**
209
     * @param int|string $id
210
     * @return bool|User|null
211
     * @throws NotFoundHttpException
212
     */
213
    private function processChangeStatus($id)
214
    {
215
        $model = $this->findModel($id);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type string; however, parameter $id of modules\admin\controller...Controller::findModel() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

215
        $model = $this->findModel(/** @scrutinizer ignore-type */ $id);
Loading history...
216
        /** @var object $identity */
217
        $identity = Yii::$app->user->identity;
218
        if ($model->id !== $identity->id && !$model->isSuperAdmin()) {
219
            $model->setStatus();
220
            $model->save(false);
221
            return $model;
222
        }
223
        return false;
224
    }
225
226
    /**
227
     * Finds the User model based on its primary key value.
228
     * If the model is not found, a 404 HTTP exception will be thrown.
229
     * @param integer $id
230
     * @return User the loaded model
231
     * @throws NotFoundHttpException if the model cannot be found
232
     */
233
    protected function findModel($id)
234
    {
235
        if (($model = User::findOne($id)) !== null) {
236
            return $model;
237
        }
238
239
        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
240
    }
241
}
242