Completed
Pull Request — master (#1480)
by Richard
01:24
created

Permission::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 12
rs 9.8666
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\Contracts\Permission as PermissionContract;
15
use Symfony\Component\Console\Output\ConsoleOutput;
16
17
class Permission extends Model implements PermissionContract
18
{
19
    use HasRoles;
20
    use RefreshesPermissionCache;
21
22
    protected $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::getPermissions(['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']])->first();
38
39
        if ($permission) {
40
            return static::permissionAlreadyExists($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 $name
120
     * @param string|null $guardName
121
     *
122
     * @return \Spatie\Permission\Contracts\Permission
123
     */
124 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...
125
    {
126
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
127
        $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
128
129
        if (! $permission) {
130
            return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
131
        }
132
133
        return $permission;
134
    }
135
136
    /**
137
     * Get the current cached permissions.
138
     */
139
    protected static function getPermissions(array $params = []): Collection
140
    {
141
        return app(PermissionRegistrar::class)
142
            ->setPermissionClass(static::class)
143
            ->getPermissions($params);
144
    }
145
146
    protected static function permissionAlreadyExists($permissionName, $guardName)
147
    {
148
        $message = "A $permissionName permission already exists for guard $guardName, seed ignored.";
149
        $output = new ConsoleOutput();
150
        $output->writeln("<error>$message.</error>");
151
152
        return $message;
153
    }
154
155
}
156