Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.71% covered (warning)
85.71%
12 / 14
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
PolicyManager
85.71% covered (warning)
85.71%
12 / 14
50.00% covered (danger)
50.00%
1 / 2
6.10
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 allowed
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
5.09
1<?php
2namespace Apie\Core\Policies;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\Metadata\Concerns\UseContextKey;
6use ReflectionException;
7use ReflectionMethod;
8
9class PolicyManager
10{
11    use UseContextKey;
12    public function __construct(
13        private readonly PolicyProviderInterface $policyProvider,
14        private readonly bool $defaultAllow = true,
15    ) {
16    }
17
18    public function allowed(ApieContext $apieContext, string $action, ?bool $enabledOnMissingRule = null): bool
19    {
20        $policy = $this->policyProvider->getPolicyFor($apieContext, $action);
21        if (is_callable([$policy, $action])) {
22            try {
23                $reflection = new ReflectionMethod($policy, $action);
24                $args = [];
25                foreach ($reflection->getParameters() as $parameter) {
26                    try {
27                        $contextKey = $this->getContextKey($apieContext, $parameter, false);
28                        $args[] = $apieContext->getContext($contextKey);
29                    } catch (\Throwable $err) {
30                        return $enabledOnMissingRule ?? $this->defaultAllow;
31                    }
32                }
33                return $policy->{$action}(...$args) ?? $enabledOnMissingRule ?? $this->defaultAllow;
34            } catch (ReflectionException $err) {
35                // for __call methods we can't do reflection, so we just call the method and hope for the best
36                return call_user_func([$policy, $action]) ?? $enabledOnMissingRule ?? $this->defaultAllow;
37            }
38        }
39        return $enabledOnMissingRule ?? $this->defaultAllow;
40    }
41}