Passed
Push — master ( 968e8c...b3f9f6 )
by Alexey
02:44
created

actionAjaxValidatePasswordForm()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace modules\users\controllers\common;
4
5
use Throwable;
6
use Yii;
7
use yii\base\Exception;
8
use yii\db\StaleObjectException;
9
use yii\web\Controller;
10
use yii\web\NotFoundHttpException;
11
use yii\bootstrap\ActiveForm;
12
use yii\web\Response;
13
use yii\web\UploadedFile;
14
use modules\users\models\UploadForm;
15
use modules\users\models\User;
16
use modules\users\models\UpdatePasswordForm;
17
use modules\users\models\UserDeleteForm;
18
use modules\rbac\models\Assignment;
19
use modules\users\Module;
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
46
     * @throws NotFoundHttpException
47
     */
48
    public function actionUpdate()
49
    {
50
        $model = $this->findModel();
51
        $uploadFormModel = new UploadForm();
52
        if ($model->profile->load(Yii::$app->request->post()) && $model->profile->save()) {
53
            /** @var yii\web\Session $session */
54
            $session = Yii::$app->session;
55
            $session->setFlash('success', Module::t('module', 'Profile successfully save.'));
56
            return $this->redirect(['update', 'tab' => 'profile']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->redirect(a...', 'tab' => 'profile')) returns the type yii\web\Response which is incompatible with the documented return type string.
Loading history...
57
        }
58
        return $this->render('update', [
59
            'model' => $model,
60
            'uploadFormModel' => $uploadFormModel,
61
            'passwordForm' => new UpdatePasswordForm($model)
62
        ]);
63
    }
64
65
    /**
66
     * @return Response
67
     * @throws NotFoundHttpException
68
     * @throws Exception
69
     */
70
    public function actionUpdateAvatar()
71
    {
72
        $model = $this->findModel();
73
        /** @var yii\web\Session $session */
74
        $session = Yii::$app->session;
75
        if ($model->profile->load(Yii::$app->request->post()) && $model->profile->save()) {
76
            $session->setFlash('success', Module::t('module', 'Form successfully saved.'));
77
        } else {
78
            $session->setFlash('error', Module::t('module', 'Error! Failed to save the form.'));
79
        }
80
        return $this->redirect(['update', 'tab' => 'avatar']);
81
    }
82
83
    /**
84
     * @return array|Response
85
     * @throws NotFoundHttpException
86
     */
87
    public function actionAjaxValidateAvatarForm()
88
    {
89
        $model = $this->findModel();
90
        if (Yii::$app->request->isAjax && $model->profile->load(Yii::$app->request->post())) {
91
            Yii::$app->response->format = Response::FORMAT_JSON;
92
            return ActiveForm::validate($model->profile);
93
        }
94
        return $this->redirect(['index']);
95
    }
96
97
    /**
98
     * Upload file
99
     * @return Response
100
     * @throws Exception
101
     */
102
    public function actionUploadImage()
103
    {
104
        $model = new UploadForm();
105
        if (Yii::$app->request->isPost) {
106
            /** @var yii\web\Session $session */
107
            $session = Yii::$app->session;
108
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
109
            if (($result = $model->upload()) && !is_string($result)) {
110
                if (isset($result['imageFile'][0])) {
111
                    $session->setFlash('error', $result['imageFile'][0]);
112
                } else {
113
                    $session->setFlash('error', Module::t('module', 'Failed to upload file.'));
114
                }
115
                return $this->redirect(['update', 'tab' => 'avatar']);
116
            }
117
        }
118
        return $this->redirect(['update', 'tab' => 'avatar', 'modal' => 'show']);
119
    }
120
121
    /**
122
     * Crop image
123
     * @return Response
124
     */
125
    public function actionCropAvatar()
126
    {
127
        $model = new UploadForm();
128
        /** @var yii\web\Session $session */
129
        $session = Yii::$app->session;
130
        if (($post = Yii::$app->request->post()) && $model->load($post) && $model->crop()) {
131
            $session->setFlash('success', Module::t('module', 'User avatar successfully save.'));
132
        }
133
        return $this->redirect(['update', 'tab' => 'avatar']);
134
    }
135
136
    /**
137
     * Get Avatar
138
     * @throws NotFoundHttpException
139
     */
140
    public function actionAvatar()
141
    {
142
        if ($file = Yii::$app->request->get('filename')) {
143
            /** @var int|string $id */
144
            $id = Yii::$app->request->get('id') ?: Yii::$app->user->id;
145
            $model = new UploadForm();
146
            $storagePath = $model->getPath($id);
147
            $response = Yii::$app->getResponse();
148
            $response->headers->set('Content-Type', 'image/jpg');
149
            $response->format = Response::FORMAT_RAW;
150
            if ($response->stream = fopen("$storagePath/$file", 'rb')) {
0 ignored issues
show
Documentation Bug introduced by
It seems like fopen($storagePath.'/'.$file, 'rb') can also be of type false. However, the property $stream is declared as type array|resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
151
                return $response->send();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $response->send() targeting yii\web\Response::send() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $response->send() targeting yii\base\Response::send() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
152
            }
153
        }
154
        throw new NotFoundHttpException('The requested page does not exist.');
155
    }
156
157
    /**
158
     * Delete Avatar files
159
     * @param int $id
160
     * @return Response
161
     */
162
    public function actionDeleteAvatar($id)
163
    {
164
        $model = new UploadForm();
165
        $fileName = $model->getFileName();
166
        $avatar = $model->getPath($id) . DIRECTORY_SEPARATOR . $fileName;
167
        $thumb = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_THUMBNAIL . $fileName;
168
        $original = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_ORIGINAL . $fileName;
169
        $model->delete([$avatar, $thumb, $original]);
170
        /** @var yii\web\Session $session */
171
        $session = Yii::$app->session;
172
        $session->setFlash('success', Module::t('module', 'Successfully deleted.'));
173
        return $this->redirect(['update', 'tab' => 'avatar']);
174
    }
175
176
    /**
177
     * @return Response
178
     * @throws NotFoundHttpException
179
     * @throws Exception
180
     */
181
    public function actionUpdatePassword()
182
    {
183
        $model = new UpdatePasswordForm($this->findModel());
184
        /** @var yii\web\Session $session */
185
        $session = Yii::$app->session;
186
        if ($model->load(Yii::$app->request->post()) && $model->resetPassword()) {
187
            $session->setFlash('success', Module::t('module', 'Password changed successfully.'));
188
        } else {
189
            $session->setFlash('error', Module::t('module', 'Error! Password changed not successfully.'));
190
        }
191
        return $this->redirect(['update', 'tab' => 'password']);
192
    }
193
194
    /**
195
     * @return array|Response
196
     * @throws NotFoundHttpException
197
     */
198
    public function actionAjaxValidatePasswordForm()
199
    {
200
        $model = new UpdatePasswordForm($this->findModel());
201
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
202
            Yii::$app->response->format = Response::FORMAT_JSON;
203
            return ActiveForm::validate($model);
204
        }
205
        return $this->redirect(['index']);
206
    }
207
208
    /**
209
     * @return array|Response
210
     * @throws NotFoundHttpException
211
     */
212
    public function actionAjaxValidatePasswordDeleteForm()
213
    {
214
        $model = new UserDeleteForm($this->findModel());
215
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
216
            Yii::$app->response->format = Response::FORMAT_JSON;
217
            return ActiveForm::validate($model);
218
        }
219
        return $this->redirect(['delete']);
220
    }
