Role::canUpdate()   B
last analyzed

Complexity

Conditions 9
Paths 37

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 36
ccs 24
cts 24
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 Senior can promote a Student to Senior. Or an Admin can promote a Junior 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 Senior cannot demote an Admin to Student.
19
     */
20 17
    public static function canUpdate(?User $currentUser, string $oldRole, string $newRole): bool
21
    {
22 17
        if ($newRole === $oldRole) {
23 6
            return true;
24
        }
25
26 14
        $currentRole = $currentUser ? $currentUser->getRole() : User::ROLE_ANONYMOUS;
27 14
        $orderedRoles = [
28 14
            User::ROLE_ANONYMOUS,
29 14
            User::ROLE_STUDENT,
30 14
            User::ROLE_JUNIOR,
31 14
            User::ROLE_SENIOR,
32 14
            User::ROLE_MAJOR,
33 14
            User::ROLE_ADMINISTRATOR,
34 14
        ];
35
36 14
        $newFound = false;
37 14
        $oldFound = false;
38 14
        foreach ($orderedRoles as $r) {
39 14
            if ($r === $oldRole) {
40 11
                $oldFound = true;
41
            }
42 14
            if ($r === $newRole) {
43 10
                $newFound = true;
44
            }
45
46 14
            if ($r === $currentRole) {
47 14
                break;
48
            }
49
        }
50
51 14
        if (!$newFound || !$oldFound) {
52 6
            return false;
53
        }
54
55 9
        return true;
56
    }
57
}
58