Completed
Push — master ( 872a00...e2f753 )
by Troy
01:33
created

BaseUser::hasRole()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.9777
c 0
b 0
f 0
cc 6
nc 7
nop 1
1
<?php
2
3
namespace MultiTenantLaravel\App\Models;
4
5
use Illuminate\Notifications\Notifiable;
6
use Illuminate\Foundation\Auth\User as Authenticatable;
7
use Illuminate\Support\Collection;
8
9
abstract class BaseUser extends Authenticatable
10
{
11
    use Notifiable;
12
13
    /**
14
     * The attributes that are mass assignable.
15
     *
16
     * @var array
17
     */
18
    protected $fillable = [
19
        'name', 'email', 'password',
20
    ];
21
22
    /**
23
     * The attributes that should be hidden for arrays.
24
     *
25
     * @var array
26
     */
27
    protected $hidden = [
28
        'password', 'remember_token',
29
    ];
30
31
    /**
32
     * Return all of the tenants this user is the owner of
33
     */
34
    public function roles()
35
    {
36
        return $this->belongsToMany(
37
            config('multi-tenant.role_class'),
38
            'multi_tenant_role_user',
39
            'user_id',
40
            'multi_tenant_role_id'
41
        );
42
    }
43
44
    /**
45
     * Assign a given role to a user
46
     */
47
    public function assignRole(BaseRole $role)
48
    {
49
        $this->roles()->syncWithoutDetaching([$role->id]);
50
51
        return $this;
52
    }
53
54
    /**
55
     * Check if a user has a given role
56
     */
57
    public function hasRole($role)
58
    {
59
        if (is_string($role)) {
60
            return $this->roles->contains('name', $role);
61
        }
62
63
        if ($role instanceof Collection) {
64
            $role = $role->toArray();
65
        }
66
67
        if (is_array($role)) {
68
            foreach($role as $r) {
69
                if ($this->roles->contains('name', $r['name'])) {
70
                    return true;
71
                }
72
            }
73
        }
74
75
        return $this->roles()->where('multi_tenant_role_id', $role->id)->exists();
76
    }
77
78
    /**
79
     * Return all of the tenants this user is the owner of
80
     */
81
    public function owns()
82
    {
83
        return $this->hasMany(config('multi-tenant.tenant_class'), 'owner_id');
84
    }
85
86
    /**
87
     * Return the currently active tenant for this user based on the session
88
     */
89
    public function activeTenant()
90
    {
91
        return config('multi-tenant.tenant_class')::findOrFail(session()->get('tenant.id'));
92
    }
93
}
94