Completed
Branch feature/pre-split (de1aa6)
by Anton
03:26
created

CompositeRule::allows()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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