Role::canUpdate()   B
last analyzed

Complexity

Conditions 9
Paths 37

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 34
ccs 22
cts 22
cp 1
rs 8.0555
c 0
b 0
f 0
cc 9
nc 37
nop 3
crap 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Service;
6
7
use Application\Model\User;
8
9
abstract class Role
10
{
11
    /**
12
     * Whether the current user can update from oldRole to newRole.
13
     *
14
     * The current user is allowed to promote another user up to the same role as himself. So
15
     * a Responsible can promote a Member to Responsible. Or an Admin can promote a Member to Admin.
16
     *
17
     * But the current user is **not** allowed to demote a user who has a higher role than himself.
18
     * That means that a Responsible cannot demote an Admin to Member.
19
     */
20 10
    public static function canUpdate(?User $currentUser, string $oldRole, string $newRole): bool
21
    {
22 10
        if ($newRole === $oldRole) {
23 5
            return true;
24
        }
25
26 8
        $currentRole = $currentUser ? $currentUser->getRole() : User::ROLE_ANONYMOUS;
27 8
        $orderedRoles = [
28 8
            User::ROLE_ANONYMOUS,
29 8
            User::ROLE_MEMBER,
30 8
            User::ROLE_FACILITATOR,
31 8
            User::ROLE_ADMINISTRATOR,
32 8
        ];
33
34 8
        $newFound = false;
35 8
        $oldFound = false;
36 8
        foreach ($orderedRoles as $r) {
37 8
            if ($r === $oldRole) {
38 5
                $oldFound = true;
39
            }
40 8
            if ($r === $newRole) {
41 4
                $newFound = true;
42
            }
43
44 8
            if ($r === $currentRole) {
45 8
                break;
46
            }
47
        }
48
49 8
        if (!$newFound || !$oldFound) {
50 5
            return false;
51
        }
52
53 3
        return true;
54
    }
55
}
56