HasRoles   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 57
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A roles() 0 4 1
A hasRole() 0 8 2
A hasPermission() 0 4 1
A assignRole() 0 10 2
1
<?php
2
3
namespace NukaCode\Users\Traits;
4
5
use NukaCode\Users\Models\Permission;
6
use NukaCode\Users\Models\Role;
7
8
trait HasRoles
9
{
10
    /**
11
     * A user may have multiple roles.
12
     *
13
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
14
     */
15
    public function roles()
16
    {
17
        return $this->belongsToMany(Role::class, 'acl_role_user');
18
    }
19
20
    /**
21
     * Assign the given role to the user.
22
     *
23
     * @param  string $role
24
     *
25
     * @return mixed
26
     * @throws \Exception
27
     */
28
    public function assignRole($role)
29
    {
30
        if (Role::count() === 0) {
31
            throw new \Exception('No roles have been created.');
32
        }
33
34
        return $this->roles()->save(
35
            Role::whereName($role)->firstOrFail()
36
        );
37
    }
38
39
    /**
40
     * Determine if the user has the given role.
41
     *
42
     * @param  mixed $role
43
     * @return bool
44
     */
45
    public function hasRole($role)
46
    {
47
        if (is_string($role)) {
48
            return $this->roles->contains('name', $role);
0 ignored issues
show
Bug introduced by
The property roles does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
49
        }
50
51
        return ! ! $role->intersect($this->roles)->count();
52
    }
53
54
    /**
55
     * Determine if the user may perform the given permission.
56
     *
57
     * @param  Permission $permission
58
     * @return bool
59
     */
60
    public function hasPermission(Permission $permission)
61
    {
62
        return $this->hasRole($permission->roles);
63
    }
64
}
65