Completed
Pull Request — master (#814)
by
unknown
02:41
created

Permission::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
rs 10
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
    public function __construct(array $attributes = [])
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::findByNameOrId($attributes['name'], $attributes['guard_name']);
38
39
        if ($permission) {
40
            throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
41
        }
42
43
        if (isNotLumen() && app()::VERSION < '5.4') {
44
            return parent::create($attributes);
45
        }
46
47
        return static::query()->create($attributes);
48
    }
49
50
    /**
51
     * A permission can be applied to roles.
52
     */
53
    public function roles(): BelongsToMany
54
    {
55
        return $this->belongsToMany(
56
            config('permission.models.role'),
57
            config('permission.table_names.role_has_permissions')
58
        );
59
    }
60
61
    /**
62
     * A permission belongs to some users of the model associated with its guard.
63
     */
64 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...
65
    {
66
        return $this->morphedByMany(
67
            getModelForGuard($this->attributes['guard_name']),
68
            'model',
69
            config('permission.table_names.model_has_permissions'),
70
            'permission_id',
71
            'model_id'
72
        );
73
    }
74
75
    /**
76
     * Find a permission by its name (and optionally guardName).
77
     *
78
     * @param string $name
79
     * @param string|null $guardName
80
     *
81
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
82
     *
83
     * @return \Spatie\Permission\Contracts\Permission
84
     */
85 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...
86
    {
87
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
88
89
        $permission = static::findByNameOrId($name, $guardName);
90
91
        if (! $permission) {
92
            throw PermissionDoesNotExist::create($name, $guardName);
93
        }
94
95
        return $permission;
96
    }
97
98
    /**
99
     * Find a permission by its id (and optionally guardName).
100
     *
101
     * @param int $id
102
     * @param string|null $guardName
103
     *
104
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
105
     *
106
     * @return \Spatie\Permission\Contracts\Permission
107
     */
108 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...
109
    {
110
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
111
112
        $permission = static::findByNameOrId($id, $guardName);
113
114
        if (! $permission) {
115
            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...
116
        }
117
118
        return $permission;
119
    }
120
121
    /**
122
     * Find or create permission by its name (and optionally guardName).
123
     *
124
     * @param string $name
125
     * @param string|null $guardName
126
     *
127
     * @return \Spatie\Permission\Contracts\Permission
128
     */
129 View Code Duplication
    public static function findOrCreate(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...
130
    {
131
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
132
133
        $permission = static::findByNameOrId($name, $guardName);
134
135
        if (! $permission) {
136
            return static::create(['name' => $name, 'guard_name' => $guardName]);
137
        }
138
139
        return $permission;
140
    }
141
142
    /**
143
     *  Find a permission by its name or id (and optionally guardName).
144
     *
145
     * @param string|int $permission
146
     * @param string|null $guardName
147
     *
148
     * @return null|\Spatie\Permission\Contracts\Permission
149
     */
150
    public static function findByNameOrId($permission, $guardName = null)
151
    {
152
        if (is_string($permission)) {
153
            return static::filterPermissionsBy('name', $permission, $guardName)->first();
154
        }
155
156
        return static::filterPermissionsBy('id', $permission, $guardName)->first();
157
    }
158
    
159
    /**
160
     * Filters permissions by a given (key , value) and guardName .
161
     *
162
     * @param string $key
163
     * @param string|int $value
164
     * @param string $guardName
165
     *
166
     * @return \Illuminate\Support\Collection
167
     */
168
    protected static function filterPermissionsBy(string $key, $value, string $guardName)
169
    {
170
        return static::getPermissions()->filter(function ($permission) use ($key,$value, $guardName) {
171
            return $permission->{$key} === $value && $permission->guard_name === $guardName;
172
        });
173
    }
174
175
    /**
176
     * Get the current cached permissions.
177
     */
178
    protected static function getPermissions(): Collection
179
    {
180
        return app(PermissionRegistrar::class)->getPermissions();
181
    }
182
}
183