Passed
Push — master ( 297549...496da9 )
by Alexey
02:51
created

ProfileController::processGenerateAuthKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
c 0
b 0
f 0
rs 10
cc 1
nc 1
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
            $id = Yii::$app->request->get('id') ?: Yii::$app->user->id;
144
            if (!is_array($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
        }
155
        throw new NotFoundHttpException('The requested page does not exist.');
156
    }
157
158
    /**
159
     * Delete Avatar files
160
     * @param int $id
161
     * @return Response
162
     */
163
    public function actionDeleteAvatar($id)
164
    {
165
        $model = new UploadForm();
166
        $fileName = $model->getFileName();
167
        $avatar = $model->getPath($id) . DIRECTORY_SEPARATOR . $fileName;
168
        $thumb = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_THUMBNAIL . $fileName;
169
        $original = $model->getPath($id) . DIRECTORY_SEPARATOR . UploadForm::PREFIX_ORIGINAL . $fileName;
170
        $model->delete([$avatar, $thumb, $original]);
171
        /** @var yii\web\Session $session */
172
        $session = Yii::$app->session;
173
        $session->setFlash('success', Module::t('module', 'Successfully deleted.'));
174
        return $this->redirect(['update', 'tab' => 'avatar']);
175
    }
176
177
    /**
178
     * @return Response
179
     * @throws NotFoundHttpException
180
     * @throws Exception
181
     */
182
    public function actionUpdatePassword()
183
    {
184
        $model = new UpdatePasswordForm($this->findModel());
185
        /** @var yii\web\Session $session */
186
        $session = Yii::$app->session;
187
        if ($model->load(Yii::$app->request->post()) && $model->resetPassword()) {
188
            $session->setFlash('success', Module::t('module', 'Password changed successfully.'));
189
        } else {
190
            $session->setFlash('error', Module::t('module', 'Error! Password changed not successfully.'));
191
        }
192
        return $this->redirect(['update', 'tab' => 'password']);
193
    }
194
195
    /**
196
     * @return array|Response
197
     * @throws NotFoundHttpException
198
     */
199
    public function actionAjaxValidatePasswordForm()
200
    {
201
        $model = new UpdatePasswordForm($this->findModel());
202
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
203
            Yii::$app->response->format = Response::FORMAT_JSON;
204
            return ActiveForm::validate($model);
205
        }
206
        return $this->redirect(['index']);
207
    }
208
209
    /**
210
     * @return array|Response
211
     * @throws NotFoundHttpException
212
     */
213
    public function actionAjaxValidatePasswordDeleteForm()
214
    {
215
        $model = new UserDeleteForm($this->findModel());
216
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
217
            Yii::$app->response->format = Response::FORMAT_JSON;
218
            return ActiveForm::validate($model);
219
        }
220
        return $this->redirect(['delete']);
221
    }
222
223
    /**
224
     * @return array|Response
225
     * @throws Exception
226
     * @throws NotFoundHttpException
227
     */
228
    public function actionGenerateAuthKey()
229
    {
230
        $model = $this->processGenerateAuthKey();
231
        if (Yii::$app->request->isAjax) {
232
            Yii::$app->response->format = Response::FORMAT_JSON;
233
            return [
234
                'success' => $model->auth_key
235
            ];
236
        }
237
        return $this->redirect(['index']);
238
    }
239
240
    /**
241
     * @return User
242
     * @throws Exception
243
     * @throws NotFoundHttpException
244
     */
245
    private function processGenerateAuthKey()
246
    {
247
        $model = $this->findModel();
248
        $model->generateAuthKey();
249
        $model->save();
250
        return $model;
251
    }
252
253
    /**
254
     * @return string|Response
255
     * @throws NotFoundHttpException
256
     * @throws Throwable
257
     * @throws StaleObjectException
258
     */
259
    public function actionDelete()
260
    {
261
        $model = new UserDeleteForm($this->findModel());
262
        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...
263
            /** @var \yii\web\User $user */
264
            $user = Yii::$app->user;
265
            $user->logout();
266
            /** @var yii\web\Session $session */
267
            $session = Yii::$app->session;
268
            $session->setFlash('success', Module::t('module', 'Your profile has been successfully deleted!'));
269
            return $this->goHome();
270
        }
271
        return $this->render('delete', [
272
            'model' => $model
273
        ]);
274
    }
275
276
    /**
277
     * @return User
278
     * @throws NotFoundHttpException
279
     */
280
    private function findModel()
281
    {
282
        /** @var \yii\web\User $user */
283
        $user = Yii::$app->user;
284
        if (!$user->isGuest) {
285
            /** @var User $identity */
286
            $identity = Yii::$app->user->identity;
287
            if (($model = User::findOne($identity->id)) !== null) {
288
                return $model;
289
            }
290
        }
291
        throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
292
    }
293
}
294