Passed
Push — master ( 5a9e1e...a9a8cf )
by Alexey
03:09
created

ProfileController::actionAjaxValidateAvatarForm()   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 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
20
/**
21
 * Class ProfileController
22
 * @package modules\users\controllers\common
23
 */
24
class ProfileController extends Controller
25
{
26
    /**
27
     * @return string
28
     * @throws NotFoundHttpException
29
     */
30
    public function actionIndex()
31
    {
32
        $model = $this->findModel();
33
34
        $assignModel = new Assignment();
35
        $assignModel->user = $model;
36
37
        return $this->render('index', [
38
            'model' => $model,
39
            'assignModel' => $assignModel
40
        ]);
41
    }
42
43
    /**
44
     * @return string
45
     * @throws NotFoundHttpException
46
     */
47
    public function actionUpdate()
48
    {
49
        $model = $this->findModel();
50
        $uploadFormModel = new UploadForm();
51
        if ($model->profile->load(Yii::$app->request->post()) && $model->profile->save()) {
52
            /** @var yii\web\Session $session */
53
            $session = Yii::$app->session;
54
            $session->setFlash('success', Module::t('module', 'Profile successfully save.'));
55
            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...
56
        }
57
        return $this->render('update', [
58
            'model' => $model,
59
            'uploadFormModel' => $uploadFormModel,
60
            'passwordForm' => new UpdatePasswordForm($model)
61
        ]);
62
    }
63
64
    /**
65
     * @return Response
66
     * @throws NotFoundHttpException
67
     * @throws Exception
68
     */
69
    public function actionUpdateAvatar()
70
    {
71
        $model = $this->findModel();
72
        /** @var yii\web\Session $session */
73
        $session = Yii::$app->session;
74
        if ($model->profile->load(Yii::$app->request->post()) && $model->profile->save()) {
75
            $session->setFlash('success', Module::t('module', 'Form successfully saved.'));
76
        } else {
77
            $session->setFlash('error', Module::t('module', 'Error! Failed to save the form.'));
78
        }
79
        return $this->redirect(['update', 'tab' => 'avatar']);
80
    }
81
82
    /**
83
     * @return array|Response
84
     * @throws NotFoundHttpException
85
     */
86
    public function actionAjaxValidateAvatarForm()
87
    {
88
        $model = $this->findModel();
89
        if (Yii::$app->request->isAjax && $model->profile->load(Yii::$app->request->post())) {
90
            Yii::$app->response->format = Response::FORMAT_JSON;
91
            return ActiveForm::validate($model->profile);
92
        }
93
        return $this->redirect(['index']);
94
    }
95
96
    /**
97
     * Upload file
98
     * @return Response
99
     * @throws Exception
100
     */
101
    public function actionUploadImage()
102
    {
103
        $model = new UploadForm();
104
        if (Yii::$app->request->isPost) {
105
            $session = Yii::$app->session;
106
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
107
            if (($result = $model->upload()) && !is_string($result)) {
108
                if (isset($result['imageFile'][0])) {
109
                    $session->setFlash('error', $result['imageFile'][0]);
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

109
                    $session->/** @scrutinizer ignore-call */ 
110
                              setFlash('error', $result['imageFile'][0]);

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...
110
                } else {
111
                    $session->setFlash('error', Module::t('module', 'Failed to upload file.'));
112
                }
113
                return $this->redirect(['update', 'tab' => 'avatar']);
114
            }
115
        }
116
        return $this->redirect(['update', 'tab' => 'avatar', 'modal' => 'show']);
117
    }
118
119
    /**
120
     * Crop image
121
     * @return Response
122
     */
123
    public function actionCropAvatar()
124
    {
125
        $model = new UploadForm();
126
        $session = Yii::$app->session;
127
        if (($post = Yii::$app->request->post()) && $model->load($post) && $model->crop()) {
128
            $session->setFlash('success', Module::t('module', 'User avatar successfully save.'));
129
        }
130
        return $this->redirect(['update', 'tab' => 'avatar']);
131
    }
132
133
    /**
134
     * Get Avatar
135
     * @throws NotFoundHttpException
136
     */
137
    public function actionAvatar()
138
    {
139
        if ($file = Yii::$app->request->get('filename')) {
140
            $id = Yii::$app->request->get('id') ?: Yii::$app->user->id;
141
            $model = new UploadForm();
142
            $storagePath = $model->getPath($id);
143
            $response = Yii::$app->getResponse();
144
            $response->headers->set('Content-Type', 'image/jpg');
145
            $response->format = Response::FORMAT_RAW;
146
            $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...
147
            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...
148
        }
149
        throw new NotFoundHttpException('The requested page does not exist.');
150
    }
151
152
    /**
153
     * Delete Avatar files
154
     * @param int $id
155
     * @return Response
156
     */
157
    public function actionDeleteAvatar($id)
158
    {
159
        $model = new UploadForm();
160
        $fileName = $model->getFileName();
161
        $avatar = $model->getPath($id) . DIRECTORY_SEPARATOR . $fileName;
162
        $thumb = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_THUMBNAIL . $fileName;
163
        $original = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_ORIGINAL . $fileName;
164
        $model->delete([$avatar, $thumb, $original]);
165
        $session = Yii::$app->session;
166
        $session->setFlash('success', Module::t('module', 'Successfully deleted.'));
167
        return $this->redirect(Yii::$app->request->referrer);
168
    }
169
170
    /**
171
     * @return Response
172
     * @throws NotFoundHttpException
173
     * @throws Exception
174
     */
175
    public function actionUpdatePassword()
176
    {
177
        $model = new UpdatePasswordForm($this->findModel());
178
        /** @var yii\web\Session $session */
179
        $session = Yii::$app->session;
180
        if ($model->load(Yii::$app->request->post()) && $model->resetPassword()) {
181
            $session->setFlash('success', Module::t('module', 'Password changed successfully.'));
182
        } else {
183
            $session->setFlash('error', Module::t('module', 'Error! Password changed not successfully.'));
184
        }
185
        return $this->redirect(['update', 'tab' => 'password']);
186
    }
187
188
    /**
189
     * @return array|Response
190
     * @throws NotFoundHttpException
191
     */
192
    public function actionAjaxValidatePasswordForm()
193
    {
194
        $model = new UpdatePasswordForm($this->findModel());
195
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
196
            Yii::$app->response->format = Response::FORMAT_JSON;
197
            return ActiveForm::validate($model);
198
        }
199
        return $this->redirect(['index']);
200
    }
