Completed
Pull Request — master (#1342)
by
unknown
01:24
created

Role::findById()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
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
    public function __construct(array $attributes = [])
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 View Code Duplication
    public static function create(array $attributes = [], $withException = true)
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...
33
    {
34
        $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
35
36
        $existingRole = static::where([
37
            'name' => $attributes['name'],
38
            'guard_name' => $attributes['guard_name'],
39
        ])->first();
40
41
        if ($existingRole) {
42
            if ($withException) {
43
                throw RoleAlreadyExists::named($attributes['name'], $attributes['guard_name']);
0 ignored issues
show
Bug introduced by
The method named() does not seem to exist on object<Spatie\Permission...ions\RoleAlreadyExists>.

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...
44
            }
45
46
            return $existingRole;
47
        }
48
49
        return static::query()->create($attributes);
50
    }
51
52
    /**
53
     * Create many roles.
54
     *
55
     * @param  iterable $records
56
     * @param  bool $withException
57
     * @return array
58
     */
59
    public static function createMany(iterable $records, $withException = false)
60
    {
61
        $instances = [];
62
63
        foreach ($records as $key => $record) {
64
            $instances[] = static::create($record, $withException);
65
        }
66
67
        return $instances;
68
    }
69
70
    /**
71
     * A role may be given various permissions.
72
     */
73
    public function permissions(): BelongsToMany
74
    {
75
        return $this->belongsToMany(
76
            config('permission.models.permission'),
77
            config('permission.table_names.role_has_permissions'),
78
            'role_id',
79
            'permission_id'
80
        );
81
    }
82
83
    /**
84
     * A role belongs to some users of the model associated with its guard.
85
     */
86 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...
87
    {
88
        return $this->morphedByMany(
89
            getModelForGuard($this->attributes['guard_name']),
90
            'model',
91
            config('permission.table_names.model_has_roles'),
92
            'role_id',
93
            config('permission.column_names.model_morph_key')
94
        );
95
    }
96
97
    /**
98
     * Find a role by its name and guard name.
99
     *
100
     * @param string $name
101
     * @param string|null $guardName
102
     *
103
     * @return \Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
104
     *
105
     * @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
106
     */
107
    public static function findByName(string $name, $guardName = null): RoleContract
108
    {
109
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
110
111
        $role = static::where(['name' => $name, 'guard_name' => $guardName])->first();
112
113
        if (! $role) {
114
            throw RoleDoesNotExist::named($name);
115
        }
116
117
        return $role;
118
    }
119
120
    public static function findById(int $id, $guardName = null): RoleContract
121
    {
122
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
123
124
        $role = static::where(['id' => $id, 'guard_name' => $guardName])->first();
125
126
        if (! $role) {
127
            throw RoleDoesNotExist::withId($id);
128
        }
129
130
        return $role;
131
    }
132
133
    /**
134
     * Find or create role by its name (and optionally guardName).
135
     *
136
     * @param string $name
137
     * @param string|null $guardName
138
     *
139
     * @return \Spatie\Permission\Contracts\Role
140
     */
141
    public static function findOrCreate(string $name, $guardName = null): RoleContract
142
    {
143
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
144
145
        $attributes = ['name' => $name, 'guard_name' => $guardName];
146
147
        $role = static::where($attributes)->first();
148
149
        if (! $role) {
150
            return static::query()->create($attributes);
151
        }
152
153
        return $role;
154
    }
155
156
    /**
157
     * Determine if the user may perform the given permission.
158
     *
159
     * @param string|Permission $permission
160
     *
161
     * @return bool
162
     *
163
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
164
     */
165
    public function hasPermissionTo($permission): bool
166
    {
167
        $permissionClass = $this->getPermissionClass();
168
169
        if (is_string($permission)) {
170
            $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
171
        }
172
173
        if (is_int($permission)) {
174
            $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
175
        }
176
177
        if (! $this->getGuardNames()->contains($permission->guard_name)) {
178
            throw GuardDoesNotMatch::create($permission->guard_name, $this->getGuardNames());
179
        }
180
181
        return $this->permissions->contains('id', $permission->id);
182
    }
183
}
184