Completed
Pull Request — master (#1538)
by
unknown
15:50
created

Role::findByName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 12
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Permission\Models;
4
5
use Spatie\Permission\Guard;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\Permission\Traits\HasPermissions;
8
use Spatie\Permission\Exceptions\RoleDoesNotExist;
9
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
10
use Spatie\Permission\Exceptions\RoleAlreadyExists;
11
use Spatie\Permission\Contracts\Role as RoleContract;
12
use Spatie\Permission\Traits\RefreshesPermissionCache;
13
use Illuminate\Database\Eloquent\Relations\MorphToMany;
14
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
15
16
class Role extends Model implements RoleContract
17
{
18
    use HasPermissions;
19
    use RefreshesPermissionCache;
20
21
    protected $guarded = ['id'];
22
23 View Code Duplication
    public function __construct(array $attributes = [])
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...
24
    {
25
        $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
26
27
        parent::__construct($attributes);
28
29
        $this->setTable(config('permission.table_names.roles'));
30
    }
31
32
    public static function create(array $attributes = [])
33
    {
34
        $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
35
36
        if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) {
37
            throw RoleAlreadyExists::create($attributes['name'], $attributes['guard_name']);
38
        }
39
40
        return static::query()->create($attributes);
41
    }
42
43
    /**
44
     * A role may be given various permissions.
45
     */
46
    public function permissions(): BelongsToMany
47
    {
48
        return $this->belongsToMany(
49
            config('permission.models.permission'),
50
            config('permission.table_names.role_has_permissions'),
51
            'role_id',
52
            'permission_id'
53
        );
54
    }
55
56
    /**
57
     * A role belongs to some users of the model associated with its guard.
58
     */
59 View Code Duplication
    public function users(): MorphToMany
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...
60
    {
61
        return $this->morphedByMany(
62
            getModelForGuard($this->attributes['guard_name']),
63
            'model',
64
            config('permission.table_names.model_has_roles'),
65
            'role_id',
66
            config('permission.column_names.model_morph_key')
67
        );
68
    }
69
70
    /**
71
     * Find a role by its name and guard name.
72
     *
73
     * @param string $name
74
     * @param string|null $guardName
75
     *
76
     * @return \Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
77
     *
78
     * @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
79
     */
80 View Code Duplication
    public static function findByName(string $name, $guardName = null): RoleContract
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...
81
    {
82
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
83
84
        $role = static::where('name', $name)->where('guard_name', $guardName)->first();
85
86
        if (! $role) {
87
            throw RoleDoesNotExist::named($name);
88
        }
89
90
        return $role;
91
    }
92
93 View Code Duplication
    public static function findById(int $id, $guardName = null): RoleContract
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...
94
    {
95
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
96
97
        $role = static::where('id', $id)->where('guard_name', $guardName)->first();
98
99
        if (! $role) {
100
            throw RoleDoesNotExist::withId($id);
101
        }
102
103
        return $role;
104
    }
105
106
    /**
107
     * Find or create role by its name (and optionally guardName).
108
     *
109
     * @param string|array $name
110
     * @param string|null  $guardName
111
     *
112
     * @return \Spatie\Permission\Contracts\Role
113
     */
114
    public static function findOrCreate($name, $guardName = null): RoleContract
115
    {
116
        if (! is_string($name) && ! is_array($name)) {
117
            return null;
118
        }
119
120
        $params = is_array($name) ? $name : ['name' => $name, 'guard_name' => $guardName];
121
122
        if (! isset($params['name']) || empty($params['name'])) {
123
            return null;
124
        }
125
126 View Code Duplication
        if (! isset($params['guard_name']) || empty($params['guard_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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
            $params['guard_name'] = Guard::getDefaultName(static::class);
128
        }
129
130
        $role = static::where('name', $params['name']);
131
132
        foreach ($params as $key => $value) {
133
            if ('name' != $key) {
134
                $role = $role->where($key, $value);
135
            }
136
        }
137
138
        $role = $role->first();
139
140
        if (! $role) {
141
            return static::query()->create($params);
142
        }
143
144
        return $role;
145
    }
146
147
    /**
148
     * Determine if the user may perform the given permission.
149
     *
150
     * @param string|Permission $permission
151
     *
152
     * @return bool
153
     *
154
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
155
     */
156
    public function hasPermissionTo($permission): bool
157
    {
158
        if (config('permission.enable_wildcard_permission', false)) {
159
            return $this->hasWildcardPermission($permission, $this->getDefaultGuardName());
160
        }
161
162
        $permissionClass = $this->getPermissionClass();
163
164
        if (is_string($permission)) {
165
            $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
166
        }
167
168
        if (is_int($permission)) {
169
            $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
170
        }
171
172
        if (! $this->getGuardNames()->contains($permission->guard_name)) {
173
            throw GuardDoesNotMatch::create($permission->guard_name, $this->getGuardNames());
174
        }
175
176
        return $this->permissions->contains('id', $permission->id);
177
    }
178
}
179