ModuleUpgraderBaseWithVariables   F
last analyzed

Complexity

Total Complexity 68

Size/Duplication

Total Lines 776
Duplicated Lines 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 68
eloc 213
c 7
b 0
f 0
dl 0
loc 776
rs 2.96

26 Methods

Rating   Name   Duplication   Size   Complexity  
A removeFromListOfTasks() 0 10 2
A __destruct() 0 3 1
A addToListOfTasks() 0 21 5
B getExistingModuleDirLocations() 0 46 10
A setRunImmediately() 0 5 1
B findNameSpaceAndCodeDirs() 0 26 7
A getBreakOnAllErrors() 0 3 1
A startPHP2CommandLine() 0 5 1
A getIsModuleUpgradeNice() 0 3 2
A findMyCodeDir() 0 18 6
A getisOnPackagistNice() 0 6 3
A setVariableForTask() 0 8 2
A setBreakOnAllErrors() 0 5 1
A getGitRootDir() 0 11 3
A getLocationOfSSUpgradeModule() 0 7 2
A getIsProjectUpgrade() 0 3 2
A addModule() 0 5 1
A getNameOfBranchForBaseCodeForComposer() 0 9 3
A getExistingModuleDirLocationsWithThemeFolders() 0 8 2
A positionForTask() 0 6 2
A getLocationOfThisUpgrader() 0 6 2
A endPHP2CommandLine() 0 5 2
A getPackageFolderNameBasic() 0 10 3
A getExistingFirstModuleDirLocation() 0 4 1
A __construct() 0 5 1
A getSessionManager() 0 17 2

How to fix   Complexity   

Complex Class

