1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Permission\Models; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Spatie\Permission\PermissionRegistrar; |
8
|
|
|
use Spatie\Permission\Traits\RefreshesPermissionCache; |
9
|
|
|
use Spatie\Permission\Exceptions\PermissionDoesNotExist; |
10
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
11
|
|
|
use Spatie\Permission\Contracts\Permission as PermissionContract; |
12
|
|
|
|
13
|
|
|
class Permission extends Model implements PermissionContract |
14
|
|
|
{ |
15
|
|
|
use RefreshesPermissionCache; |
16
|
|
|
|
17
|
|
|
public $guarded = ['id']; |
18
|
|
|
|
19
|
|
View Code Duplication |
public function __construct(array $attributes = []) |
|
|
|
|
20
|
|
|
{ |
21
|
|
|
if (empty($attributes['guard_name'])) { |
22
|
|
|
$attributes['guard_name'] = config('auth.defaults.guard'); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
parent::__construct($attributes); |
26
|
|
|
|
27
|
|
|
$this->setTable(config('permission.table_names.permissions')); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* A permission can be applied to roles. |
32
|
|
|
*/ |
33
|
|
|
public function roles(): BelongsToMany |
34
|
|
|
{ |
35
|
|
|
return $this->belongsToMany( |
36
|
|
|
config('permission.models.role'), |
37
|
|
|
config('permission.table_names.role_has_permissions') |
38
|
|
|
); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Find a permission by its name (and optionally guardName). |
43
|
|
|
* |
44
|
|
|
* @param string $name |
45
|
|
|
* @param string|null $guardName |
46
|
|
|
* |
47
|
|
|
* @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist |
48
|
|
|
* |
49
|
|
|
* @return \Spatie\Permission\Contracts\Permission |
50
|
|
|
*/ |
51
|
|
|
public static function findByName(string $name, $guardName = null): PermissionContract |
52
|
|
|
{ |
53
|
|
|
$guardName = $guardName ?? config('auth.defaults.guard'); |
54
|
|
|
|
55
|
|
|
$permission = static::getPermissions()->where('name', $name)->where('guard_name', $guardName)->first(); |
56
|
|
|
|
57
|
|
|
if (! $permission) { |
58
|
|
|
throw PermissionDoesNotExist::create($name); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $permission; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Get the current cached permissions. |
66
|
|
|
*/ |
67
|
|
|
protected static function getPermissions(): Collection |
68
|
|
|
{ |
69
|
|
|
return app(PermissionRegistrar::class)->getPermissions(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
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.