Passed
Pull Request — 2.x (#1049)
by
unknown
05:53
created

afterSaveHandleUserPermissions()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 24
rs 8.8333
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
        $oldFields = \Session::get("user-{$object->id}");
49
50
        foreach ($fields as $key => $value) {
51
            if (Str::endsWith($key, '_permission')) {
52
                // Old permission
53
                if (isset($oldFields[$key]) && $oldFields[$key] == $value) {
54
                    continue;
55
                }
56
57
                $item_name = explode('_', $key)[0];
58
                $item_id = explode('_', $key)[1];
59
                $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

59
                $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...
60
61
                // Only value existed, do update or create
62
                if ($value) {
63
                    $object->grantModuleItemPermission($value, $item);
64
                } else {
65
                    $object->revokeModuleItemAllPermissions($item);
66
                }
67
            }
68
        }
69
    }
70
71
    /**
72
     * Get user permissions fields
73
     *
74
     * @param Model|User $user
75
     * @param array $fields
76
     * @return void
77
     */
78
    protected function getUserPermissionsFields($user, $fields)
79
    {
80
        if (!config('twill.enabled.permissions-management')) {
81
            return $fields;
82
        }
83
84
        $itemScopes = Permission::available(Permission::SCOPE_ITEM);
85
86
        // looking for group permissions that belongs to the user
87
        foreach ($user->publishedGroups as $group) {
0 ignored issues
show
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...
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...
88
89
            // get each permissions that belongs to a module from this group
90
            foreach ($group->permissions()->moduleItem()->get() as $permission) {
91
                $model = $permission->permissionable()->first();
92
93
                if (!$model) {
94
                    continue;
95
                }
96
97
                $moduleName = getModuleNameByModel($model);
98
                $index = $moduleName . '_' . $model->id . '_permission';
99
100
                if (isset($fields[$index])) {
101
                    $current = array_search($fields[$index], $itemScopes);
102
                    $group = array_search($permission->name, $itemScopes);
103
104
                    // check that group permission is greater that current permission level
105
                    if ($group > $current) {
106
                        $fields[$index] = $permission->name;
107
                    }
108
                } else {
109
                    $fields[$index] = $permission->name;
110
                }
111
            }
112
        }
113
114
        // looking for global permissions, if the user has the 'manage-modules' permission
115
        $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...
116
117
        // looking for role module permission
118
        $globalPermissions = [];
119
        if (!$isManageAllModules) {
120
            foreach ($user->role->permissions()->module()->get() as $permission) {
121
                if ($permission->permissionable_type) {
122
                    $permissionName = str_replace("-module", "-item", $permission->name);
123
                    $globalPermissions[getModuleNameByModel($permission->permissionable_type)] = $permissionName;
124
                }
125
            }
126
        }
127
128
        // merge all permissions
129
        // go through all existing modules
130
        foreach (Permission::permissionableParentModuleItems() as $moduleName => $moduleItems) {
131
            if (isset($globalPermissions[$moduleName]) || $isManageAllModules) {
132
                $permission = $isManageAllModules ? 'manage-item' : $globalPermissions[$moduleName];
133
134
                foreach ($moduleItems as $moduleItem) {
135
                    $index = $moduleName . '_' . $moduleItem->id . '_permission';
136
                    if (!isset($fields[$index])) {
137
                        $fields[$index] = "\"{$permission}\"";
138
                    } else {
139
                        $current = array_search($fields[$index], $itemScopes);
140
                        $global = array_search($permission, $itemScopes);
141
142
                        // check permission level
143
                        if ($global > $current) {
144
                            $fields[$index] = "\"{$permission}\"";
145
                        }
146
                    }
147
                }
148
            }
149
        }
150
151
        return $fields;
152
    }
153
154
    /**
155
     * Retrieve count of user for 'activated' and 'pending' status slug
156
     *
157
     * @param string $slug
158
     * @param array $scope
159
     * @return int|boolean
160
     */
161
    public function getCountByStatusSlugHandleUserPermissions($slug, $scope = [])
162
    {
163
        $query = $this->model->where($scope);
164
165
        if (get_class($this->model) === twillModel('user')) {
166
            if ($slug === 'activated') {
167
                return $query->notSuperAdmin()->activated()->count();
168
            }
169
170
            if ($slug === 'pending') {
171
                return $query->notSuperAdmin()->pending()->count();
172
            }
173
        }
174
175
        return false;
176
    }
177
}
178