Completed
Push — master ( 38a9f6...3da316 )
by Pavel
02:42
created

AccountController::actionConfirm()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
rs 9.6666
cc 3
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace inblank\activeuser\controllers;
4
5
use inblank\activeuser\models\forms\LoginForm;
6
use inblank\activeuser\models\forms\RegisterForm;
7
use inblank\activeuser\models\forms\ResendForm;
8
use inblank\activeuser\models\forms\RestoreForm;
9
use inblank\activeuser\traits\CommonTrait;
10
use yii;
11
use yii\web\Controller;
12
13
class AccountController extends Controller
14
{
15
16
    use CommonTrait;
17
18
    /**
19
     * @inheritdoc
20
     */
21
    public function beforeAction($action)
22
    {
23
        if (!parent::beforeAction($action)) {
24
            return false;
25
        }
26
        if (!Yii::$app->user->isGuest
27
            && in_array($action->id, ['register', 'login', 'resend', 'restore', 'confirm'])
28
        ) {
29
            // unavailable action for authorized user
30
            return $this->redirect('/');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirect('/'); (yii\web\Response) is incompatible with the return type of the parent method yii\web\Controller::beforeAction of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
31
        }
32
        return true;
33
    }
34
35
    /**
36
     * User registering action
37
     */
38
    public function actionRegister()
39
    {
40
        if (!$this->module->isRegistrationEnabled()) {
41
            return $this->render('registerDisable');
42
        }
43
        $flashMessageId = 'activeuser_register';
44
45
        $email = Yii::$app->session->getFlash($flashMessageId);
46 View Code Duplication
        if (!empty($email)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
            return $this->render('registerAfter', [
48
                'user' => Yii::createObject(self::di('User'))->findOne(['email' => $email]),
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
49
            ]);
50
        }
51
        /** @var RegisterForm $model */
52
        $model = Yii::createObject(RegisterForm::className());
53 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->register()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
            // congratulation and instruction
55
            Yii::$app->session->setFlash($flashMessageId, $model->email);
56
            return $this->redirect(['/activeuser/account/register']);
57
        }
58
        return $this->render('register', [
59
            'model' => $model,
60
        ]);
61
    }
62
63
    /**
64
     * User login action
65
     */
66
    public function actionLogin()
67
    {
68
        // TODO filter too many login request
69
        /** @var LoginForm $model */
70
        $model = Yii::createObject(LoginForm::className());
71
        if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
72
            return $this->goBack();
73
        }
74
        return $this->render('login', [
75
            'model' => $model,
76
        ]);
77
    }
78
79
    /**
80
     * User logout action
81
     */
82
    public function actionLogout()
83
    {
84
        Yii::$app->user->logout();
85
        return $this->redirect('/');
86
    }
87
88
    /**
89
     * Request password change
90
     * @return string|yii\web\Response
91
     * @throws yii\base\InvalidConfigException
92
     * @throws yii\web\NotFoundHttpException
93
     */
94
    public function actionRestore()
95
    {
96
        // TODO filter too many restore request and set in Module period for restore
97
        if (!$this->getModule()->enablePasswordRestore) {
98
            throw new yii\web\NotFoundHttpException();
99
        }
100
        $flashMessageId = 'activeuser_restore_sent';
101
        $email = Yii::$app->session->getFlash($flashMessageId);
102
        if ($email !== null) {
103
            // message with instructions sent
104
            return $this->render('restoreSent', [
105
                'email' => $email,
106
            ]);
107
        }
108
109
        /** @var RestoreForm $model */
110
        $model = Yii::createObject(RestoreForm::className());
111
        $model->setScenario($model::SCENARIO_EMAIL);
112 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->restore()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
            Yii::$app->session->setFlash($flashMessageId, $model->email);
114
            return $this->redirect(['/activeuser/account/restore']);
115
        }
116
        $error = Yii::$app->session->getFlash('activeuser_error');
