Passed
Push — master ( eb813a...d19f6b )
by Nicolaas
02:04
created

getisOnPackagistNice()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
namespace Sunnysideup\UpgradeToSilverstripe4;
4
5
use Sunnysideup\PHP2CommandLine\PHP2CommandLineSingleton;
6
7
use Sunnysideup\UpgradeToSilverstripe4\Api\SessionManagement;
8
use Sunnysideup\UpgradeToSilverstripe4\Interfaces\ModuleUpgraderInterface;
9
use Sunnysideup\UpgradeToSilverstripe4\Interfaces\SessionManagementInterface;
10
use Sunnysideup\UpgradeToSilverstripe4\Traits\GettersAndSetters;
11
12
use Sunnysideup\UpgradeToSilverstripe4\Traits\Misc;
13
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss31ToSs37;
14
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss33ToSs37;
15
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss35ToSs37;
16
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\ApplyNamespacing;
17
18
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss3ToSs4;
19
use Sunnysideup\UpgradeToSilverstripe4\UpgradeRecipes\Ss4Lint;
20
21
class ModuleUpgraderBaseWithVariables implements ModuleUpgraderInterface
22
{
23
    use GettersAndSetters;
24
    use Misc;
25
26
    #########################################
27
    # Arguments
28
    #########################################
29
30
    protected $argv = [];
31
32
    #########################################
33
    # RECIPE
34
    #########################################
35
36
    /**
37
     * @var string
38
     */
39
    protected $recipe = 'SS4';
40
41
    /**
42
     * list of recipes available
43
     * @var array
44
     */
45
    protected $availableRecipes = [
46
        'SS4' => Ss3ToSs4::class,
47
        'SS4-LINT' => Ss4Lint::class,
48
        'SS33-37' => Ss33ToSs37::class,
49
        'SS35-37' => Ss35ToSs37::class,
50
        'ApplyNamespacing' => ApplyNamespacing::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()
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
     * @return ModuleUpgraderInterface
443
     */
444
    public function addModule(array $a): ModuleUpgraderInterface
445
    {
446
        $this->arrayOfModules[] = $a;
447
448
        return $this;
449
    }
450
451
    /**
452
     * Inserts another task to the list of tasks at a given position in the order of execution, if it is set
453
     * TODO These parameter names need some more refining
454
     * @param string|array  $oneOrMoreTasks the tasks to be inserted
455
     * @param bool          $insertBeforeOrAfter If to insert before or after
456
     * @param bool          $isBefore
457
     *
458
     * @return ModuleUpgraderInterface
459
     */
460
    public function addToListOfTasks($oneOrMoreTasks, $insertBeforeOrAfter, $isBefore): ModuleUpgraderInterface
461
    {
462
        if (! is_array($oneOrMoreTasks)) {
463
            $oneOrMoreTasks = [$oneOrMoreTasks];
464
        }
465
        foreach ($this->listOfTasks as $key => $task) {
466
            if ($task === $insertBeforeOrAfter) {
467
                if ($isBefore) {
468
                    $pos = $key - 1;
469
                } else {
470
                    $pos = $key;
471
                }
472
                array_splice(
473
                    $this->listOfTasks,
474
                    $pos,
475
                    0,
476
                    $oneOrMoreTasks
477
                );
478
            }
479
        }
480
        return $this;
481
    }
482
483
    /**
484
     * Removes the given task from the list of tasks to execute
485
     * @param  string $s name of the task to remove
486
     *
487
     * @return ModuleUpgraderInterface
488
     */
489
    public function removeFromListOfTasks($s): ModuleUpgraderInterface
490
    {
491
        $key = $this->positionForTask($s);
492
        if ($key !== false) {
0 ignored issues
show
introduced by
The condition $key !== false is always true.
Loading history...
493
            unset($this->listOfTasks[$key]);
494
        } else {
495
            user_error('Removing non existent task ' . $key . '. Choose from ' . implode(', ', $this->listOfTasks));
496
        }
497
498
        return $this;
499
    }
500
501
    /**
502
     * @param bool $b
503
     * @return ModuleUpgraderInterface
504
     */
505
    public function setRunImmediately(bool $b): ModuleUpgraderInterface
506
    {
507
        $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

507
        $this->commandLineExec->/** @scrutinizer ignore-call */ 
508
                                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...
508
509
        return $this;
510
    }
511
512
    /**
513
     * @return string
514
     */
515
    public function getLocationOfThisUpgrader(): string
516
    {
517
        if (! $this->locationOfThisUpgrader) {
518
            $this->locationOfThisUpgrader = dirname(__DIR__);
519
        }
520
        return $this->locationOfThisUpgrader;
521
    }
522
523
    /**
524
     * @return string
525
     */
526
    public function getLocationOfSSUpgradeModule(): string
527
    {
528
        if (! $this->locationOfSSUpgradeModule) {
529
            $this->locationOfSSUpgradeModule = $this->getLocationOfThisUpgrader() .
530
                '/vendor/silverstripe/upgrader/bin/upgrade-code';
531
        }
532
        return $this->locationOfSSUpgradeModule;
533
    }
534
535
    public function getSessionManager(): SessionManagementInterface
536
    {
537
        if ($this->sessionManager === null) {
538
            $sessionFileLocation = trim(
539
                $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

539
                $this->/** @scrutinizer ignore-call */ 
540
                       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

539
                /** @scrutinizer ignore-type */ $this->getAboveWebRootDirLocation() .
Loading history...
540
                '/' .
541
                $this->sessionFileName .
542
                '_' .
543
                $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

543
                $this->/** @scrutinizer ignore-call */ 
544
                       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

543
                /** @scrutinizer ignore-type */ $this->getVendorNamespace() .
Loading history...
544
                '_' .
545
                $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

545
                $this->/** @scrutinizer ignore-call */ 
546
                       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

545
                /** @scrutinizer ignore-type */ $this->getPackageNamespace() .
Loading history...
546
                '.json'
547
            );
548
            $this->sessionManager = SessionManagement::initSession($sessionFileLocation);
549
        }
550
551
        return $this->sessionManager;
552
    }
553
554
    /**
555
     * returns an array of existing paths
556
     *
557
     * @return array
558
     */
559
    public function getExistingModuleDirLocations(): array
560
    {
561
        //moduleDirLocation
562
        if ($this->isModuleUpgrade) {
563
            $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

563
            /** @scrutinizer ignore-call */ 
564
            $vendorModuleLocation = $this->vendorModuleLocation();
Loading history...
564
            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

564
            if (file_exists(/** @scrutinizer ignore-type */ $vendorModuleLocation)) {
Loading history...
565
                $this->moduleDirLocations = [
566
                    $vendorModuleLocation,
567
                ];
568
            } else {
569
                $this->moduleDirLocations = [
570
                    $this->webRootDirLocation . '/' . $this->packageFolderNameForInstall,
571
                ];
572
            }
573
            $this->themeDirLocation = '';
574
        } else {
575
            if (count($this->moduleDirLocations) === 0) {
576
                $this->moduleDirLocations[] = $this->webRootDirLocation . '/mysite';
577
                $this->moduleDirLocations[] = $this->webRootDirLocation . '/app';
578
            } else {
579
                foreach ($this->moduleDirLocations as $key => $location) {
580
                    if(! file_exists($location)) {
581
                        $this->moduleDirLocations[$key] = $this->webRootDirLocation . '/' . $location;
582
                    }
583
                }
584
            }
585
        }
586
        $array = [];
587
        foreach ($this->moduleDirLocations as $location) {
588
            echo $location;
589
            $location = (string) $this->checkIfPathExistsAndCleanItUp($location, false);
590
            echo $location;
591
            if ($location) {
592
                $array[$location] = $location;
593
            }
594
        }
595
        if (count($array) === 0) {
596
            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

596
            if ($this->/** @scrutinizer ignore-call */ getIsModuleUpgrade()) {
Loading history...
597
            } else {
598
                user_error(
599
                    'You need to set moduleDirLocations (setModuleDirLocations)
600
                    as there are currently none.
601
                    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

601
                    We tried to look at: '. /** @scrutinizer ignore-type */ print_r($this->moduleDirLocations, 1)
Loading history...
602
                );
603
            }
604
        }
605
606
        return $array;
607
    }
608
609
    /**
610
     * Whether execution should come to a halt when an error is reached
611
     * @return self
612
     */
613
    public function setBreakOnAllErrors(bool $b): self
614
    {
615
        $this->commandLineExec->setBreakOnAllErrors($b);
616
617
        return $this;
618
    }
619
620
    /**
621
     * Whether execution should come to a halt when an error is reached
622
     * @return bool
623
     */
624
    public function getBreakOnAllErrors(): bool
625
    {
626
        return $this->commandLineExec->getBreakOnAllErrors();
627
    }
628
629
    /**
630
     * Whether execution should come to a halt when an error is reached
631
     * @return bool
632
     */
633
    public function getIsProjectUpgrade(): bool
634
    {
635
        return $this->isModuleUpgrade ? false : true;
636
    }
637
638
    public function getExistingModuleDirLocationsWithThemeFolders(): array
639
    {
640
        $array = $this->getExistingModuleDirLocations();
641
        if ($this->themeDirLocation) {
642
            $array[$this->themeDirLocation] = $this->themeDirLocation;
643
        }
644
645
        return $array;
646
    }
647
648
    /**
649
     * returns path for module
650
     *
651
     * @return string
652
     */
653
    public function getExistingFirstModuleDirLocation()
654
    {
655
        $locations = array_values($this->getExistingModuleDirLocations());
656
        return array_shift($locations);
657
    }
658
659
    public function getNameOfBranchForBaseCodeForComposer(): string
660
    {
661
        if ($this->nameOfBranchForBaseCode) {
662
            if (substr($this->nameOfBranchForBaseCode, 0, 4) === 'dev-') {
663
                return $this->nameOfBranchForBaseCode;
664
            }
665
            return 'dev-' . $this->nameOfBranchForBaseCode;
666
        }
667
        return 'dev-master';
668
    }
669
670
    /**
671
     * Locates the directory in which the code is kept within the module directory
672
     *
673
     * If it can be found returns the location otherwise it errors
674
     *
675
     * @return array codedirlocation
676
     */
677
    public function findNameSpaceAndCodeDirs()
678
    {
679
        $codeDirs = [];
680
        $locations = $this->getExistingModuleDirLocations();
681
        foreach ($locations as $location) {
682
            $codeDir = $this->findMyCodeDir($location);
683
            if ($codeDir) {
684
                if ($this->getIsModuleUpgrade()) {
685
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . $this->getPackageNamespace() . '\\';
0 ignored issues
show
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

685
                    $baseNameSpace = /** @scrutinizer ignore-type */ $this->getVendorNamespace() . '\\' . $this->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

685
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . /** @scrutinizer ignore-type */ $this->getPackageNamespace() . '\\';
Loading history...
686
                } else {
687
                    $nameSpaceKey = ucwords(basename($location));
688
                    if (strtolower($nameSpaceKey) === 'app' || strtolower($nameSpaceKey) === 'mysite') {
689
                        $nameSpaceKey = $this->getPackageNamespace();
690
                    }
691
                    $baseNameSpace = $this->getVendorNamespace() . '\\' . $nameSpaceKey . '\\';
692
                }
693
                $codeDirs[$baseNameSpace] = $codeDir;
694
            }
695
        }
696
        if (count($codeDirs) === 0) {
697
            user_error('
698
                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

698
                Could not find any code dirs. The locations searched: ' . /** @scrutinizer ignore-type */ print_r($locations, true)
Loading history...
699
                . ' Using the ' . $this->getIsModuleUpgradeNice() . ' approach');
700
        }
701
702
        return $codeDirs;
703
    }
704
705
    public function findMyCodeDir(string $moduleDir): string
706
    {
707
        if (file_exists($moduleDir)) {
708
            $test1 = $moduleDir . '/code';
709
            $test2 = $moduleDir . '/src';
710
            if (file_exists($test1) && file_exists($test2)) {
711
                user_error('There is a code and a src dir for ' . $moduleDir, E_USER_NOTICE);
712
            } elseif (file_exists($test1)) {
713
                return $moduleDir . '/code';
714
            } elseif (file_exists($test2)) {
715
                return $moduleDir . '/src';
716
            } else {
717
                user_error('Can not find code/src dir for ' . $moduleDir, E_USER_NOTICE);
718
            }
719
        }
720
721
        //return empty string
722
        return '';
723
    }
724
725
    public function getGitRootDir(): string
726
    {
727
        if ($this->getIsModuleUpgrade()) {
728
            $location = $this->getExistingFirstModuleDirLocation();
729
            if (! $location) {
730
                return $this->moduleDirLocations[0];
731
            }
732
        } else {
733
            $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

733
            /** @scrutinizer ignore-call */ 
734
            $location = $this->getWebRootDirLocation();
Loading history...
734
        }
735
        return $location;
736
    }
737
738
    public function getIsModuleUpgradeNice(): string
739
    {
740
        return $this->getIsModuleUpgrade() ? 'module upgrade' : 'website project upgrade';
741
    }
742
    public function getisOnPackagistNice(): string
743
    {
744
        if ($this->getIsModuleUpgrade()) {
745
            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

745
            return $this->/** @scrutinizer ignore-call */ getisOnPackagist() ? 'listed on packagist' : 'not listed on packagist';
Loading history...
746
        } else {
747
            return 'not listed on packagist';
748
        }
749
    }
750
751
    /**
752
     * Removes the given task from the list of tasks to execute
753
     * @param  string $taskName name of the task
754
     * @param  string $variableName name of the task
755
     * @param  mixed $variableValue name of the task
756
     *
757
     * @return  ModuleUpgraderInterface
758
     */
759
    public function setVariableForTask(string $taskName, string $variableName, $variableValue): ModuleUpgraderInterface
760
    {
761
        if (! isset($this->customVariablesForTasks[$taskName])) {
762
            $this->customVariablesForTasks[$taskName] = [];
763
        }
764
        $this->customVariablesForTasks[$taskName][$variableName] = $variableValue;
765
766
        return $this;
767
    }
768
769
    /**
770
     * What is the index of given task within the sequence
771
     *
772
     * @param string $s name of the task to find
773
     *
774
     * @return mixed the key/index of task
775
     */
776
    protected function positionForTask($s)
777
    {
778
        if (isset($this->listOfTasks[$s])) {
779
            return $s;
780
        }
781
        return array_search($s, $this->listOfTasks, true);
782
    }
783
784
    protected function getPackageFolderNameBasic(?bool $withoutSilverstripePrefix = false): string
785
    {
786
        $link = 'mysite';
787
        if ($this->isModuleUpgrade) {
788
            $link = $this->packageName;
789
            if ($withoutSilverstripePrefix) {
790
                $link = str_replace('silverstripe-', '', $this->packageName);
791
            }
792
        }
793
        return $link;
794
    }
795
796
    /**
797
     * Starts the logger. Extra checking may be put in here to see if you
798
     * want to start the logger or not in different scenarios.
799
     *
800
     * For now it defaults to always existing
801
     * @return PHP2CommandLineSingleton
802
     */
803
    protected function startPHP2CommandLine(): PHP2CommandLineSingleton
804
    {
805
        $this->commandLineExec = PHP2CommandLineSingleton::create();
806
807
        return $this->commandLineExec;
808
    }
809
810
    /**
811
     * deconstructs Command Line
812
     * important as this outputs the whole thing
813
     */
814
    protected function endPHP2CommandLine()
815
    {
816
        if ($this->commandLineExec !== null) {
817
            PHP2CommandLineSingleton::delete();
818
            $this->commandLineExec = null;
819
        }
820
    }
821
}
822