221
222
    /**
223
     * @return array|Response
224
     * @throws Exception
225
     * @throws NotFoundHttpException
226
     */
227
    public function actionGenerateAuthKey()
228
    {
229
        $model = $this->processGenerateAuthKey();
230
        if (Yii::$app->request->isAjax) {
231
            Yii::$app->response->format = Response::FORMAT_JSON;
232
            return [
233
                'success' => $model->auth_key
234
            ];
235
        }
236
        return $this->redirect(['index']);
237
    }
238
239
    /**
240
     * @return User
241
     * @throws Exception
242
     * @throws NotFoundHttpException
243
     */
244
    private function processGenerateAuthKey()
245
    {
246
        $model = $this->findModel();
247
        $model->generateAuthKey();
248
        $model->save();
249
        return $model;
250
    }
251
252
    /**
253
     * @return string|Response
254
     * @throws NotFoundHttpException
255
     * @throws Throwable
256
     * @throws StaleObjectException
257
     */
258
    public function actionDelete()
259
    {
260
        $model = new UserDeleteForm($this->findModel());
261
        if ($model->load(Yii::$app->request->post()) && $model->userDelete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model->userDelete() of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
262
            /** @var \yii\web\User $user */
263
            $user = Yii::$app->user;
264
            $user->logout();
265
            /** @var yii\web\Session $session */
266
            $session = Yii::$app->session;
267
            $session->setFlash('success', Module::t('module', 'Your profile has been successfully deleted!'));
268
            return $this->goHome();
269
        }
270
        return $this->render('delete', [
271
            'model' => $model
272
        ]);
273
    }
274
275
    /**
276
     * @return User
277
     * @throws NotFoundHttpException
278
     */
279
    private function findModel()
280
    {
281
        /** @var \yii\web\User $user */
282
        $user = Yii::$app->user;
283
        if (!$user->isGuest) {
284
            /** @var User $identity */
285
            $identity = Yii::$app->user->identity;
286
            if (($model = User::findOne($identity->id)) !== null) {
287
                return $model;
288
            }
289
        }
290
        throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
291
    }
292
}
293