Complex classes like ModuleUpgraderBaseWithVariables 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.

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 ModuleUpgraderBaseWithVariables, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Sunnysideup\UpgradeToSilverstripe4;
4
5
use Sunnysideup\PHP2CommandLine\PHP2CommandLineSingleton;
6
use Sunnysideup\UpgradeToSilverstripe4\Api\SessionManagement;
7
use Sunnysideup\UpgradeToSilverstripe4\Interfaces\ModuleUpgraderInterface;
8
use Sunnysideup\UpgradeToSilverstripe4\Interfaces\SessionManagementInterface;
9
use Sunnysideup\UpgradeToSilverstripe4\Traits\GettersAndSetters;
10
use Sunnysideup\UpgradeToSilverstripe4\Traits\Misc;
11
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\ApplyNamespacing;
12
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss33ToSs37;
13
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss35ToSs37;
14
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss3ToSs4;
15
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss4Lint;
16
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss4ToSs5FindAndReplaceOnly;
17
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss4ToSs5FindAndReplaceOnlyModule;
18
19
class ModuleUpgraderBaseWithVariables implements ModuleUpgraderInterface
20
{
21
    use GettersAndSetters;
22
    use Misc;
23
24
    #########################################
25
    # Arguments
26
    #########################################
27
28
    protected $argv = [];
29
30
    #########################################
31
    # RECIPE
32
    #########################################
33
34
    /**
35
     * @var string
36
     */
37
    protected $recipe = 'SS4';
38
39
    /**
40
     * list of recipes available
41
     * @var array
42
     */
43
    protected $availableRecipes = [
44
        'SS4' => Ss3ToSs4::class,
45
        'SS4-LINT' => Ss4Lint::class,
46
        'SS33-37' => Ss33ToSs37::class,
47
        'SS35-37' => Ss35ToSs37::class,
48
        'ApplyNamespacing' => ApplyNamespacing::class,
49
        'SS5-SEARCH-REPLACE-ONLY' => Ss4ToSs5FindAndReplaceOnly::class,
50
        'SS5-SEARCH-REPLACE-ONLY-MODULE' => Ss4ToSs5FindAndReplaceOnlyModule::class,
51
    ];
52
53
    #########################################
54
    # TASKS
55
    #########################################
56
57
    /**
58
     * A list of task groups
59
     * this will be set from recipe - so we need this!
60
     * @var array
61
     */
62
    protected $taskSteps = [];
63
64
    /**
65
     * An array of all the 'taskName's of the tasks that you wish to run during the execution of this upgrader task.
66
     * This array can be overriden in the example-index.php file that you create.
67
     * You can enter a full name space if you need to.
68
     * The final -x will be removed.  We add -1 or -2 to run the same task multiple times.
69
     *
70
     * @var array
71
     */
72
    protected $listOfTasks = [];
73
74
    /**
75
     * e.g. ^4.4
76
     * @var string
77
     */
78
    protected $frameworkComposerRestraint = '';
79
80
    /**
81
     * e.g. [email protected]:sunnysideup/silverstripe-ecommerce_test.git
82
     * @var string
83
     */
84
    protected $parentProjectForModule = '';
85
86
    /**
87
     * e.g. master or 4.2.2
88
     * @var string
89
     */
90
    protected $parentProjectForModuleBranchOrTag = 'master';
91
92
    /**
93
     * Should the session details be deleted before we start?
94
     * @var bool
95
     */
96
    protected $restartSession = false;
97
98
    /**
99
     * Do we run the last step again?
100
     * @var bool
101
     */
102
    protected $runLastOneAgain = false;
103
104
    /**
105
     * command that is currently running
106
     * @var string
107
     */
108
    protected $currentlyRunning = '';
109
110
    /**
111
     * are we upgrading a module or a whole project?
112
     * @var bool
113
     */
114
    protected $isModuleUpgrade = true;
115
116
    /**
117
     * The default namespace for all tasks
118
     * @var string
119
     */
120
    protected $defaultNamespaceForTasks = 'Sunnysideup\UpgradeToSilverstripe4\Tasks\IndividualTasks';
121
122
    /**
123
     * if set to true it will run each step and then stop.
124
     * It was save the last step.
125
     * When your run it again, it will start on the next step.
126
     *
127
     * @var bool
128
     */
129
    protected $runInteractively = true;
130
131
    /**
132
     * Show ALL the information or just a little bit.
133
     * @var bool
134
     */
135
    protected $verbose = false;
136
137
    /**
138
     * start the upgrade sequence at a particular task
139
     * @var string
140
     */
141
    protected $startFrom = '';
142
143
    /**
144
     * end the upgrade sequence after a particular task
145
     * @var string
146
     */
147
    protected $endWith = '';
148
149
    /**
150
     * only run this task ...
151
     * @var string
152
     */
153
    protected $onlyRun = '';
154
155
    /**
156
     * finish the run with a merge into master.
157
     * @var bool
158
     */
159
    protected $runIrreversibly = false;
160
161
    /**
162
     * is this out of order - i.e. no influence on next task
163
     * @var bool
164
     */
165
    protected $outOfOrderTask = false;
166
167
    #########################################
168
    # MODULES
169
    #########################################
170
171
    /**
172
     * specified like this:
173
     *      [
174
     *          'VendorName' => 'A',
175
     *          'VendorNamespace' => 'A',
176
     *          'PackageName' => 'Package1',
177
     *          'PackageNamespace' => 'Package1',
178
     *          'GitLink' => '[email protected]:foor/bar-1.git',
179
     *          'UpgradeAsFork' => false,
180
     *          'NameOfBranchForBaseCode' => 'develop',
181
     *      ],
182
     *      [
183
     *          'VendorName' => 'A',
184
     *          'VendorNamespace' => 'A',
185
     *          'PackageName' => 'Package2',
186
     *          'PackageNamespace' => 'Package2',
187
     *          'GitLink' => '[email protected]:foor/bar-2.git',
188
     *          'UpgradeAsFork' => false,
189
     *          'NameOfBranchForBaseCode' => 'master',
190
     *      ],
191
     * required are:
192
     * - VendorName
193
     * - PacakageName
194
     * The rest can be deduced (theoretically)
195
     * @var array of array modules to upgrade
196
     */
197
    protected $arrayOfModules = [];
198
199
    #########################################
200
    # VENDOR / PACKAGE / GIT DETAILS
201
    #########################################
202
203
    /**
204
     * name of the branch that exists as the starting point for upgrade
205
     * @var string branch name
206
     */
207
    protected $nameOfBranchForBaseCode = 'master';
208
209
    /**
210
     * name of the branch to be created that we use a starter branch for upgrade
211
     * @var string branch name
212
     */
213
    protected $nameOfUpgradeStarterBranch = 'upgrades/starting-point';
214
215
    /**
216
     * name of the branch created to do the upgrade
217
     * @var string branch name
218
     */
219
    protected $nameOfTempBranch = 'upgrades/temp-automated-upgrade-branch';
220
221
    /**
222
     * Name of module vendor
223
     * @var string
224
     */
225
    protected $vendorName = '';
226
227
    /**
228
     * module vendors namespace
229
     * @var string
230
     */
231
    protected $vendorNamespace = '';
232
233
    /**
234
     * Package name for the module
235
     * @var string
236
     */
237
    protected $packageName = '';
238
239
    /**
240
     * e.g. install folder for package in SS3.
241
     * @var string
242
     */
243
    protected $packageFolderNameForInstall = '';
244
245
    /**
246
     * e.g. sunnysideup/my-cool-module
247
     * @var string
248
     */
249
    protected $vendorAndPackageFolderNameForInstall = '';
250
251
    /**
252
     *Name space for the modules package
253
     * @var string
254
     */
255
    protected $packageNamespace = '';
256
257
    /**
258
     * git link for the module in ssh form
259
     * e.g. [email protected]:sunnysideup/silverstripe-dynamiccache.git
260
     * @var string
261
     */
262
    protected $gitLink = '';
263
264
    /**
265
     * @var bool
266
     */
267
    protected $isOnPackagist = false;
268
269
    /**
270
     * git link for the module in https form
271
     * e.g. https://github.com/sunnysideup/silverstripe-dynamiccache/
272
     * @var string
273
     */
274
    protected $gitLinkAsHTTPS = '';
275
276
    /**
277
     * git link for the module in raw https form
278
     * e.g. https://raw.githubusercontent.com/sunnysideup/silverstripe-dynamiccache/
279
     * @var string
280
     */
281
    protected $gitLinkAsRawHTTPS = '';
282
283
    /**
284
     * Should the upgrade to this module create a fork
285
     * @var bool
286
     */
287
    protected $upgradeAsFork = false;
288
289
    #########################################
290
    # COMPOSER
291
    #########################################
292
293
    /**
294
     * e.g. COMPOSER_HOME="/home/UserName"
295
     *
296
     * @var string
297
     */
298
    protected $composerEnvironmentVars = '';
299
300
    #########################################
301
    # LOCATIONS
302
    #########################################
303
304
    //TODO double check descriptions for these variables as still rather ambiguous
305
306
    /**
307
     * The folder for storing the log file in
308
     * used in setting the php2 command line printer up
309
     * @var string
310
     */
311
    protected $logFolderDirLocation = '';
312
313
    /**
314
     * location of web root above module
315
     * @var string directory
316
     */
317
    protected $aboveWebRootDirLocation = '/var/www';
318
319
    /**
320
     * @var string
321
     */
322
    protected $webRootName = 'upgradeto4';
323
324
    /**
325
     * //e.g. 'upgrade-code'
326
     * //e.g. '~/.composer/vendor/bin/upgrade-code'
327
     * //e.g. '/var/www/silverstripe-upgrade_to_silverstripe_4/vendor/silverstripe/upgrader/bin/upgrade-code'
328
     * @var string
329
     */
330
    protected $locationOfThisUpgrader = '';
331
332
    /**
333
     * //e.g. 'upgrade-code'
334
     * //e.g. '~/.composer/vendor/bin/upgrade-code'
335
     * //e.g. '/var/www/silverstripe-upgrade_to_silverstripe_4/vendor/silverstripe/upgrader/bin/upgrade-code'
336
     * @var string
337
     */
338
    protected $locationOfSSUpgradeModule = '';
339
340
    ###############################
341
    # HELPERS
342
    ###############################
343
344
    /**
345
     *Reference to the commandline printer that outputs everything to the command line
346
     * @var PHP2CommandLineSingleton|null
347
     */
348
    protected $commandLineExec = null;
349
350
    /**
351
     *Reference to the commandline printer that outputs everything to the command line
352
     * @var SessionManagementInterface|null
353
     */
354
    protected $sessionManager = null;
355
356
    /**
357
     * @var string
358
     */
359
    protected $sessionFileName = 'Session_For';
360
361
    /**
362
     * does the exec output Key Notes?
363
     * @var bool
364
     */
365
    protected $makeKeyNotes = false;
366
367
    /**
368
     * @var string
369
     */
370
    protected $originComposerFileLocation = '';
371
372
    /**
373
     * Is this the last TASK we are running?
374
     * @var bool
375
     */
376
    protected $lastMethodHasBeenRun = false;
377
378
    /**
379
     * @var string
380
     */
381
    protected $logFileLocation = '';
382
383
    /**
384
     * Combination of the web dir root name and the aboveWebRootDirLocation
385
     * @var string
386
     */
387
    protected $webRootDirLocation = '';
388
389
    /**
390
     * Combination of the web dir root name and the aboveWebRootDirLocation
391
     * @var string
392
     */
393
    protected $themeDirLocation = '';
394
395
    /**
396
     * Directory that holds the module
397
     * or project.
398
     *
399
     * This is an array because a project can hold more than one
400
     * folder (e.g. mysite or app and specialstuff)
401
     *
402
     * a module is only one folder
403
     *
404
     * @var array
405
     */
406
    protected $moduleDirLocations = [];
407
408
    /**
409
     * records variables for tasks, like this:
410
     *      [
411
     *          'TaskName' => [
412
     *              'VariableName' => 'VariableValue',
413
     *          ],
414
     *      ]
415
     * @var array
416
     */
417
    protected $customVariablesForTasks = [];
418
419
    /**
420
     * Starts the output to the commandline / browser
421
     */
422
    public function __construct(?array $argv = null)
0 ignored issues
show
Unused Code introduced by
The parameter $argv is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

422
    public function __construct(/** @scrutinizer ignore-unused */ ?array $argv = null)

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

Loading history...
423
    {
424
        global $argv;
425
        $this->argv = $argv;
426
        $this->startPHP2CommandLine();
427
    }
428
429
    /**
430
     * Ends output to commandline / browser
431
     */
432
    public function __destruct()
433
    {
434
        $this->endPHP2CommandLine();
435
    }
436
437
    /**
438
     * Appends the given module in the form of all its module data that has to be formatted in an array
439
     * to the array of modules that will be worked with during the upgrade procedure.
440
     *
441
     * @param array $a data to append
442
     */
443
    public function addModule(array $a): ModuleUpgraderInterface
444
    {
445
        $this->arrayOfModules[] = $a;
446
447
        return $this;
448
    }
449
450
    /**
451
     * Inserts another task to the list of tasks at a given position in the order of execution, if it is set
452
     * TODO These parameter names need some more refining
453
     * @param string|array  $oneOrMoreTasks the tasks to be inserted
454
     * @param bool          $insertBeforeOrAfter If to insert before or after
455
     * @param bool          $isBefore
456
     */
457
    public function addToListOfTasks($oneOrMoreTasks, $insertBeforeOrAfter, $isBefore): ModuleUpgraderInterface
458
    {
459
        if (! is_array($oneOrMoreTasks)) {
460
            $oneOrMoreTasks = [$oneOrMoreTasks];
461
        }
462
        foreach ($this->listOfTasks as $key => $task) {
463
            if ($task === $insertBeforeOrAfter) {
464
                if ($isBefore) {
465
                    $pos = $key - 1;
466
                } else {
467
                    $pos = $key;
468
                }
469
                array_splice(
470
                    $this->listOfTasks,
471
                    $pos,
472
                    0,
473
                    $oneOrMoreTasks
474
                );
475
            }
476
        }
477
        return $this;
478
    }
479
480
    /**
481
     * Removes the given task from the list of tasks to execute
482
     * @param  string $s name of the task to remove
483
     */
484
    public function removeFromListOfTasks($s): ModuleUpgraderInterface
485
    {
486
        $key = $this->positionForTask($s);
487
        if ($key !== false) {
0 ignored issues
show
introduced by
The condition $key !== false is always true.
Loading history...
488
            unset($this->listOfTasks[$key]);
489
        } else {
490
            user_error('Removing non existent task ' . $key . '. Choose from ' . implode(', ', $this->listOfTasks));
491
        }
492
493
        return $this;
494
    }
495
496
    public function setRunImmediately(bool $b): ModuleUpgraderInterface
497
    {
498
        $this->commandLineExec->setRunImmediately($b);
0 ignored issues
show
Bug introduced by
The method setRunImmediately() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

498
        $this->commandLineExec->/** @scrutinizer ignore-call */ 
499
                                setRunImmediately($b);

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...
499
500
        return $this;
501
    }
502
503
    public function getLocationOfThisUpgrader(): string
504
    {
505
        if (! $this->locationOfThisUpgrader) {
506
            $this->locationOfThisUpgrader = dirname(__DIR__);
507
        }
508
        return $this->locationOfThisUpgrader;
509
    }
510
511
    public function getLocationOfSSUpgradeModule(): string
512
    {
513
        if (! $this->locationOfSSUpgradeModule) {
514
            $this->locationOfSSUpgradeModule = $this->getLocationOfThisUpgrader() .
515
                '/vendor/silverstripe/upgrader/bin/upgrade-code';
516
        }
517
        return $this->locationOfSSUpgradeModule;
518
    }
519
520
    public function getSessionManager(): SessionManagementInterface
521
    {
522
        if ($this->sessionManager === null) {
523
            $sessionFileLocation = trim(
524
                $this->getAboveWebRootDirLocation() .
0 ignored issues
show
Bug introduced by
The method getAboveWebRootDirLocation() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

524
                $this->/** @scrutinizer ignore-call */ 
525
                       getAboveWebRootDirLocation() .
Loading history...
Bug introduced by
Are you sure $this->getAboveWebRootDirLocation() of type Sunnysideup\UpgradeToSil...ithVariables|mixed|null can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

524
                /** @scrutinizer ignore-type */ $this->getAboveWebRootDirLocation() .
Loading history...
525
                    '/' .
526
                    $this->sessionFileName .
527
                    '_' .
528
                    $this->getVendorNamespace() .
0 ignored issues
show
Bug introduced by
The method getVendorNamespace() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

528
                    $this->/** @scrutinizer ignore-call */ 
529
                           getVendorNamespace() .
Loading history...
Bug introduced by
Are you sure $this->getVendorNamespace() of type Sunnysideup\UpgradeToSil...ithVariables|mixed|null can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

528
                    /** @scrutinizer ignore-type */ $this->getVendorNamespace() .
Loading history...
529
                    '_' .
530
                    $this->getPackageNamespace() .
0 ignored issues
show
Bug introduced by
The method getPackageNamespace() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

530
                    $this->/** @scrutinizer ignore-call */ 
531
                           getPackageNamespace() .
Loading history...
Bug introduced by
Are you sure $this->getPackageNamespace() of type Sunnysideup\UpgradeToSil...ithVariables|mixed|null can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

530
                    /** @scrutinizer ignore-type */ $this->getPackageNamespace() .
Loading history...
531
                    '.json'
532
            );
533
            $this->sessionManager = SessionManagement::initSession($sessionFileLocation);
534
        }
535
536
        return $this->sessionManager;
537
    }
538
539
    /**
540
     * returns an array of existing paths
541
     */
542
    public function getExistingModuleDirLocations(): array
543
    {
544
        //moduleDirLocation
545
        if ($this->isModuleUpgrade) {
546
            $vendorModuleLocation = $this->vendorModuleLocation();
0 ignored issues
show
Bug introduced by
The method vendorModuleLocation() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

546
            /** @scrutinizer ignore-call */ 
547
            $vendorModuleLocation = $this->vendorModuleLocation();
Loading history...
547
            if (file_exists($vendorModuleLocation)) {
0 ignored issues
show
Bug introduced by
It seems like $vendorModuleLocation can also be of type Sunnysideup\UpgradeToSil...graderBaseWithVariables and null; however, parameter $filename of file_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

547
            if (file_exists(/** @scrutinizer ignore-type */ $vendorModuleLocation)) {
Loading history...
548
                $this->moduleDirLocations = [
549
                    $vendorModuleLocation,
550
                ];
551
            } else {
552
                $this->moduleDirLocations = [
553
                    $this->webRootDirLocation . '/' . $this->packageFolderNameForInstall,
554
                ];
555
            }
556
            $this->themeDirLocation = '';
557
        } else {
558
            if (count($this->moduleDirLocations) === 0) {
559
                $this->moduleDirLocations[] = $this->webRootDirLocation . '/mysite';
560
                $this->moduleDirLocations[] = $this->webRootDirLocation . '/app';
561
            } else {
562
                foreach ($this->moduleDirLocations as $key => $location) {
563
                    if (! file_exists($location)) {
564
                        $this->moduleDirLocations[$key] = $this->webRootDirLocation . '/' . $location;
565
                    }
566
                }
567
            }
568
        }
569
        $array = [];
570
        foreach ($this->moduleDirLocations as $location) {
571
            $location = (string) $this->checkIfPathExistsAndCleanItUp($location, false);
572
            if ($location) {
573
                $array[$location] = $location;
574
            }
575
        }
576
        if (count($array) === 0) {
577
            if ($this->getIsModuleUpgrade()) {
0 ignored issues
show
Bug introduced by
The method getIsModuleUpgrade() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

577
            if ($this->/** @scrutinizer ignore-call */ getIsModuleUpgrade()) {
Loading history...
578
            } else {
579
                user_error(
580
                    'You need to set moduleDirLocations (setModuleDirLocations)
581
                    as there are currently none.
582
                    We tried to look at: ' . print_r($this->moduleDirLocations, 1)
0 ignored issues
show
Bug introduced by
Are you sure print_r($this->moduleDirLocations, 1) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

582
                    We tried to look at: ' . /** @scrutinizer ignore-type */ print_r($this->moduleDirLocations, 1)
Loading history...
583
                );
584
            }
585
        }
586
587
        return $array;
588
    }
589
590
    /**
591
     * Whether execution should come to a halt when an error is reached
592
     */
593
    public function setBreakOnAllErrors(bool $b): self
594
    {
595
        $this->commandLineExec->setBreakOnAllErrors($b);
596
597
        return $this;
598
    }
599
600
    /**
601
     * Whether execution should come to a halt when an error is reached
602
     */
603
    public function getBreakOnAllErrors(): bool
604
    {
605
        return $this->commandLineExec->getBreakOnAllErrors();
606
    }
607
608
    /**
609
     * Whether execution should come to a halt when an error is reached
610
     */
611
    public function getIsProjectUpgrade(): bool
612
    {
613
        return $this->isModuleUpgrade ? false : true;
614
    }
615
616
    public function getExistingModuleDirLocationsWithThemeFolders(): array
617
    {
618
        $array = $this->getExistingModuleDirLocations();
619
        if ($this->themeDirLocation) {
620
            $array[$this->themeDirLocation] = $this->themeDirLocation;
621
        }
622
623
        return $array;
624
    }
625
626
    /**
627
     * returns path for module
628
     *
629
     * @return string
630
     */
631
    public function getExistingFirstModuleDirLocation()
632
    {
633
        $locations = array_values($this->getExistingModuleDirLocations());
634
        return array_shift($locations);
635
    }
636
637
    public function getNameOfBranchForBaseCodeForComposer(): string
638
    {
639
        if ($this->nameOfBranchForBaseCode) {
640
            if (substr($this->nameOfBranchForBaseCode, 0, 4) === 'dev-') {
641
                return $this->nameOfBranchForBaseCode;
642
            }
643
            return 'dev-' . $this->nameOfBranchForBaseCode;
644
        }
645
        return 'dev-master';
646
    }
647
648
    /**
649
     * Locates the directory in which the code is kept within the module directory
650
     *
651
     * If it can be found returns the location otherwise it errors
652
     *
653
     * @return array codedirlocation
654
     */
655
    public function findNameSpaceAndCodeDirs()
656
    {
657
        $codeDirs = [];
658
        $locations = $this->getExistingModuleDirLocations();
659
        foreach ($locations as $location) {
660
            $codeDir = $this->findMyCodeDir($location);
661
            if ($codeDir) {
662
                if ($this->getIsModuleUpgrade()) {
663
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . $this->getPackageNamespace() . '\\';
0 ignored issues
show
Bug introduced by
Are you sure $this->getPackageNamespace() of type Sunnysideup\UpgradeToSil...ithVariables|mixed|null can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

663
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . /** @scrutinizer ignore-type */ $this->getPackageNamespace() . '\\';
Loading history...
Bug introduced by
Are you sure $this->getVendorNamespace() of type Sunnysideup\UpgradeToSil...ithVariables|mixed|null can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

663
                    $baseNameSpace = /** @scrutinizer ignore-type */ $this->getVendorNamespace() . '\\' . $this->getPackageNamespace() . '\\';
Loading history...
664
                } else {
665
                    $nameSpaceKey = ucwords(basename($location));
666
                    if (strtolower($nameSpaceKey) === 'app' || strtolower($nameSpaceKey) === 'mysite') {
667
                        $nameSpaceKey = $this->getPackageNamespace();
668
                    }
669
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . $nameSpaceKey . '\\';
670
                }
671
                $codeDirs[$baseNameSpace] = $codeDir;
672
            }
673
        }
674
        if (count($codeDirs) === 0) {
675
            user_error('
676
                Could not find any code dirs. The locations searched: ' . print_r($locations, true)
0 ignored issues
show
Bug introduced by
Are you sure print_r($locations, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

676
                Could not find any code dirs. The locations searched: ' . /** @scrutinizer ignore-type */ print_r($locations, true)
Loading history...
677
                . ' Using the ' . $this->getIsModuleUpgradeNice() . ' approach');
678
        }
679
680
        return $codeDirs;
681
    }
682
683
    public function findMyCodeDir(string $moduleDir): string
684
    {
685
        if (file_exists($moduleDir)) {
686
            $test1 = $moduleDir . '/code';
687
            $test2 = $moduleDir . '/src';
688
            if (file_exists($test1) && file_exists($test2)) {
689
                user_error('There is a code and a src dir for ' . $moduleDir, E_USER_NOTICE);
690
            } elseif (file_exists($test1)) {
691
                return $moduleDir . '/code';
692
            } elseif (file_exists($test2)) {
693
                return $moduleDir . '/src';
694
            } else {
695
                user_error('Can not find code/src dir for ' . $moduleDir, E_USER_NOTICE);
696
            }
697
        }
698
699
        //return empty string
700
        return '';
701
    }
702
703
    public function getGitRootDir(): string
704
    {
705
        if ($this->getIsModuleUpgrade()) {
706
            $location = $this->getExistingFirstModuleDirLocation();
707
            if (! $location) {
708
                return $this->moduleDirLocations[0];
709
            }
710
        } else {
711
            $location = $this->getWebRootDirLocation();
0 ignored issues
show
Bug introduced by
The method getWebRootDirLocation() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

711
            /** @scrutinizer ignore-call */ 
712
            $location = $this->getWebRootDirLocation();
Loading history...
712
        }
713
        return $location;
714
    }
715
716
    public function getIsModuleUpgradeNice(): string
717
    {
718
        return $this->getIsModuleUpgrade() ? 'module upgrade' : 'website project upgrade';
719
    }
720
721
    public function getisOnPackagistNice(): string
722
    {
723
        if ($this->getIsModuleUpgrade()) {
724
            return $this->getisOnPackagist() ? 'listed on packagist' : 'not listed on packagist';
0 ignored issues
show
Bug introduced by
The method getisOnPackagist() does not exist on Sunnysideup\UpgradeToSil...graderBaseWithVariables. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

724
            return $this->/** @scrutinizer ignore-call */ getisOnPackagist() ? 'listed on packagist' : 'not listed on packagist';
Loading history...
725
        } else {
726
            return 'not listed on packagist';
727
        }
728
    }
729
730
    /**
731
     * Removes the given task from the list of tasks to execute
732
     * @param  string $taskName name of the task
733
     * @param  string $variableName name of the task
734
     * @param  mixed $variableValue name of the task
735
     */
736
    public function setVariableForTask(string $taskName, string $variableName, $variableValue): ModuleUpgraderInterface
737
    {
738
        if (! isset($this->customVariablesForTasks[$taskName])) {
739
            $this->customVariablesForTasks[$taskName] = [];
740
        }
741
        $this->customVariablesForTasks[$taskName][$variableName] = $variableValue;
742
743
        return $this;
744
    }
745
746
    /**
747
     * What is the index of given task within the sequence
748
     *
749
     * @param string $s name of the task to find
750
     *
751
     * @return mixed the key/index of task
752
     */
753
    protected function positionForTask($s)
754
    {
755
        if (isset($this->listOfTasks[$s])) {
756
            return $s;
757
        }
758
        return array_search($s, $this->listOfTasks, true);
759
    }
760
761
    protected function getPackageFolderNameBasic(?bool $withoutSilverstripePrefix = false): string
762
    {
763
        $link = 'mysite';
764
        if ($this->isModuleUpgrade) {
765
            $link = $this->packageName;
766
            if ($withoutSilverstripePrefix) {
767
                $link = str_replace('silverstripe-', '', $this->packageName);
768
            }
769
        }
770
        return $link;
771
    }
772
773
    /**
774
     * Starts the logger. Extra checking may be put in here to see if you
775
     * want to start the logger or not in different scenarios.
776
     *
777
     * For now it defaults to always existing
778
     */
779
    protected function startPHP2CommandLine(): PHP2CommandLineSingleton
780
    {
781
        $this->commandLineExec = PHP2CommandLineSingleton::create();
782
783
        return $this->commandLineExec;
784
    }
785
786
    /**
787
     * deconstructs Command Line
788
     * important as this outputs the whole thing
789
     */
790
    protected function endPHP2CommandLine()
791
    {
792
        if ($this->commandLineExec !== null) {
793
            PHP2CommandLineSingleton::delete();
794
            $this->commandLineExec = null;
795
        }
796
    }
797
}
798