Passed
Push — master ( 7e90a1...3954fd )
by Adrien
08:08
created

Role::canUpdate()   B

Complexity

Conditions 9
Paths 37

Size

Total Lines 37
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 37
ccs 17
cts 17
cp 1
rs 8.0555
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 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
        $orderedRoles = [
28 8
            User::ROLE_ANONYMOUS,
29
            User::ROLE_INDIVIDUAL,
30
            User::ROLE_MEMBER,
31
            User::ROLE_TRAINER,
32
            User::ROLE_BOOKING_ONLY,
33
            User::ROLE_RESPONSIBLE,
34
            User::ROLE_ADMINISTRATOR,
35
        ];
36
37 8
        $newFound = false;
38 8
        $oldFound = false;
39 8
        foreach ($orderedRoles as $r) {
40 8
            if ($r === $oldRole) {
41 5
                $oldFound = true;
42
            }
43 8
            if ($r === $newRole) {
44 4
                $newFound = true;
45
            }
46
47 8
            if ($r === $currentRole) {
48 8
                break;
49
            }
50
        }
51
52 8
        if (!$newFound || !$oldFound) {
53 5
            return false;
54
        }
55
56 4
        return true;
57
    }
58
}
59