Completed
Pull Request — master (#245)
by Sebastian
05:44 queued 03:45
created

HasPermissions::getGuardName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Spatie\Permission\Contracts\Permission;
6
use Spatie\Permission\Exceptions\GuardMismatch;
7
8
trait HasPermissions
9
{
10
    /**
11
     * Grant the given permission(s) to a role.
12
     *
13
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
14
     *
15
     * @return $this
16
     */
17 View Code Duplication
    public function givePermissionTo(...$permissions)
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...
18
    {
19
        $permissions = collect($permissions)
20
            ->flatten()
21
            ->map(function ($permission) {
22
                return $this->getStoredPermission($permission);
23
            })
24
            ->each(function ($permission) {
25
                $this->ensureGuardIsEqual($permission);
26
            })
27
            ->all();
28
29
        $this->permissions()->saveMany($permissions);
0 ignored issues
show
Bug introduced by
The method permissions() does not exist on Spatie\Permission\Traits\HasPermissions. Did you maybe mean syncPermissions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
30
31
        $this->forgetCachedPermissions();
0 ignored issues
show
Bug introduced by
It seems like forgetCachedPermissions() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
32
33
        return $this;
34
    }
35
36
    /**
37
     * Remove all current permissions and set the given ones.
38
     *
39
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
40
     *
41
     * @return $this
42
     */
43
    public function syncPermissions(...$permissions)
44
    {
45
        $this->permissions()->detach();
0 ignored issues
show
Bug introduced by
The method permissions() does not exist on Spatie\Permission\Traits\HasPermissions. Did you maybe mean syncPermissions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
46
47
        return $this->givePermissionTo($permissions);
48
    }
49
50
    /**
51
     * Revoke the given permission.
52
     *
53
     * @param \Spatie\Permission\Contracts\Permission|string $permission
54
     *
55
     * @return $this
56
     */
57
    public function revokePermissionTo($permission)
58
    {
59
        $this->permissions()->detach($this->getStoredPermission($permission));
0 ignored issues
show
Bug introduced by
The method permissions() does not exist on Spatie\Permission\Traits\HasPermissions. Did you maybe mean syncPermissions()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
60
61
        $this->forgetCachedPermissions();
0 ignored issues
show
Bug introduced by
It seems like forgetCachedPermissions() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
62
63
        return $this;
64
    }
65
66
    /**
67
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
68
     *
69
     * @return \Spatie\Permission\Contracts\Permission
70
     */
71
    protected function getStoredPermission($permissions): Permission
72
    {
73
        if (is_string($permissions)) {
74
            return app(Permission::class)->findByName($permissions, $this->getGuardName());
75
        }
76
77
        if (is_array($permissions)) {
78
            return app(Permission::class)->whereIn('name', $permissions)->where('guard_name', $this->getGuardName())->get();
79
        }
80
81
        return $permissions;
82
    }
83
84
    /**
85
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
86
     *
87
     * @throws \Spatie\Permission\Exceptions\GuardMismatch
88
     */
89
    protected function ensureGuardIsEqual($roleOrPermission)
90
    {
91
        if ($roleOrPermission->guard_name !== $this->getGuardName()) {
92
            throw new GuardMismatch();
93
        }
94
    }
95
96
    /**
97
     * Check if the class is assigned to a guard in `config/auth.php`.
98
     */
99
    protected function isAssignedToGuard(): bool
100
    {
101
        return (bool) $this->getGuardName();
102
    }
103
104
    /**
105
     * Get the name of the guard that this class is assigned to based on it's `guard_name` property or the auth config
106
     * file.
107
     */
108
    protected function getGuardName(): string
109
    {
110
        return $this->guard_name ?? array_search(get_class($this), $this->getAllAuthGuardProviderModels());
0 ignored issues
show
Bug introduced by
The property guard_name does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
111
    }
112
113
    /**
114
     * Get an array of all models assigned to guards with the guard names as the keys.
115
     */
116
    protected function getAllAuthGuardProviderModels(): array
117
    {
118
        return collect(config('auth.guards'))
119
            ->map(function ($guard) {
120
                return config("auth.providers.{$guard['provider']}.model");
121
            })->toArray();
122
    }
123
}
124