Completed
Branch feature/pre-split (afd44c)
by Anton
07:02
created

PermissionManager::deassociate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
rs 10
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
namespace Spiral\Security;
9
10
use Spiral\Core\Component;
11
use Spiral\Core\Container\SingletonInterface;
12
use Spiral\Security\Exceptions\PermissionException;
13
use Spiral\Security\Exceptions\RoleException;
14
use Spiral\Security\Rules\ForbidRule;
15
use Spiral\Support\Patternizer;
16
17
/**
18
 * Default implementation of associations repository and manager. Provides ability to set
19
 * permissions in bulk using * syntax.
20
 *
21
 * Attention, this class is serializable and can be cached in memory.
22
 *
23
 * Example:
24
 * $associations->associate('admin', '*');
25
 * $associations->associate('editor', 'posts.*', Allows::class);
26
 * $associations->associate('user', 'posts.*', Forbid::class);
27
 */
28
class PermissionManager extends Component implements PermissionsInterface, SingletonInterface
29
{
30
    /**
31
     * Roles associated with their permissions.
32
     *
33
     * @var array
34
     */
35
    private $permissions = [];
36
37
    /**
38
     * @var RulesInterface
39
     */
40
    private $rules = null;
41
42
    /**
43
     * @var Patternizer
44
     */
45
    private $patternizer = null;
46
47
    /**
48
     * @param RulesInterface   $rules
49
     * @param Patternizer|null $patternizer
50
     */
51
    public function __construct(RulesInterface $rules, Patternizer $patternizer)
52
    {
53
        $this->rules = $rules;
54
        $this->patternizer = $patternizer;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function hasRole(string $role): bool
61
    {
62
        return array_key_exists($role, $this->permissions);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     *
68
     * @return $this
69
     */
70 View Code Duplication
    public function addRole(string $role): PermissionManager
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
    {
72
        if ($this->hasRole($role)) {
73
            throw new RoleException("Role '{$role}' already exists");
74
        }
75
76
        $this->permissions[$role] = [
77
            //No associated permissions
78
        ];
79
80
        return $this;
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     *
86
     * @return $this
87
     */
88 View Code Duplication
    public function removeRole(string $role): PermissionManager
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
    {
90
        if (!$this->hasRole($role)) {
91
            throw new RoleException("Undefined role '{$role}'");
92
        }
93
94
        unset($this->permissions[$role]);
95
96
        return $this;
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getRoles(): array
103
    {
104
        return array_keys($this->permissions);
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function getRule(string $role, string $permission): RuleInterface
111
    {
112
        if (!$this->hasRole($role)) {
113
            throw new RoleException("Undefined role '{$role}'");
114
        }
115
116
        //Behaviour points to rule
117
        return $this->rules->get(
118
            $this->findRule($role, $permission)
119
        );
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     *
125
     * @return $this|self
126
     */
127
    public function associate(
128
        string $role,
129
        string $permission,
130
        string $rule = 'Spiral\Security\Rules\AllowRule'
131
    ): PermissionManager {
132
        if (!$this->hasRole($role)) {
133
            throw new RoleException("Undefined role '{$role}'");
134
        }
135
136
        if (!$this->rules->has($rule)) {
137
            throw new PermissionException("Undefined rule '{$rule}'");
138
        }
139
140
        $this->permissions[$role][$permission] = $rule;
141
142
        return $this;
143
    }
144
145
    /**
146
     * Associate role/permission with Forbid rule.
147
     *
148
     * @param string $role
149
     * @param string $permission
150
     *
151
     * @return $this|self
152
     *
153
     * @throws RoleException
154
     * @throws PermissionException
155
     */
156
    public function deassociate(string $role, string $permission): PermissionManager
157
    {
158
        return $this->associate($role, $permission, ForbidRule::class);
159
    }
160
161
    /**
162
     * @param string $role
163
     * @param string $permission
164
     *
165
     * @return string
166
     *
167
     * @throws PermissionException
168
     */
169
    private function findRule(string $role, string $permission): string
170
    {
171
        if (isset($this->permissions[$role][$permission])) {
172
            //O(1) check
1 ignored issue
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
            return $this->permissions[$role][$permission];
174
        }
175
176
        //Matching using star syntax
177
        foreach ($this->permissions[$role] as $pattern => $rule) {
178
            if ($this->patternizer->matches($permission, $pattern)) {
179
                return $rule;
180
            }
181
        }
182
183
        throw new PermissionException(
184
            "Unable to resolve role/permission association for '{$role}'/'{$permission}'"
185
        );
186
    }
187
}