ImportStockistsTask::deleteAll()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 4
nc 2
nop 0
1
<?php
2
3
4
/**
5
 * allows the creation of stockists from a CSV
6
 * data should be formatted in CSV like this:
7
 *
8
 * NAME (name of stockist)
9
 * COUNTRY - New Zealand
10
 * COUNTRYCODE - e.g. NZ, AU, US
11
 * TYPE (retailler / agent)
12
 * CITY - e.g. Amsterdam
13
 * WEB - e.g. http://www.mysite.co.nz
14
 * EMAIL
15
 * PHONE e.g. +31 33323321
16
 * ADDRESS
17
 * PHYSICAL (YES / NO)
18
 * ONLINE (YES / NO)
19
20
 */
21
22
class ImportStockistsTask extends BuildTask
23
{
24
    protected $title = "Import all the stockists and link countries";
25
26
    protected $description = "
27
        Does not delete any record, it only updates and adds.
28
        ";
29
30
    /**
31
     * excluding base folder
32
     *
33
     * e.g. assets/files/mycsv.csv
34
     * @var String
35
     */
36
    protected $fileLocation = "_dev/_data/stockists.csv";
37
38
    /**
39
     * excluding base folder
40
     *
41
     * e.g. assets/files/mycsv.csv
42
     * @var String
43
     */
44
    protected $csvSeparator = ",";
45
46
47
    /**
48
     * @var Boolean
49
     */
50
    protected $debug = true;
51
52
53
    /**
54
     * the original data from the CVS
55
     * @var Array
56
     */
57
    protected $csv = array();
58
59
    public function getDescription()
60
    {
61
        return $this->description ." The file to be used is: ".$this->fileLocation;
62
    }
63
64
    /**
65
     *
66
     */
67
    public function run($request)
68
    {
69
        increase_time_limit_to(3600);
70
        set_time_limit(3600);
71
        increase_memory_limit_to('1024M');
72
73
        $this->readFile();
74
75
        $this->deleteAll();
76
77
        $this->createStockists();
78
    }
79
80
    protected function readFile()
81
    {
82
        DB::alteration_message("================================================ READING FILE ".ini_get('max_execution_time')."seconds available. ".(ini_get('memory_limit'))."MB available ================================================");
83
        ob_start();
84
85
        $rowCount = 1;
86
        $rows = array();
87
        $fileLocation = Director::baseFolder()."/".$this->fileLocation;
88
        flush();
89
        ob_end_flush();
90
        DB::alteration_message("reading file $fileLocation", "deleted");
91
        ob_start();
92
        if (($handle = fopen($fileLocation, "r")) !== false) {
93
            while (($data = fgetcsv($handle, 100000, $this->csvSeparator)) !== false) {
94
                $cleanArray = array();
95
                foreach ($data as $key => $value) {
96
                    $cleanArray[trim($key)] = trim($value);
97
                }
98
                $rows[] = $cleanArray;
99
                $rowCount++;
100
            }
101
            fclose($handle);
102
        }
103
        //$rows = str_getcsv(file_get_contents(, ",", '"');
104
105
        $header = array_shift($rows);
106
107
        $this->csv = array();
108
        $rowCount = 1;
109
        foreach ($rows as $row) {
110
            if (count($header) != count($row)) {
111
                flush();
112
                ob_end_flush();
113
                DB::alteration_message("I am trying to merge ".implode(", ", $header)." with ".implode(", ", $row)." but the column count does not match!", "deleted");
114
                ob_start();
115
                die("STOPPED");
116
            }
117
            $this->csv[] = array_combine($header, $row);
118
            $rowCount++;
119
        }
120
        flush();
121
        ob_end_flush();
122
        DB::alteration_message("Imported ".count($this->csv)." rows with ".count($header)." cells each");
123
        ob_start();
124
        flush();
125
        ob_end_flush();
126
        DB::alteration_message("Fields are: ".implode(", ", $header));
127
        ob_start();
128
        flush();
129
        ob_end_flush();
130
        DB::alteration_message("================================================");
131
        ob_start();
132
    }
133
134
    /**
135
     *
136
     *
137
     */
138
    protected function createStockists()
139
    {
140
        flush();
141
        ob_end_flush();
142
        DB::alteration_message("================================================ CREATING STOCKISTS ================================================");
143
        ob_start();
144
        $stockistsCompleted = array();
0 ignored issues
show
Unused Code introduced by
$stockistsCompleted 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...
145
        $rootPage = StockistSearchPage::get()->filter(array("ClassName" => "ShopfinderPage"))->first();
146
        if (!$rootPage) {
147
            die("You must setup a stockist search page first");
148
        }
149
        flush();
150
        ob_end_flush();
151
        DB::alteration_message("<h2>Found Root Page: ".$rootPage->Title." (".$rootPage->ID.")</h2>");
152
        ob_start();
153
        $rowCount = 0;
154
        $continents = array();
0 ignored issues
show
Unused Code introduced by
$continents 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...
155
        $countryCheckArray = array();
156
        $types = array();
157
        foreach ($this->csv as $row) {
158
            $rowCount++;
159
            print_r($row);
160
            flush();
161
            ob_end_flush();
162
            DB::alteration_message("<h2>$rowCount: Creating stockist: ".$row["NAME"]."</h2>");
163
            ob_start();
164
165
            if (!isset($countryCheckArray[$row['COUNTRYCODE']])) {
166
                $countryPage = StockistCountryPage::get()
167
                    ->filter(array("CountryCode" => $row['COUNTRYCODE']))
168
                    ->first();
169
                $countryCheckArray[$row['COUNTRYCODE']] = $countryPage;
170
            } else {
171
                $countryPage = $countryCheckArray[$row['COUNTRYCODE']];
172
            }
173
174 View Code Duplication
            if (!$countryPage) {
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...
175
                $countryPage = new StockistCountryPage();
176
                flush();
177
                ob_end_flush();
178
                DB::alteration_message(" --- Creating new country page page ".$row['COUNTRYCODE'], "created");
179
                ob_start();
180
            } else {
181
                flush();
182
                ob_end_flush();
183
                DB::alteration_message(" --- Existing country page ".$row['COUNTRYCODE'], "changed");
184
                ob_start();
185
            }
186
187
            $countryPage->Title = $row['COUNTRY'];
188
            $countryPage->MetaTitle = $row['COUNTRY'];
189
            $countryPage->MenuTitle = $row['COUNTRY'];
190
            $countryPage->URLSegment = $row['COUNTRY'];
191
            $countryPage->CountryCode = $row['COUNTRYCODE'];
192
            $countryPage->ParentID = $rootPage->ID;
193
            $countryPage->writeToStage("Stage");
194
            $countryPage->Publish('Stage', 'Live');
195
196
            //stockist page
197
            $stockistPage = StockistPage::get()->filter(array("Title" => $row["NAME"]))->first();
198 View Code Duplication
            if (!$stockistPage) {
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...
199
                $stockistPage = new StockistPage();
200
                flush();
201
                ob_end_flush();
202
                DB::alteration_message(" --- Creating Stockist: ".$row["NAME"], "created");
203
                ob_start();
204
            } else {
205
                flush();
206
                ob_end_flush();
207
                DB::alteration_message(" --- Updating Stockist: ".$row["NAME"], "changed");
208
                ob_start();
209
            }
210
            $name = trim($row["NAME"]);
211
            $stockistPage->ParentID = $countryPage->ID;
212
            $stockistPage->Title = $name;
213
            $stockistPage->MenuTitle = $name;
214
            $stockistPage->URLSegment = $name;
215
            $stockistPage->Address = trim($row["ADDRESS"]);
216
217
            $stockistPage->Phone = trim($row["PHONE"]);
218
            $stockistPage->City = trim($row["CITY"]);
219
            $stockistPage->HasPhysicalStore =  1;
220
            $stockistPage->writeToStage('Stage');
221
            $stockistPage->Publish('Stage', 'Live');
222
223
            //types
224
225
            $type = "Retailer";
226
227
            flush();
228
            ob_end_flush();
229
            DB::alteration_message(" --- Adding type: ".$type, "changed");
230
            ob_start();
231
232
            if (!isset($types[$type])) {
233
                $typeObject = StockistPage_Type::get()->filter(array("Type" => $type))->first();
234
                $types[$type] = $typeObject;
235
            } else {
236
                $typeObject = $types[$type];
0 ignored issues
show
Unused Code introduced by
$typeObject 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...
237
            }
238
        }
239
        flush();
240
        ob_end_flush();
241
        DB::alteration_message("====================== END ==========================");
242
        ob_start();
243
    }
244
245
    protected function deleteAll()
246
    {
247
        if (isset($_GET["reset"]) || isset($_GET["resetonly"])) {
248
            die("you have to manually remove this message to run ...");
249
            DB::alteration_message("Deleting all pages!", "deleted");
0 ignored issues
show
Unused Code introduced by
\DB::alteration_message(...ll pages!', 'deleted'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
250
            $pages = SiteTree::get()->filter(array("ClassName" => array("StockistCountryPage", "StockistPage", "StockistSearchPage")));
251
            foreach ($pages as $page) {
252
                $page->deleteFromStage('Live');
253
                $page->deleteFromStage('Draft');
254
                $page->delete();
255
            }
256
        }
257
    }
258
}
259