Completed
Push — master ( ce2dd0...10a6ac )
by Nicolaas
04:02
created

code/cms/dev/EcommerceDatabaseAdmin.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
4
/**
5
 * One stop shop for massaging e-commerce related data
6
 * AND running tests.
7
 *
8
 * You can customise this menu by "decorating" this class
9
 * and adding the method: "updateEcommerceDevMenu".
10
 *
11
 * Here is an example:
12
13
 <code php>
14
 <?php
15
16
 ####################### in mysite/code/tasks/MyMigration.php
17
18
 class MyMigration extends BuildTask {
19
20
 protected $title = "Mysite Database Fixes";
21
22
 protected $description = "General DB fixes";
23
24
 function run(SS_HTTPRequest $request) {
25
 DB::query("TRUNCATE TABLE MyUselessTable;");
26
 }
27
28
 }
29
30
 class MyMigration_EXT extends Extension {
31
32
 private static $allowed_actions = array(
33
 "mymigration" => true
34
 );
35
36
 //NOTE THAT updateEcommerceDevMenuConfig adds to Config options
37
 //but you can als have: updateEcommerceDevMenuDebugActions, or updateEcommerceDevMenuMaintenanceActions
38
 function updateEcommerceDevMenuConfig($buildTasks){
39
 $buildTasks[] = "mymigration";
40
 return $buildTasks;
41
 }
42
43
 function mymigration(SS_HTTPRequest $request){
44
 $this->owner->runTask("MyMigration", $request);
45
 }
46
47
 }
48
49
50
 ####################### in mysite/_config.php:
51
52
 Object::add_extension("EcommerceDatabaseAdmin", "MyMigration_EXT");
53
54
55
 </code>
56
57
 *
58
 * SECTIONS
59
 *
60
 * 0. check settings
61
 * 1. ecommerce setup (default records)
62
 * 2. data review
63
 * 3. regular maintance
64
 * 4. debug
65
 * 5. migration
66
 * 6. reset
67
 * 7. tests
68
 *
69
 * @todo: work out a standard "silent" option and a display option the "display" options shows all output when running it from ecommerce/dev/
70
 * We also have to work out an easy way to extend this.
71
 *
72
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
73
 * @package: ecommerce
74
 * @sub-package: cms
75
 * @inspiration: Silverstripe Ltd, Jeremy
76
 **/
