Passed
Push — master ( 7f699f...e24ab0 )
by Kirill
03:06
created

GuardedTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 52
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A allows() 0 3 1
A denies() 0 3 1
A resolvePermission() 0 8 2
A getGuard() 0 10 3
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\Traits;
13
14
use Spiral\Core\ContainerScope;
15
use Spiral\Core\Exception\ScopeException;
16
use Spiral\Security\GuardInterface;
17
18
/**
19
 * Embeds GuardInterface functionality into class and provides ability to isolate permissions
20
 * using guard namespace. GuardedTrait operates using global container scope.
21
 */
22
trait GuardedTrait
23
{
24
    /**
25
     * @return GuardInterface
26
     * @throws ScopeException
27
     */
28
    public function getGuard(): GuardInterface
29
    {
30
        $container = ContainerScope::getContainer();
31
        if (empty($container) || !$container->has(GuardInterface::class)) {
32
            throw new ScopeException(
33
                'Unable to get `GuardInterface`, binding is missing or container scope is not set'
34
            );
35
        }
36
37
        return $container->get(GuardInterface::class);
38
    }
39
40
    /**
41
     * @param string $permission
42
     * @param array  $context
43
     * @return bool
44
     */
45
    protected function allows(string $permission, array $context = []): bool
46
    {
47
        return $this->getGuard()->allows($this->resolvePermission($permission), $context);
48
    }
49
50
    /**
51
     * @param string $permission
52
     * @param array  $context
53
     * @return bool
54
     */
55
    protected function denies(string $permission, array $context = []): bool
56
    {
57
        return !$this->allows($permission, $context);
58
    }
59
60
    /**
61
     * Automatically prepend permission name with local RBAC namespace.
62
     *
63
     * @param string $permission
64
     * @return string
65
     */
66
    protected function resolvePermission(string $permission): string
67
    {
68
        if (defined('static::GUARD_NAMESPACE')) {
69
            // Yay! Isolation
70
            $permission = constant(get_called_class() . '::' . 'GUARD_NAMESPACE') . '.' . $permission;
71
        }
72
73
        return $permission;
74
    }
75
}
76