Passed
Push — master ( a39faa...c94eb5 )
by Jelmer
02:19
created

ClosureBasedAccessEvaluator::validateSignature()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 16
ccs 11
cts 11
cp 1
crap 2
rs 9.9666
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace jschreuder\MiddleAuth\Abac;
4
5
use jschreuder\MiddleAuth\AuthorizationEntityInterface;
6
use Closure;
7
use InvalidArgumentException;
8
use ReflectionFunction;
9
use ReflectionParameter;
10
11
final class ClosureBasedAccessEvaluator implements AccessEvaluatorInterface
12
{
13
    private Closure $evaluator;
14
15 10
    public function __construct(callable $evaluator)
16
    {
17 10
        $this->evaluator = Closure::fromCallable($evaluator);
18 10
        $this->validateSignature();
19
    }
20
21 5
    public function hasAccess(AuthorizationEntityInterface $actor, AuthorizationEntityInterface $resource, string $action, array $context): bool
22
    {
23 5
        return ($this->evaluator)($actor, $resource, $action, $context);
24
    }
25
26 10
    private function validateSignature(): void
27
    {
28 10
        $reflection = new ReflectionFunction($this->evaluator);
29 10
        $parameters = $reflection->getParameters();
30
31 10
        if (count($parameters) !== 4) {
32 1
            throw new InvalidArgumentException(
33 1
                'AccessEvaluator must accept exactly 4 parameters (AuthorizationEntityInterface, AuthorizationEntityInterface, string, array)'
34 1
            );
35
        }
36
37
        // If we have 4 parameters, validate their types if type hints are present
38 9
        $this->checkType($parameters[0], 1, AuthorizationEntityInterface::class);
39 8
        $this->checkType($parameters[1], 2, AuthorizationEntityInterface::class);
40 7
        $this->checkType($parameters[2], 3, 'string');
41 6
        $this->checkType($parameters[3], 4, 'array');
42
    }
43
44 9
    private function checkType(ReflectionParameter $parameter, int $number, string $type)
45
    {
46 9
        if (!$parameter->hasType() || strval($parameter->getType()) !== $type) {
47 4
            throw new InvalidArgumentException('Parameter '.$number.' must be '.$type);
48
        }
49
    }
50
}