77
class EcommerceDatabaseAdmin extends TaskRunner
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...
78
{
79
80
81
    //##############################
82
    // BASIC FUNCTIONS
83
    //##############################
84
85
    public function index()
86
    {
87
        if (Director::is_cli()) {
88
            echo "SILVERSTRIPE ECOMMERCE TOOLS: Tasks\n--------------------------\n\n";
89
            foreach ($tasks as $task) {
0 ignored issues
show
The variable $tasks 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...
90
                echo " * $task[title]: sake dev/tasks/".$task['class']."\n";
91
            }
92
        } else {
93
            $renderer = new DebugView_EcommerceDatabaseAdmin();
94
            $renderer->writeHeader();
95
            $renderer->writeInfo('SilverStripe Ecommerce Tools', Director::absoluteBaseURL());
96
            $renderer->writeContent($this);
97
            $renderer->writeFooter();
98
        }
99
    }
100
101
    /**
102
     * standard, required method.
103
     *
104
     * @param string $action
0 ignored issues
show
Should the type for parameter $action not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
105
     *
106
     * @return string link for the "Controller"
107
     */
108
    public function Link($action = null)
109
    {
110
        return Controller::join_links(
111
            Director::BaseURL(),
112
            'dev/ecommerce/',
113
            $action
114
        );
115
    }
116
117
    //##############################
118
    // 0. OVERALL CONFIG
119
    //##############################
120
121
    /**
122
     * List of overall configuration BuildTasks.
123
     *
124
     * @var array
125
     */
126
    protected $overallconfig = array(
127
        'ecommercetaskcheckconfiguration',
128
        'ecommercetaskapiandmore',
129
    );
130
131
    /**
132
     * list of config tasks.
133
     *
134
     * @return ArrayList
135
     */
136
    public function OverallConfig()
137
    {
138
        return $this->createMenuDOSFromArray($this->overallconfig, $type = 'Config');
139
    }
140
141
    //##############################
142
    // 1. ECOMMERCE SETUP (DEFAULT RECORDS)
143
    //##############################
144
145
    /**
146
     * List of setup BuildTasks.
147
     *
148
     * @var array
149
     */
150
    protected $ecommerceSetup = array(
151
        'ecommercetasksetorderidstartingnumber',
152
        'ecommercetaskcreatemembergroups',
153
        'ecommercetaskdefaultrecords',
154
        'ecommercetaskcountryandregion',
155
        'ecommercetaskcountryandregion_disallowallcountries',
156
        'ecommercetaskcountryandregion_allowallcountries',
157
        'ecommercetaskadddefaultproducts',
158
        'ecommercetasklinkproductwithimages',
159
    );
160
161
    /**
162
     * list of data setup tasks.
163
     *
164
     * @return ArrayList
165
     */
166
    public function EcommerceSetup()
167
    {
168
        return $this->createMenuDOSFromArray($this->ecommerceSetup, $type = 'EcommerceSetup');
169
    }
170
171
    //##############################
172
    // 2. DATA REVIEW MAINTENANCE
173
    //##############################
174
175
    /**
176
     * List of regular maintenance BuildTasks.
177
     *
178
     * @var array
179
     */
180
    protected $dataReview = array(
181
        'ecommercetaskreviewreports',
182
        'ecommercetaskreviewsearches',
183
        'ecommercetaskorderitemspercustomer'
184
    );
185
186
    /**
187
     * regular data cleanup tasks.
188
     *
189
     * @return ArrayList
190
     */
191
    public function DataReview()
192
    {
193
        return $this->createMenuDOSFromArray($this->dataReview, $type = 'DataReview');
194
    }
195
196
    //##############################
197
    // 3. REGULAR MAINTENANCE
198
    //##############################
199
200
    /**
201
     * List of regular maintenance BuildTasks.
202
     *
203
     * @var array
204
     */
205
    protected $regularMaintenance = array(
206
        'ecommercetaskcartcleanup',
207
        'ecommercetaskaddcustomerstocustomergroups',
208
        'ecommercetaskfixbrokenordersubmissiondata',
209
        'ecommercetaskcleanupproductfullsitetreesorting',
210
        'ecommercetaskproductvariationsfixes',
211
        'ecommercetaskproductimagereset',
212
        'ecommercetasktrytofinaliseorders',
213
        'ecommercetaskprocessorderqueue',
214
        'ecommercetaskarchiveallsubmittedorders',
215
        'ecommercetasklinkorderaddressesatbothends',
216
        'EcommerceTaskCleanupProducts'
217
    );
218
219
    /**
220
     * regular data cleanup tasks.
221
     *
222
     * @return ArrayList
223
     */
224
    public function RegularMaintenance()
225
    {
226
        return $this->createMenuDOSFromArray($this->regularMaintenance, $type = 'RegularMaintenance');
227
    }
228
229
    //##############################
230
    // 4. DEBUG ACTIONS
231
    //##############################
232
233
    /**
234
     * List of debug actions BuildTasks.
235
     *
236
     * @var array
237
     */
238
    protected $debugActions = array(
239
        'ecommercetasktemplatetest',
240
        'ecommercetaskcartmanipulation_current',
241
        'ecommercetaskcartmanipulation_debug',
242
        'ecommercetaskbuilding_model',
243
        'ecommercetaskbuilding_extending',
244
    );
245
246
    /**
247
     * list of data debug actions.
248
     *
249
     * @return ArrayList
250
     */
251
    public function DebugActions()
252
    {
253
        return $this->createMenuDOSFromArray($this->debugActions, $type = 'DebugActions');
254
    }
255
256
    //##############################
257
    // 5. MIGRATIONS
258
    //##############################
259
260
    /**
261
     * List of migration BuildTasks.
262
     *
263
     * @var array
264
     */
265
    protected $migrations = array(
266
        'ecommercetaskmigration',
267
        'ecommercetaskcheckconfiguration',
268
        'ecommercetasksetdefaultproductgroupvalues',
269
    );
270
271
    /**
272
     * list of migration tasks.
273
     *
274
     * @return ArrayList
275
     */
276
    public function Migrations()
277
    {
278
        return $this->createMenuDOSFromArray($this->migrations, $type = 'Migrations');
279
    }
280
281
    //##############################
282
    // 6. CRAZY SHIT
283
    //##############################
284
285
    /**
286
     * List of crazy shit BuildTasks.
287
     *
288
     * @var array
289
     */
290
    protected $crazyshit = array(
291
        'ecommercetaskdeleteallorders',
292
        'ecommercetaskdeleteproducts',
293
        'ecommercetaskarchiveallorderswithitems',
294
    );
295
296
    /**
297
     * list of crazy actions tasks.
298
     *
299
     * @return ArrayList
300
     */
301
    public function CrazyShit()
302
    {
303
        return $this->createMenuDOSFromArray($this->crazyshit, $type = 'CrazyShit');
304
    }
305
306
    //##############################
307
    // 7. TESTS
308
    //##############################
309
310
    /**
311
     * List of tests.
312
     *
313
     * @var array
314
     */
315
    protected $tests = array(
316
        //'ShoppingCartTest' => 'Shopping Cart'
317
    );
318
319
    public function Tests()
320
    {
321
        $arrayList = new ArrayList();
322
        foreach ($this->tests as $class => $name) {
323
            $arrayList->push(
324
                new ArrayData(
325
                    array(
326
                        'Name' => $name,
327
                        'Class' => $class,
328
                    )
329
                )
330
            );
331
        }
332
333
        return $arrayList;
334
    }
335
336
    /**
337
     * @return array ????
0 ignored issues
show
Should the return type not be string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
338
     */
339
    public function AllTests()
340
    {
341
        return implode(',', array_keys($this->tests));
342
    }
343
344
    //##############################
345
    // INTERNAL FUNCTIONS
346
    //##############################
347
348
    /**
349
     * @param array  $buildTasksArray array of build tasks
350
     * @param string $type
351
     *
352
     * @return ArrayList(ArrayData(Link, Title, Description))
0 ignored issues
show
The doc-type ArrayList(ArrayData(Link, could not be parsed: Expected "|" or "end of type", but got "(" at position 9. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
353
     */
354
    protected function createMenuDOSFromArray(array $buildTasksArray, $type = '')
355
    {
356
        $extendedArray = $this->extend('updateEcommerceDevMenu'.$type, $buildTasksArray);
357
        if ($extendedArray !== null && is_array($extendedArray) && count($extendedArray)) {
358
            foreach ($extendedArray as $extendedBuildTasks) {
359
                $buildTasksArray = array_merge($buildTasksArray, $extendedBuildTasks);
360
            }
361
        }
362
        $buildTasksArray = array_unique($buildTasksArray);
363
        $arrayList = new ArrayList();
364
        foreach ($buildTasksArray as $buildTask) {
365
            $obj = new $buildTask();
366
            $do = new ArrayData(
367
                array(
368
                    'Link' => $this->Link($buildTask),
369
                    'Title' => $obj->getTitle(),
370
                    'Description' => $obj->getDescription(),
371
                )
372
            );
373
            $arrayList->push($do);
374
        }
375
376
        return $arrayList;
377
    }
378
379
    public function runTask($request)
380
    {
381
        $taskName = $request->param('TaskName');
382
        $renderer = new DebugView_EcommerceDatabaseAdmin();
383
        $renderer->writeHeader();
384
        $renderer->writeInfo('SilverStripe Ecommerce Tools', Director::absoluteBaseURL());
385
        $renderer->writePreOutcome();
386
        if (class_exists($taskName) && is_subclass_of($taskName, 'BuildTask')) {
387
            $title = singleton($taskName)->getTitle();
388
            if (Director::is_cli()) {
389
                echo "Running task '$title'...\n\n";
390
            } elseif (!Director::is_ajax()) {
391
                echo "<h1>Running task '$title'...</h1>\n";
392
            }
393
394
            $task = new $taskName();
395
            if ($task->isEnabled()) {
396
                $task->verbose = true;
397
                $task->run($request);
398
            } else {
399
                echo "<p>{$title} is disabled</p>";
400
            }
401
        } else {
402
            echo "Build task '$taskName' not found.";
403
            if (class_exists($taskName)) {
404
                echo "  It isn't a subclass of BuildTask.";
405
            }
406
            echo "\n";
407
        }
408
        $this->displayCompletionMessage($task);
0 ignored issues
show
The variable $task does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
409
        $renderer->writePostOutcome();
410
        $renderer->writeContent($this);
411
        $renderer->writeFooter();
412
    }
413
414
    /**
415
     * shows a "Task Completed Message" on the screen.
416
     *
417
     * @param BuildTask $buildTask
418
     * @param string    $extraMessage
419
     */
420
    protected function displayCompletionMessage(BuildTask $buildTask, $extraMessage = '')
421
    {
422
        DB::alteration_message('
423
424
            ------------------------------------------------------- <br />
425
            COMPLETED THE FOLLOWING TASK:<br />
426
            <strong>'.$buildTask->getTitle().'</strong><br />
427
            '.$buildTask->getDescription()." <br />
428
            ------------------------------------------------------- <br />
429
            $extraMessage
430
        ");
431
    }
432
}
433
434
class DebugView_EcommerceDatabaseAdmin extends DebugView
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...
435
{
436
    public function writePreOutcome()
437
    {
438
        echo "<div id='TaskHolder' style=\"background-color: #e8e8e8; border-radius: 15px; margin: 20px; padding: 20px\">";
439
    }
440
441
    public function writePostOutcome()
442
    {
443
        echo '</div>';
444
    }
445
446
    public function writeContent(Controller $controller)
447
    {
448
        echo $controller->RenderWith($controller->class);
449
    }
450
}
451