1 | <?php |
||
29 | class CacheStrategy implements MultiStrategy |
||
30 | { |
||
31 | /** |
||
32 | * @var array<string,\Caridea\Acl\Acl> contains the ACLs indexed by Target and Subjects string |
||
33 | */ |
||
34 | protected $cache = []; |
||
35 | /** |
||
36 | * @var \Caridea\Acl\Strategy The actual loading strategy |
||
37 | */ |
||
38 | protected $delegate; |
||
39 | |||
40 | /** |
||
41 | * Creates a new CacheStrategy. |
||
42 | * |
||
43 | * @param \Caridea\Acl\Strategy $delegate The actual loading strategy to use |
||
44 | */ |
||
45 | 6 | public function __construct(Strategy $delegate) |
|
46 | { |
||
47 | 6 | $this->delegate = $delegate; |
|
48 | 6 | } |
|
49 | |||
50 | /** |
||
51 | * Loads the ACL for a Target. |
||
52 | * |
||
53 | * @param \Caridea\Acl\Target $target The `Target` whose ACL will be loaded |
||
54 | * @param \Caridea\Acl\Subject[] $subjects An array of `Subject`s |
||
55 | * @param \Caridea\Acl\Service $service The ACL service (to load parent ACLs) |
||
56 | * @return \Caridea\Acl\Acl The loaded ACL |
||
57 | * @throws \Caridea\Acl\Exception\Unloadable If the resource provided is invalid |
||
58 | * @throws \InvalidArgumentException If the `subjects` argument contains invalid values |
||
59 | */ |
||
60 | 3 | public function load(Target $target, array $subjects, Service $service): Acl |
|
61 | { |
||
62 | 3 | $key = $this->buildKey($target, $subjects); |
|
63 | 2 | if (!isset($this->cache[$key])) { |
|
64 | 2 | $acl = $this->delegate->load($target, $subjects, $service); |
|
65 | 2 | $this->cache[$key] = $acl; |
|
66 | } |
||
67 | 2 | return $this->cache[$key]; |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * Loads the ACLs for several Targets. |
||
72 | * |
||
73 | * @since 2.1.0 |
||
74 | * @param \Caridea\Acl\Target[] $targets The `Target` whose ACL will be loaded |
||
75 | * @param \Caridea\Acl\Subject[] $subjects An array of `Subject`s |
||
76 | * @param \Caridea\Acl\Service $service The ACL service (to load parent ACLs) |
||
77 | * @return array<string,\Caridea\Acl\Acl> The loaded ACLs |
||
78 | * @throws \Caridea\Acl\Exception\Unloadable If the target provided is invalid |
||
79 | * @throws \InvalidArgumentException If the `subjects` argument contains invalid values |
||
80 | */ |
||
81 | 4 | public function loadAll(array $targets, array $subjects, Service $service): array |
|
114 | |||
115 | /** |
||
116 | * Generates the key to use for caching the ACL. |
||
117 | * |
||
118 | * @param \Caridea\Acl\Target $target The `Target` whose ACL will be loaded |
||
119 | * @param array $subjects An array of `Subject`s |
||
120 | * @return string The cache key |
||
121 | * @throws \InvalidArgumentException If the `subjects` argument contains invalid values |
||
122 | */ |
||
123 | 4 | protected function buildKey(Target $target, array $subjects): string |
|
134 | } |
||
135 |