Test Failed
Pull Request — master (#160)
by Maximo
07:08
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 Canvas\Models\Companies;
9
use Phalcon\Http\Response;
10
use Phalcon\Validation;
11
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...
12
use Canvas\Exception\BadRequestHttpException;
13
use Canvas\Exception\ModelException;
14
use Canvas\Exception\NotFoundHttpException;
15
use Canvas\Models\AccessList;
16
use Canvas\Exception\ServerErrorHttpException;
17
use Zend\Http\Header\Server;
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 \Baka\Auth\UsersController
30
{
31
    /*
32
     * fields we accept to create
33
     *
34
     * @var array
35
     */
36
    protected $createFields = ['name', 'firstname', 'lastname', 'displayname', 'language', 'country_id', 'timezone', 'email', 'password', 'created_at', 'updated_at', 'default_company', 'default_company_branch', 'family', 'cell_phone_number', 'country_id'];
37
38
    /*
39
     * fields we accept to create
40
     *
41
     * @var array
42
     */
43
    protected $updateFields = ['name', 'firstname', 'lastname', 'displayname', 'language', 'country_id', 'timezone', 'email', 'password', 'created_at', 'updated_at', 'default_company', 'default_company_branch', 'cell_phone_number', 'country_id'];
44
45
    /**
46
     * set objects.
47
     *
48
     * @return void
49
     */
50
    public function onConstruct()
51
    {
52
        $this->model = new Users();
53
54
        //if you are not a admin you cant see all the users
55
        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

55
        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...
56
            $this->additionalSearchFields = [
57
                ['id', ':', $this->userData->getId()],
58
            ];
59
        } else {
60
            //admin get all the users for this company
61
            $this->additionalSearchFields = [
62
                ['id', ':', implode('|', $this->userData->getDefaultCompany()->getAssociatedUsersByApp())],
63
            ];
64
        }
65
    }
66
67
    /**
68
     * Get Uer.
69
     *
70
     * @param mixed $id
71
     *
72
     * @method GET
73
     * @url /v1/users/{id}
74
     *
75
     * @return Response
76
     */
77
    public function getById($id) : Response
78
    {
79
        //none admin users can only edit themselves
80
        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

80
        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...
81
            $id = $this->userData->getId();
82
        }
83
84
        /**
85
         * @todo filter only by user from this app / company
86
         */
87
        $user = $this->model->findFirstOrFail([
88
            'id = ?0 AND is_deleted = 0',
89
            'bind' => [$id],
90
        ]);
91
        $userObject = $user;
92
93
        //get the results and append its relationships
94
        $user = $this->appendRelationshipsToResult($this->request, $user);
95
96
        //if you search for roles we give you the access for this app
97
        //@todo move this to DTO
98
        if (array_key_exists('roles', $user)) {
99
            if (!isset($user['roles'][0])) {
100
                throw new ServerErrorHttpException('User with no Role , please contact system admin');
101
            }
102
            $accesList = AccessList::find([
103
                'conditions' => 'roles_name = ?0 and apps_id = ?1 and allowed = 0',
104
                'bind' => [$user['roles'][0]->name, $this->app->getId()]
105
            ]);
106
107
            if (count($accesList) > 0) {
108
                foreach ($accesList as $access) {
109
                    $user['access_list'][strtolower($access->resources_name)][$access->access_name] = 0;
110
                }
111
            }
112
113
            $user['default_company'] = $userObject->getDefaultCompany()->getId();
114
        }
115
116
        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...
117
    }
118
119
    /**
120
     * Update a User Info.
121
     *
122
     * @method PUT
123
     * @url /v1/users/{id}
124
     *
125
     * @return Response
126
     */
127
    public function edit($id) : Response
128
    {
129
        //none admin users can only edit themselves
130
        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

130
        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...
131
            $id = $this->userData->getId();
132
        }
133
134
        $user = $this->model->findFirstOrFail($id);
135
        $request = $this->request->getPutData();
136
137
        if (empty($request)) {
138
            throw new BadRequestHttpException(_('No data to update this account with '));
139
        }
140
141
        //update password
142
        if (array_key_exists('new_password', $request) && (!empty($request['new_password']) && !empty($request['current_password']))) {
143
            //Ok let validate user password
144
            $validation = new Validation();
145
            $validation->add('new_password', new PresenceOf(['message' => 'The new_password is required.']));
146
            $validation->add('current_password', new PresenceOf(['message' => 'The current_password is required.']));
147
            $validation->add('confirm_new_password', new PresenceOf(['message' => 'The confirm_new_password is required.']));
148
            $messages = $validation->validate($request);
149
150
            if (count($messages)) {
151
                foreach ($messages as $message) {
152
                    throw new BadRequestHttpException((string)$message);
153
                }
154
            }
155
156
            $user->updatePassword($request['current_password'], $request['new_password'], $request['confirm_new_password']);
157
        } else {
158
            //remove on any actino that doesnt involve password
159
            unset($request['password']);
160
        }
161
162
        //change my default company , the #teamfrontend is sending us the branchid instead of the company id
163
        //on this value so we use is as the branch
164
        if (array_key_exists('default_company', $request) && !array_key_exists('default_company_branch', $request)) {
165
            $user->switchDefaultCompanyByBranch((int) $request['default_company']);
166
            unset($request['default_company'], $request['default_company_branch']);
167
        } else {
168
            $user->switchDefaultCompanyByBranch((int) $request['default_company_branch']);
169
            unset($request['default_company'], $request['default_company_branch']);
170
        }
171
172
        //update
173
        $user->updateOrFail($request, $this->updateFields);
174
        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...
175
    }
176
177
    /**
178
     * Given the results we will proess the output
179
     * we will check if a DTO transformer exist and if so we will send it over to change it.
180
     *
181
     * @param object|array $results
182
     * @return void
183
     */
184
    protected function processOutput($results)
185
    {
186
        /**
187
         * remove password.
188
         * @todo move to DTO
189
         */
190
        if (is_object($results)) {
191
            $results->password = null;
192
            $results->bypassRoutes = null;
193
        }
194
195
        return $results;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $results returns the type array|object which is incompatible with the documented return type void.
Loading history...
196
    }
197
198
    /**
199
     * Add users notifications.
200
     *
201
     * @param int $id
202
     * @method PUT
203
     * @return Response
204
     */
205
    public function updateNotifications(int $id) : Response
206
    {
207
        //get the notification array
208
        //delete the current ones
209
        //iterate and save into users
210
211
        return $this->response(['OK' => $id]);
212
    }
213
214
    /**
215
     * Delete a Record.
216
     *
217
     * @throws Exception
218
     * @return Response
219
     */
220
    public function delete($id): Response
221
    {
222
        if ((int) $this->userData->getId() === (int) $id) {
223
            throw new ServerErrorHttpException('Cant delete your own user . If you want to close your account contact support or go to app settings');
224
        }
225
226
        return parent::delete($id);
227
    }
228
}
229