Completed
Push — master ( a6a548...9f65cb )
by Alexey
11:15
created

ProfileController::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 0
1
<?php
2
3
namespace modules\users\controllers\frontend;
4
5
use Yii;
6
use yii\helpers\Url;
7
use yii\web\Controller;
8
use modules\users\models\frontend\User;
9
use modules\users\models\UploadForm;
10
use yii\web\UploadedFile;
11
use modules\users\models\frontend\SignupForm;
12
use modules\users\models\LoginForm;
13
use modules\users\models\frontend\EmailConfirmForm;
14
use modules\users\models\frontend\ResetPasswordForm;
15
use modules\users\models\frontend\PasswordResetRequestForm;
16
use yii\base\InvalidParamException;
17
use yii\web\BadRequestHttpException;
18
use yii\filters\VerbFilter;
19
use yii\filters\AccessControl;
20
use yii\web\NotFoundHttpException;
21
use yii\bootstrap\ActiveForm;
22
use yii\web\Response;
23
use modules\users\Module;
24
25
/**
26
 * Class ProfileController
27
 * @package modules\users\controllers\frontend
28
 */
29
class ProfileController extends Controller
30
{
31
    /**
32
     * @return array
33
     */
34
    public function behaviors()
35
    {
36
        return [
37
            'verbs' => [
38
                'class' => VerbFilter::className(),
39
                'actions' => [
40
                    'logout' => ['post'],
41
                    'delete' => ['post'],
42
                ],
43
            ],
44
        ];
45
    }
46
47
    /**
48
     * @return string
49
     * @throws NotFoundHttpException
50
     */
51
    public function actionIndex()
52
    {
53
        return $this->render('index', [
54
            'model' => $this->findModel(),
55
        ]);
56
    }
57
58
    /**
59
     * @return array|string|Response
60
     * @throws NotFoundHttpException
61
     */
62
    public function actionUpdate()
63
    {
64
        $model = $this->findModel();
65
        $user_role = $model->getUserRoleValue();
66
        $model->role = $user_role ? $user_role : $model::RBAC_DEFAULT_ROLE;
67
68
        return $this->render('update', [
69
            'model' => $model,
70
        ]);
71
    }
72
73
    /**
74
     * @return array|string|Response
75
     * @throws NotFoundHttpException
76
     */
77
    public function actionUpdatePassword()
78
    {
79
        $model = $this->findModel();
80
        $model->scenario = $model::SCENARIO_PASSWORD_UPDATE;
81
82
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
83
            Yii::$app->response->format = Response::FORMAT_JSON;
84
            return ActiveForm::validate($model);
85
        }
86
87
        if ($model->load(Yii::$app->request->post())) {
88
            if ($model->save())
89
                Yii::$app->session->setFlash('success', Module::t('module', 'Password changed successfully.'));
90
        }
91
        return $this->redirect(['update', 'tab' => 'password']);
92
    }
93
94
    /**
95
     * @return string|Response
96
     * @throws NotFoundHttpException
97
     */
98
    public function actionUpdateProfile()
99
    {
100
        $model = $this->findModel();
101
        $user_role = $model->getUserRoleValue();
102
        $model->role = $user_role ? $user_role : $model::RBAC_DEFAULT_ROLE;
103
        $model->scenario = $model::SCENARIO_PROFILE_UPDATE;
104
105
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
106
            Yii::$app->session->setFlash('success', Module::t('module', 'Profile successfully changed.'));
107
        }
108
        return $this->redirect(['update', 'tab' => 'profile']);
109
    }
110
111
    /**
112
     * @return string|Response
113
     * @throws NotFoundHttpException
114
     */
115
    public function actionUpdateAvatar()
116
    {
117
        $model = $this->findModel();
118
        $model->scenario = $model::SCENARIO_AVATAR_UPDATE;
119
        $avatar = $model->avatar;
120
        if ($model->load(Yii::$app->request->post()) && ($model->scenario === $model::SCENARIO_AVATAR_UPDATE)) {
121
            if ($model->isDel) {
122
                if ($avatar) {
123
                    $upload = Yii::$app->getModule('users')->uploads;
124
                    $path = str_replace('\\', '/', Url::to('@upload') . DIRECTORY_SEPARATOR . $upload . DIRECTORY_SEPARATOR . $model->id);
125
                    $avatar = $path . '/' . $avatar;
126
                    if (file_exists($avatar))
127
                        unlink($avatar);
128
                    $model->avatar = null;
129
                    $model->save();
130
                }
131
            }
132
            $uploadModel = new UploadForm();
133
            if ($uploadModel->imageFile = UploadedFile::getInstance($model, 'imageFile'))
134
                $uploadModel->upload();
135
        }
136
        return $this->redirect(['update', 'tab' => 'avatar']);
137
    }
