1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* @author enea dhack <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Enea\Authorization\Drivers\Cache\Repositories; |
13
|
|
|
|
14
|
|
|
use Closure; |
15
|
|
|
use Enea\Authorization\Contracts\Deniable; |
16
|
|
|
use Enea\Authorization\Contracts\Grantable; |
17
|
|
|
use Enea\Authorization\Contracts\PermissionContract; |
18
|
|
|
use Enea\Authorization\Contracts\PermissionsOwner; |
19
|
|
|
use Enea\Authorization\Contracts\RolesOwner; |
20
|
|
|
use Enea\Authorization\Facades\Helper; |
21
|
|
|
use Illuminate\Support\Collection; |
22
|
|
|
|
23
|
|
|
class PermissionRepository extends Repository |
24
|
|
|
{ |
25
|
34 |
|
public static function getSuffix(): string |
26
|
|
|
{ |
27
|
34 |
|
return 'permissions'; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function toCollection(PermissionsOwner $owner): Collection |
31
|
|
|
{ |
32
|
25 |
|
return $this->remember($owner, function () use ($owner) { |
33
|
25 |
|
return $this->permissions($owner); |
34
|
25 |
|
}); |
35
|
|
|
} |
36
|
|
|
|
37
|
25 |
|
private function permissions(PermissionsOwner $owner): Collection |
38
|
|
|
{ |
39
|
25 |
|
$permissions = $owner->permissions()->get(); |
40
|
|
|
|
41
|
25 |
|
if ($owner instanceof RolesOwner) { |
42
|
20 |
|
$names = $permissions->pluck('secret_name')->toArray(); |
43
|
20 |
|
$permissions = $this->clean($this->permissionsFromRole($owner), $names)->merge($permissions); |
44
|
|
|
} |
45
|
|
|
|
46
|
25 |
|
return $permissions->filter($this->allowed())->map($this->parse()); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function allowed(): Closure |
50
|
|
|
{ |
51
|
25 |
|
return function (PermissionContract $permission): bool { |
52
|
17 |
|
return $permission->pivot instanceof Deniable ? ! $permission->pivot->isDenied() : true; |
|
|
|
|
53
|
25 |
|
}; |
54
|
|
|
} |
55
|
|
|
|
56
|
20 |
|
private function clean(Collection $permissions, array $exceptNames): Collection |
57
|
|
|
{ |
58
|
20 |
|
return Helper::except($permissions, $exceptNames); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function permissionsFromRole(RolesOwner $owner): Collection |
62
|
|
|
{ |
63
|
20 |
|
return $this->extractPermissions($owner)->unique(function (Grantable $grantable): string { |
64
|
3 |
|
return $grantable->getIdentificationKey(); |
65
|
20 |
|
}); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function extractPermissions(RolesOwner $owner): Collection |
69
|
|
|
{ |
70
|
20 |
|
return $owner->roles()->with('permissions')->get()->map(function (PermissionsOwner $owner): Collection { |
71
|
3 |
|
return $owner->getPermissionModels(); |
72
|
20 |
|
})->collapse(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|