Passed
Push — feature/permission-manager ( 41e93d )
by
unknown
09:00
created

HandleUserPermissions::getUserPermissionsFields()   F

Complexity

Conditions 18
Paths 241

Size

Total Lines 74
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 18
eloc 37
c 2
b 0
f 0
nc 241
nop 2
dl 0
loc 74
rs 3.5208

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use A17\Twill\Models\User;
6
use A17\Twill\Models\Model;
7
use Illuminate\Support\Str;
8
use A17\Twill\Models\Permission;
9
10
trait HandleUserPermissions
11
{
12
    /**
13
     * Retrieve user permissions fields
14
     *
15
     * @param Model|User $object
16
     * @param array $fields
17
     * @return array
18
     */
19
    public function getFormFieldsHandleUserPermissions($object, $fields)
20
    {
21
        if (!config('twill.enabled.permissions-management')) {
22
            return $fields;
23
        }
24
25
        foreach ($object->permissions()->moduleItem()->get() as $permission) {
0 ignored issues
show
Bug introduced by
The call to Illuminate\Support\Collection::get() has too few arguments starting with key. ( Ignorable by Annotation )

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

25
        foreach ($object->permissions()->moduleItem()->/** @scrutinizer ignore-call */ get() as $permission) {

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
26
            $model = $permission->permissionable()->first();
27
            $moduleName = getModuleNameByModel($model);
28
            $fields[$moduleName . '_' . $model->id . '_permission'] = $permission->name;
29
        }
30
31
        \Session::put("user-{$object->id}", $fields = $this->getUserPermissionsFields($object, $fields));
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fields is correct as $this->getUserPermissionsFields($object, $fields) targeting A17\Twill\Repositories\B...UserPermissionsFields() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

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

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

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

Loading history...
32
33
        return $fields;
34
    }
35
36
    /**
37
     * Function executed after save on user form
38
     *
39
     * @param Model|User $object
40
     * @param array $fields
41
     */
42
    public function afterSaveHandleUserPermissions($object, $fields)
43
    {
44
        if (!config('twill.enabled.permissions-management')) {
45
            return;
46
        }
47
48
        $this->addOrRemoveUserToEveryoneGroup($object);
49
50
        $this->updateUserItemPermissions($object, $fields);
51
    }
52
53
    private function addOrRemoveUserToEveryoneGroup($user)
54
    {
55
        $everyoneGroup = twillModel('group')::getEveryoneGroup();
56
57
        if ($user->role->in_everyone_group) {
58
            $user->groups()->syncWithoutDetaching([$everyoneGroup->id]);
59
        } else {
60
            $user->groups()->detach([$everyoneGroup->id]);
61
        }
62
    }
63
64
    private function updateUserItemPermissions($user, $fields)
65
    {
66
        $oldFields = \Session::get("user-{$user->id}");
67
68
        foreach ($fields as $key => $value) {
69
            if (Str::endsWith($key, '_permission')) {
70
                // Old permission
71
                if (isset($oldFields[$key]) && $oldFields[$key] == $value) {
72
                    continue;
73
                }
74
75
                $item_name = explode('_', $key)[0];
76
                $item_id = explode('_', $key)[1];
77
                $item = getRepositoryByModuleName($item_name)->getById($item_id);
0 ignored issues
show
Bug introduced by
The method getById() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

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

77
                $item = getRepositoryByModuleName($item_name)->/** @scrutinizer ignore-call */ getById($item_id);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
78
79
                // Only value existed, do update or create
80
                if ($value) {
81
                    $user->grantModuleItemPermission($value, $item);
82
                } else {
83
                    $user->revokeModuleItemAllPermissions($item);
84
                }
85
            }
86
        }
87
    }
88
89
    /**
90
     * Get user permissions fields
91
     *
92
     * @param Model|User $user
93
     * @param array $fields
94
     * @return void
95
     */
96
    protected function getUserPermissionsFields($user, $fields)
97
    {
98
        if (!config('twill.enabled.permissions-management')) {
99
            return $fields;
100
        }
101
102
        $itemScopes = Permission::available(Permission::SCOPE_ITEM);
103
104
        // looking for group permissions that belongs to the user
105
        foreach ($user->publishedGroups as $group) {
0 ignored issues
show
Bug introduced by
The property publishedGroups does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
Bug introduced by
The property publishedGroups does not seem to exist on A17\Twill\Models\User. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
106
107
            // get each permissions that belongs to a module from this group
108
            foreach ($group->permissions()->moduleItem()->get() as $permission) {
109
                $model = $permission->permissionable()->first();
110
111
                if (!$model) {
112
                    continue;
113
                }
114
115
                $moduleName = getModuleNameByModel($model);
116
                $index = $moduleName . '_' . $model->id . '_permission';
117
118
                if (isset($fields[$index])) {
119
                    $current = array_search($fields[$index], $itemScopes);
120
                    $group = array_search($permission->name, $itemScopes);
121
122
                    // check that group permission is greater that current permission level
123
                    if ($group > $current) {
124
                        $fields[$index] = $permission->name;
125
                    }
126
                } else {
127
                    $fields[$index] = $permission->name;
128
                }
129
            }
130
        }
131
132
        // looking for global permissions, if the user has the 'manage-modules' permission
133
        $isManageAllModules = $user->isSuperAdmin() || ($user->role->permissions()->global()->where('name', 'manage-modules')->first() != null);
0 ignored issues
show
Bug introduced by
The property role does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
134
135
        // looking for role module permission
136
        $globalPermissions = [];
137
        if (!$isManageAllModules) {
138
            foreach ($user->role->permissions()->module()->get() as $permission) {
139
                if ($permission->permissionable_type) {
140
                    $permissionName = str_replace("-module", "-item", $permission->name);
141
                    $globalPermissions[getModuleNameByModel($permission->permissionable_type)] = $permissionName;
142
                }
143
            }
144
        }
145
146
        // merge all permissions
147
        // go through all existing modules
148
        foreach (Permission::permissionableParentModuleItems() as $moduleName => $moduleItems) {
149
            if (isset($globalPermissions[$moduleName]) || $isManageAllModules) {
150
                $permission = $isManageAllModules ? 'manage-item' : $globalPermissions[$moduleName];
151
152
                foreach ($moduleItems as $moduleItem) {
153
                    $index = $moduleName . '_' . $moduleItem->id . '_permission';
154
                    if (!isset($fields[$index])) {
155
                        $fields[$index] = "{$permission}";
156
                    } else {
157
                        $current = array_search($fields[$index], $itemScopes);
158
                        $global = array_search($permission, $itemScopes);
159
160
                        // check permission level
161
                        if ($global > $current) {
162
                            $fields[$index] = "{$permission}";
163
                        }
164
                    }
165
                }
166
            }
167
        }
168
169
        return $fields;
170
    }
171
172
    /**
173
     * Retrieve count of user for 'activated' and 'pending' status slug
174
     *
175
     * @param string $slug
176
     * @param array $scope
177
     * @return int|boolean
178
     */
179
    public function getCountByStatusSlugHandleUserPermissions($slug, $scope = [])
180
    {
181
        $query = $this->model->where($scope);
182
183
        if (config('twill.enabled.permissions-management')) {
184
            $query = $query->accessible();
185
        }
186
187
        if (get_class($this->model) === twillModel('user')) {
188
            if ($slug === 'activated') {
189
                return $query->notSuperAdmin()->activated()->count();
190
            }
191
192
            if ($slug === 'pending') {
193
                return $query->notSuperAdmin()->pending()->count();
194
            }
195
        }
196
197
        return false;
198
    }
199
}
200