138
139
    /**
140
     * Deletes an existing User model.
141
     * This delete set status blocked, is successful, logout and the browser will be redirected to the 'home' page.
142
     * @return mixed
143
     */
144
    public function actionDelete()
145
    {
146
        $model = $this->findModel();
147
        $model->scenario = $model::SCENARIO_PROFILE_DELETE;
148
        $model->status = $model::STATUS_DELETED;
149
        if ($model->save())
150
            Yii::$app->user->logout();
151
        return $this->goHome();
152
    }
153
154
    /**
155
     * Logs in a user.
156
     *
157
     * @return mixed
158
     */
159
    public function actionLogin()
160
    {
161
        if (!Yii::$app->user->isGuest) {
162
            return $this->goHome();
163
        }
164
165
        $model = new LoginForm();
166
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
167
            return $this->goBack();
168
        } else {
169
            return $this->render('login', [
170
                'model' => $model,
171
            ]);
172
        }
173
    }
174
175
    /**
176
     * Logs out the current user.
177
     *
178
     * @return mixed
179
     */
180
    public function actionLogout()
181
    {
182
        Yii::$app->user->logout();
183
184
        return $this->goHome();
185
    }
186
187
    /**
188
     * Signs user up.
189
     *
190
     * @return mixed
191
     */
192
    public function actionSignup()
193
    {
194
        $model = new SignupForm();
195
        if ($model->load(Yii::$app->request->post())) {
196
            if ($user = $model->signup()) {
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
197
                Yii::$app->getSession()->setFlash('success', Module::t('module', 'It remains to activate the account.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
198
                return $this->goHome();
199
            }
200
        }
201
202
        return $this->render('signup', [
203
            'model' => $model,
204
        ]);
205
    }
206
207
    /**
208
     * @param $token
209
     * @return \yii\web\Response
210
     * @throws BadRequestHttpException
211
     */
212
    public function actionEmailConfirm($token)
213
    {
214
        try {
215
            $model = new EmailConfirmForm($token);
216
        } catch (InvalidParamException $e) {
217
            throw new BadRequestHttpException($e->getMessage());
218
        }
219
220
        if ($model->confirmEmail()) {
221
            Yii::$app->getSession()->setFlash('success', Module::t('module', 'Thank you for registering!'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
222
        } else {
223
            Yii::$app->getSession()->setFlash('error', Module::t('module', 'Error sending message!'));
224
        }
225
226
        return $this->goHome();
227
    }
228
229
    /**
230
     * Requests password reset.
231
     *
232
     * @return mixed
233
     */
234
    public function actionRequestPasswordReset()
235
    {
236
        $model = new PasswordResetRequestForm();
237
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
238
            if ($model->sendEmail()) {
239
                Yii::$app->session->setFlash('success', Module::t('module', 'Check your email for further instructions.'));
240
241
                return $this->goHome();
242
            } else {
243
                Yii::$app->session->setFlash('error', Module::t('module', 'Sorry, we are unable to reset password.'));
244
            }
245
        }
246
247
        return $this->render('requestPasswordResetToken', [
248
            'model' => $model,
249
        ]);
250
    }
251
252
    /**
253
     * Resets password.
254
     *
255
     * @param string $token
256
     * @return mixed
257
     * @throws BadRequestHttpException
258
     */
259
    public function actionResetPassword($token)
260
    {
261
        try {
262
            $model = new ResetPasswordForm($token);
263
        } catch (InvalidParamException $e) {
264
            throw new BadRequestHttpException($e->getMessage());
265
        }
266
267
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
268
            Yii::$app->session->setFlash('success', Module::t('module', 'Password changed successfully.'));
269
270
            return $this->goHome();
271
        }
272
273
        return $this->render('resetPassword', [
274
            'model' => $model,
275
        ]);
276
    }
277
278
    /**
279
     * Finds the User model based on its primary key value.
280
     * If the model is not found, a 404 HTTP exception will be thrown.
281
     * @return User the loaded model
282
     * @throws NotFoundHttpException if the model cannot be found
283
     */
284
    protected function findModel()
285
    {
286
        $id = Yii::$app->user->identity->getId();
287
        if (($model = User::findOne($id)) !== null) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \modules\users\models\frontend\User::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 288 which is incompatible with the return type documented by modules\users\controller...leController::findModel of type modules\users\models\frontend\User.
Loading history...
288
            return $model;
289
        } else {
290
            throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
291
        }
292
    }
293
}
294