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

Role::createMany()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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