Completed
Push — master ( bf23bc...4f23d4 )
by Patrick
06:42
created

GroupsAPI   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 230
Duplicated Lines 18.7 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 43
loc 230
rs 8.2608
c 0
b 0
f 0
wmc 40
lcom 1
cbo 3

12 Methods

Rating   Name   Duplication   Size   Complexity  
A setup() 0 7 1
A validateLoggedIn() 0 8 2
A validateIsAdmin() 17 17 4
A getGroups() 0 12 2
A expandGroupMembers() 0 20 4
C getGroup() 0 47 8
B getAllGroupsAndUsers() 20 30 5
A getTypeOfEntity() 0 11 2
A getNonMemberEntities() 6 14 3
B getNonMembers() 0 24 4
A updateGroup() 0 13 2
A getGroupForUserByName() 0 13 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like GroupsAPI often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GroupsAPI, and based on these observations, apply Extract Interface, too.

1
<?php
2
class GroupsAPI extends Http\Rest\RestAPI
3
{
4
    public function setup($app)
5
    {
6
        $app->get('[/]', array($this, 'getGroups'));
7
        $app->get('/{name}[/]', array($this, 'getGroup'));
8
        $app->patch('/{name}[/]', array($this, 'updateGroup'));
9
        $app->get('/{name}/non-members', array($this, 'getNonMembers'));
10
    }
11
12
    public function validateLoggedIn($request)
13
    {
14
        $this->user = $request->getAttribute('user');
0 ignored issues
show
Bug introduced by
The property user does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
15
        if($this->user === false)
16
        {
17
            throw new Exception('Must be logged in', \Http\Rest\ACCESS_DENIED);
18
        }
19
    }
20
21 View Code Duplication
    public function validateIsAdmin($request, $nonFatal = false)
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...
22
    {
23
        $this->user = $request->getAttribute('user');
24
        if($this->user === false)
25
        {
26
            throw new Exception('Must be logged in', \Http\Rest\ACCESS_DENIED);
27
        }
28
        if(!$this->user->isInGroupNamed('LDAPAdmins'))
29
        {
30
            if($nonFatal)
31
            {
32
                return false;
33
            }
34
            throw new Exception('Must be Admin', \Http\Rest\ACCESS_DENIED);
35
        }
36
        return true;
37
    }
38
39
    public function getGroups($request, $response, $args)
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
40
    {
41
        if($this->validateIsAdmin($request, true) === false)
42
        {
43
            return $response->withStatus(301)->withHeader('Location', '../users/me/groups');
44
        }
45
        $auth = AuthProvider::getInstance();
46
        $odata = $request->getAttribute('odata', new \ODataParams(array()));
47
        $groups = $auth->getGroupsByFilter($odata->filter, $odata->select, $odata->top, $odata->skip, 
48
                                           $odata->orderby);
49
        return $response->withJson($groups);
50
    }
51
52
    private function expandGroupMembers($group, $odata, $directOnly)
53
    {
54
        if($odata->expand !== false && in_array('member', $odata->expand))
55
        {
56
            $ret = array();
57
            $ret['cn'] = $group->getGroupName();
58
            $ret['description'] = $group->getDescription();
59
            $ret['member'] = $group->members(true, ($directOnly !== true));
60
            return json_decode(json_encode($ret), true);
61
        }
62
        else if($directOnly)
63
        {
64
            $ret = array();
65
            $ret['cn'] = $group->getGroupName();
66
            $ret['description'] = $group->getDescription();
67
            $ret['member'] = $group->getMemberUids(false);
68
            return json_decode(json_encode($ret), true);
69
        }
70
        return json_decode(json_encode($group), true);
71
    }
72
73
    private function getGroupForUserByName($name)
74
    {
75
        $groups = $this->user->getGroups();
76
        $count = count($groups);
77
        for($i = 0; $i < $count; $i++)
78
        {
79
            if(strcasecmp($groups[$i]->getGroupName(), $name) === 0)
80
            {
81
                return $groups[$i];
82
            }
83
        }
84
        return false;
85
    }
86
87
    public function getGroup($request, $response, $args)
88
    {
89
        $odata = $request->getAttribute('odata', new \ODataParams(array()));
90
        $group = false;
0 ignored issues
show
Unused Code introduced by
$group is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
91
        $expand = false;
92
        $user = $request->getAttribute('user');
93
        if($user === false)
94
        {
95
            $local = $request->getServerParam('SERVER_ADDR');
96
            $remote = $request->getServerParam('REMOTE_ADDR');
97
            if($local === $remote)
98
            {
99
                $auth = AuthProvider::getInstance();
100
                $group = $auth->getGroupByName($args['name']);
101
                $expand = true;
102
            }
103
            else
104
            {
105
                return $response->withStatus(401);
106
            }
107
        }
108
        else if($this->validateIsAdmin($request, true) === false)
109
        {
110
            $group = $this->getGroupForUserByName($args['name']);
111
        }
112
        else
113
        {
114
            $auth = AuthProvider::getInstance();
115
            $group = $auth->getGroupByName($args['name']);
116
            $expand = true;
117
        }
118
        if(empty($group))
119
        {
120
            return $response->withStatus(404);
121
        }
122
        $params = $request->getQueryParams();
123
        $directOnly = false;
124
        if(isset($params['directOnly']) && $params['directOnly'] === 'true')
125
        {
126
            $directOnly = true;
127
        }
128
        if($expand)
129
        {
130
            $group = $this->expandGroupMembers($group, $odata, $directOnly);
131
        }
132
        return $response->withJson($group);
133
    }
134
135
    public function getAllGroupsAndUsers($keys)
136
    {
137
        $auth = AuthProvider::getInstance();
138
        $groups = $auth->getGroupsByFilter(false);
139
        $count  = count($groups);
140
        $res = array();
141 View Code Duplication
        for($i = 0; $i < $count; $i++)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
142
        {
143
            $tmp = json_decode(json_encode($groups[$i]), true);
144
            $tmp['type'] = 'Group';
145
            if($keys !== false)
146
            {
147
                $tmp = array_intersect_key($tmp, $keys);
148
            }
149
            $res[] = $tmp;
150
        }
151
        $users  = $auth->getUsersByFilter(false);
152
        $count  = count($users);
153 View Code Duplication
        for($i = 0; $i < $count; $i++)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
154
        {
155
            $tmp = json_decode(json_encode($users[$i]), true);
156
            $tmp['type'] = 'User';
157
            if($keys !== false)
158
            {
159
                $tmp = array_intersect_key($tmp, $keys);
160
            }
161
            $res[] = $tmp;
162
        }
163
        return $res;
164
    }
165
166
    public function getTypeOfEntity($entity)
167
    {
168
        if(is_subclass_of($entity, 'Auth\Group'))
169
        {
170
            return 'Group';
171
        }
172
        else
173
        {
174
            return 'User';
175
        }
176
    }
177
178
    public function getNonMemberEntities($nonMembers, $keys)
179
    {
180
        if($keys !== false)
181
        {
182
            $count = count($nonMembers);
183 View Code Duplication
            for($i = 0; $i < $count; $i++)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
184
            {
185
                $tmp = json_decode(json_encode($nonMembers[$i]), true);
186
                $tmp['type'] = $this->getTypeOfEntity($nonMembers[$i]);
187
                $nonMembers[$i] = array_intersect_key($tmp, $keys);
188
            }
189
        }
190
        return $nonMembers;
191
    }
192
193
    public function getNonMembers($request, $response, $args)
194
    {
195
        $this->validateIsAdmin($request);
196
        $odata = $request->getAttribute('odata', new \ODataParams(array()));
197
        $keys = false;
198
        if($odata->select !== false)
199
        {
200
            $keys = array_flip($odata->select);
201
        }
202
        $auth = AuthProvider::getInstance();
203
        if($args['name'] === 'none')
204
        {
205
            $res = $this->getAllGroupsAndUsers($keys);
206
            return $response->withJson($res);
207
        }
208
        $group = $auth->getGroupByName($args['name']);
209
        if($group === false)
210
        {
211
            return $response->withStatus(404);
212
        }
213
        $res = $group->getNonMembers($odata->select);
214
        $res = $this->getNonMemberEntities($res, $keys);
215
        return $response->withJson($res);
216
    }
217
218
    public function updateGroup($request, $response, $args)
219
    {
220
        $this->validateIsAdmin($request);
221
        $auth = AuthProvider::getInstance();
222
        $group = $auth->getGroupByName($args['name']);
223
        if($group === false)
224
        {
225
            return $response->withStatus(404);
226
        }
227
        $obj = $request->getParsedBody();
228
        $ret = $group->editGroup($obj);
229
        return $response->withJson($ret);
230
    }
231
}
232
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
233