117
        if (!empty($error) && !empty($error['token'])) {
118
            $error = $error['token'][0];
119
        } else {
120
            $error = null;
121
        }
122
        return $this->render('restore', [
123
            'model' => $model,
124
            'error' => $error,
125
        ]);
126
    }
127
128
    /**
129
     * Change user password
130
     * @param string $token user token for restore
131
     * @return string|yii\web\Response
132
     * @throws yii\base\InvalidConfigException
133
     * @throws yii\web\NotFoundHttpException
134
     */
135
    public function actionPassword($token = null)
136
    {
137
        $flashMessageId = 'activeuser_restore';
138
139
        $email = Yii::$app->session->getFlash($flashMessageId);
140 View Code Duplication
        if (!empty($email)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
            // congratulation message
142
            return $this->render('restoreComplete', [
143
                'user' => Yii::createObject(self::di('User'))->findOne(['email' => $email]),
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
            ]);
145
        }
146
147
        /** @var \inblank\activeuser\models\User $user */
148
        if (!$this->getModule()->enablePasswordRestore || $token === null || !($user = Yii::createObject(self::di('User'))->findByToken($token))) {
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
149
            throw new yii\web\NotFoundHttpException();
150
        }
151
152
        if ($user->isRestoreTokenExpired()) {
153
            Yii::$app->session->setFlash('activeuser_error', ['token' => Yii::t('activeuser_general', 'You token was expired')]);
154
            return $this->redirect(['/activeuser/account/restore']);
155
        }
156
157
        /** @var RestoreForm $model */
158
        $model = Yii::createObject(RestoreForm::className());
159
        $model->setScenario($model::SCENARIO_PASSWORD);
160
        if ($this->getModule()->generatePassOnRestore) {
161
            // password auto generation
162
            $changed = $user->changePassword();
163
        } else {
164
            // change to user entered
165
            $model->email = $user->email;
166
            $changed = $model->load(Yii::$app->getRequest()->post()) && $model->changePassword();
167
        }
168
        if ($changed) {
169
            Yii::$app->session->setFlash($flashMessageId, $user->email);
170
            return $this->redirect(['/activeuser/account/password']);
171
        }
172
        return $this->render('restorePass', [
173
            'model' => $model
174
        ]);
175
    }
176
177
    /**
178
     * User resend confirmation message
179
     */
180
    public function actionResend()
181
    {
182
        // TODO filter too many resend request and set in Module period for resend
183
        if (!$this->getModule()->enableConfirmation) {
184
            throw new yii\web\NotFoundHttpException();
185
        }
186
187
        $email = Yii::$app->session->getFlash('resend');
188
        if ($email !== null) {
189
            // already sent
190
            return $this->render('resendComplete', [
191
                'email' => $email,
192
            ]);
193
        }
194
195
        // new resend
196
        /** @var ResendForm $model */
197
        $model = Yii::createObject(ResendForm::className());
198 View Code Duplication
        if ($model->load(Yii::$app->getRequest()->post()) && $model->resend()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
199
            // resend complete, even if the user is not found
200
            Yii::$app->session->setFlash('resend', $model->email);
201
            return $this->redirect(['/activeuser/account/resend']);
202
        }
203
        return $this->render('resend', [
204
            'model' => $model,
205
        ]);
206
    }
207
208
    /**
209
     * Confirm email page
210
     * @param string $token user token for confirm email
211
     * @return string
212
     * @throws yii\base\InvalidConfigException
213
     */
214
    public function actionConfirm($token = '')
215
    {
216
        /** @var \inblank\activeuser\models\User $user */
217
        $user = Yii::createObject(self::di('User'))->findByToken($token);
0 ignored issues
show
Documentation introduced by
self::di('User') is of type *, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
218
        if ($user !== null && $user->confirm()) {
219
            return $this->render('confirm', ['user' => $user]);
220
        }
221
        return $this->render('confirmWrong');
222
    }
223
224
}
225