1 | <?php |
||
8 | trait HasPermissions |
||
9 | { |
||
10 | /** |
||
11 | * Grant the given permission(s) to a role. |
||
12 | * |
||
13 | * @param string|array|Permission|\Illuminate\Support\Collection $permissions |
||
14 | * |
||
15 | * @return HasPermissions |
||
|
|||
16 | */ |
||
17 | public function givePermissionTo(...$permissions) |
||
18 | { |
||
19 | if(count($permissions) < 1) { |
||
20 | throw new PermissionMustNotBeEmpty(); |
||
21 | } |
||
22 | |||
23 | if (!$this->usingMultipleArguments($permissions)) { |
||
24 | $permissions = current($permissions); |
||
25 | } |
||
26 | |||
27 | $this->savePermissions($permissions); |
||
28 | |||
29 | $this->forgetCachedPermissions(); |
||
30 | |||
31 | return $this; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * Save the given permissions to a role. |
||
36 | * |
||
37 | * @param array|Permission|\Illuminate\Support\Collection $permissions |
||
38 | * |
||
39 | * @return array|\Illuminate\Database\Eloquent\Model |
||
40 | */ |
||
41 | protected function savePermissions($permissions) |
||
42 | { |
||
43 | $permissions = $this->getStoredPermission($permissions); |
||
44 | |||
45 | if($permissions instanceof \Illuminate\Database\Eloquent\Collection) { |
||
46 | return $this->permissions()->saveMany($permissions); |
||
47 | } |
||
48 | |||
49 | return $this->permissions()->save($permissions); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Revoke the given permission. |
||
54 | * |
||
55 | * @param $permission |
||
56 | * |
||
57 | * @return HasPermissions |
||
58 | */ |
||
59 | public function revokePermissionTo($permission) |
||
67 | |||
68 | /** |
||
69 | * @param string|array|Permission|\Illuminate\Support\Collection $permissions |
||
70 | * |
||
71 | * @return Permission |
||
72 | */ |
||
73 | protected function getStoredPermission($permissions) |
||
85 | |||
86 | /** |
||
87 | * @param $params |
||
88 | * @return bool |
||
89 | */ |
||
90 | private function usingMultipleArguments($params) |
||
94 | |||
95 | } |
||
96 |
In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.
If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.