Completed
Branch feature/currentUserRefactoring (c13c1d)
by Schlaefer
04:13
created

Role::check()   B

Complexity

Conditions 9
Paths 32

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 32
nop 3
dl 0
loc 31
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace Saito\User\Permission\Allowance;
14
15
class Role
16
{
17
    protected $subjects = [];
18
    protected $objects = [];
19
    protected $resource;
20
21
    /**
22
     * Constructor
23
     *
24
     * @param string $resource What is granted permission to
25
     * @param string|array $subjects Who is granted permission
26
     * @param string|array $objects Qualifier for permission resource
27
     */
28
    public function __construct($resource, $subjects, $objects = null)
29
    {
30
        $subjects = is_array($subjects) ? $subjects : [$subjects];
31
        $objects = $objects ?: [];
32
        $objects = is_array($objects) ? $objects : [$objects];
33
34
        $this->subjects = array_fill_keys($subjects, true);
35
        $this->objects = array_fill_keys($objects, true);
36
        $this->resource = $resource;
37
    }
38
39
    /**
40
     * Check if allowed
41
     *
42
     * @param string $resource Resource-ID
43
     * @param string|array $roles Subject
44
     * @param string $object Object
45
     * @return bool
46
     */
47
    public function check(string $resource, $roles, string $object = null): bool
48
    {
49
        $roles = is_array($roles) ? $roles : [$roles];
50
51
        if ($this->resource !== $resource) {
52
            return false;
53
        }
54
55
        $isRole = false;
56
        foreach ($roles as $role) {
57
            if (isset($this->subjects[$role])) {
58
                $isRole = true;
59
                break;
60
            }
61
        }
62
        if (!$isRole) {
63
            return false;
64
        }
65
66
        if (!empty($this->objects)) {
67
            if (empty($object)) {
68
                return false;
69
            }
70
71
            if (!isset($this->objects[$object])) {
72
                return false;
73
            }
74
        }
75
76
        return true;
77
    }
78
}
79