Completed
Push — feature/admin-cp ( e1b9fd...634a7d )
by Vladimir
02:52
created

AdminController::isEditorFor()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 2
1
<?php
2
3
use Symfony\Component\HttpFoundation\Request;
4
5
/**
6
 * @todo Configure the AdminController to be behind a Symfony firewall
7
 */
8
class AdminController extends HTMLController
9
{
10
    private static $wipeableModels = ['Ban', 'Map', 'Match', 'News', 'NewsCategory', 'Page', 'Server', 'Team'];
0 ignored issues
show
Unused Code introduced by
The property $wipeableModels is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
11
12
    public function listAction()
13
    {
14
        $rolesToDisplay = Role::getLeaderRoles();
15
        $roles = array();
16
17
        foreach ($rolesToDisplay as $role) {
18
            $roleMembers = $role->getUsers();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Model as the method getUsers() does only exist in the following sub-classes of Model: Role. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
19
20
            if (count($roleMembers) > 0) {
21
                $roles[] = array(
22
                    "role"    => $role,
23
                    "members" => $roleMembers
24
                );
25
            }
26
        }
27
28
        return array("role_sections" => $roles);
29
    }
30
31
    public function landingAction(Player $me)
32
    {
33
        if (!$me->isValid()) {
34
            throw new ForbiddenException('Please log in to view this page.');
35
        }
36
37
        // @todo Model editing should be a generic permission
38
        $canViewModelEditor = true;
39
        $canViewPageEditor = $this->isEditorFor(Page::class, $me);
40
        $canViewRoleEditor = $this->isEditorFor(Role::class, $me);
41
        $canViewVisitLog   = $me->hasPermission(Permission::VIEW_VISITOR_LOG);
42
43
        if (!$canViewPageEditor && !$canViewRoleEditor && !$canViewVisitLog) {
44
            throw new ForbiddenException('Contact a site administrator if you feel you should have access to this page.');
45
        }
46
47
        return [
48
            'canViewPageEditor' => $canViewPageEditor,
49
            'canViewRoleEditor' => $canViewRoleEditor,
50
            'canViewModelEditor' => $canViewModelEditor,
51
            'canViewVisitLog' => $canViewVisitLog,
52
        ];
53
    }
54
55 View Code Duplication
    public function pageListAction(Player $me)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
    {
57
        if (!$me->isValid()) {
58
            throw new ForbiddenException('Please log in to view this page.');
59
        }
60
61
        if (!$this->isEditorFor(Page::class, $me)) {
62
            throw new ForbiddenException('Contact a site administrator if you feel you should have access to this page.');
63
        }
64
65
        $pages = Page::getQueryBuilder()
66
            ->where('status')->notEquals('deleted')
67
            ->getModels(true)
68
        ;
69
70
        return [
71
            'pages' => $pages,
72
            'canCreate' => $me->hasPermission(Page::CREATE_PERMISSION),
73
            'canEdit' => $me->hasPermission(Page::EDIT_PERMISSION),
74
            'canDelete' => $me->hasPermission(Page::SOFT_DELETE_PERMISSION),
75
            'canWipe' => $me->hasPermission(Page::HARD_DELETE_PERMISSION),
76
        ];
77
    }
78
79 View Code Duplication
    public function roleListAction(Player $me)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
    {
81
        if (!$me->isValid()) {
82
            throw new ForbiddenException('Please log in to view this page.');
83
        }
84
85
        if (!$this->isEditorFor(Role::class, $me)) {
86
            throw new ForbiddenException('Contact a site administrator if you feel you should have access to this page.');
87
        }
88
89
        $roles = Role::getQueryBuilder()
90
            ->sortBy('display_order')
91
            ->getModels($fast = true)
92
        ;
93
94
        return [
95
            'roles' => $roles,
96
            'canCreate' => $me->hasPermission(Role::CREATE_PERMISSION),
97
            'canEdit' => $me->hasPermission(Role::EDIT_PERMISSION),
98
            'canDelete' => $me->hasPermission(Role::SOFT_DELETE_PERMISSION),
99
            'canWipe' => $me->hasPermission(Role::HARD_DELETE_PERMISSION),
100
        ];
101
    }
102
103
    public function modelListAction(Request $request, Player $me, $type)
104
    {
105
        $type = ucfirst($type);
106
107
        if (!$me->isValid()) {
108
            throw new ForbiddenException('Please log in to view this page.');
109
        }
110
111
        if (!$me->hasPermission($type::SOFT_DELETE_PERMISSION)) {
112
            throw new ForbiddenException('Contact a site administrator if you feel you should have access to this page.');
113
        }
114
115
        $searchTerm = $request->get('search');
116
117
        $currentPage = $this->getCurrentPage();
118
119
        /** @var QueryBuilder $qb */
120
        $qb = $type::getQueryBuilder()
121
            ->where('status')->equals('deleted')
122
            ->sortBy('name')
123
        ;
124
125
        if ($searchTerm !== null) {
126
            $qb->where('name')->isLike($searchTerm);
127
        }
128
129
        $models = $qb
130
            ->limit(15)
131
            ->fromPage($currentPage)
132
            ->getModels()
133
        ;
134
135
        return [
136
            'type' => $type,
137
            'models' => $models,
138
            'canRestore' => $me->hasPermission($type::SOFT_DELETE_PERMISSION),
139
            'canWipe' => $me->hasPermission($type::HARD_DELETE_PERMISSION),
140
            'currentPage' => $currentPage,
141
            'totalPages' => $qb->countPages(),
142
            'searchTerm' => $searchTerm,
143
        ];
144
    }
145
146
    public function wipeAction(Player $me)
147
    {
148
        $canViewThisPage = false;
149
        $wipeable = array('Ban', 'Map', 'Match', 'News', 'NewsCategory', 'Page', 'Server', 'Team');
150
        $models   = array();
151
152
        foreach ($wipeable as $type) {
153
            if (!$me->hasPermission($type::HARD_DELETE_PERMISSION)) {
154
                continue;
155
            }
156
157
            $canViewThisPage = true;
158
            $models = array_merge($models, $type::getQueryBuilder()
159
                ->where('status')->equals('deleted')
160
                ->getModels());
161
        }
162
163
        // Permission checking
164
        if (!$me->isValid()) {
165
            throw new ForbiddenException("Please log in to view this page.");
166
        }
167
        if (!$canViewThisPage) {
168
            throw new ForbiddenException("Contact a site administrator if you feel you should have access to this page.");
169
        }
170
171
        return array('models' => $models);
172
    }
173
174
    private function isEditorFor($className, Player $me)
175
    {
176
        $permissionConstants = [
177
            'CREATE_PERMISSION',
178
            'EDIT_PERMISSION',
179
            'SOFT_DELETE_PERMISSION',
180
            'HARD_DELETE_PERMISSION',
181
        ];
182
183
        $reflector = new ReflectionClass($className);
184
185
        foreach ($permissionConstants as $permission) {
186
            $permissionName = $reflector->getConstant($permission);
187
188
            if ($me->hasPermission($permissionName)) {
189
                return true;
190
            }
191
        }
192
193
        return false;
194
    }
195
}
196