1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Icybee\Modules\Users;
13
14 class PermissionResolver implements \ArrayAccess, \IteratorAggregate, PermissionResolverInterface
15 {
16 17 18 19 20 21 22
23 static public function synthesize_config(array $fragments)
24 {
25 $list = [];
26 $weight = [];
27
28 foreach ($fragments as $fragment)
29 {
30 if (empty($fragment['permission_resolver_list']))
31 {
32 continue;
33 }
34
35 foreach ($fragment['permission_resolver_list'] as $resolver_id => $resolver)
36 {
37 $resolver = ((array) $resolver) + [ 'weight' => 0 ];
38
39 $list[$resolver_id] = $resolver[0];
40 $weight[$resolver_id] = $resolver['weight'];
41 }
42 }
43
44 return \ICanBoogie\sort_by_weight($list, function($v, $k) use($weight) {
45
46 return $weight[$k];
47
48 });
49 }
50
51 private $list = [];
52
53 54 55 56 57 58
59 public function __construct(array $resolver_list=[])
60 {
61 foreach ($resolver_list as $resolver_id => $resolver)
62 {
63 $this[$resolver_id] = $resolver;
64 }
65 }
66
67 public function __invoke(User $user, $permission, $target=null)
68 {
69 $granted = false;
70
71 foreach ($this->list as $resolver_id => &$resolver)
72 {
73 if (!is_callable($resolver))
74 {
75 $resolver = new $resolver;
76 }
77
78 $resolver_grant = call_user_func($resolver, $user, $permission, $target);
79
80 if ($resolver_grant === null)
81 {
82 continue;
83 }
84
85 $granted = $resolver_grant;
86 }
87
88 return $granted;
89 }
90
91 public function getIterator()
92 {
93 return new \ArrayIterator($this->list);
94 }
95
96 public function offsetExists($resolver_id)
97 {
98 return isset($this->list[$resolver_id]);
99 }
100
101 public function offsetGet($resolver_id)
102 {
103 return $this->list[$resolver_id];
104 }
105
106 public function offsetSet($resolver_id, $resolver)
107 {
108 $this->list[$resolver_id] = $resolver;
109 }
110
111 public function offsetUnset($resolver_id)
112 {
113 unset($this->list[$resolver_id]);
114 }
115 }
116
117 interface PermissionResolverInterface
118 {
119 120 121 122 123 124 125 126 127
128 public function __invoke(User $user, $permission, $target=null);
129 }