-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rbac.php
109 lines (96 loc) · 2.55 KB
/
Rbac.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Rad\Authorization;
use RuntimeException;
use InvalidArgumentException;
use Rad\Authorization\Rbac\Role;
use Rad\Authorization\Rbac\RoleInterface;
use Rad\Authorization\Rbac\ResourceInterface;
use Rad\Authorization\Rbac\ResourceCollection;
/**
* Rbac
*
* Role Based Access Control
*
* @package Rad\Authorization
*/
class Rbac
{
/**
* @var RoleInterface[]
*/
protected static $roles = [];
/**
* Add role override if exists
*
* @param RoleInterface|string $role Role name or object
* @param ResourceCollection|array $resources Role resources
*/
public static function addRole($role, array $resources = [])
{
if ($role instanceof RoleInterface) {
self::$roles[$role->getName()] = $role;
} else {
$role = new Role($role, $resources);
self::$roles[$role->getName()] = $role;
}
}
/**
* Get role
*
* @param string $roleName Role name
*
* @return null|RoleInterface
*/
public static function getRole($roleName)
{
if (!is_string($roleName)) {
throw new InvalidArgumentException('Role name argument must be string.');
}
if (isset(self::$roles[$roleName])) {
return self::$roles[$roleName];
}
return null;
}
/**
* Has role exists
*
* @param RoleInterface|string $role Role name or object
*
* @return bool
*/
public static function hasRole($role)
{
if ($role instanceof RoleInterface) {
$role = $role->getName();
}
if (!is_string($role)) {
throw new InvalidArgumentException(
'Role argument must be string or an object implemented "Rad\Authorization\Rbac\RoleInterface".'
);
}
return isset(self::$roles[$role]);
}
/**
* Role is granted
*
* @param RoleInterface|string $role Role name or object
* @param ResourceInterface|string $resource Resource name or object
*
* @return bool
*/
public static function isGranted($role, $resource)
{
if (self::hasRole($role)) {
if ($role instanceof RoleInterface) {
$role = $role->getName();
}
return self::$roles[$role]->hasResource($resource);
}
throw new RuntimeException(
sprintf(
'Role "%s" does not exists.',
gettype($role) === 'string' ? $role : $role->getName()
)
);
}
}