Passed
Push — master ( 4d4163...319ade )
by Nico
10:25 queued 04:57
created

WormholeEntryPrivilegeUtility::checkPrivilegeFor()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 10
ccs 0
cts 7
cp 0
crap 12
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Component\Ship\Wormhole;
6
7
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Stu\Orm\Entity\WormholeRestriction;
9
use Stu\Orm\Entity\Spacecraft;
10
use Stu\Orm\Entity\WormholeEntry;
11
use Stu\Orm\Entity\User;
12
13
final class WormholeEntryPrivilegeUtility implements WormholeEntryPrivilegeUtilityInterface
14
{
15
    #[Override]
16
    public function checkPrivilegeFor(WormholeEntry $wormholeEntry, User|Spacecraft $source): bool
17
    {
18
        try {
19
            return $wormholeEntry->getRestrictions()->reduce(
20
                fn(bool $isAllowed, WormholeRestriction $restriction): bool => $isAllowed || $this->isAllowed($restriction, $source),
21
                false
22
            );
23
        } catch (WormholeEntryUnallowedException) {
24
            return false;
25
        }
26
    }
27
28
    private function isAllowed(WormholeRestriction $restriction, User|Spacecraft $source): bool
29
    {
30
        $user = $source instanceof User ? $source : $source->getUser();
31
        $userAlliance = $user->getAlliance();
32
33
        $privilegeType = $restriction->getPrivilegeType();
34
        if ($privilegeType === null) {
35
            return false;
36
        }
37
38
        $isMatch = match ($privilegeType) {
39
            WormholeEntryTypeEnum::USER => $restriction->getTargetId() === $user->getId(),
40
            WormholeEntryTypeEnum::ALLIANCE => $userAlliance !== null && $restriction->getTargetId() === $userAlliance->getId(),
41
            WormholeEntryTypeEnum::FACTION => $restriction->getTargetId() == $user->getFactionId(),
42
            WormholeEntryTypeEnum::SHIP => $source instanceof Spacecraft && $restriction->getTargetId() == $source->getId(),
43
        };
44
45
        if (!$isMatch) {
46
            return false;
47
        }
48
49
        if ($restriction->getMode() === WormholeEntryModeEnum::DENY->value) {
50
            throw new WormholeEntryUnallowedException();
51
        }
52
53
        return true;
54
    }
55
}