PermissionProviderFactory::CreateGroup()   F
last analyzed

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 200

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 200
rs 0
c 0
b 0
f 0
cc 38
nc 4730880
nop 7

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
class PermissionProviderFactory extends Object
0 ignored issues
show
Coding Style Compatibility introduced by Sunny Side Up
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
5
{
6
    private static $_instance = null;
7
8
    public static function inst()
9
    {
10
        if (self::$_instance === null) {
11
            self::$_instance = Injector::inst()->get('PermissionProviderFactory');
12
        }
13
14
        return self::$_instance;
15
    }
16
17
    protected $email = '';
18
    protected $firstName = '';
19
    protected $surname = '';
20
    protected $password = '';
21
    protected $code = '';
22
    protected $name = '';
23
    protected $parentGroup = null;
24
    protected $permissionCode = '';
25
    protected $roleTitle = '';
26
    protected $permissionArray = [];
27
    protected $member = null;
28
29
    public function setEmail($email)
30
    {
31
        $this->email = $email;
32
        return $this;
33
    }
34
    public function setFirstName($firstName)
35
    {
36
        $this->firstName = $firstName;
37
38
        return $this;
39
    }
40
    public function setSurname($surname)
41
    {
42
        $this->surname = $surname;
43
44
        return $this;
45
    }
46
    public function setPassword($password)
47
    {
48
        $this->password = $password;
49
50
        return $this;
51
    }
52
    public function setCode($code)
53
    {
54
        $this->code = $code;
55
56
        return $this;
57
    }
58
    public function setName($name)
59
    {
60
        $this->name = $name;
61
62
        return $this;
63
    }
64
    public function setParentGroup($parentGroup)
65
    {
66
        $this->parentGroup = $parentGroup;
67
68
        return $this;
69
    }
70
    public function setPermissionCode($permissionCode)
71
    {
72
        $this->permissionCode = $permissionCode;
73
74
        return $this;
75
    }
76
    public function setRoleTitle($roleTitle)
77
    {
78
        $this->roleTitle = $roleTitle;
79
80
        return $this;
81
    }
82
    public function setPermissionArray($permissionArray)
83
    {
84
        $this->permissionArray = $permissionArray;
85
86
        return $this;
87
    }
88
    public function setMember($member)
89
    {
90
        $this->member = $member;
91
92
        return $this;
93
    }
94
95
    /**
96
     *
97
     * @return Group and member, using the default settings
98
     */
99
    public function CreateGroupAndMember()
100
    {
101
        $member = $this->CreateDefaultMember(
102
            $this->email,
103
            $this->firstName,
104
            $this->surname,
105
            $this->password
106
        );
107
        $group = $this->CreateGroup(
108
            $this->code,
109
            $this->name,
110
            $this->parentGroup,
111
            $this->permissionCode,
112
            $this->roleTitle,
113
            $this->permissionArray,
114
            $member
115
        );
116
117
        return $group;
118
    }
119
120
121
    /**
122
     * Create a member
123
     * @param       string $email
124
     * @param       string $firstName   OPTIONAL
125
     * @param       string $surname     OPTIONAL
126
     * @param       string $password    OPTIONAL
127
     *
128
     * @return Member
129
     */
130
    public function CreateDefaultMember(
131
        $email,
132
        $firstName = '',
133
        $surname = '',
134
        $password = ''
135
    ) {
136
        if (! $email) {
137
            $email = $this->email;
138
        }
139
        if (! $firstName) {
140
            $firstName = $this->firstName;
141
        }
142
        if (! $surname) {
143
            $surname = $this->surname;
144
        }
145
        if (! $password) {
146
            $password = $this->password;
147
        }
148
149
        if (! $email) {
150
            $baseURL = Director::absoluteBaseURL();
151
            $baseURL = str_replace('https://', '', $baseURL);
152
            $baseURL = str_replace('http://', '', $baseURL);
153
            $baseURL = trim($baseURL, '/');
154
            $email = 'random.email.'.rand(0, 999999).'@'.$baseURL;
155
        }
156
        if (! $firstName) {
157
            $firstName = 'Default';
158
        }
159
        if (! $surname) {
160
            $surname = 'User';
161
        }
162
163
        $filter = array('Email' => $email);
164
        $member = DataObject::get_one(
165
            'Member',
166
            $filter,
167
            $cacheDataObjectGetOne = false
168
        );
169
        if (! $member) {
170
            $member = Member::create($filter);
171
        }
172
173
        $member->FirstName = $firstName;
174
        $member->Surname = $surname;
175
        $member->write();
176
        if ($password) {
177
            $member->changePassword($password);
178
            $member->PasswordExpiry = date('Y-m-d');
179
            $member->write();
180
        }
181
182
        return $member;
183
    }
184
185
    /**
186
     * set up a group with permissions, roles, etc...
187
     * also note that this class implements PermissionProvider.
188
     *
189
     * @param string          $code            code for the group - will always be converted to lowercase
190
     * @param string          $name            title for the group
191
     * @param Group | String  $parentGroup     group object that is the parent of the group. You can also provide a string (name / title of group)
192
     * @param string          $permissionCode  Permission Code for the group (e.g. CMS_DO_THIS_OR_THAT)
193
     * @param string          $roleTitle       Role Title - e.g. Store Manager
194
     * @param array           $permissionArray Permission Array - list of permission codes applied to the group
195
     * @param Member | String $member          Default Member added to the group (e.g. [email protected]). You can also provide an email address
196
     */
197
    public function CreateGroup(
0 ignored issues
show
Documentation introduced by Nicolaas
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
198
        $code = '',
199
        $name,
0 ignored issues
show
Coding Style introduced by Nicolaas
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
200
        $parentGroup = null,
201
        $permissionCode = '',
202
        $roleTitle = '',
203
        array $permissionArray = [],
204
        $member = null
205
    ) {
206
        if (! $name) {
207
            $name = $this->name;
208
        }
209
        if (! $code) {
210
            $code = $this->code;
211
        }
212
        if (! $parentGroup) {
213
            $parentGroup = $this->parentGroup;
214
        }
215
        if (! $permissionCode) {
216
            $permissionCode = $this->permissionCode;
217
        }
218
        if (! $permissionArray || count($permissionArray) === 0) {
0 ignored issues
show
Bug Best Practice introduced by Nicolaas Thiemen Francken @ B&C
The expression $permissionArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
219
            $permissionArray = $this->permissionArray;
220
        }
221
        if (! $member) {
222
            $member = $this->member;
223
        }
224
        if (!$name) {
225
            $name = 'New Group '.rand(0, 999999);
226
        }
227
        if (!$code) {
228
            $code = $name;
229
        }
230
        $code = str_replace(' ', '_', $code);
231
        $code = preg_replace("/[\W_]+/u", '', $code);
232
        //changing to lower case seems to be very important
233
        //unidentified bug so far
234
        $code = strtolower($code);
235
236
        $filterArrayForGroup = array('Code' => $code);
237
        $groupDataList = Group::get()->filter($filterArrayForGroup);
238
        $groupCount = $groupDataList->count();
239
        $groupStyle = 'updated';
240
        if ($groupCount > 1) {
241
            user_error("There is more than one group with the $name ($code) Code");
242
        }
243
        if ($groupCount == 0) {
244
            $group = Group::create($filterArrayForGroup);
245
            $groupStyle = 'created';
246
        } else {
247
            $group = $groupDataList->First();
248
        }
249
        $group->Locked = 1;
250
        $group->Title = $name;
251
        $parentGroupStyle = 'updated';
0 ignored issues
show
Unused Code introduced by Sunny Side Up
$parentGroupStyle 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...
252
        if ($parentGroup) {
253
            DB::alteration_message('adding parent group');
254
            if (is_string($parentGroup)) {
255
                $parentGroupName = $parentGroup;
256
                $parentGroup = DataObject::get_one(
257
                    'Group',
258
                    array('Title' => $parentGroupName),
259
                    $cacheDataObjectGetOne = false
260
                );
261
                if (!$parentGroup) {
262
                    $parentGroup = Group::create();
263
                    $parentGroupStyle = 'created';
264
                    $parentGroup->Title = $parentGroupName;
265
                    $parentGroup->write();
266
                    DB::alteration_message("$parentGroupStyle $parentGroupName", $parentGroupStyle);
267
                }
268
            }
269
            if ($parentGroup) {
270
                $group->ParentID = $parentGroup->ID;
271
            }
272
        }
273
        $group->write();
274
        DB::alteration_message("$groupStyle $name ($code) group", $groupStyle);
275
        $doubleGroups = Group::get()
276
            ->filter(array('Code' => $code))
277
            ->exclude(array('ID' => $group->ID));
278
        if ($doubleGroups->count()) {
279
            DB::alteration_message($doubleGroups->count().' groups with the same name', 'deleted');
280
            $realMembers = $group->Members();
281
            foreach ($doubleGroups as $doubleGroup) {
282
                $fakeMembers = $doubleGroup->Members();
283
                foreach ($fakeMembers as $fakeMember) {
284
                    DB::alteration_message('adding customers: '.$fakeMember->Email, 'created');
285
                    $realMembers->add($fakeMember);
286
                }
287
                DB::alteration_message('deleting double group ', 'deleted');
288
                $doubleGroup->delete();
289
            }
290
        }
291
        if ($permissionCode) {
292
            $permissionCodeCount = DB::query("SELECT * FROM \"Permission\" WHERE \"GroupID\" = '".$group->ID."' AND \"Code\" LIKE '".$permissionCode."'")->numRecords();
293
            if ($permissionCodeCount == 0) {
294
                DB::alteration_message('granting '.$name." permission code $permissionCode ", 'created');
295
                Permission::grant($group->ID, $permissionCode);
296
            } else {
297
                DB::alteration_message($name." permission code $permissionCode already granted");
298
            }
299
        }
300
        //we unset it here to avoid confusion with the
301
        //other codes we use later on
302
        $permissionArray[] = $permissionCode;
303
        unset($permissionCode);
304
        if ($roleTitle) {
305
            $permissionRoleCount = PermissionRole::get()
306
                ->Filter(array('Title' => $roleTitle))
307
                ->Count();
308
            if ($permissionRoleCount > 1) {
309
                db::alteration_message("There is more than one Permission Role with title $roleTitle ($permissionRoleCount)", 'deleted');
310
                $permissionRolesFirst = DataObject::get_one(
311
                    'PermissionRole',
312
                    array('Title' => $roleTitle),
313
                    $cacheDataObjectGetOne = false
314
                );
315
                $permissionRolesToDelete = PermissionRole::get()
316
                    ->Filter(array('Title' => $roleTitle))
317
                    ->Exclude(array('ID' => $permissionRolesFirst->ID));
318
                foreach ($permissionRolesToDelete as $permissionRoleToDelete) {
319
                    db::alteration_message("DELETING double permission role $roleTitle", 'deleted');
320
                    $permissionRoleToDelete->delete();
321
                }
322
            } elseif ($permissionRoleCount == 1) {
323
                //do nothing
324
                DB::alteration_message("$roleTitle role in place");
325
            } else {
326
                DB::alteration_message("adding $roleTitle role", 'created');
327
                $permissionRole = PermissionRole::create();
328
                $permissionRole->Title = $roleTitle;
329
                $permissionRole->OnlyAdminCanApply = true;
330
                $permissionRole->write();
331
            }
332
            $permissionRole = DataObject::get_one(
333
                'PermissionRole',
334
                array('Title' => $roleTitle),
335
                $cacheDataObjectGetOne = false
336
            );
337
            if ($permissionRole) {
338
                if (is_array($permissionArray) && count($permissionArray)) {
339
                    DB::alteration_message('working with '.implode(', ', $permissionArray));
340
                    foreach ($permissionArray as $permissionRoleCode) {
341
                        $permissionRoleCodeObject = DataObject::get_one(
342
                            'PermissionRoleCode',
343
                            array('Code' => $permissionRoleCode, 'RoleID' => $permissionRole->ID),
344
                            $cacheDataObjectGetOne = false
345
                        );
346
                        $permissionRoleCodeObjectCount = PermissionRoleCode::get()
347
                            ->Filter(array('Code' => $permissionRoleCode, 'RoleID' => $permissionRole->ID))
348
                            ->Count();
349
                        if ($permissionRoleCodeObjectCount > 1) {
350
                            $permissionRoleCodeObjectsToDelete = PermissionRoleCode::get()
351
                                ->Filter(array('Code' => $permissionRoleCode, 'RoleID' => $permissionRole->ID))
352
                                ->Exclude(array('ID' => $permissionRoleCodeObject->ID));
353
                            foreach ($permissionRoleCodeObjectsToDelete as $permissionRoleCodeObjectToDelete) {
354
                                db::alteration_message("DELETING double permission code $permissionRoleCode for ".$permissionRole->Title, 'deleted');
355
                                $permissionRoleCodeObjectToDelete->delete();
356
                            }
357
                            db::alteration_message('There is more than one Permission Role Code in '.$permissionRole->Title." with Code = $permissionRoleCode ($permissionRoleCodeObjectCount)", 'deleted');
358
                        } elseif ($permissionRoleCodeObjectCount == 1) {
0 ignored issues
show
Unused Code introduced by Nicolaas
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
359
                            //do nothing
360
                        } else {
361
                            $permissionRoleCodeObject = PermissionRoleCode::create();
362
                            $permissionRoleCodeObject->Code = $permissionRoleCode;
363
                            $permissionRoleCodeObject->RoleID = $permissionRole->ID;
364
                        }
365
                        DB::alteration_message('adding '.$permissionRoleCodeObject->Code.' to '.$permissionRole->Title);
366
                        $permissionRoleCodeObject->write();
367
                    }
368
                }
369
                if ($group && $permissionRole) {
370
                    if (DB::query('SELECT COUNT(*) FROM Group_Roles WHERE GroupID = '.$group->ID.' AND PermissionRoleID = '.$permissionRole->ID)->value() == 0) {
371
                        db::alteration_message('ADDING '.$permissionRole->Title.' permission role  to '.$group->Title.' group', 'created');
372
                        $existingGroups = $permissionRole->Groups();
373
                        $existingGroups->add($group);
374
                    } else {
375
                        db::alteration_message('CHECKED '.$permissionRole->Title.' permission role  to '.$group->Title.' group');
376
                    }
377
                } else {
378
                    db::alteration_message('ERROR: missing group or permissionRole', 'deleted');
379
                }
380
            }
381
        }
382
        if ($member) {
383
            if (is_string($member)) {
384
                $email = $member;
385
                $member = $this->CreateDefaultMember($email, $code, $name);
386
            }
387
            if ($member) {
388
                DB::alteration_message(' adding member '.$member->Email.' to group '.$group->Title, 'created');
389
                $member->Groups()->add($group);
390
            }
391
        } else {
392
            DB::alteration_message('No user provided.');
393
        }
394
395
        return $group;
396
    }
397
}
398