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

Permission   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 151
Duplicated Lines 27.81 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
dl 42
loc 151
rs 10
c 0
b 0
f 0
wmc 15
lcom 2
cbo 6

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A create() 0 12 2
A createResource() 0 16 3
A roles() 0 9 1
A users() 10 10 1
A findByName() 10 10 2
A findById() 11 11 2
A findOrCreate() 11 11 2
A getPermissions() 0 6 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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