Completed
Pull Request — master (#732)
by
unknown
02:24
created

Permission::create()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 3
nop 1
dl 0
loc 16
rs 9.2
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(['name' => $name, 'guard_name' => $guardName])->first();
0 ignored issues
show
Bug introduced by
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $guardName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
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
    public function users(): MorphToMany
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
        $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
89
        if (! $permission) {
90
            throw PermissionDoesNotExist::create($name, $guardName);
91
        }
92
93
        return $permission;
94
    }
95
96
    /**
97
     * Find a permission by its id (and optionally guardName).
98
     *
99
     * @param int $id
100
     * @param string|null $guardName
101
     *
102
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
103
     *
104
     * @return \Spatie\Permission\Contracts\Permission
105
     */
106 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...
107
    {
108
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
109
110
        $permission = static::getPermissions(['id' => $id, 'guard_name' => $guardName])->first();
111
112
        if (! $permission) {
113
            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...
114
        }
115
116
        return $permission;
117
    }
118
119
    /**
120
     * Find or create permission by its name (and optionally guardName).
121
     *
122
     * @param string $name
123
     * @param string|null $guardName
124
     *
125
     * @return \Spatie\Permission\Contracts\Permission
126
     */
127
    public static function findOrCreate(string $name, $guardName = null): PermissionContract
128
    {
129
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
130
131
        $permission = static::getPermissions()->filter(function ($permission) use ($name, $guardName) {
132
            return $permission->name === $name && $permission->guard_name === $guardName;
133
        })->first();
134
135
        if (! $permission) {
136
            return static::create(['name' => $name, 'guard_name' => $guardName]);
137
        }
138
139
        return $permission;
140
    }
141
142
    /**
143
     * Get the current cached permissions.
144
     */
145
    protected static function getPermissions($params = null): Collection
146
    {
147
        return app(PermissionRegistrar::class)->getPermissions($params);
148
    }
149
}
150