Completed
Pull Request — master (#710)
by Barry
02:39 queued 57s
created

Permission::create()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 3
nop 1
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Permission\Models;
4
5
use Spatie\Permission\Guard;
6
use Illuminate\Support\Collection;
7
use Spatie\Permission\Traits\HasRoles;
8
use Illuminate\Database\Eloquent\Model;
9
use Spatie\Permission\PermissionRegistrar;
10
use Spatie\Permission\Traits\RefreshesPermissionCache;
11
use Illuminate\Database\Eloquent\Relations\MorphToMany;
12
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
13
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
14
use Spatie\Permission\Exceptions\PermissionAlreadyExists;
15
use Spatie\Permission\Contracts\Permission as PermissionContract;
16
17
class Permission extends Model implements PermissionContract
18
{
19
    use HasRoles;
20
    use RefreshesPermissionCache;
21
22
    public $guarded = ['id'];
23
24 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...
25
    {
26
        $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
27
28
        parent::__construct($attributes);
29
30
        $this->setTable(config('permission.table_names.permissions'));
31
    }
32
33
    public static function create(array $attributes = [])
34
    {
35
        $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
36
37
        $permission = static::getPermissions()->filter(function ($permission) use ($attributes) {
38
            return $permission->name === $attributes['name'] && $permission->guard_name === $attributes['guard_name'];
39
        })->first();
40
41
        if ($permission) {
42
            throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
43
        }
44
45
        if (isNotLumen() && app()::VERSION < '5.4') {
46
            return parent::create($attributes);
47
        }
48
49
        return static::query()->create($attributes);
50
    }
51
52
    /**
53
     * A permission can be applied to roles.
54
     */
55
    public function roles(): BelongsToMany
56
    {
57
        return $this->belongsToMany(
58
            config('permission.models.role'),
59
            config('permission.table_names.role_has_permissions')
60
        );
61
    }
62
63
    /**
64
     * A permission belongs to some users of the model associated with its guard.
65
     */
66
    public function users(): MorphToMany
67
    {
68
        return $this->morphedByMany(
69
            getModelForGuard($this->attributes['guard_name']),
70
            'model',
71
            config('permission.table_names.model_has_permissions'),
72
            'permission_id',
73
            'model_id'
74
        );
75
    }
76
77
    /**
78
     * Find a permission by its name (and optionally guardName).
79
     *
80
     * @param string $name
81
     * @param string|null $guardName
82
     *
83
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
84
     *
85
     * @return \Spatie\Permission\Contracts\Permission
86
     */
87 View Code Duplication
    public static function findByName(string $name, $guardName = null): PermissionContract
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...
88
    {
89
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
90
91
        $permission = static::getPermissions()->filter(function ($permission) use ($name, $guardName) {
92
            return $permission->name === $name && $permission->guard_name === $guardName;
93
        })->first();
94
95
        if (! $permission) {
96
            throw PermissionDoesNotExist::create($name, $guardName);
97
        }
98
99
        return $permission;
100
    }
101
102
    /**
103
     * Find a permission by its id (and optionally guardName).
104
     *
105
     * @param int $id
106
     * @param string|null $guardName
107
     *
108
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
109
     *
110
     * @return \Spatie\Permission\Contracts\Permission
111
     */
112 View Code Duplication
    public static function findById(int $id, $guardName = null): PermissionContract
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...
113
    {
114
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
115
116
        $permission = static::getPermissions()->filter(function ($permission) use ($id, $guardName) {
117
            return $permission->id === $id && $permission->guard_name === $guardName;
118
        })->first();
119
120
        if (! $permission) {
121
            throw PermissionDoesNotExist::withId($id, $guardName);
0 ignored issues
show
Unused Code introduced by
The call to PermissionDoesNotExist::withId() has too many arguments starting with $guardName.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
122
        }
123
124
        return $permission;
125
    }
126
127
    /**
128
     * Find or create permission by its name (and optionally guardName).
129
     *
130
     * @param string $name
131
     * @param string|null $guardName
132
     *
133
     * @return \Spatie\Permission\Contracts\Permission
134
     */
135
    public static function findOrCreate(string $name, $guardName = null): PermissionContract
136
    {
137
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
138
139
        $permission = static::getPermissions()->filter(function ($permission) use ($name, $guardName) {
140
            return $permission->name === $name && $permission->guard_name === $guardName;
141
        })->first();
142
143
        if (! $permission) {
144
            return static::create(['name' => $name, 'guard_name' => $guardName]);
145
        }
146
147
        return $permission;
148
    }
149
150
    /**
151
     * Get the current cached permissions.
152
     */
153
    protected static function getPermissions(): Collection
154
    {
155
        return app(PermissionRegistrar::class)->getPermissions();
156
    }
157
}
158