1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yajra\Acl; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Contracts\Auth\Access\Gate as GateContract; |
7
|
|
|
use Illuminate\Contracts\Cache\Repository; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
use Illuminate\Support\Str; |
10
|
|
|
use Yajra\Acl\Models\Permission; |
11
|
|
|
|
12
|
|
|
class GateRegistrar |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var GateContract |
16
|
|
|
*/ |
17
|
|
|
private $gate; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Repository |
21
|
|
|
*/ |
22
|
|
|
private $cache; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* GateRegistrar constructor. |
26
|
|
|
* |
27
|
|
|
* @param GateContract $gate |
28
|
|
|
* @param Repository $cache |
29
|
|
|
*/ |
30
|
|
|
public function __construct(GateContract $gate, Repository $cache) |
31
|
|
|
{ |
32
|
|
|
$this->gate = $gate; |
33
|
|
|
$this->cache = $cache; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Handle permission gate registration. |
38
|
|
|
*/ |
39
|
|
|
public function register() |
40
|
|
|
{ |
41
|
|
|
$this->getPermissions()->each(function ($permission) { |
42
|
|
|
$ability = $permission->slug; |
43
|
|
|
$policy = function ($user) use ($permission) { |
44
|
|
|
return collect($user->getPermissions())->contains($permission->slug); |
45
|
|
|
}; |
46
|
|
|
|
47
|
|
|
if (Str::contains($permission->slug, '@')) { |
48
|
|
|
$policy = $permission->slug; |
49
|
|
|
$ability = $permission->name; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$this->gate->define($ability, $policy); |
53
|
|
|
}); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Get all permissions. |
58
|
|
|
* |
59
|
|
|
* @return Collection |
60
|
|
|
*/ |
61
|
|
|
protected function getPermissions(): Collection |
62
|
|
|
{ |
63
|
|
|
$key = config('acl.cache.key', 'permissions.policies'); |
64
|
|
|
try { |
65
|
|
|
if (config('acl.cache.enabled', true)) { |
66
|
|
|
return $this->cache->rememberForever($key, function () { |
67
|
|
|
return $this->getPermissionClass()->with('roles')->get(); |
68
|
|
|
}); |
69
|
|
|
} else { |
70
|
|
|
return $this->getPermissionClass()->with('roles')->get(); |
71
|
|
|
} |
72
|
|
|
} catch (Exception $exception) { |
73
|
|
|
$this->cache->forget($key); |
74
|
|
|
|
75
|
|
|
return new Collection; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @return Permission |
81
|
|
|
*/ |
82
|
|
|
protected function getPermissionClass(): Permission |
83
|
|
|
{ |
84
|
|
|
return resolve(config('acl.permission', Permission::class)); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|