Test Failed
Pull Request — master (#160)
by Maximo
07:12
created

UsersController::updateNotifications()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Api\Controllers;
6
7
use Canvas\Models\Users;
8
use Phalcon\Http\Response;
9
use Phalcon\Validation;
10
use Phalcon\Validation\Validator\PresenceOf;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Canvas\Exception\BadRequestHttpException;
12
use Canvas\Exception\ServerErrorHttpException;
13
use \Baka\Auth\UsersController as BakaUsersController;
14
use Canvas\Contracts\Controllers\ProcessOutputMapperTrait;
15
use Canvas\Dto\User as UserDto;
16
use Canvas\Mapper\UserMapper;
17
18
/**
19
 * Class UsersController.
20
 *
21
 * @package Canvas\Api\Controllers
22
 *
23
 * @property Users $userData
24
 * @property Request $request
25
 * @property Config $config
26
 * @property Apps $app
27
 */
28
class UsersController extends BakaUsersController
29
{
30
    use ProcessOutputMapperTrait;
31
    /*
32
     * fields we accept to create
33
     *
34
     * @var array
35
     */
36
    protected $createFields = [
37
        'name',
38
        'firstname',
39
        'lastname',
40
        'displayname',
41
        'language',
42
        'country_id',
43
        'timezone',
44
        'email',
45
        'password',
46
        'created_at',
47
        'updated_at',
48
        'default_company',
49
        'default_company_branch',
50
        'family',
51
        'cell_phone_number',
52
        'country_id'
53
    ];
54
55
    /*
56
     * fields we accept to create
57
     *
58
     * @var array
59
     */
60
    protected $updateFields = [
61
        'name',
62
        'firstname',
63
        'lastname',
64
        'displayname',
65
        'language',
66
        'country_id',
67
        'timezone',
68
        'email',
69
        'password',
70
        'created_at',
71
        'updated_at',
72
        'default_company',
73
        'default_company_branch',
74
        'cell_phone_number',
75
        'country_id'
76
    ];
77
78
    /**
79
     * set objects.
80
     *
81
     * @return void
82
     */
83
    public function onConstruct()
84
    {
85
        $this->model = new Users();
86
        $this->dto = UserDto::class;
87
        $this->dtoMapper = new UserMapper();
88
89
        //if you are not a admin you cant see all the users
90
        if (!$this->userData->hasRole('Defaults.Admins')) {
0 ignored issues
show
Unused Code introduced by
The call to Canvas\Models\Users::hasRole() has too many arguments starting with 'Defaults.Admins'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

90
        if (!$this->userData->/** @scrutinizer ignore-call */ hasRole('Defaults.Admins')) {

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. Please note the @ignore annotation hint above.

Loading history...
91
            $this->additionalSearchFields = [
92
                ['id', ':', $this->userData->getId()],
93
            ];
94
        } else {
95
            //admin get all the users for this company
96
            $this->additionalSearchFields = [
97
                ['id', ':', implode('|', $this->userData->getDefaultCompany()->getAssociatedUsersByApp())],
98
            ];
99
        }
100
    }
101
102
    /**
103
     * Get Uer.
104
     *
105
     * @param mixed $id
106
     *
107
     * @method GET
108
     * @url /v1/users/{id}
109
     *
110
     * @return Response
111
     */
112
    public function getById($id) : Response
113
    {
114
        //none admin users can only edit themselves
115
        if (!$this->userData->hasRole('Default.Admins') || (int) $id === 0) {
0 ignored issues
show
Unused Code introduced by
The call to Canvas\Models\Users::hasRole() has too many arguments starting with 'Default.Admins'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

115
        if (!$this->userData->/** @scrutinizer ignore-call */ hasRole('Default.Admins') || (int) $id === 0) {

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. Please note the @ignore annotation hint above.

Loading history...
116
            $id = $this->userData->getId();
117
        }
118
119
        /**
120
         * @todo filter only by user from this app / company
121
         */
122
        $user = $this->model->findFirstOrFail([
123
            'id = ?0 AND is_deleted = 0',
124
            'bind' => [$id],
125
        ]);
126
        $userObject = $user;
0 ignored issues
show
Unused Code introduced by
The assignment to $userObject is dead and can be removed.
Loading history...
127
128
        //get the results and append its relationships
129
        $user = $this->appendRelationshipsToResult($this->request, $user);
130
131
        return $this->response($this->processOutput($user));
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->processOutput($user) targeting Canvas\Api\Controllers\U...roller::processOutput() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
132
    }
133
134
    /**
135
     * Update a User Info.
136
     *
137
     * @method PUT
138
     * @url /v1/users/{id}
139
     *
140
     * @return Response
141
     */
142
    public function edit($id) : Response
143
    {
144
        //none admin users can only edit themselves
145
        if (!$this->userData->hasRole('Default.Admins')) {
0 ignored issues
show
Unused Code introduced by
The call to Canvas\Models\Users::hasRole() has too many arguments starting with 'Default.Admins'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

145
        if (!$this->userData->/** @scrutinizer ignore-call */ hasRole('Default.Admins')) {

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. Please note the @ignore annotation hint above.

Loading history...
146
            $id = $this->userData->getId();
147
        }
148
149
        $user = $this->model->findFirstOrFail($id);
150
        $request = $this->request->getPutData();
151
152
        if (empty($request)) {
153
            throw new BadRequestHttpException(_('No data to update this account with '));
154
        }
155
156
        //update password
157
        if (isset($request['new_password']) && (!empty($request['new_password']) && !empty($request['current_password']))) {
158
            //Ok let validate user password
159
            $validation = new Validation();
160
            $validation->add('new_password', new PresenceOf(['message' => 'The new_password is required.']));
161
            $validation->add('current_password', new PresenceOf(['message' => 'The current_password is required.']));
162
            $validation->add('confirm_new_password', new PresenceOf(['message' => 'The confirm_new_password is required.']));
163
            $messages = $validation->validate($request);
164
165
            if (count($messages)) {
166
                foreach ($messages as $message) {
167
                    throw new BadRequestHttpException((string)$message);
168
                }
169
            }
170
171
            $user->updatePassword($request['current_password'], $request['new_password'], $request['confirm_new_password']);
172
        } else {
173
            //remove on any actino that doesnt involve password
174
            unset($request['password']);
175
        }
176
177
        //change my default company , the #teamfrontend is sending us the branchid instead of the company id
178
        //on this value so we use is as the branch
179
        if (isset($request['default_company']) && !isset($request['default_company_branch'])) {
180
            $user->switchDefaultCompanyByBranch((int) $request['default_company']);
181
            unset($request['default_company'], $request['default_company_branch']);
182
        } else {
183
            $user->switchDefaultCompanyByBranch((int) $request['default_company_branch']);
184
            unset($request['default_company'], $request['default_company_branch']);
185
        }
186
187
        //update
188
        $user->updateOrFail($request, $this->updateFields);
189
        return $this->response($this->processOutput($user));
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->processOutput($user) targeting Canvas\Api\Controllers\U...roller::processOutput() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
190
    }
191
192
    /**
193
     * Add users notifications.
194
     *
195
     * @param int $id
196
     * @method PUT
197
     * @return Response
198
     */
199
    public function updateNotifications(int $id) : Response
200
    {
201
        //get the notification array
202
        //delete the current ones
203
        //iterate and save into users
204
205
        return $this->response(['OK' => $id]);
206
    }
207
208
    /**
209
     * Delete a Record.
210
     *
211
     * @throws Exception
212
     * @return Response
213
     */
214
    public function delete($id): Response
215
    {
216
        if ((int) $this->userData->getId() === (int) $id) {
217
            throw new ServerErrorHttpException('Cant delete your own user . If you want to close your account contact support or go to app settings');
218
        }
219
220
        return parent::delete($id);
221
    }
222
}
223