Completed
Push — master ( 295182...440812 )
by Derek Stephen
01:52
created

UserController::resetPassAction()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 43
ccs 0
cts 20
cp 0
rs 8.6097
c 0
b 0
f 0
cc 6
nc 6
nop 0
crap 42
1
<?php
2
3
namespace App\Controller;
4
5
use App\Form\User\RegistrationForm;
6
use Del\Common\ContainerService;
7
use Del\Exception\EmailLinkException;
8
use Del\Exception\UserException;
9
use Del\Service\UserService;
10
use Del\Value\User\State;
11
use Exception;
12
13
class UserController extends BaseController
14
{
15
    /** @var UserService */
16
    private $userService;
17
18
    public function init()
19
    {
20
        $c = ContainerService::getInstance()->getContainer();
21
        $this->userService = $c['service.user'];
22
    }
23
24
    /**
25
     * Fetch user details by ID.
26
     *
27
     * @SWG\Get(
28
     *     path="/user/{id}",
29
     *     tags={"users"},
30
     *     @SWG\Parameter(
31
     *         name="id",
32
     *         in="path",
33
     *         type="integer",
34
     *         description="the type of response",
35
     *         required=false,
36
     *         default=1
37
     *     ),
38
     *     @SWG\Response(response="200", description="Sends user details")
39
     * )
40
     *
41
     */
42
    public function indexAction()
43
    {
44
        if (!$this->httpMethodCheck('POST')) { return; }
45
46
        $id = $this->getParam('id');
47
48
        /** @var UserService $userSvc */
49
        $userSvc = ContainerService::getInstance()->getContainer()['service.user'];
50
51
        $user = $userSvc->findUserById($id);
52
        if (!$user) {
53
            $this->sendJsonResponse(['error' => 'User not found'], 404);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 404.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
54
            return;
55
        }
56
57
        $this->sendJsonObjectResponse($user);
58
    }
59
60
61
62
    /**
63
     * Activate from the email link token.
64
     *
65
     * @SWG\Get(
66
     *     path="/user/activate/{email}/{token}",
67
     *     tags={"users"},
68
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
69
     *     @SWG\Parameter(
70
     *         name="email",
71
     *         in="path",
72
     *         type="string",
73
     *         description="the users email",
74
     *         required=true,
75
     *         default="[email protected]"
76
     *     ),
77
     *     @SWG\Parameter(
78
     *         name="token",
79
     *         in="path",
80
     *         type="string",
81
     *         description="the email link token",
82
     *         required=true,
83
     *         default="r4nd0mT0k3n"
84
     *     )
85
     * )
86
     * @throws Exception
87
     */
88
    public function activateAction()
89
    {
90
        if (!$this->httpMethodCheck('GET')) { return; }
91
92
        $email = $this->getParam('email');
93
        $token = $this->getParam('token');
94
95
        $userService = $this->userService;
96
97
        try {
98
99
            /** @todo  handle exceptions */
100
            $link = $userService->findEmailLink($email, $token);
101
102
            $user = $link->getUser();
103
            $user->setState(new State(State::STATE_ACTIVATED));
104
            $userService->saveUser($user);
105
            $userService->deleteEmailLink($link);
106
            $data = ['success' => true];
107
            $code = 200;
108
109
        } catch (EmailLinkException $e) {
110
            switch ($e->getMessage()) {
111
                case EmailLinkException::LINK_EXPIRED:
112
                    $data = [
113
                        'success' => false,
114
                        'error' => 'The activation link has expired. You can send a new activation <a href="/user/activate/resend/' . $email . '">here.</a>',
115
                    ];
116
                    $code = 403;
117
                    break;
118
                default:
119
                    $data = [
120
                        'success' => false,
121
                        'error' => $e->getMessage(),
122
                    ];
123
                    $code = 500;
124
                    break;
125
            }
126
        }
127
128
        $this->sendJsonResponse($data, $code);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with $code.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
129
    }
130
131
132
    /**
133
     * Refresh the activation email link token.
134
     *
135
     * @SWG\Get(
136
     *     path="/user/activate/resend/{email}",
137
     *     tags={"users"},
138
     *     @SWG\Parameter(
139
     *         name="email",
140
     *         in="path",
141
     *         type="string",
142
     *         description="the email of the user registering",
143
     *         required=true,
144
     *         default="[email protected]"
145
     *     ),
146
     *     @SWG\Response(response="200", description="Sends email link details")
147
     * )
148
     * @throws Exception
149
     */
150 View Code Duplication
    public function resendActivationAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
151
    {
152
        if (!$this->httpMethodCheck('GET')) { return; }
153
154
        $email = $this->getParam('email');
155
156
        $user = $this->userService->findUserByEmail($email);
157
        if (!$user) {
158
            $this->sendJsonResponse(['error' => UserException::USER_NOT_FOUND], 404);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 404.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
159
            return;
160
        }
161
162
        if ($user->getState()->getValue() == State::STATE_ACTIVATED) {
163
            $this->sendJsonResponse(['error' => UserException::USER_ACTIVATED], 400);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 400.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
164
            return;
165
        }
166
167
        $link = $this->userService->generateEmailLink($user);
168
        $this->sendJsonObjectResponse($link);
169
    }
170
171
    /**
172
     * Get a lost password email link token.
173
     *
174
     * @SWG\Get(
175
     *     path="/user/lost-password/{email}",
176
     *     tags={"users"},
177
     *     @SWG\Parameter(
178
     *         name="email",
179
     *         in="path",
180
     *         type="string",
181
     *         description="the email of the user",
182
     *         required=true,
183
     *         default="[email protected]"
184
     *     ),
185
     *     @SWG\Response(response="200", description="Sends email link details")
186
     * )
187
     * @throws Exception
188
     */
189 View Code Duplication
    public function lostPasswordAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
190
    {
191
        if (!$this->httpMethodCheck('GET')) { return; }
192
193
        $email = $this->getParam('email');
194
195
        $user = $this->userService->findUserByEmail($email);
196
        if (!$user) {
197
            $this->sendJsonResponse(['error' => UserException::USER_NOT_FOUND], 404);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 404.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
198
            return;
199
        }
200
201
        if ($user->getState()->getValue() == State::STATE_UNACTIVATED) {
202
            $this->sendJsonResponse(['error' => UserException::USER_UNACTIVATED], 400);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 400.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
203
            return;
204
        }
205
206
        $link = $this->userService->generateEmailLink($user);
207
        $this->sendJsonObjectResponse($link);
208
    }
209
210
    /**
211
     * Register as a new user. Returns an email link token.
212
     *
213
     * @SWG\Post(
214
     *     path="/user/register",
215
     *     tags={"users"},
216
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
217
     *     @SWG\Parameter(
218
     *         name="email",
219
     *         in="formData",
220
     *         type="string",
221
     *         description="the users email",
222
     *         required=true,
223
     *         default="[email protected]"
224
     *     ),
225
     *     @SWG\Parameter(
226
     *         name="password",
227
     *         in="formData",
228
     *         type="string",
229
     *         description="a password for the user",
230
     *         required=true,
231
     *         default="password"
232
     *     ),
233
     *     @SWG\Parameter(
234
     *         name="confirm",
235
     *         in="formData",
236
     *         type="string",
237
     *         description="password confirmation",
238
     *         required=true,
239
     *         default="password"
240
     *     )
241
     * )
242
     * @throws Exception
243
     */
244
    public function registerAction()
245
    {
246
        if (!$this->httpMethodCheck('POST')) { return; }
247
248
        $form = new RegistrationForm('register');
249
250
        if ($this->getRequest()->getMethod() == 'POST') {
251
252
            $formData = $this->getRequest()->getParsedBody();
253
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData defined by $this->getRequest()->getParsedBody() on line 252 can also be of type null or object; however, Del\Form\AbstractForm::populate() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
254
255
            try {
256
                $data = $form->getValues();
257
                $user = $this->userService->registerUser($data);
258
                $link = $this->userService->generateEmailLink($user);
259
                $this->sendJsonObjectResponse($link);
260
261
            } catch (UserException $e) {
262
263
                switch ($e->getMessage()) {
264
                    case UserException::USER_EXISTS:
265
                    case UserException::WRONG_PASSWORD:
266
                        throw new Exception($e->getMessage(), 400);
267
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
268
                }
269
                throw $e;
270
            }
271
        }
272
    }
273
274
    /**
275
     * Resets the users password. Requires an email link token.
276
     *
277
     * @SWG\Post(
278
     *     path="/user/reset-password/{email}/{token}",
279
     *     tags={"users"},
280
     *     @SWG\Response(response="200", description="Resets a users email"),
281
     *     @SWG\Parameter(
282
     *         name="email",
283
     *         in="path",
284
     *         type="string",
285
     *         description="the email of the user",
286
     *         required=true,
287
     *         default="[email protected]"
288
     *     ),
289
     *     @SWG\Parameter(
290
     *         name="token",
291
     *         in="path",
292
     *         type="string",
293
     *         description="the email link token",
294
     *         required=true,
295
     *         default="r4nd0mT0k3n"
296
     *     ),
297
     *     @SWG\Parameter(
298
     *         name="password",
299
     *         in="formData",
300
     *         type="string",
301
     *         description="a password for the user",
302
     *         required=true,
303
     *         default="password"
304
     *     ),
305
     *     @SWG\Parameter(
306
     *         name="confirm",
307
     *         in="formData",
308
     *         type="string",
309
     *         description="password confirmation",
310
     *         required=true,
311
     *         default="password"
312
     *     )
313
     * )
314
     * @throws Exception
315
     * @todo keep working!
316
     */
317
    public function resetPassAction()
318
    {
319
        if (!$this->httpMethodCheck('POST')) { return; }
320
321
        $email = $this->getParam('email');
322
        $token = $this->getParam('token');
323
324
        $user = $this->userService->findUserByEmail($email);
325
        if (!$user) {
326
            $this->sendJsonResponse(['error' => UserException::USER_NOT_FOUND], 404);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 404.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
327
            return;
328
        }
329
330
        try {
331
            $link = $this->userService->findEmailLink($email, $token);
0 ignored issues
show
Unused Code introduced by
$link 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...
332
        } catch (EmailLinkException $e) {
333
            $code = $e->getMessage() == EmailLinkException::LINK_EXPIRED ? 400 : 404;
334
            $this->sendJsonResponse(['error' => $e->getMessage(), $code]);
335
            return;
336
        } catch (Exception $e) {
337
            throw $e;
338
        }
339
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
340
        $form = new Application_Form_ResetPass();
341
342
        $data = $this->getRequest()->getParams();
343
344
        if ($form->isValid($data)) {
345
346
            if ($data['password'] == $data['confirm']) {
347
                $this->getUserService()->changePassword($user, $data['password']);
348
                $this->getUserService()->deleteEmailLink($link);
349
                $this->view->message = [' You have successfully changed your password.', 'success'];
350
                $this->view->success = true;
351
            } else {
352
                $this->view->message = $this->view->message = ['Passwords did not match, please try again.', 'danger'];
353
                $this->view->form = $form;
354
            }
355
        } else {
356
            $this->view->form = $form;
357
        }
358
*/
359
    }
360
}
361