Completed
Push — master ( 2190e2...295182 )
by Derek Stephen
01:54
created

UserController::lostPasswordAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 18
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 18
loc 18
ccs 0
cts 15
cp 0
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
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
        $id = $this->getParam('id');
45
46
        /** @var UserService $userSvc */
47
        $userSvc = ContainerService::getInstance()->getContainer()['service.user'];
48
49
        $user = $userSvc->findUserById($id);
50
        if (!$user) {
51
            $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...
52
        }
53
54
        $this->sendJsonObjectResponse($user);
55
    }
56
57
    /**
58
     * Get a lost password email link token.
59
     *
60
     * @SWG\Get(
61
     *     path="/user/lost-password/{email}",
62
     *     tags={"users"},
63
     *     @SWG\Parameter(
64
     *         name="email",
65
     *         in="path",
66
     *         type="string",
67
     *         description="the email of the user",
68
     *         required=true,
69
     *         default="[email protected]"
70
     *     ),
71
     *     @SWG\Response(response="200", description="Sends email link details")
72
     * )
73
     * @throws Exception
74
     */
75 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...
76
    {
77
        $email = $this->getParam('email');
78
79
        $user = $this->userService->findUserByEmail($email);
80
        if (!$user) {
81
            $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...
82
            return;
83
        }
84
85
        if ($user->getState()->getValue() == State::STATE_UNACTIVATED) {
86
            $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...
87
            return;
88
        }
89
90
        $link = $this->userService->generateEmailLink($user);
91
        $this->sendJsonObjectResponse($link);
92
    }
93
94
95
96
    /**
97
     * Activate from the email link token.
98
     *
99
     * @SWG\Get(
100
     *     path="/user/activate/{email}/{token}",
101
     *     tags={"users"},
102
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
103
     *     @SWG\Parameter(
104
     *         name="email",
105
     *         in="path",
106
     *         type="string",
107
     *         description="the users email",
108
     *         required=true,
109
     *         default="[email protected]"
110
     *     ),
111
     *     @SWG\Parameter(
112
     *         name="token",
113
     *         in="path",
114
     *         type="string",
115
     *         description="the email link token",
116
     *         required=true,
117
     *         default="r4nd0mT0k3n"
118
     *     )
119
     * )
120
     * @throws Exception
121
     */
122
    public function activateAction()
123
    {
124
        $email = $this->getParam('email');
125
        $token = $this->getParam('token');
126
127
        $userService = $this->userService;
128
129
        try {
130
131
            $link = $userService->findEmailLink($email, $token);
132
            $user = $link->getUser();
133
            $user->setState(new State(State::STATE_ACTIVATED));
134
            $userService->saveUser($user);
135
            $userService->deleteEmailLink($link);
136
            $data = ['success' => true];
137
            $code = 200;
138
139
        } catch (EmailLinkException $e) {
140
            switch ($e->getMessage()) {
141
                case EmailLinkException::LINK_EXPIRED:
142
                    $data = [
143
                        'success' => false,
144
                        'error' => 'The activation link has expired. You can send a new activation <a href="/user/activate/resend/' . $email . '">here.</a>',
145
                    ];
146
                    $code = 403;
147
                    break;
148
                default:
149
                    $data = [
150
                        'success' => false,
151
                        'error' => $e->getMessage(),
152
                    ];
153
                    $code = 500;
154
                    break;
155
            }
156
        }
157
158
        $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...
159
    }
160
161
162
    /**
163
     * Refresh the activation email link token.
164
     *
165
     * @SWG\Get(
166
     *     path="/user/activate/resend/{email}",
167
     *     tags={"users"},
168
     *     @SWG\Parameter(
169
     *         name="email",
170
     *         in="path",
171
     *         type="string",
172
     *         description="the email of the user registering",
173
     *         required=true,
174
     *         default="[email protected]"
175
     *     ),
176
     *     @SWG\Response(response="200", description="Sends email link details")
177
     * )
178
     * @throws Exception
179
     */
180 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...
181
    {
182
        $email = $this->getParam('email');
183
184
        $user = $this->userService->findUserByEmail($email);
185
        if (!$user) {
186
            $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...
187
            return;
188
        }
189
190
        if ($user->getState()->getValue() == State::STATE_ACTIVATED) {
191
            $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...
192
            return;
193
        }
194
195
        $link = $this->userService->generateEmailLink($user);
196
        $this->sendJsonObjectResponse($link);
197
    }
198
199
    /**
200
     * Register as a new user. Returns an email link token.
201
     *
202
     * @SWG\Post(
203
     *     path="/user/register",
204
     *     tags={"users"},
205
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
206
     *     @SWG\Parameter(
207
     *         name="email",
208
     *         in="formData",
209
     *         type="string",
210
     *         description="the users email",
211
     *         required=true,
212
     *         default="[email protected]"
213
     *     ),
214
     *     @SWG\Parameter(
215
     *         name="password",
216
     *         in="formData",
217
     *         type="string",
218
     *         description="a password for the user",
219
     *         required=true,
220
     *         default="password"
221
     *     ),
222
     *     @SWG\Parameter(
223
     *         name="confirm",
224
     *         in="formData",
225
     *         type="string",
226
     *         description="password confirmation",
227
     *         required=true,
228
     *         default="password"
229
     *     )
230
     * )
231
     * @throws Exception
232
     */
233
    public function registerAction()
234
    {
235
        $form = new RegistrationForm('register');
236
237
        if ($this->getRequest()->getMethod() == 'POST') {
238
239
            $formData = $this->getRequest()->getParsedBody();
240
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData defined by $this->getRequest()->getParsedBody() on line 239 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...
241
242
            try {
243
                $data = $form->getValues();
244
                $user = $this->userService->registerUser($data);
245
                $link = $this->userService->generateEmailLink($user);
246
                $this->sendJsonObjectResponse($link);
247
248
            } catch (UserException $e) {
249
250
                switch ($e->getMessage()) {
251
                    case UserException::USER_EXISTS:
252
                    case UserException::WRONG_PASSWORD:
253
                        throw new Exception($e->getMessage(), 400);
254
                        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...
255
                }
256
                throw $e;
257
            }
258
        }
259
    }
260
}
261