ProfileController   A
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 272
Duplicated Lines 0 %

Importance

Changes 9
Bugs 5 Features 1
Metric Value
wmc 42
eloc 112
c 9
b 5
f 1
dl 0
loc 272
rs 9.0399

15 Methods

Rating   Name   Duplication   Size   Complexity  
A actionIndex() 0 10 1
A actionUpdate() 0 15 3
A actionUpdateAvatar() 0 12 3
A actionAjaxValidateAvatarForm() 0 8 3
A actionCropAvatar() 0 9 4
A actionUploadImage() 0 17 5
A findModel() 0 12 3
A actionDeleteAvatar() 0 12 1
A actionUpdatePassword() 0 12 3
A actionDelete() 0 15 3
A actionAjaxValidatePasswordDeleteForm() 0 8 3
A actionGenerateAuthKey() 0 10 2
A actionAjaxValidatePasswordForm() 0 8 3
A processGenerateAuthKey() 0 6 1
A actionAvatar() 0 17 4

How to fix   Complexity   

Complex Class

Complex classes like ProfileController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProfileController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace modules\users\controllers\common;
4
5
use Yii;
6
use yii\base\Exception;
7
use yii\db\StaleObjectException;
8
use yii\web\Controller;
9
use yii\web\NotFoundHttpException;
10
use yii\bootstrap\ActiveForm;
11
use yii\web\Response;
12
use yii\web\UploadedFile;
13
use modules\users\models\UploadForm;
14
use modules\users\models\User;
15
use modules\users\models\UpdatePasswordForm;
16
use modules\users\models\UserDeleteForm;
17
use modules\rbac\models\Assignment;
18
use modules\users\Module;
19
use Throwable;
20
21
/**
22
 * Class ProfileController
23
 * @package modules\users\controllers\common
24
 */
25
class ProfileController extends Controller
26
{
27
    /**
28
     * @return string
29
     * @throws NotFoundHttpException
30
     */
31
    public function actionIndex()
32
    {
33
        $model = $this->findModel();
34
35
        $assignModel = new Assignment();
36
        $assignModel->user = $model;
37
38
        return $this->render('index', [
39
            'model' => $model,
40
            'assignModel' => $assignModel
41
        ]);
42
    }
43
44
    /**
45
     * @return string|Response
46
     * @throws NotFoundHttpException
47
     */
48
    public function actionUpdate()
49
    {
50
        $model = $this->findModel();
51
        $uploadFormModel = new UploadForm();
52
        $load = $model->profile->load(Yii::$app->request->post());
53
        if ($load && $model->profile->save()) {
54
            /** @var yii\web\Session $session */
55
            $session = Yii::$app->session;
56
            $session->setFlash('success', Module::translate('module', 'Profile successfully save.'));
57
            return $this->redirect(['update', 'tab' => 'profile']);
58
        }
59
        return $this->render('update', [
60
            'model' => $model,
61
            'uploadFormModel' => $uploadFormModel,
62
            'passwordForm' => new UpdatePasswordForm($model)
63
        ]);
64
    }
65
66
    /**
67
     * @return Response
68
     * @throws NotFoundHttpException
69
     */
70
    public function actionUpdateAvatar()
71
    {
72
        $model = $this->findModel();
73
        /** @var yii\web\Session $session */
74
        $session = Yii::$app->session;
75
        $load = $model->profile->load(Yii::$app->request->post());
76
        if ($load && $model->profile->save()) {
77
            $session->setFlash('success', Module::translate('module', 'Form successfully saved.'));
78
        } else {
79
            $session->setFlash('error', Module::translate('module', 'Error! Failed to save the form.'));
80
        }
81
        return $this->redirect(['update', 'tab' => 'avatar']);
82
    }
83
84
    /**
85
     * @return array|Response
86
     * @throws NotFoundHttpException
87
     */
88
    public function actionAjaxValidateAvatarForm()
89
    {
90
        $model = $this->findModel();
91
        if (Yii::$app->request->isAjax && $model->profile->load(Yii::$app->request->post())) {
92
            Yii::$app->response->format = Response::FORMAT_JSON;
93
            return ActiveForm::validate($model->profile);
94
        }
95
        return $this->redirect(['index']);
96
    }
97
98
    /**
99
     * Upload file
100
     * @return Response
101
     * @throws Exception
102
     */
103
    public function actionUploadImage()
104
    {
105
        $model = new UploadForm();
106
        if (Yii::$app->request->isPost) {
107
            /** @var yii\web\Session $session */
108
            $session = Yii::$app->session;
109
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
110
            if (($result = $model->upload()) && !is_string($result)) {
111
                if (isset($result['imageFile'][0])) {
112
                    $session->setFlash('error', $result['imageFile'][0]);
113
                } else {
114
                    $session->setFlash('error', Module::translate('module', 'Failed to upload file.'));
115
                }
116
                return $this->redirect(['update', 'tab' => 'avatar']);
117
            }
118
        }
119
        return $this->redirect(['update', 'tab' => 'avatar', 'modal' => 'show']);
120
    }
121
122
    /**
123
     * Crop image
124
     * @return Response
125
     */
126
    public function actionCropAvatar()
127
    {
128
        $model = new UploadForm();
129
        /** @var yii\web\Session $session */
130
        $session = Yii::$app->session;
131
        if (($post = Yii::$app->request->post()) && $model->load($post) && $model->crop()) {
132
            $session->setFlash('success', Module::translate('module', 'User avatar successfully save.'));
133
        }
134
        return $this->redirect(['update', 'tab' => 'avatar']);
135
    }
136
137
    /**
138
     * Get Avatar
139
     * @return bool
140
     * @throws NotFoundHttpException
141
     */
142
    public function actionAvatar()
143
    {
144
        if ($file = Yii::$app->request->get('filename')) {
145
            /** @var int|string $id */
146
            $id = Yii::$app->request->get('id') ?: Yii::$app->user->id;
147
            $model = new UploadForm();
148
            $storagePath = $model->getPath($id);
149
            $response = Yii::$app->getResponse();
150
            if (($steam = fopen("$storagePath/$file", 'rb')) !== false) {
151
                $response->headers->set('Content-Type', 'image/jpg');
152
                $response->format = Response::FORMAT_RAW;
153
                $response->stream = $steam;
154
                $response->send();
155
                return true;
156
            }
157
        }
158
        throw new NotFoundHttpException('The requested page does not exist.');
159
    }
160
161
    /**
162
     * Delete Avatar files
163
     * @param int|string $id
164
     * @return Response
165
     */
166
    public function actionDeleteAvatar($id)
167
    {
168
        $model = new UploadForm();
169
        $fileName = $model->getFileName();
170
        $avatar = $model->getPath($id) . DIRECTORY_SEPARATOR . $fileName;
171
        $thumb = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_THUMBNAIL . $fileName;
172
        $original = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_ORIGINAL . $fileName;
173
        $model->delete([$avatar, $thumb, $original]);
174
        /** @var yii\web\Session $session */
175
        $session = Yii::$app->session;
176
        $session->setFlash('success', Module::translate('module', 'Successfully deleted.'));
177
        return $this->redirect(['update', 'tab' => 'avatar']);
178
    }
179
180
    /**
181
     * @return Response
182
     * @throws NotFoundHttpException
183
     * @throws Exception
184
     */
185
    public function actionUpdatePassword()
186
    {
187
        $model = new UpdatePasswordForm($this->findModel());
188
        /** @var yii\web\Session $session */
189
        $session = Yii::$app->session;
190
        $load = $model->load(Yii::$app->request->post());
191
        if ($load && $model->resetPassword()) {
192
            $session->setFlash('success', Module::translate('module', 'Password changed successfully.'));
193
        } else {
194
            $session->setFlash('error', Module::translate('module', 'Error! Password changed not successfully.'));
195
        }
196
        return $this->redirect(['update', 'tab' => 'password']);
197
    }
198
199
    /**
200
     * @return array|Response
201
     * @throws NotFoundHttpException
202
     */
203
    public function actionAjaxValidatePasswordForm()
204
    {
205
        $model = new UpdatePasswordForm($this->findModel());
206
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
207
            Yii::$app->response->format = Response::FORMAT_JSON;
208
            return ActiveForm::validate($model);
209
        }
210
        return $this->redirect(['index']);
211
    }