201
202
    /**
203
     * @return array|Response
204
     * @throws NotFoundHttpException
205
     */
206
    public function actionAjaxValidatePasswordDeleteForm()
207
    {
208
        $model = new UserDeleteForm($this->findModel());
209
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
210
            Yii::$app->response->format = Response::FORMAT_JSON;
211
            return ActiveForm::validate($model);
212
        }
213
        return $this->redirect(['delete']);
214
    }
215
216
    /**
217
     * @return array|Response
218
     * @throws Exception
219
     * @throws NotFoundHttpException
220
     */
221
    public function actionGenerateAuthKey()
222
    {
223
        $model = $this->processGenerateAuthKey();
224
        if (Yii::$app->request->isAjax) {
225
            Yii::$app->response->format = Response::FORMAT_JSON;
226
            return [
227
                'success' => $model->auth_key
228
            ];
229
        }
230
        return $this->redirect(['index']);
231
    }
232
233
    /**
234
     * @return User
235
     * @throws Exception
236
     * @throws NotFoundHttpException
237
     */
238
    private function processGenerateAuthKey()
239
    {
240
        $model = $this->findModel();
241
        $model->generateAuthKey();
242
        $model->save();
243
        return $model;
244
    }
245
246
    /**
247
     * @return string|Response
248
     * @throws NotFoundHttpException
249
     * @throws \Throwable
250
     * @throws StaleObjectException
251
     */
252
    public function actionDelete()
253
    {
254
        $model = new UserDeleteForm($this->findModel());
255
        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...
256
            /** @var \yii\web\User $user */
257
            $user = Yii::$app->user;
258
            $user->logout();
259
            /** @var yii\web\Session $session */
260
            $session = Yii::$app->session;
261
            $session->setFlash('success', Module::t('module', 'Your profile has been successfully deleted!'));
262
            return $this->goHome();
263
        }
264
        return $this->render('delete', [
265
            'model' => $model
266
        ]);
267
    }
268
269
    /**
270
     * @return User
271
     * @throws NotFoundHttpException
272
     */
273
    private function findModel()
274
    {
275
        /** @var \yii\web\User $user */
276
        $user = Yii::$app->user;
277
        if (!$user->isGuest) {
278
            /** @var User $identity */
279
            $identity = Yii::$app->user->identity;
280
            if (($model = User::findOne($identity->id)) !== null) {
281
                return $model;
282
            }
283
        }
284
        throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
285
    }
286
}
287