Completed
Push — master ( 71fa65...a9822c )
by Derek Stephen
01:47
created

UserController::activateAction()   B

Complexity

Conditions 3
Paths 11

Size

Total Lines 39
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 39
ccs 0
cts 34
cp 0
rs 8.8571
c 1
b 0
f 0
cc 3
eloc 29
nc 11
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
use OAuth\User;
13
14
class UserController extends BaseController
15
{
16
    /** @var UserService */
17
    private $userService;
18
19
    public function init()
20
    {
21
        $c = ContainerService::getInstance()->getContainer();
22
        $this->userService = $c['service.user'];
23
    }
24
25
    /**
26
     * Fetch user details
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
        /** @var UserService $userSvc */
46
        $userSvc = ContainerService::getInstance()->getContainer()['service.user'];
47
        /** @var User $user */
48
        $user = $userSvc->findUserById($id);
49
        if (!$user) {
50
            $this->sendJsonResponse(['User not found']);
51
        }
52
        $this->sendJsonResponse(['email' => $user->getEmail()]);
53
    }
54
55
    /**
56
     * Register as a new user.
57
     * @SWG\Post(
58
     *     path="/user/register",
59
     *     tags={"users"},
60
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
61
     *     @SWG\Parameter(
62
     *         name="email",
63
     *         in="formData",
64
     *         type="string",
65
     *         description="the users email",
66
     *         required=true,
67
     *         default="[email protected]"
68
     *     ),
69
     *     @SWG\Parameter(
70
     *         name="password",
71
     *         in="formData",
72
     *         type="string",
73
     *         description="a password for the user",
74
     *         required=true,
75
     *         default="password"
76
     *     ),
77
     *     @SWG\Parameter(
78
     *         name="confirm",
79
     *         in="formData",
80
     *         type="string",
81
     *         description="password confirmation",
82
     *         required=true,
83
     *         default="password"
84
     *     )
85
     * )
86
     * @throws Exception
87
     */
88
    public function registerAction()
89
    {
90
        $form = new RegistrationForm('register');
91
92
        if ($this->getRequest()->getMethod() == 'POST') {
93
94
            $formData = $this->getRequest()->getParsedBody();
95
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData defined by $this->getRequest()->getParsedBody() on line 94 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...
96
97
            try {
98
                $data = $form->getValues();
99
                $user = $this->userService->registerUser($data);
100
                $link = $this->userService->generateEmailLink($user);
101
                $this->sendJsonResponse([
102
                    'user' => $this->userService->toArray($user),
103
                    'link' => [
104
                        'token' => $link->getToken(),
105
                        'expires' => $link->getExpiryDate()->format('Y-m-d H:i:s'),
106
                    ],
107
                ]);
108
109
            } catch (UserException $e) {
110
111
                switch ($e->getMessage()) {
112
                    case UserException::USER_EXISTS:
113
                        throw new Exception($e->getMessage(), 400);
114
                        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...
115
                    case UserException::WRONG_PASSWORD:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
116
117
                        throw new Exception($e->getMessage(), 400);
118
                        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...
119
                }
120
                throw $e;
121
            }
122
123
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData defined by $this->getRequest()->getParsedBody() on line 94 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...
124
        }
125
    }
126
127
128
129
    /**
130
     * Activate from the email link.
131
     * @SWG\Get(
132
     *     path="/user/activate/{email}/{token}",
133
     *     tags={"users"},
134
     *     @SWG\Response(response="200", description="Registers a new unactivated user"),
135
     *     @SWG\Parameter(
136
     *         name="email",
137
     *         in="path",
138
     *         type="string",
139
     *         description="the users email",
140
     *         required=true,
141
     *         default="[email protected]"
142
     *     ),
143
     *     @SWG\Parameter(
144
     *         name="token",
145
     *         in="path",
146
     *         type="string",
147
     *         description="the email link token",
148
     *         required=true,
149
     *         default="r4nd0mT0k3n"
150
     *     )
151
     * )
152
     * @throws Exception
153
     */
154
    public function activateAction()
155
    {
156
        $email = $this->getParam('email');
157
        $token = $this->getParam('token');
158
159
        $userService = $this->userService;
160
        $this->view->success = false;
161
162
        try {
163
164
            $link = $userService->findEmailLink($email, $token);
165
            $user = $link->getUser();
166
            $user->setState(new State(State::STATE_ACTIVATED));
167
            $userService->saveUser($user);
168
            $userService->deleteEmailLink($link);
169
            $this->view->success = true;
170
            return;
171
172
        } catch (EmailLinkException $e) {
173
            switch ($e->getMessage()) {
174
                case EmailLinkException::LINK_EXPIRED:
175
                    $this->sendJsonResponse([
176
                        'success' => false,
177
                        'error' => 'The activation link has expired. You can send a new activation <a href="/user/resend-activation-mail/' . $email . '">here.</a>',
178
                    ], 403);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 403.

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...
179
                    break;
180
                default:
181
                    $this->sendJsonResponse([
182
                        'success' => false,
183
                        'error' => $e->getMessage(),
184
                    ], 500);
0 ignored issues
show
Unused Code introduced by
The call to UserController::sendJsonResponse() has too many arguments starting with 500.

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...
185
                    break;
186
            }
187
        }
188
189
        $this->sendJsonResponse([
190
            'success' => true,
191
        ]);
192
    }
193
}
194