Completed
Pull Request — master (#1455)
by
unknown
01:21
created

Permission::users()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 10
loc 10
rs 9.9332
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
    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
            throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
41
        }
42
43
        return static::query()->create($attributes);
44
    }
45
46
    /**
47
     * Create permissions for resource controllers.
48
     * @param  string|array $permissions
49
     * @return \Illuminate\Support\Collection
50
     */
51
    public static function createResource(...$permissions): Collection
52
    {
53
        return collect($permissions)->flatten()->map(function ($permission) {
54
            if (!is_string($permission)) return false;
55
            foreach (['index', 'create', 'store', 'show', 'edit', 'update', 'delete'] as $crud) {
56
                $array[] = ['name' => "$crud $permission"];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
57
            }
58
            return $array;
0 ignored issues
show
Bug introduced by
The variable $array does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
59
        })->collapse()->filter()->map(function ($permission) {
60
            return static::create($permission);
61
        });
62
    }
63
64
    /**
65
     * A permission can be applied to roles.
66
     */
67
    public function roles(): BelongsToMany
68
    {
69
        return $this->belongsToMany(
70
            config('permission.models.role'),
71
            config('permission.table_names.role_has_permissions'),
72
            'permission_id',
73
            'role_id'
74
        );
75
    }
76
77
    /**
78
     * A permission belongs to some users of the model associated with its guard.
79
     */
80 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...
81
    {
82
        return $this->morphedByMany(
83
            getModelForGuard($this->attributes['guard_name']),
84
            'model',
85
            config('permission.table_names.model_has_permissions'),
86
            'permission_id',
87
            config('permission.column_names.model_morph_key')
88
        );
89
    }
90
91
    /**
92
     * Find a permission by its name (and optionally guardName).
93
     *
94
     * @param string $name
95
     * @param string|null $guardName
96
     *
97
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
98
     *
99
     * @return \Spatie\Permission\Contracts\Permission
100
     */
101 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...
102
    {
103
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
104
        $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
105
        if (! $permission) {
106
            throw PermissionDoesNotExist::create($name, $guardName);
107
        }
108
109
        return $permission;
110
    }
111
112
    /**
113
     * Find a permission by its id (and optionally guardName).
114
     *
115
     * @param int $id
116
     * @param string|null $guardName
117
     *
118
     * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
119
     *
120
     * @return \Spatie\Permission\Contracts\Permission
121
     */
122 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...
123
    {
124
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
125
        $permission = static::getPermissions(['id' => $id, 'guard_name' => $guardName])->first();
126
127
        if (! $permission) {
128
            throw PermissionDoesNotExist::withId($id, $guardName);
129
        }
130
131
        return $permission;
132
    }
133
134
    /**
135
     * Find or create permission by its name (and optionally guardName).
136
     *
137
     * @param string $name
138
     * @param string|null $guardName
139
     *
140
     * @return \Spatie\Permission\Contracts\Permission
141
     */
142 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...
143
    {
144
        $guardName = $guardName ?? Guard::getDefaultName(static::class);
145
        $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
146
147
        if (! $permission) {
148
            return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
149
        }
150
151
        return $permission;
152
    }
153
154
    /**
155
     * Get the current cached permissions.
156
     */
157
    protected static function getPermissions(array $params = []): Collection
158
    {
159
        return app(PermissionRegistrar::class)
160
            ->setPermissionClass(static::class)
161
            ->getPermissions($params);
162
    }
163
}
164