Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.44% covered (success)
94.44%
17 / 18
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Policy
94.44% covered (success)
94.44%
17 / 18
50.00% covered (danger)
50.00%
1 / 2
7.01
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
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
6.01
1<?php
2namespace Apie\Core\Attributes;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\ContextConstants;
6use Apie\Core\Policies\PolicyManager;
7
8final class Policy implements ApieContextAttribute
9{
10    /**
11     * @param array<string, mixed> $additionalContext
12     */
13    public function __construct(
14        public string $rule,
15        public ?string $globalRule = null,
16        public ?bool $enabledOnMissingRule = null,
17        public array $additionalContext = []
18    ) {
19    }
20
21    public function applies(ApieContext $context): bool
22    {
23        $policyManager = $context->getContext(PolicyManager::class, false);
24        $resource = $context->getContext(ContextConstants::RESOURCE, false);
25        $rule = $this->rule;
26        if ($this->globalRule && !$resource) {
27            $rule = $this->globalRule;
28        }
29    
30        $context = $context->withMultipleContext($this->additionalContext);
31        // this makes it possible to write just the entity as a function argument in a policy class.
32        if ($resource && !$context->hasContext(get_debug_type($resource))) {
33            $context = $context
34                ->registerInstance($resource)
35                ->withContext(get_debug_type($resource), $resource);
36        }
37        
38        if ($policyManager instanceof PolicyManager) {
39            return $policyManager->allowed(
40                $context,
41                $rule,
42                $this->enabledOnMissingRule
43            );
44        }
45
46        return $this->enabledOnMissingRule ?? false;
47    }
48}