Completed
Pull Request — master (#1538)
by
unknown
15:50
created

Permission::findOrCreate()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 24

Duplication

Lines 3
Ratio 12.5 %

Importance

Changes 0
Metric Value
cc 9
nc 11
nop 2
dl 3
loc 24
rs 8.0555
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
    protected $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' => $attributes['name'], 'guard_name' => $attributes['guard_name']])->first();
38
39
        if ($permission) {
40
            throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
41
        }
42
43
        return static::query()->create($attributes);
44
    }
45
46
    /**
47
     * A permission can be applied to roles.
48
     */
49
    public function roles(): BelongsToMany
50
    {
51
        return $this->belongsToMany(
52
            config('permission.models.role'),
53
            config('permission.table_names.role_has_permissions'),
54
            'permission_id',
55
            'role_id'
56
        );
57
    }
58
59
    /**
60
     * A permission belongs to some users of the model associated with its guard.
61
     */
62 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...
63
    {
64
        return $this->morphedByMany(
65
            getModelForGuard($this->attributes['guard_name']),
66
            'model',
67
            config('permission.table_names.model_has_permissions'),
68
            'permission_id',
69
            config('permission.column_names.model_morph_key')
70
        );
71
    }
72
73
    /**
74
     * Find a permission by its name (and optionally guardName).
75
     *
76
     * @param string $name
77
     * @param string|null $guardName
78
     *
79
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
80
     *
81
     * @return \Spatie\Permission\Contracts\Permission
82
     */
83 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...
84
    {
85
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
86
        $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
87
        if (! $permission) {
88
            throw PermissionDoesNotExist::create($name, $guardName);
89
        }
90
91
        return $permission;
92
    }
93
94
    /**
95
     * Find a permission by its id (and optionally guardName).
96
     *
97
     * @param int $id
98
     * @param string|null $guardName
99
     *
100
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
101
     *
102
     * @return \Spatie\Permission\Contracts\Permission
103
     */
104 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...
105
    {
106
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
107
        $permission = static::getPermissions(['id' => $id, 'guard_name' => $guardName])->first();
108
109
        if (! $permission) {
110
            throw PermissionDoesNotExist::withId($id, $guardName);
111
        }
112
113
        return $permission;
114
    }
115
116
    /**
117
     * Find or create permission by its name (and optionally guardName).
118
     *
119
     * @param string|array $name
120
     * @param string|null  $guardName
121
     *
122
     * @return \Spatie\Permission\Contracts\Permission
123
     */
124
    public static function findOrCreate($name, $guardName = null): PermissionContract
125
    {
126
        if (! is_string($name) && ! is_array($name)) {
127
            return null;
128
        }
129
130
        $params = is_array($name) ? $name : ['name' => $name, 'guard_name' => $guardName];
131
132
        if (! isset($params['name']) || empty($params['name'])) {
133
            return null;
134
        }
135
136 View Code Duplication
        if (! isset($params['guard_name']) || empty($params['guard_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
137
            $params['guard_name'] = Guard::getDefaultName(static::class);
138
        }
139
140
        $permission = static::getPermissions($params)->first();
141
142
        if (! $permission) {
143
            return static::query()->create($params);
144
        }
145
146
        return $permission;
147
    }
148
149
    /**
150
     * Get the current cached permissions.
151
     */
152
    protected static function getPermissions(array $params = []): Collection
153
    {
154
        return app(PermissionRegistrar::class)
155
            ->setPermissionClass(static::class)
156
            ->getPermissions($params);
157
    }
158
}
159