Test Failed
Pull Request — master (#160)
by Maximo
06:15
created

UsersController::getById()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 26
ccs 0
cts 15
cp 0
crap 20
rs 9.9332
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\Models\AccessList;
13
use Canvas\Exception\ServerErrorHttpException;
14
use \Baka\Auth\UsersController as BakaUsersController;
15
use Canvas\Contracts\Controllers\ProcessOutputMapperTrait;
16
use Canvas\Dto\User as UserDto;
17
use Canvas\Mapper\UserMapper;
18
19
/**
20
 * Class UsersController.
21
 *
22
 * @package Canvas\Api\Controllers
23
 *
24
 * @property Users $userData
25
 * @property Request $request
26
 * @property Config $config
27
 * @property Apps $app
28
 */
29
class UsersController extends BakaUsersController
30
{
31
    use ProcessOutputMapperTrait;
32
    /*
33
     * fields we accept to create
34
     *
35
     * @var array
36
     */
37
    protected $createFields = [
38
        'name',
39
        'firstname',
40
        'lastname',
41
        'displayname',
42
        'language',
43
        'country_id',
44
        'timezone',
45
        'email',
46
        'password',
47
        'created_at',
48
        'updated_at',
49
        'default_company',
50
        'default_company_branch',
51
        'family',
52
        'cell_phone_number',
53
        'country_id'
54
    ];
55
56
    /*
57
     * fields we accept to create
58
     *
59
     * @var array
60
     */
61
    protected $updateFields = [
62
        'name',
63
        'firstname',
64
        'lastname',
65
        'displayname',
66
        'language',
67
        'country_id',
68
        'timezone',
69
        'email',
70
        'password',
71
        'created_at',
72
        'updated_at',
73
        'default_company',
74
        'default_company_branch',
75
        'cell_phone_number',
76
        'country_id'
77
    ];
78
79
    /**
80
     * set objects.
81
     *
82
     * @return void
83
     */
84
    public function onConstruct()
85
    {
86
        $this->model = new Users();
87
        $this->dto = UserDto::class;
88
        $this->dtoMapper = new UserMapper();
89
90
        //if you are not a admin you cant see all the users
91
        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

91
        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...
92
            $this->additionalSearchFields = [
93
                ['id', ':', $this->userData->getId()],
94
            ];
95
        } else {
96
            //admin get all the users for this company
97
            $this->additionalSearchFields = [
98
                ['id', ':', implode('|', $this->userData->getDefaultCompany()->getAssociatedUsersByApp())],
99
            ];
100
        }
101
    }
102
103
    /**
104
     * Get Uer.
105
     *
106
     * @param mixed $id
107
     *
108
     * @method GET
109
     * @url /v1/users/{id}
110
     *
111
     * @return Response
112
     */
113
    public function getById($id) : Response
114
    {
115
        //none admin users can only edit themselves
116
        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

116
        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...
117
            $id = $this->userData->getId();
118
        }
119
120
        /**
121
         * @todo filter only by user from this app / company
122
         */
123
        $user = $this->model->findFirstOrFail([
124
            'id = ?0 AND is_deleted = 0',
125
            'bind' => [$id],
126
        ]);
127
        $userObject = $user;
128
129
        //get the results and append its relationships
130
        $user = $this->appendRelationshipsToResult($this->request, $user);
131
132
        //if you search for roles we give you the access for this app
133
        //@todo move this to DTO
134
        if (array_key_exists('roles', $user)) {
135
            $user['default_company'] = $userObject->getDefaultCompany()->getId();
136
        }
137
138
        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...
139
    }
140
141
    /**
142
     * Update a User Info.
143
     *
144
     * @method PUT
145
     * @url /v1/users/{id}
146
     *
147
     * @return Response
148
     */
149
    public function edit($id) : Response
150
    {
151
        //none admin users can only edit themselves
152
        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

152
        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...
153
            $id = $this->userData->getId();
154
        }
155
156
        $user = $this->model->findFirstOrFail($id);
157
        $request = $this->request->getPutData();
158
159
        if (empty($request)) {
160
            throw new BadRequestHttpException(_('No data to update this account with '));
161
        }
162
163
        //update password
164
        if (array_key_exists('new_password', $request) && (!empty($request['new_password']) && !empty($request['current_password']))) {
165
            //Ok let validate user password
166
            $validation = new Validation();
167
            $validation->add('new_password', new PresenceOf(['message' => 'The new_password is required.']));
168
            $validation->add('current_password', new PresenceOf(['message' => 'The current_password is required.']));
169
            $validation->add('confirm_new_password', new PresenceOf(['message' => 'The confirm_new_password is required.']));
170
            $messages = $validation->validate($request);
171
172
            if (count($messages)) {
173
                foreach ($messages as $message) {
174
                    throw new BadRequestHttpException((string)$message);
175
                }
176
            }
177
178
            $user->updatePassword($request['current_password'], $request['new_password'], $request['confirm_new_password']);
179
        } else {
180
            //remove on any actino that doesnt involve password
181
            unset($request['password']);
182
        }
183
184
        //change my default company , the #teamfrontend is sending us the branchid instead of the company id
185
        //on this value so we use is as the branch
186
        if (array_key_exists('default_company', $request) && !array_key_exists('default_company_branch', $request)) {
187
            $user->switchDefaultCompanyByBranch((int) $request['default_company']);
188
            unset($request['default_company'], $request['default_company_branch']);
189
        } else {
190
            $user->switchDefaultCompanyByBranch((int) $request['default_company_branch']);
191
            unset($request['default_company'], $request['default_company_branch']);
192
        }
193
194
        //update
195
        $user->updateOrFail($request, $this->updateFields);
196
        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...
197
    }
198
199
    /**
200
     * Add users notifications.
201
     *
202
     * @param int $id
203
     * @method PUT
204
     * @return Response
205
     */
206
    public function updateNotifications(int $id) : Response
207
    {
208
        //get the notification array
209
        //delete the current ones
210
        //iterate and save into users
211
212
        return $this->response(['OK' => $id]);
213
    }
214
215
    /**
216
     * Delete a Record.
217
     *
218
     * @throws Exception
219
     * @return Response
220
     */
221
    public function delete($id): Response
222
    {
223
        if ((int) $this->userData->getId() === (int) $id) {
224
            throw new ServerErrorHttpException('Cant delete your own user . If you want to close your account contact support or go to app settings');
225
        }
226
227
        return parent::delete($id);
228
    }
229
}
230