Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
10 / 11
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Policy
90.91% covered (success)
90.91%
10 / 11
50.00% covered (danger)
50.00%
1 / 2
5.02
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
 applies
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
4.02
1<?php
2namespace Apie\Core\Attributes;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\ContextConstants;
6use Apie\Core\Policies\PolicyManager;
7use Attribute;
8
9#[Attribute(Attribute::TARGET_CLASS)]
10final class Policy implements ApieContextAttribute
11{
12    /**
13     * @param array<string, mixed> $additionalContext
14     */
15    public function __construct(
16        public string $rule,
17        public ?string $globalRule = null,
18        public array $additionalContext = []
19    ) {
20    }
21
22    public function applies(ApieContext $context): bool
23    {
24        $policyManager = $context->getContext(PolicyManager::class, false);
25        $rule = $this->rule;
26        if ($this->globalRule && !$context->hasContext(ContextConstants::RESOURCE)) {
27            $rule = $this->globalRule;
28        }
29        if ($policyManager instanceof PolicyManager) {
30            return $policyManager->allowed(
31                $context->withMultipleContext($this->additionalContext),
32                $rule
33            );
34        }
35
36        return false;
37    }
38}