ImportModulesTask   C
last analyzed

Complexity

Total Complexity 60

Size/Duplication

Total Lines 328
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 60
lcom 1
cbo 12
dl 0
loc 328
c 0
b 0
f 0
rs 6.0975

13 Methods

Rating   Name   Duplication   Size   Complexity  
A get_parent_url_segment() 0 4 1
A set_parent_url_segment() 0 4 1
A get_data_source() 0 4 1
A set_data_source() 0 4 1
A getTitle() 0 4 1
A getDescription() 0 4 1
A run() 0 7 1
A cleantags() 0 4 1
B importmodules() 0 39 4
A createAuthorGroup() 0 16 3
F makeModules() 0 179 35
A sortPagesAlphabetically() 0 17 3
C deleteobsoletemoduleowners() 0 27 7

How to fix   Complexity   

Complex Class

Complex classes like ImportModulesTask 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 ImportModulesTask, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
4
5
class ImportModulesTask extends BuildTask
0 ignored issues
show
Coding Style Compatibility introduced by
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...
6
{
7
    private static $parent_url_segment = "new-modules";
8
    public function get_parent_url_segment()
9
    {
10
        return self::$parent_url_segment;
11
    }
12
    public function set_parent_url_segment($s)
13
    {
14
        self::$parent_url_segment = $s;
15
    }
16
17
    private static $data_source = "/mysite/data/modules.csv";
18
    public function get_data_source()
19
    {
20
        return self::$data_source;
21
    }
22
    public function set_data_source($s)
23
    {
24
        self::$data_source = $s;
25
    }
26
27
    public function getTitle()
28
    {
29
        return "Import modules from csv";
30
    }
31
32
    public function getDescription()
33
    {
34
        return "Opens the local csv file and imports all the modules";
35
    }
36
37
    public function run($request)
38
    {
39
        $this->createAuthorGroup();
40
        $this->importmodules();
41
        $this->sortPagesAlphabetically();
42
        return "BBBBBBBBBBBBBBB";
43
    }
44
45
    public function cleantags()
46
    {
47
        DB::query("DELETE FROM \"EcommerceProductTag\" WHERE TRIM(Title) = '' OR TRIM(Code) = '' OR Title IS NULL or Code IS NULL;");
48
    }
49
50
    public function importmodules()
51
    {
52
        $rowPosition = 1;
53
        $fields = array(
54
            0 => "ImportID",
55
            1 => "ScreenName",
56
            2 => "Email",
57
            3 => "GithubURL",
58
            4 => "SilverstripeDotOrgURL",
59
            5 => "CompanyName",
60
            6 => "CompanyURL",
61
            7 => "Code",
62
            8 => "Title",
63
            9=> "MainURL",
64
            10=> "ReadMeURL",
65
            11=> "DemoURL",
66
            12=> "SvnURL",
67
            13=> "GitURL",
68
            14=> "OtherURL",
69
            15=> "Tags",
70
            16=> "Description"
71
        );
72
        $fullArray = array();
73
        $file = Director::baseFolder().self::get_data_source();
74
        if (($handle = fopen($file, "r")) !== false) {
75
            while (($row = fgetcsv($handle)) !== false) {
76
                $numberOfFields = count($row);
77
                //echo "<p> $num fields in line $rowPosition: <br /></p>\n";
78
                $rowPosition++;
79
                for ($fieldPosition = 0; $fieldPosition < $numberOfFields; $fieldPosition++) {
80
                    $fullArray[$rowPosition][$fields[$fieldPosition]] = $row[$fieldPosition];
81
                    //echo $fields[$fieldPosition]." = ".$row[$fieldPosition] . "<br />\n";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
82
                }
83
            }
84
            fclose($handle);
85
        }
86
        $this->makeModules($fullArray);
87
        return $fullArray;
88
    }
89
90
    private function createAuthorGroup()
91
    {
92
        if (!$group = Group::get()
93
            ->filter(array("Code" => Config::inst()->get("SoftwareAuthorMemberDOD", "register_group_code")))
94
            ->first()
95
        ) {
96
            $group = new Group();
97
            $group->Code = SoftwareAuthorMemberDOD::get_register_group_code();
98
            $group->Title = SoftwareAuthorMemberDOD::get_register_group_title();
99
            $group->write();
100
            Permission::grant($group->ID, SoftwareAuthorMemberDOD::get_register_group_access_key());
101
            DB::alteration_message("GROUP: ".SoftwareAuthorMemberDOD::get_register_group_code().' ('.SoftwareAuthorMemberDOD::get_register_group_title().')', "created");
102
        } elseif (DB::query("SELECT * FROM Permission WHERE GroupID = ".$group->ID." AND Code = '".SoftwareAuthorMemberDOD::get_register_group_access_key()."'")->numRecords() == 0) {
103
            Permission::grant($group->ID, SoftwareAuthorMemberDOD::get_register_group_access_key());
104
        }
105
    }
106
107
    private function makeModules($rows)
108
    {
109
        increase_time_limit_to(600);
110
        DB::query("DELETE FROM \"EcommerceProductTag\" WHERE TRIM(Title) = '';");
111
        $parent = ModuleProductGroup::get()
112
            ->filter(array("URLSegment" => self::$parent_url_segment))
113
            ->first();
114
        if ($parent) {
115
            $parentID = $parent->ID;
116
            unset($parent);
117
        } else {
118
            $parentID = 0;
119
        }
120
        $group = Group::get()
121
            ->filter(array("Code" => SoftwareAuthorMemberDOD::get_register_group_code()))
122
            ->first();
123
        if (!$group) {
124
            user_error("Group for authors could not be found!");
125
        }
126
        if ($parentID) {
127
            if ($rows) {
128
                foreach ($rows as $row) {
129
                    $new = null;
0 ignored issues
show
Unused Code introduced by
$new 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...
130
                    $ImportID = intval($row["ImportID"]);
131
                    if ($ImportID) {
132
                        $ScreenName = Convert::raw2sql($row["ScreenName"]);
133
                        $Email = Convert::raw2sql($row["Email"]);
134
                        $GithubURL = Convert::raw2sql($row["GithubURL"]);
135
                        $SilverstripeDotOrgURL = Convert::raw2sql($row["SilverstripeDotOrgURL"]);
136
                        $CompanyName = Convert::raw2sql($row["CompanyName"]);
137
                        $CompanyURL = Convert::raw2sql($row["CompanyURL"]);
138
                        $Code = Convert::raw2sql($row["Code"]);
139
                        $Title = Convert::raw2sql($row["Title"]);
140
                        $MainURL = Convert::raw2sql($row["MainURL"]);
141
                        $ReadMeURL = Convert::raw2sql($row["ReadMeURL"]);
142
                        $DemoURL = Convert::raw2sql($row["DemoURL"]);
143
                        $SvnURL = Convert::raw2sql($row["SvnURL"]);
144
                        $GitURL = Convert::raw2sql($row["GitURL"]);
145
                        $OtherURL = Convert::raw2sql($row["OtherURL"]);
146
                        $Tags =  Convert::raw2sql($row["Tags"]);
147
                        $Description =  Convert::raw2sql($row["Description"]);
148
                        $page = ModuleProduct::get()
149
                            ->filter(array("ImportID" => $ImportID))
150
                            ->first();
151
                        if (!$page) {
152
                            $new = true;
153
                            $page = new ModuleProduct();
154
                        } else {
155
                            $new = false;
156
                        }
157
                        if ($new == false && isset($page->ParentID) && $page->ParentID  && $page->ParentID > 0 && $page->ParentID != $parentID) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if 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 if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
158
                            //do nothing
159
                        } else {
160
                            if (!$new) {
161
                                DB::query("DELETE FROM \"EcommerceProductTag_Products\" WHERE ProductID = ".$page->ID);
162
                            }
163
                            if ($Title && $Code) {
164
                                $member = null;
165
                                //member
166
                                if ($ScreenName) {
167
                                    $member = Member::get()
168
                                        ->filter(array("ScreenName" => $ScreenName))
169
                                        ->first();
170
                                }
171
                                $identifierField = Member::get_unique_identifier_field();
0 ignored issues
show
Deprecated Code introduced by
The method Member::get_unique_identifier_field() has been deprecated with message: 4.0 Use the "Member.unique_identifier_field" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
172
                                if (!$member) {
173
                                    $member = Member::get()
174
                                        ->filter(array($identifierField, $Email));
175
                                }
176
                                if ($member) {
177
                                    $i = 0;
178
                                    while ($replaceMember = Member::get()
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $replaceMember = (\Membe...first() && $i < 100000), Probably Intended Meaning: ($replaceMember = \Membe...first()) && $i < 100000
Loading history...
179
                                    ->filter(array($identifierField => $Email))
180
                                    ->exclude("ID", $member->ID)
181
                                    ->first()
182
                                    && $i < 100000
183
                                ) {
184
                                        if ($replaceMember) {
185
                                            $i++;
186
                                            $member = $replaceMember;
187
                                            $Email = $Email."_DOUBLE_$i";
188
                                        }
189
                                    }
190
                                }
191
                                if (!$member) {
192
                                    $member = new Member();
193
                                }
194
                                if ($ScreenName) {
195
                                    $member->ScreenName = $ScreenName;
196
                                    $member->Email = $Email;
197
                                    $member->GithubURL = $GithubURL;
198
                                    $member->SilverstripeDotOrgURL = $SilverstripeDotOrgURL;
199
                                    $member->CompanyName = $CompanyName;
200
                                    $member->CompanyURL = $CompanyURL;
201
                                    if (!$member->Password) {
202
                                        $member->Password = Member::create_new_password();
203
                                    }
204
                                    $member->write();
0 ignored issues
show
Bug introduced by
The method write does only exist in DataObject, but not in DataList.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
205
                                    $member->Groups()->add($group);
206
                                } else {
207
                                    DB::alteration_message("no screen name provided for <b>$Title</b>", "deleted");
208
                                }
209
                                //page
210
                                $page->ImportID = $ImportID;
211
                                $page->ParentID = $parentID;
212
                                $page->ShowInSearch = 1;
213
                                $page->ShowInMenus = 1;
214
                                $page->Title = $Title;
215
                                $page->MenuTitle = $Title;
216
                                $page->MetaDescription = strip_tags($Description);
217
                                $page->Code = $Code;
218
                                $page->InternalItemID = $Code;
219
                                $page->URLSegment = $Code;
220
                                $page->ProvideComments = true;
221
222
                                $page->MainURL = $MainURL;
223
                                $page->ReadMeURL = $ReadMeURL;
224
                                $page->DemoURL= $DemoURL;
225
                                $page->SvnURL = $SvnURL;
226
                                $page->GitURL = $GitURL;
227
                                $page->OtherURL = $OtherURL;
228
229
                                $page->writeToStage('Stage');
230
                                $page->Publish('Stage', 'Live');
231
                                $page->Status = "Published";
232
                                $tagsArray = explode(",", $Tags);
233
                                if ($tagsArray && count($tagsArray)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tagsArray 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...
234
                                    foreach ($tagsArray as $tag) {
235
                                        $tag = Convert::raw2sql(trim($tag));
236
                                        if ($tag) {
237
                                            $tagObject = EcommerceProductTag::get()
238
                                                ->filter(array("Title" => $tag))
239
                                                ->First();
240
                                            if (!$tagObject) {
241
                                                $tagObject = EcommerceProductTag::get()
242
                                                    ->filter(array("Synonyms:PartialMatch" => $tag))
243
                                                    ->first();
244
                                            }
245
                                            if (!$tagObject) {
246
                                                $tagObject = new EcommerceProductTag();
247
                                                $tagObject->Title = $tag;
248
                                                $tagObject->write();
249
                                            }
250
                                            $existingTags = $page->EcommerceProductTags();
251
                                            $existingTags->add($tagObject);
252
                                        }
253
                                    }
254
                                }
255
                                if ($member) {
256
                                    DB::query("DELETE FROM \"ModuleProduct_Authors\" WHERE \"ModuleProductID\" = ".$page->ID." AND MemberID <> ".$member->ID);
257
                                    $existingAuthors = $page->Authors();
258
                                    $existingAuthors->add($member);
259
                                } else {
260
                                    DB::alteration_message("no member for  <b>$Title</b>", "deleted");
261
                                }
262
                                if ($new === true) {
263
                                    DB::alteration_message("added <b>$Title</b>", "created");
264
                                } elseif ($new === false) {
265
                                    DB::alteration_message("updated <b>$Title</b>", "edited");
266
                                } elseif ($new === null) {
267
                                    DB::alteration_message("error updating <b>$Title</b>", "deleted");
268
                                } else {
269
                                    DB::alteration_message("BIG error updating <b>$Title</b>", "deleted");
270
                                }
271
                            } else {
272
                                DB::alteration_message("row found without title or code", "deleted");
273
                            }
274
                        }
275
                    } else {
276
                        DB::alteration_message("row found without import id", "deleted");
277
                    }
278
                }
279
            } else {
280
                DB::alteration_message("no data found", "deleted");
281
            }
282
        } else {
283
            DB::alteration_message("no parent group page found (a ModuleProductGroup with new-modules as URL Segment", "deleted");
284
        }
285
    }
