1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Spiral Framework. |
5
|
|
|
* |
6
|
|
|
* @license MIT |
7
|
|
|
* @author Anton Titov (Wolfy-J) |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Spiral\Security\Rule; |
13
|
|
|
|
14
|
|
|
use Spiral\Security\ActorInterface; |
15
|
|
|
use Spiral\Security\RuleInterface; |
16
|
|
|
use Spiral\Security\RulesInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Provides ability to evaluate multiple sub rules using boolean joiner. |
20
|
|
|
* |
21
|
|
|
* Example: |
22
|
|
|
* |
23
|
|
|
* class AuthorOrModeratorRule extends BooleanRule |
24
|
|
|
* { |
25
|
|
|
* const BEHAVIOUR = self::AT_LEAST_ONE; |
26
|
|
|
* const RULES = [AuthorRule::class, ModeratorRule::class]; |
27
|
|
|
* } |
28
|
|
|
*/ |
29
|
|
|
abstract class CompositeRule implements RuleInterface |
30
|
|
|
{ |
31
|
|
|
protected const ALL = 'ALL'; |
32
|
|
|
protected const AT_LEAST_ONE = 'ONE'; |
33
|
|
|
|
34
|
|
|
/** How to process results on sub rules. */ |
35
|
|
|
protected const BEHAVIOUR = self::ALL; |
36
|
|
|
|
37
|
|
|
/** List of rules to be composited. */ |
38
|
|
|
protected const RULES = []; |
39
|
|
|
|
40
|
|
|
/** @var RulesInterface */ |
41
|
|
|
private $repository = null; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param RulesInterface $repository |
45
|
|
|
*/ |
46
|
|
|
public function __construct(RulesInterface $repository) |
47
|
|
|
{ |
48
|
|
|
$this->repository = $repository; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
|
|
public function allows(ActorInterface $actor, string $permission, array $context): bool |
55
|
|
|
{ |
56
|
|
|
$allowed = 0; |
57
|
|
|
foreach (static::RULES as $rule) { |
58
|
|
|
$rule = $this->repository->get($rule); |
59
|
|
|
|
60
|
|
|
if ($rule->allows($actor, $permission, $context)) { |
61
|
|
|
if (static::BEHAVIOUR == self::AT_LEAST_ONE) { |
62
|
|
|
return true; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$allowed++; |
66
|
|
|
} elseif (static::BEHAVIOUR == self::ALL) { |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $allowed === count(static::RULES); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|