212
213
    /**
214
     * @return array|Response
215
     * @throws NotFoundHttpException
216
     */
217
    public function actionAjaxValidatePasswordDeleteForm()
218
    {
219
        $model = new UserDeleteForm($this->findModel());
220
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
221
            Yii::$app->response->format = Response::FORMAT_JSON;
222
            return ActiveForm::validate($model);
223
        }
224
        return $this->redirect(['delete']);
225
    }
226
227
    /**
228
     * @return array|Response
229
     * @throws Exception
230
     * @throws NotFoundHttpException
231
     */
232
    public function actionGenerateAuthKey()
233
    {
234
        $model = $this->processGenerateAuthKey();
235
        if (Yii::$app->request->isAjax) {
236
            Yii::$app->response->format = Response::FORMAT_JSON;
237
            return [
238
                'success' => $model->auth_key
239
            ];
240
        }
241
        return $this->redirect(['index']);
242
    }
243
244
    /**
245
     * @return User
246
     * @throws Exception
247
     * @throws NotFoundHttpException
248
     */
249
    private function processGenerateAuthKey()
250
    {
251
        $model = $this->findModel();
252
        $model->generateAuthKey();
253
        $model->save();
254
        return $model;
255
    }
256
257
    /**
258
     * @return string|Response
259
     * @throws NotFoundHttpException
260
     * @throws Throwable
261
     * @throws StaleObjectException
262
     */
263
    public function actionDelete()
264
    {
265
        $model = new UserDeleteForm($this->findModel());
266
        $load = $model->load(Yii::$app->request->post());
267
        if ($load && $model->userDelete() !== false) {
268
            /** @var \yii\web\User $user */
269
            $user = Yii::$app->user;
270
            $user->logout();
271
            /** @var yii\web\Session $session */
272
            $session = Yii::$app->session;
273
            $session->setFlash('success', Module::translate('module', 'Your profile has been successfully deleted!'));
274
            return $this->goHome();
275
        }
276
        return $this->render('delete', [
277
            'model' => $model
278
        ]);
279
    }
280
281
    /**
282
     * @return User
283
     * @throws NotFoundHttpException
284
     */
285
    private function findModel()
286
    {
287
        /** @var \yii\web\User $user */
288
        $user = Yii::$app->user;
289
        if (!$user->isGuest) {
290
            /** @var User $identity */
291
            $identity = Yii::$app->user->identity;
292
            if (($model = User::findOne($identity->id)) !== null) {
293
                return $model;
294
            }
295
        }
296
        throw new NotFoundHttpException(Module::translate('module', 'The requested page does not exist.'));
297
    }
298
}
299