286
287
    private function sortPagesAlphabetically()
288
    {
289
        $parent = ModuleProductGroup::get()
290
            ->filter(array("URLSegment" => self::$parent_url_segment))
291
            ->first();
292
        if ($parent) {
293
            $pages = ModuleProduct::get()
294
                ->filter(array("ParentID" => $parent->ID))
295
                ->sort("Title", "ASC");
296
            $i = 0;
297
            foreach ($pages as $page) {
298
                $i++;
299
                DB::query("Update \"SiteTree\"      SET \"Sort\" = $i WHERE \"ID\" = ".$page->ID);
300
                DB::query("Update \"SiteTree_Live\" SET \"Sort\" = $i WHERE \"ID\" = ".$page->ID);
301
            }
302
        }
303
    }
304
305
    public function deleteobsoletemoduleowners($request = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
306
    {
307
        $group = Group::get()
308
            ->filter(array("Code" => SoftwareAuthorMemberDOD::get_register_group_code()))
309
            ->first();
310
        if ($group) {
311
            $members = $group->Members();
312
            if ($members) {
313
                foreach ($members as $member) {
314
                    if ($member->ModuleProducts() && $member->ModuleProducts()->count()) {
315
                        DB::alteration_message("The following member own modules so will not be deleted ...".$member->Email.": ".$member->Title, "created");
316
                    } else {
317
                        DB::alteration_message("The following member does not seem to have any module products ...".$member->Email.": ".$member->Title, "deleted");
318
                        if (!$member->inGroup("ADMIN")) {
319
                            $member->delete();
320
                        } else {
321
                            DB::alteration_message("The following member is an Admin so will not be deleted ...".$member->Email.": ".$member->Title, "created");
322
                        }
323
                    }
324
                }
325
            } else {
326
                DB::alteration_message("could not find members for group with code = ".self::get_register_group_code(), "deleted");
0 ignored issues
show
Bug introduced by
The method get_register_group_code() does not seem to exist on object<ImportModulesTask>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
327
            }
328
        } else {
329
            DB::alteration_message("could not find group with code = ".self::get_register_group_code(), "deleted");
0 ignored issues
show
Bug introduced by
The method get_register_group_code() does not seem to exist on object<ImportModulesTask>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
330
        }
331
    }
332
}
333
334
335
336
337
338
339
340
class ImportModulesTask_AdminDecorator extends Extension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
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...
341
{
342
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $allowed_actions 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...
343
        "importmodulestask" => true,
344
        "deleteobsoletemoduleowners" => true
345
    );
346
347
    public function updateEcommerceDevMenuMigrations($buildTasks)
348
    {
349
        $buildTasks[] = "importmodulestask";
350
        //$buildTasks[] = "deleteobsoletemoduleowners";
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
351
        return $buildTasks;
352
    }
353
354
355
    /**
356
     * executes build task: ImportModulesTask
357
     *
358
     */
359
    public function importmodulestask($request)
360
    {
361
        $buildTask = new ImportModulesTask($request);
0 ignored issues
show
Unused Code introduced by
The call to ImportModulesTask::__construct() has too many arguments starting with $request.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
362
        $buildTask->run($request);
363
        $this->owner->displayCompletionMessage($buildTask);
364
    }
365
366
367
    public function deleteobsoletemoduleowners()
368
    {
369
        $this->runTask("ImportModulesTask", $request);
0 ignored issues
show
Bug introduced by
The variable $request does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The method runTask() does not seem to exist on object<ImportModulesTask_AdminDecorator>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
370
    }
371
}
372