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
|
|
|
} |