Role::canUpdate()   B
last analyzed

Complexity

Conditions 9
Paths 37

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 39
ccs 27
cts 27
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 Individual 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 Individual.
19
     */
20 11
    public static function canUpdate(?User $currentUser, string $oldRole, string $newRole): bool
21
    {
22 11
        if ($newRole === $oldRole) {
23 6
            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_ACCOUNTING_VERIFICATOR,
30 8
            User::ROLE_INDIVIDUAL,
31 8
            User::ROLE_MEMBER,
32 8
            User::ROLE_TRAINER,
33 8
            User::ROLE_BOOKING_ONLY,
34 8
            User::ROLE_FORMATION_RESPONSIBLE,
35 8
            User::ROLE_RESPONSIBLE,
36 8
            User::ROLE_ADMINISTRATOR,
37 8
        ];
38
39 8
        $newFound = false;
40 8
        $oldFound = false;
41 8
        foreach ($orderedRoles as $r) {
42 8
            if ($r === $oldRole) {
43 5
                $oldFound = true;
44
            }
45 8
            if ($r === $newRole) {
46 4
                $newFound = true;
47
            }
48
49 8
            if ($r === $currentRole) {
50 8
                break;
51
            }
52
        }
53
54 8
        if (!$newFound || !$oldFound) {
55 5
            return false;
56
        }
57
58 4
        return true;
59
    }
60
}
61