Passed
Push — master ( 69cdea...cc536d )
by Mostafa Abd El-Salam
03:48
created

HasRoles::getPermissionNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Maklad\Permission\Traits;
5
6
use Illuminate\Support\Collection;
7
use Jenssegers\Mongodb\Eloquent\Builder;
8
use Jenssegers\Mongodb\Eloquent\Model;
9
use Jenssegers\Mongodb\Relations\BelongsToMany;
10
use Maklad\Permission\Contracts\PermissionInterface as Permission;
11
use Maklad\Permission\Contracts\RoleInterface as Role;
12
use ReflectionException;
13
14
/**
15
 * Trait HasRoles
16
 * @package Maklad\Permission\Traits
17
 */
18
trait HasRoles
19
{
20
    use HasPermissions;
21
22
    public static function bootHasRoles()
23
    {
24 123
        static::deleting(function (Model $model) {
25 5
            if (isset($model->forceDeleting) && !$model->forceDeleting) {
26 2
                return;
27
            }
28
29 3
            $model->roles()->sync([]);
30 123
        });
31 123
    }
32
33
    /**
34
     * A model may have multiple roles.
35
     */
36 69
    public function roles(): BelongsToMany
37
    {
38 69
        return $this->belongsToMany(\config('permission.models.role'))->withTimestamps();
0 ignored issues
show
Bug introduced by
It seems like belongsToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Security Code Execution introduced by
\config('permission.models.role') can contain request data and is used in code execution context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_SERVER, and $server is assigned
    in vendor/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php on line 22
  2. Data is passed through array_replace()
    in vendor/Request.php on line 357
  3. Data is passed through call_user_func()
    in vendor/Request.php on line 2059
  4. \Illuminate\Http\Request::create($uri, 'GET', array(), array(), array(), $server) is passed to Container::instance()
    in vendor/src/Illuminate/Foundation/Bootstrap/SetRequestForConsole.php on line 31
  5. Container::$instances is assigned
    in vendor/src/Illuminate/Container/Container.php on line 379
  6. Tainted property Container::$instances is read
    in vendor/src/Illuminate/Container/Container.php on line 620
  7. Container::resolve() returns tainted data
    in vendor/src/Illuminate/Container/Container.php on line 586
  8. Container::make() returns tainted data
    in vendor/src/Illuminate/Foundation/helpers.php on line 110
  9. app() returns tainted data
    in vendor/src/Illuminate/Foundation/helpers.php on line 265
  10. config() returns tainted data
    in src/Traits/HasRoles.php on line 38

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
39
    }
40
41
    /**
42
     * Scope the model query to certain roles only.
43
     *
44
     * @param Builder $query
45
     * @param string|array|Role|Collection $roles
46
     *
47
     * @return Builder
48
     */
49 4
    public function scopeRole(Builder $query, $roles): Builder
50
    {
51 4
        $roles = $this->convertToRoleModels($roles);
52
53 4
        return $query->whereIn('role_ids', $roles->pluck('_id'));
54
    }
55
56
    /**
57
     * Assign the given role to the model.
58
     *
59
     * @param array|string|Role ...$roles
60
     *
61
     * @return array|Role|string
62
     */
63 55 View Code Duplication
    public function assignRole(...$roles)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
    {
65 55
        $roles = \collect($roles)
66 55
            ->flatten()
67 55
            ->map(function ($role) {
68 55
                return $this->getStoredRole($role);
69 55
            })
70 53
            ->each(function ($role) {
71 53
                $this->ensureModelSharesGuard($role);
72 53
            })
73 51
            ->all();
74
75 51
        $this->roles()->saveMany($roles);
76
77 51
        $this->forgetCachedPermissions();
78
79 51
        return $roles;
80
    }
81
82
    /**
83
     * Revoke the given role from the model.
84
     *
85
     * @param array|string|Role ...$roles
86
     *
87
     * @return array|Role|string
88
     */
89 3 View Code Duplication
    public function removeRole(...$roles)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
    {
91 3
        \collect($roles)
92 3
            ->flatten()
93 3
            ->map(function ($role) {
94 3
                $role = $this->getStoredRole($role);
95 3
                $this->roles()->detach($role);
0 ignored issues
show
Documentation introduced by
$role is of type object<Maklad\Permission\Contracts\RoleInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
96
97 3
                return $role;
98 3
            });
99
100 3
        $this->forgetCachedPermissions();
101
102 3
        return $roles;
103
    }
104
105
    /**
106
     * Remove all current roles and set the given ones.
107
     *
108
     * @param array ...$roles
109
     *
110
     * @return $this
111
     */
112 6
    public function syncRoles(...$roles)
113
    {
114 6
        $this->roles()->sync([]);
115
116 6
        return $this->assignRole($roles);
117
    }
118
119
    /**
120
     * Determine if the model has (one of) the given role(s).
121
     *
122
     * @param string|array|Role|\Illuminate\Support\Collection $roles
123
     *
124
     * @return bool
125
     */
126 48 View Code Duplication
    public function hasRole($roles): bool
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127
    {
128 48
        if (\is_string($roles) && false !== \strpos($roles, '|')) {
129 3
            $roles = \explode('|', $roles);
130
        }
131
132 48
        if (\is_string($roles) || $roles instanceof Role) {
133 22
            return $this->roles->contains('name', $roles->name ?? $roles);
134
        }
135
136 29
        $roles = \collect()->make($roles)->map(function ($role) {
137 16
            return $role instanceof Role ? $role->name : $role;
0 ignored issues
show
Bug introduced by
Accessing name on the interface Maklad\Permission\Contracts\RoleInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
138 29
        });
139
140 29
        return ! $roles->intersect($this->roles->pluck('name'))->isEmpty();
141
    }
142
143
    /**
144
     * Determine if the model has any of the given role(s).
145
     *
146
     * @param string|array|Role|\Illuminate\Support\Collection $roles
147
     *
148
     * @return bool
149
     */
150 13
    public function hasAnyRole($roles): bool
151
    {
152 13
        return $this->hasRole($roles);
153
    }
154
155
    /**
156
     * Determine if the model has all of the given role(s).
157
     *
158
     * @param string|Role|\Illuminate\Support\Collection $roles
159
     *
160
     * @return bool
161
     */
162 7 View Code Duplication
    public function hasAllRoles($roles): bool
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
    {
164 7
        if (\is_string($roles) && false !== strpos($roles, '|')) {
165 4
            $roles = \explode('|', $roles);
166
        }
167
168 7
        if (\is_string($roles) || $roles instanceof Role) {
169 2
            return $this->hasRole($roles);
170
        }
171
172 6
        $roles = \collect()->make($roles)->map(function ($role) {
173 6
            return $role instanceof Role ? $role->name : $role;
0 ignored issues
show
Bug introduced by
Accessing name on the interface Maklad\Permission\Contracts\RoleInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
174 6
        });
175
176 6
        return $roles->intersect($this->roles->pluck('name')) == $roles;
177
    }
178
179
    /**
180
     * Return Role object
181
     *
182
     * @param String|Role $role role name
183
     *
184
     * @return Role
185
     * @throws ReflectionException
186
     */
187 55
    protected function getStoredRole($role): Role
188
    {
189 55
        if (\is_string($role)) {
190 47
            return \app(Role::class)->findByName($role, $this->getDefaultGuardName());
191
        }
192
193 13
        return $role;
194
    }
195
196
    /**
197
     * Return a collection of role names associated with this user.
198
     *
199
     * @return Collection
200
     */
201 1
    public function getRoleNames(): Collection
202
    {
203 1
        return $this->roles()->pluck('name');
204
    }
205
206
    /**
207
     * Convert to Role Models
208
     *
209
     * @param $roles
210
     *
211
     * @return Collection
212
     */
213 4 View Code Duplication
    private function convertToRoleModels($roles): Collection
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
    {
215 4
        if (is_array($roles)) {
216 3
            $roles = collect($roles);
217
        }
218
219 4
        if (!$roles instanceof Collection) {
220 2
            $roles = collect([$roles]);
221
        }
222
223 4
        $roles = $roles->map(function ($role) {
224 4
            return $this->getStoredRole($role);
225 4
        });
226
227 4
        return $roles;
228
    }
229
}
230