Completed
Push — master ( a97424...f904c2 )
by Daniel
14:31
created

RestrictedResourceVoter   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
eloc 21
c 1
b 0
f 0
dl 0
loc 41
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A vote() 0 5 3
A isSupported() 0 6 3
B rolesVote() 0 17 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Silverback\ApiComponentBundle\Security;
6
7
use Silverback\ApiComponentBundle\Entity\Content\AbstractContent;
8
use Silverback\ApiComponentBundle\Entity\RestrictedResourceInterface;
9
use Symfony\Component\Security\Core\Security;
10
11
/**
12
 * @author Daniel West <[email protected]>
13
 */
14
class RestrictedResourceVoter
15
{
16
    private $security;
17
18
    public function __construct(Security $security)
19
    {
20
        $this->security = $security;
21
    }
22
23
    private function rolesVote(array $roles): bool
24
    {
25
        if (!count($roles)) {
26
            return true;
27
        }
28
        $negativeRoles = [];
29
        $positiveRoles = [];
30
        foreach ($roles as $role) {
31
            if (strpos($role, '!') === 0) {
32
                $negativeRoles[] = substr($role, 1);
33
                continue;
34
            }
35
            $positiveRoles[] = $role;
36
        }
37
        $positivePass = count($positiveRoles) && $this->security->isGranted($positiveRoles);
38
        $negativePass = count($negativeRoles) && !$this->security->isGranted($negativeRoles);
39
        return $positivePass || $negativePass;
40
    }
41
42
    public function isSupported($data): ?RestrictedResourceInterface
43
    {
44
        if ($data instanceof RestrictedResourceInterface && !$data instanceof AbstractContent) {
45
            return $data;
46
        }
47
        return null;
48
    }
49
50
    public function vote($object): bool
51
    {
52
        return (!($restrictedResource = $this->isSupported($object)) ||
53
            !($roles = $restrictedResource->getSecurityRoles()) === null ||
54
            $this->rolesVote($roles))
0 ignored issues
show
Bug introduced by
It seems like $roles can also be of type null; however, parameter $roles of Silverback\ApiComponentB...ourceVoter::rolesVote() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

54
            $this->rolesVote(/** @scrutinizer ignore-type */ $roles))
Loading history...
55
        ;
56
    }
57
}
58