Completed
Push — master ( 3e5621...2190e2 )
by Derek Stephen
01:43
created

UserController::resendActivationAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
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 View Code Duplication
    public function indexAction()
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...
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(['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
     * Register as a new user. Gives an email link token.
59
     *
60
     * @SWG\Post(
61
     *     path="/user/register",
62
     *     tags={"users"},
63
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
64
     *     @SWG\Parameter(
65
     *         name="email",
66
     *         in="formData",
67
     *         type="string",
68
     *         description="the users email",
69
     *         required=true,
70
     *         default="[email protected]"
71
     *     ),
72
     *     @SWG\Parameter(
73
     *         name="password",
74
     *         in="formData",
75
     *         type="string",
76
     *         description="a password for the user",
77
     *         required=true,
78
     *         default="password"
79
     *     ),
80
     *     @SWG\Parameter(
81
     *         name="confirm",
82
     *         in="formData",
83
     *         type="string",
84
     *         description="password confirmation",
85
     *         required=true,
86
     *         default="password"
87
     *     )
88
     * )
89
     * @throws Exception
90
     */
91
    public function registerAction()
92
    {
93
        $form = new RegistrationForm('register');
94
95
        if ($this->getRequest()->getMethod() == 'POST') {
96
97
            $formData = $this->getRequest()->getParsedBody();
98
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData defined by $this->getRequest()->getParsedBody() on line 97 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...
99
100
            try {
101
                $data = $form->getValues();
102
                $user = $this->userService->registerUser($data);
103
                $link = $this->userService->generateEmailLink($user);
104
                $this->sendJsonObjectResponse($link);
105
106
            } catch (UserException $e) {
107
108
                switch ($e->getMessage()) {
109
                    case UserException::USER_EXISTS:
110
                    case UserException::WRONG_PASSWORD:
111
                        throw new Exception($e->getMessage(), 400);
112
                        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...
113
                }
114
                throw $e;
115
            }
116
        }
117
    }
118
119
120
    /**
121
     * Get a new activation email link.
122
     *
123
     * @SWG\Get(
124
     *     path="/user/activate/resend/{email}",
125
     *     tags={"users"},
126
     *     @SWG\Parameter(
127
     *         name="email",
128
     *         in="path",
129
     *         type="string",
130
     *         description="the email of the user registering",
131
     *         required=true,
132
     *         default="[email protected]"
133
     *     ),
134
     *     @SWG\Response(response="200", description="Sends email link details")
135
     * )
136
     * @throws Exception
137
     */
138
    public function resendActivationAction()
139
    {
140
        $email = $this->getParam('email');
141
142
        $user = $this->userService->findUserByEmail($email);
143
        if (!$user) {
144
            $this->sendJsonResponse(['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...
145
            return;
146
        }
147
148
        if ($user->getState()->getValue() == State::STATE_ACTIVATED) {
149
            $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...
150
            return;
151
        }
152
153
        $link = $this->userService->generateEmailLink($user);
154
        $this->sendJsonObjectResponse($link);
155
    }
156
157
158
159
    /**
160
     * Activate from the email link.
161
     *
162
     * @SWG\Get(
163
     *     path="/user/activate/{email}/{token}",
164
     *     tags={"users"},
165
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
166
     *     @SWG\Parameter(
167
     *         name="email",
168
     *         in="path",
169
     *         type="string",
170
     *         description="the users email",
171
     *         required=true,
172
     *         default="[email protected]"
173
     *     ),
174
     *     @SWG\Parameter(
175
     *         name="token",
176
     *         in="path",
177
     *         type="string",
178
     *         description="the email link token",
179
     *         required=true,
180
     *         default="r4nd0mT0k3n"
181
     *     )
182
     * )
183
     * @throws Exception
184
     */
185
    public function activateAction()
186
    {
187
        $email = $this->getParam('email');
188
        $token = $this->getParam('token');
189
190
        $userService = $this->userService;
191
        $this->view->success = false;
192
193
        try {
194
195
            $link = $userService->findEmailLink($email, $token);
196
            $user = $link->getUser();
197
            $user->setState(new State(State::STATE_ACTIVATED));
198
            $userService->saveUser($user);
199
            $userService->deleteEmailLink($link);
200
            $data = ['success' => true];
201
            $code = 200;
202
203
        } catch (EmailLinkException $e) {
204
            switch ($e->getMessage()) {
205
                case EmailLinkException::LINK_EXPIRED:
206
                    $data = [
207
                        'success' => false,
208
                        'error' => 'The activation link has expired. You can send a new activation <a href="/user/activate/resend/' . $email . '">here.</a>',
209
                    ];
210
                    $code = 403;
211
                    break;
212
                default:
213
                    $data = [
214
                        'success' => false,
215
                        'error' => $e->getMessage(),
216
                    ];
217
                    $code = 500;
218
                    break;
219
            }
220
        }
221
222
        $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...
223
    }
224
}
225