-
Notifications
You must be signed in to change notification settings - Fork 19
/
NewCommand.php
950 lines (782 loc) · 27.2 KB
/
NewCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
<?php
namespace Statamic\Cli;
use GuzzleHttp\Client;
use function Laravel\Prompts\confirm;
use Laravel\Prompts\ConfirmPrompt;
use Laravel\Prompts\Prompt;
use function Laravel\Prompts\select;
use Laravel\Prompts\SelectPrompt;
use function Laravel\Prompts\suggest;
use Laravel\Prompts\SuggestPrompt;
use function Laravel\Prompts\text;
use Laravel\Prompts\TextPrompt;
use RuntimeException;
use Statamic\Cli\Theme\ConfirmPromptRenderer;
use Statamic\Cli\Theme\SelectPromptRenderer;
use Statamic\Cli\Theme\SuggestPromptRenderer;
use Statamic\Cli\Theme\TextPromptRenderer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
class NewCommand extends Command
{
use Concerns\RunsCommands, Concerns\ConfiguresPrompts;
const BASE_REPO = 'statamic/statamic';
const OUTPOST_ENDPOINT = 'https://outpost.statamic.com/v3/starter-kits/';
const GITHUB_LATEST_RELEASE_ENDPOINT = 'https://api.github.com/repos/statamic/cli/releases/latest';
const STATAMIC_API_URL = 'https://statamic.com/api/v1/';
public $input;
public $output;
public $relativePath;
public $absolutePath;
public $name;
public $version;
public $starterKit;
public $starterKits;
public $starterKitLicense;
public $local;
public $withConfig;
public $withoutDependencies;
public $force;
public $baseInstallSuccessful;
public $shouldUpdateCliToVersion = false;
public $makeUser = false;
public $spreadJoy = false;
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this
->setName('new')
->setDescription('Create a new Statamic application')
->addArgument('name', InputArgument::REQUIRED, 'Statamic application directory name')
->addOption('dev', null, InputOption::VALUE_NONE, 'Installs the latest "development" release')
->addArgument('starter-kit', InputArgument::OPTIONAL, 'Optionally install specific starter kit')
->addOption('license', null, InputOption::VALUE_OPTIONAL, 'Optionally provide explicit starter kit license')
->addOption('local', null, InputOption::VALUE_NONE, 'Optionally install from local repo configured in composer config.json')
->addOption('with-config', null, InputOption::VALUE_NONE, 'Optionally copy starter-kit.yaml config for local development')
->addOption('without-dependencies', null, InputOption::VALUE_NONE, 'Optionally install starter kit without dependencies')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Force install even if the directory already exists');
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->configurePrompts($input, $output);
$this
->setupTheme()
->checkCliVersion()
->notifyIfOldCliVersion()
->showStatamicTitleArt();
}
protected function interact(InputInterface $input, OutputInterface $output)
{
if (! $this->input->getArgument('name')) {
$this->input->setArgument('name', text(
label: 'What is the name of your project?',
placeholder: 'E.g. example-app',
required: 'The project name is required.',
validate: fn ($value) => preg_match('/[^\pL\pN\-_.]/', $value) !== 0
? 'The name may only contain letters, numbers, dashes, underscores, and periods.'
: null,
));
}
}
/**
* Execute the command.
*
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this
->processArguments()
->validateArguments()
->askForRepo()
->validateStarterKitLicense()
->askToMakeSuperUser()
->askToSpreadJoy()
->readySetGo()
->installBaseProject()
->installStarterKit()
->makeSuperUser()
->notifyIfOldCliVersion()
->showSuccessMessage()
->showPostInstallInstructions();
return 0;
}
protected function promptUntilValid($prompt, $required, $validate, $output)
{
while (true) {
$result = $prompt();
if ($required && ($result === '' || $result === [] || $result === false)) {
$output->writeln('<error>'.(is_string($required) ? $required : 'Required.').'</error>');
continue;
}
if ($validate) {
$error = $validate($result);
if (is_string($error) && strlen($error) > 0) {
$output->writeln("<error>{$error}</error>");
continue;
}
}
return $result;
}
}
protected function setupTheme()
{
Prompt::addTheme('statamic', [
SelectPrompt::class => SelectPromptRenderer::class,
SuggestPrompt::class => SuggestPromptRenderer::class,
ConfirmPrompt::class => ConfirmPromptRenderer::class,
TextPrompt::class => TextPromptRenderer::class,
]);
Prompt::theme('statamic');
return $this;
}
/**
* Check cli version.
*
* @return $this
*/
protected function checkCliVersion()
{
$request = new Client;
if (! $currentVersion = Version::get()) {
return $this;
}
try {
$response = $request->get(self::GITHUB_LATEST_RELEASE_ENDPOINT);
$latestVersion = json_decode($response->getBody(), true)['tag_name'];
} catch (\Throwable $exception) {
return $this;
}
if (version_compare($currentVersion, $latestVersion, '<')) {
$this->shouldUpdateCliToVersion = $latestVersion;
}
return $this;
}
/**
* Notify user if a statamic/cli upgrade exists.
*
* @return $this
*/
protected function notifyIfOldCliVersion()
{
if (! $this->shouldUpdateCliToVersion) {
return $this;
}
$this->output->write(PHP_EOL);
$this->output->write("<comment>This is an old version of the Statamic CLI Tool, please upgrade to {$this->shouldUpdateCliToVersion}!</comment>".PHP_EOL);
$this->output->write('<comment>If you have a global composer installation, you may upgrade by running the following command:</comment>'.PHP_EOL);
$this->output->write('<comment>composer global update statamic/cli</comment>'.PHP_EOL);
return $this;
}
/**
* Process arguments and options.
*
* @return $this
*/
protected function processArguments()
{
$this->relativePath = $this->input->getArgument('name');
$this->absolutePath = $this->relativePath && $this->relativePath !== '.'
? getcwd().'/'.$this->relativePath
: getcwd();
$this->name = pathinfo($this->absolutePath)['basename'];
$this->version = $this->input->getOption('dev')
? 'dev-master'
: '';
$this->starterKit = $this->input->getArgument('starter-kit');
$this->starterKitLicense = $this->input->getOption('license');
$this->local = $this->input->getOption('local');
$this->withConfig = $this->input->getOption('with-config');
$this->withoutDependencies = $this->input->getOption('without-dependencies');
$this->force = $this->input->getOption('force');
return $this;
}
/**
* Validate arguments and options.
*
* @return $this
*
* @throws RuntimeException
*/
protected function validateArguments()
{
if (! $this->force && $this->applicationExists()) {
throw new RuntimeException('Application already exists!');
}
if ($this->force && $this->pathIsCwd()) {
throw new RuntimeException('Cannot use --force option when using current directory for installation!');
}
if ($this->starterKit && $this->isInvalidStarterKit()) {
throw new RuntimeException('Please enter a valid composer package name (eg. hasselhoff/kung-fury)!');
}
if (! $this->starterKit && $this->starterKitLicense) {
throw new RuntimeException('Starter kit is required when using `--license` option!');
}
if (! $this->starterKit && $this->local) {
throw new RuntimeException('Starter kit is required when using `--local` option!');
}
if (! $this->starterKit && $this->withConfig) {
throw new RuntimeException('Starter kit is required when using `--with-config` option!');
}
if (! $this->starterKit && $this->withoutDependencies) {
throw new RuntimeException('Starter kit is required when using `--without-dependencies` option!');
}
return $this;
}
/**
* Show Statamic title art.
*
* @return $this
*/
protected function showStatamicTitleArt()
{
$this->output->write(PHP_EOL."<fg=#FF269E> $$\ $$\ $$\
$$ | $$ | \__|
$$$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\$$$$\ $$\ $$$$$$$\
$$ _____|\_$$ _| \____$$\\_$$ _| \____$$\ $$ _$$ _$$\ $$ |$$ _____|
\$$$$$$\ $$ | $$$$$$$ | $$ | $$$$$$$ |$$ / $$ / $$ |$$ |$$ /
\____$$\ $$ |$$\ $$ __$$ | $$ |$$\ $$ __$$ |$$ | $$ | $$ |$$ |$$ |
$$$$$$$ | \\$$$$ |\\$$$$$$$ | \\$$$$ |\\$$$$$$$ |$$ | $$ | $$ |$$ |\\$$$$$$$\
\_______/ \____/ \_______| \____/ \_______|\__| \__| \__|\__| \_______|
</>".PHP_EOL);
return $this;
}
/**
* Ask which starter kit repo to install.
*
* @return $this
*/
protected function askForRepo()
{
if ($this->starterKit || ! $this->input->isInteractive()) {
return $this;
}
$choice = select(
'Would you like to install a starter kit?',
options: [
$blankSiteOption = 'No, start with a blank site.',
'Yes, let me pick a Starter Kit.',
],
);
if ($choice === $blankSiteOption) {
return $this;
}
$this->output->write(' You can find starter kits at <info>https://statamic.com/starter-kits</info> 🏄'.PHP_EOL.PHP_EOL);
$this->starterKit = $this->normalizeStarterKitSelection(suggest(
'Which starter kit would you like to install?',
fn ($value) => $this->searchStarterKits($value)
));
if ($this->isInvalidStarterKit()) {
throw new RuntimeException('Please enter a valid composer package name (eg. hasselhoff/kung-fury)!');
}
return $this;
}
/**
* Validate starter kit license.
*
* @return $this
*/
protected function validateStarterKitLicense()
{
if (! $this->starterKit) {
return $this;
}
$request = new Client;
try {
$response = $request->get(self::OUTPOST_ENDPOINT."{$this->starterKit}");
} catch (\Exception $exception) {
$this->throwConnectionException();
}
$details = json_decode($response->getBody(), true);
// If $details === `false`, then no product was returned and we'll consider it a free starter kit.
if ($details['data'] === false) {
return $this->confirmUnlistedKit();
}
// If the returned product doesn't have a price, then we'll consider it a free starter kit.
if (! $details['data']['price']) {
return $this;
}
$sellerSlug = $details['data']['seller']['slug'];
$kitSlug = $details['data']['slug'];
$marketplaceUrl = "https://statamic.com/starter-kits/{$sellerSlug}/{$kitSlug}";
if ($this->input->isInteractive()) {
$this->output->write(' <comment>This is a paid starter kit. If you haven\'t already, you may purchase a license at:</comment>'.PHP_EOL);
$this->output->write(" <comment>{$marketplaceUrl}</comment>".PHP_EOL);
$this->output->write(PHP_EOL);
}
$license = $this->getStarterKitLicense();
try {
$response = $request->post(self::OUTPOST_ENDPOINT.'validate', ['json' => [
'license' => $license,
'package' => $this->starterKit,
]]);
} catch (\Exception $exception) {
$this->throwConnectionException();
}
$validation = json_decode($response->getBody(), true);
if (! $validation['data']['valid']) {
throw new RuntimeException("Invalid license for [{$this->starterKit}]!");
}
$this->output->write('<info>Starter kit license valid!</info>'.PHP_EOL);
$this->starterKitLicense = $license;
return $this->confirmSingleSiteLicense();
}
/**
* Confirm unlisted kit.
*
* @return $this
*/
protected function confirmUnlistedKit()
{
if (! confirm('Starter kit not found on Statamic Marketplace! Install unlisted starter kit?')) {
return $this->exitInstallation();
}
return $this;
}
/**
* Confirm single-site license.
*
* @return $this
*/
protected function confirmSingleSiteLicense()
{
$this->output->write(PHP_EOL);
$this->output->write('<comment>Once successfully installed, this single-site license will be marked as used</comment>'.PHP_EOL);
$this->output->write('<comment>and cannot be installed on future Statamic sites!</comment>');
if (! $this->input->isInteractive()) {
return $this;
}
$this->output->write(PHP_EOL.PHP_EOL);
if (! confirm('Would you like to continue installation?', false, 'I understand. Install now.', "No, I'll install it later.")) {
return $this->exitInstallation();
}
return $this;
}
/**
* Final confirmation
*
* @return $this
*/
protected function readySetGo()
{
if (! $this->input->isInteractive()) {
return $this;
}
if (! confirm('Ready?', yes: "Yes, let's do this!", no: 'No, shut it down.')) {
return $this->exitInstallation();
}
if ($this->spreadJoy) {
if (PHP_OS_FAMILY == 'Darwin') {
exec('open https://github.com/statamic/cms');
} elseif (PHP_OS_FAMILY == 'Windows') {
exec('start https://github.com/statamic/cms');
} elseif (PHP_OS_FAMILY == 'Linux') {
exec('xdg-open https://github.com/statamic/cms');
}
}
return $this;
}
/**
* Install base project.
*
* @return $this
*
* @throws RuntimeException
*/
protected function installBaseProject()
{
$commands = [];
if ($this->force && ! $this->pathIsCwd()) {
if (PHP_OS_FAMILY == 'Windows') {
$commands[] = "rd /s /q \"$this->absolutePath\"";
} else {
$commands[] = "rm -rf \"$this->absolutePath\"";
}
}
$commands[] = $this->createProjectCommand();
if (PHP_OS_FAMILY != 'Windows') {
$commands[] = "chmod 755 \"$this->absolutePath/artisan\"";
$commands[] = "chmod 755 \"$this->absolutePath/please\"";
}
$this->runCommands($commands);
if (! $this->wasBaseInstallSuccessful()) {
throw new RuntimeException('There was a problem installing Statamic!');
}
$this->updateEnvVars();
$this->baseInstallSuccessful = true;
return $this;
}
/**
* Install starter kit.
*
* @return $this
*
* @throws RuntimeException
*/
protected function installStarterKit()
{
if (! $this->baseInstallSuccessful || ! $this->starterKit) {
return $this;
}
$options = [
'--cli-install',
'--clear-site',
];
if (! $this->input->isInteractive()) {
$options[] = '--no-interaction';
}
if ($this->local) {
$options[] = '--local';
}
if ($this->withConfig) {
$options[] = '--with-config';
}
if ($this->starterKitLicense) {
$options[] = '--license';
$options[] = $this->starterKitLicense;
}
if ($this->withoutDependencies) {
$options[] = '--without-dependencies';
}
$statusCode = (new Please($this->output))
->cwd($this->absolutePath)
->run('starter-kit:install', $this->starterKit, ...$options);
if ($statusCode !== 0) {
throw new RuntimeException('There was a problem installing Statamic with the chosen starter kit!');
}
return $this;
}
protected function askToMakeSuperUser()
{
if (! $this->input->isInteractive()) {
return $this;
}
$this->makeUser = confirm('Create a super user?', false);
$this->output->write($this->makeUser
? " Great. You'll be prompted for details after installation."
: ' No problem. You can create one later with <comment>php please make:user</comment>.'
);
$this->output->write(PHP_EOL.PHP_EOL);
return $this;
}
/**
* Make super user.
*
* @return $this
*/
protected function makeSuperUser()
{
if (! $this->makeUser) {
return $this;
}
// Since Windows cannot TTY, we'll capture their input here and make a user.
if (PHP_OS_FAMILY === 'Windows') {
return $this->makeSuperUserInWindows();
}
// Otherwise, delegate to the `make:user` command with interactivity and let core handle the finer details.
(new Please($this->output))
->cwd($this->absolutePath)
->run('make:user', '--super');
return $this;
}
/**
* Make super user in Windows.
*
* @return $this
*/
protected function makeSuperUserInWindows()
{
$please = (new Please($this->output))->cwd($this->absolutePath);
// Ask for email
while (! isset($email) || ! $this->validateEmail($email)) {
$email = $this->askForBasicInput('Email');
}
// Ask for name
$name = $this->askForBasicInput('Name');
// Ask for password
while (! isset($password) || ! $this->validatePassword($password)) {
$password = $this->askForBasicInput('Password (Your input will be hidden)', true);
}
// Create super user and update with captured input.
$please->run('make:user', '--super', $email);
$updateUser = '\Statamic\Facades\User::findByEmail('.escapeshellarg($email).')'
.'->password('.escapeshellarg($password).')'
.'->makeSuper()';
if ($name) {
$updateUser .= '->set("name", '.escapeshellarg($name).')';
}
$updateUser .= '->save();';
$please->run('tinker', '--execute', $updateUser);
return $this;
}
/**
* Ask for basic input.
*
* @param string $label
* @param bool $hiddenInput
* @return mixed
*/
protected function askForBasicInput($label, $hiddenInput = false)
{
return $this->getHelper('question')->ask(
$this->input,
new SymfonyStyle($this->input, $this->output),
(new Question("{$label}: "))->setHidden($hiddenInput)
);
}
/**
* Validate email address.
*
* @param string $email
* @return bool
*/
protected function validateEmail($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
$this->output->write('<error>Invalid email address.</error>'.PHP_EOL);
return false;
}
/**
* Validate password.
*
* @param string $password
* @return bool
*/
protected function validatePassword($password)
{
if (strlen($password) >= 8) {
return true;
}
$this->output->write('<error>The input must be at least 8 characters.</error>'.PHP_EOL);
return false;
}
/**
* Show success message.
*
* @return $this
*/
protected function showSuccessMessage()
{
$this->output->writeln(PHP_EOL."<info>[✔] Statamic has been successfully installed into the <comment>{$this->relativePath}</comment> directory.</info>");
if (! $this->spreadJoy) {
$this->output->writeln('Spread some joy and star our GitHub repo! https://github.com/statamic/cms');
}
$this->output->writeln('Build something rad!');
return $this;
}
/**
* Show cached post-install instructions, if provided.
*
* @return $this
*/
protected function showPostInstallInstructions()
{
if (! file_exists($instructionsPath = $this->absolutePath.'/storage/statamic/tmp/cli/post-install-instructions.txt')) {
return $this;
}
$this->output->write(PHP_EOL);
foreach (file($instructionsPath) as $line) {
$this->output->write('<comment>'.trim($line).'</comment>'.PHP_EOL);
}
return $this;
}
/**
* Ask if user wants to star our GitHub repo.
*
* @return $this
*/
protected function askToSpreadJoy()
{
if (! $this->input->isInteractive()) {
return $this;
}
$response = select('Would you like to spread the joy of Statamic by starring the repo?', [
$yes = "Absolutely. I'll star it while you finish installing.",
$no = 'Maybe later',
], $no);
if ($this->spreadJoy = $response === $yes) {
$this->output->write(' Awesome. The browser will open when the installation begins.');
} else {
$this->output->write(' You can star the GitHub repo at any time if you change your mind.');
}
$this->output->write(PHP_EOL.PHP_EOL);
return $this;
}
/**
* Check if the application path already exists.
*
* @return bool
*/
protected function applicationExists()
{
if ($this->pathIsCwd()) {
return is_file("{$this->absolutePath}/composer.json");
}
return is_dir($this->absolutePath) || is_file($this->absolutePath);
}
/**
* Check if the application path is the current working directory.
*
* @return bool
*/
protected function pathIsCwd()
{
return $this->absolutePath === getcwd();
}
/**
* Check if the starter kit is invalid.
*
* @return bool
*/
protected function isInvalidStarterKit()
{
return ! preg_match("/^[^\/\s]+\/[^\/\s]+$/", $this->starterKit);
}
/**
* Determine if base install was successful.
*
* @return bool
*/
protected function wasBaseInstallSuccessful()
{
return is_file("{$this->absolutePath}/composer.json")
&& is_dir("{$this->absolutePath}/vendor")
&& is_file("{$this->absolutePath}/artisan")
&& is_file("{$this->absolutePath}/please");
}
/**
* Create the composer create-project command.
*
* @return string
*/
protected function createProjectCommand()
{
$composer = $this->findComposer();
$baseRepo = self::BASE_REPO;
$directory = $this->pathIsCwd() ? '.' : $this->relativePath;
return $composer." create-project {$baseRepo} \"{$directory}\" {$this->version} --remove-vcs --prefer-dist";
}
/**
* Get the composer command for the environment.
*
* @return string
*/
protected function findComposer()
{
$composerPath = getcwd().'/composer.phar';
if (file_exists($composerPath)) {
return '"'.PHP_BINARY.'" '.$composerPath;
}
return 'composer';
}
/**
* Update application env vars.
*/
protected function updateEnvVars()
{
$this->replaceInFile(
'APP_URL=http://localhost',
'APP_URL=http://'.$this->name.'.test',
$this->absolutePath.'/.env'
);
$this->replaceInFile(
'DB_DATABASE=laravel',
'DB_DATABASE='.str_replace('-', '_', strtolower($this->name)),
$this->absolutePath.'/.env'
);
}
/**
* Replace the given string in the given file.
*/
protected function replaceInFile(string $search, string $replace, string $file)
{
file_put_contents(
$file,
str_replace($search, $replace, file_get_contents($file))
);
}
/**
* Throw guzzle connection exception.
*
* @throws RuntimeException
*/
protected function throwConnectionException()
{
throw new RuntimeException('Cannot connect to [statamic.com] to validate license!');
}
/**
* Get starter kit license from parsed options, or ask user for license.
*
* @return string
*/
protected function getStarterKitLicense()
{
if ($this->starterKitLicense) {
return $this->starterKitLicense;
}
if (! $this->input->isInteractive()) {
throw new RuntimeException('A starter kit license is required, please pass using the `--license` option!');
}
return text('Please enter your license key', required: true);
}
/**
* Exit installation.
*
* @return \stdClass
*/
protected function exitInstallation()
{
return new class
{
public function __call($method, $args)
{
return $this;
}
};
}
private function searchStarterKits($value)
{
$kits = $this->getStarterKits();
return array_filter($kits, fn ($kit) => str_contains(strtolower($kit), strtolower($value)));
}
private function getStarterKits()
{
return $this->starterKits ??= $this->fetchStarterKits();
}
private function fetchStarterKits()
{
$request = new Client(['base_uri' => self::STATAMIC_API_URL]);
try {
$response = $request->get('marketplace/starter-kits', ['query' => ['perPage' => 100]]);
$results = json_decode($response->getBody(), true)['data'];
$options = [];
foreach ($results as $value) {
$options[$value['package']] = $value['name'].' ('.$value['package'].')';
}
return $options;
} catch (\Exception $e) {
return [];
}
}
private function normalizeStarterKitSelection($kit)
{
// If it doesn't have a bracket it means they manually entered a value and didn't pick a suggestion.
if (! str_contains($kit, ' (')) {
return $kit;
}
return array_search($kit, $this->getStarterKits());
}
}