-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathNewCommand.php
1067 lines (925 loc) · 37.3 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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Laravel\Installer\Console;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Composer;
use Illuminate\Support\ProcessUtils;
use RuntimeException;
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\Terminal;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\select;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;
class NewCommand extends Command
{
use Concerns\ConfiguresPrompts;
use Concerns\InteractsWithHerdOrValet;
/**
* The Composer instance.
*
* @var \Illuminate\Support\Composer
*/
protected $composer;
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this
->setName('new')
->setDescription('Create a new Laravel application')
->addArgument('name', InputArgument::REQUIRED)
->addOption('dev', null, InputOption::VALUE_NONE, 'Installs the latest "development" release')
->addOption('git', null, InputOption::VALUE_NONE, 'Initialize a Git repository')
->addOption('branch', null, InputOption::VALUE_REQUIRED, 'The branch that should be created for a new repository', $this->defaultBranch())
->addOption('github', null, InputOption::VALUE_OPTIONAL, 'Create a new repository on GitHub', false)
->addOption('organization', null, InputOption::VALUE_REQUIRED, 'The GitHub organization to create the new repository for')
->addOption('database', null, InputOption::VALUE_REQUIRED, 'The database driver your application will use')
->addOption('stack', null, InputOption::VALUE_OPTIONAL, 'The Breeze / Jetstream stack that should be installed')
->addOption('breeze', null, InputOption::VALUE_NONE, 'Installs the Laravel Breeze scaffolding')
->addOption('jet', null, InputOption::VALUE_NONE, 'Installs the Laravel Jetstream scaffolding')
->addOption('dark', null, InputOption::VALUE_NONE, 'Indicate whether Breeze or Jetstream should be scaffolded with dark mode support')
->addOption('typescript', null, InputOption::VALUE_NONE, 'Indicate whether Breeze should be scaffolded with TypeScript support')
->addOption('eslint', null, InputOption::VALUE_NONE, 'Indicate whether Breeze should be scaffolded with ESLint and Prettier support')
->addOption('ssr', null, InputOption::VALUE_NONE, 'Indicate whether Breeze or Jetstream should be scaffolded with Inertia SSR support')
->addOption('api', null, InputOption::VALUE_NONE, 'Indicates whether Jetstream should be scaffolded with API support')
->addOption('teams', null, InputOption::VALUE_NONE, 'Indicates whether Jetstream should be scaffolded with team support')
->addOption('verification', null, InputOption::VALUE_NONE, 'Indicates whether Jetstream should be scaffolded with email verification support')
->addOption('pest', null, InputOption::VALUE_NONE, 'Installs the Pest testing framework')
->addOption('phpunit', null, InputOption::VALUE_NONE, 'Installs the PHPUnit testing framework')
->addOption('prompt-breeze', null, InputOption::VALUE_NONE, 'Issues a prompt to determine if Breeze should be installed (Deprecated)')
->addOption('prompt-jetstream', null, InputOption::VALUE_NONE, 'Issues a prompt to determine if Jetstream should be installed (Deprecated)')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Forces install even if the directory already exists');
}
/**
* Interact with the user before validating the input.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
parent::interact($input, $output);
$this->configurePrompts($input, $output);
$output->write(PHP_EOL.' <fg=red> _ _
| | | |
| | __ _ _ __ __ ___ _____| |
| | / _` | \'__/ _` \ \ / / _ \ |
| |___| (_| | | | (_| |\ V / __/ |
|______\__,_|_| \__,_| \_/ \___|_|</>'.PHP_EOL.PHP_EOL);
$this->ensureExtensionsAreAvailable($input, $output);
if (! $input->getArgument('name')) {
$input->setArgument('name', text(
label: 'What is the name of your project?',
placeholder: 'E.g. example-app',
required: 'The project name is required.',
validate: function ($value) use ($input) {
if (preg_match('/[^\pL\pN\-_.]/', $value) !== 0) {
return 'The name may only contain letters, numbers, dashes, underscores, and periods.';
}
if ($input->getOption('force') !== true) {
try {
$this->verifyApplicationDoesntExist($this->getInstallationDirectory($value));
} catch (RuntimeException $e) {
return 'Application already exists.';
}
}
},
));
}
if ($input->getOption('force') !== true) {
$this->verifyApplicationDoesntExist(
$this->getInstallationDirectory($input->getArgument('name'))
);
}
if (! $input->getOption('breeze') && ! $input->getOption('jet')) {
match (select(
label: 'Would you like to install a starter kit?',
options: [
'none' => 'No starter kit',
'breeze' => 'Laravel Breeze',
'jetstream' => 'Laravel Jetstream',
],
default: 'none',
)) {
'breeze' => $input->setOption('breeze', true),
'jetstream' => $input->setOption('jet', true),
default => null,
};
}
if ($input->getOption('breeze')) {
$this->promptForBreezeOptions($input);
} elseif ($input->getOption('jet')) {
$this->promptForJetstreamOptions($input);
}
if (! $input->getOption('phpunit') && ! $input->getOption('pest')) {
$input->setOption('pest', select(
label: 'Which testing framework do you prefer?',
options: ['Pest', 'PHPUnit'],
default: 'Pest',
) === 'Pest');
}
// if (! $input->getOption('git') && $input->getOption('github') === false && Process::fromShellCommandline('git --version')->run() === 0) {
// $input->setOption('git', confirm(label: 'Would you like to initialize a Git repository?', default: false));
// }
}
/**
* Ensure that the required PHP extensions are installed.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*
* @throws \RuntimeException
*/
protected function ensureExtensionsAreAvailable(InputInterface $input, OutputInterface $output): void
{
$availableExtensions = get_loaded_extensions();
$missingExtensions = collect([
'ctype',
'filter',
'hash',
'mbstring',
'openssl',
'session',
'tokenizer',
])->reject(fn ($extension) => in_array($extension, $availableExtensions));
if ($missingExtensions->isEmpty()) {
return;
}
throw new \RuntimeException(
sprintf('The following PHP extensions are required but are not installed: %s', $missingExtensions->join(', ', ', and '))
);
}
/**
* Execute the command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->validateDatabaseOption($input);
$this->validateStackOption($input);
$name = mb_rtrim($input->getArgument('name'), '/\\');
$directory = $this->getInstallationDirectory($name);
$this->composer = new Composer(new Filesystem(), $directory);
$version = $this->getVersion($input);
if (! $input->getOption('force')) {
$this->verifyApplicationDoesntExist($directory);
}
if ($input->getOption('force') && $directory === '.') {
throw new RuntimeException('Cannot use --force option when using current directory for installation!');
}
$composer = $this->findComposer();
$phpBinary = $this->phpBinary();
$commands = [
$composer." create-project laravel/laravel \"$directory\" $version --remove-vcs --prefer-dist --no-scripts",
$composer." run post-root-package-install -d \"$directory\"",
$phpBinary." \"$directory/artisan\" key:generate --ansi",
];
if ($directory != '.' && $input->getOption('force')) {
if (PHP_OS_FAMILY == 'Windows') {
array_unshift($commands, "(if exist \"$directory\" rd /s /q \"$directory\")");
} else {
array_unshift($commands, "rm -rf \"$directory\"");
}
}
if (PHP_OS_FAMILY != 'Windows') {
$commands[] = "chmod 755 \"$directory/artisan\"";
}
if (($process = $this->runCommands($commands, $input, $output))->isSuccessful()) {
if ($name !== '.') {
$this->replaceInFile(
'APP_URL=http://localhost',
'APP_URL='.$this->generateAppUrl($name),
$directory.'/.env'
);
[$database, $migrate] = $this->promptForDatabaseOptions($directory, $input);
$this->configureDefaultDatabaseConnection($directory, $database, $name);
if ($migrate) {
if ($database === 'sqlite') {
touch($directory.'/database/database.sqlite');
}
$commands = [
trim(sprintf(
$this->phpBinary().' artisan migrate %s',
! $input->isInteractive() ? '--no-interaction' : '',
)),
];
$this->runCommands($commands, $input, $output, workingPath: $directory);
}
}
if ($input->getOption('git') || $input->getOption('github') !== false) {
$this->createRepository($directory, $input, $output);
}
if ($input->getOption('breeze')) {
$this->installBreeze($directory, $input, $output);
} elseif ($input->getOption('jet')) {
$this->installJetstream($directory, $input, $output);
} elseif ($input->getOption('pest')) {
$this->installPest($directory, $input, $output);
}
if ($input->getOption('github') !== false) {
$this->pushToGitHub($name, $directory, $input, $output);
$output->writeln('');
}
$this->configureComposerDevScript($directory);
$output->writeln(" <bg=blue;fg=white> INFO </> Application ready in <options=bold>[{$name}]</>. You can start your local development using:".PHP_EOL);
$output->writeln('<fg=gray>➜</> <options=bold>cd '.$name.'</>');
$output->writeln('<fg=gray>➜</> <options=bold>npm install && npm run build</>');
if ($this->isParkedOnHerdOrValet($directory)) {
$url = $this->generateAppUrl($name);
$output->writeln('<fg=gray>➜</> Open: <options=bold;href='.$url.'>'.$url.'</>');
} else {
$output->writeln('<fg=gray>➜</> <options=bold>composer run dev</>');
}
$output->writeln('');
$output->writeln(' New to Laravel? Check out our <href=https://bootcamp.laravel.com>bootcamp</> and <href=https://laravel.com/docs/installation#next-steps>documentation</>. <options=bold>Build something amazing!</>');
$output->writeln('');
}
return $process->getExitCode();
}
/**
* Return the local machine's default Git branch if set or default to `main`.
*
* @return string
*/
protected function defaultBranch()
{
$process = new Process(['git', 'config', '--global', 'init.defaultBranch']);
$process->run();
$output = trim($process->getOutput());
return $process->isSuccessful() && $output ? $output : 'main';
}
/**
* Configure the default database connection.
*
* @param string $directory
* @param string $database
* @param string $name
* @return void
*/
protected function configureDefaultDatabaseConnection(string $directory, string $database, string $name)
{
$this->pregReplaceInFile(
'/DB_CONNECTION=.*/',
'DB_CONNECTION='.$database,
$directory.'/.env'
);
$this->pregReplaceInFile(
'/DB_CONNECTION=.*/',
'DB_CONNECTION='.$database,
$directory.'/.env.example'
);
if ($database === 'sqlite') {
$environment = file_get_contents($directory.'/.env');
// If database options aren't commented, comment them for SQLite...
if (! str_contains($environment, '# DB_HOST=127.0.0.1')) {
$this->commentDatabaseConfigurationForSqlite($directory);
return;
}
return;
}
// Any commented database configuration options should be uncommented when not on SQLite...
$this->uncommentDatabaseConfiguration($directory);
$defaultPorts = [
'pgsql' => '5432',
'sqlsrv' => '1433',
];
if (isset($defaultPorts[$database])) {
$this->replaceInFile(
'DB_PORT=3306',
'DB_PORT='.$defaultPorts[$database],
$directory.'/.env'
);
$this->replaceInFile(
'DB_PORT=3306',
'DB_PORT='.$defaultPorts[$database],
$directory.'/.env.example'
);
}
$this->replaceInFile(
'DB_DATABASE=laravel',
'DB_DATABASE='.str_replace('-', '_', strtolower($name)),
$directory.'/.env'
);
$this->replaceInFile(
'DB_DATABASE=laravel',
'DB_DATABASE='.str_replace('-', '_', strtolower($name)),
$directory.'/.env.example'
);
}
/**
* Determine if the application is using Laravel 11 or newer.
*
* @param string $directory
* @return bool
*/
public function usingLaravelVersionOrNewer(int $usingVersion, string $directory): bool
{
$version = json_decode(file_get_contents($directory.'/composer.json'), true)['require']['laravel/framework'];
$version = str_replace('^', '', $version);
$version = explode('.', $version)[0];
return $version >= $usingVersion;
}
/**
* Comment the irrelevant database configuration entries for SQLite applications.
*
* @param string $directory
* @return void
*/
protected function commentDatabaseConfigurationForSqlite(string $directory): void
{
$defaults = [
'DB_HOST=127.0.0.1',
'DB_PORT=3306',
'DB_DATABASE=laravel',
'DB_USERNAME=root',
'DB_PASSWORD=',
];
$this->replaceInFile(
$defaults,
collect($defaults)->map(fn ($default) => "# {$default}")->all(),
$directory.'/.env'
);
$this->replaceInFile(
$defaults,
collect($defaults)->map(fn ($default) => "# {$default}")->all(),
$directory.'/.env.example'
);
}
/**
* Uncomment the relevant database configuration entries for non SQLite applications.
*
* @param string $directory
* @return void
*/
protected function uncommentDatabaseConfiguration(string $directory)
{
$defaults = [
'# DB_HOST=127.0.0.1',
'# DB_PORT=3306',
'# DB_DATABASE=laravel',
'# DB_USERNAME=root',
'# DB_PASSWORD=',
];
$this->replaceInFile(
$defaults,
collect($defaults)->map(fn ($default) => substr($default, 2))->all(),
$directory.'/.env'
);
$this->replaceInFile(
$defaults,
collect($defaults)->map(fn ($default) => substr($default, 2))->all(),
$directory.'/.env.example'
);
}
/**
* Install Laravel Breeze into the application.
*
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function installBreeze(string $directory, InputInterface $input, OutputInterface $output)
{
$commands = array_filter([
$this->findComposer().' require laravel/breeze --dev',
trim(sprintf(
$this->phpBinary().' artisan breeze:install %s %s %s %s %s %s',
$input->getOption('stack'),
$input->getOption('typescript') ? '--typescript' : '',
$input->getOption('pest') ? '--pest' : '',
$input->getOption('dark') ? '--dark' : '',
$input->getOption('ssr') ? '--ssr' : '',
$input->getOption('eslint') ? '--eslint' : '',
)),
]);
$this->runCommands($commands, $input, $output, workingPath: $directory);
$this->commitChanges('Install Breeze', $directory, $input, $output);
}
/**
* Install Laravel Jetstream into the application.
*
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function installJetstream(string $directory, InputInterface $input, OutputInterface $output)
{
$commands = array_filter([
$this->findComposer().' require laravel/jetstream',
trim(sprintf(
$this->phpBinary().' artisan jetstream:install %s %s %s %s %s %s %s',
$input->getOption('stack'),
$input->getOption('api') ? '--api' : '',
$input->getOption('dark') ? '--dark' : '',
$input->getOption('teams') ? '--teams' : '',
$input->getOption('pest') ? '--pest' : '',
$input->getOption('verification') ? '--verification' : '',
$input->getOption('ssr') ? '--ssr' : '',
)),
]);
$this->runCommands($commands, $input, $output, workingPath: $directory);
$this->commitChanges('Install Jetstream', $directory, $input, $output);
}
/**
* Determine the default database connection.
*
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @return array
*/
protected function promptForDatabaseOptions(string $directory, InputInterface $input)
{
$defaultDatabase = collect(
$databaseOptions = $this->databaseOptions()
)->keys()->first();
if (! $input->getOption('database') && $input->isInteractive()) {
$input->setOption('database', select(
label: 'Which database will your application use?',
options: $databaseOptions,
default: $defaultDatabase,
));
$migrate = confirm(
label: $input->getOption('database') !== 'sqlite'
? 'Default database updated. Would you like to run the default database migrations?'
: 'Would you like to run the default database migrations?',
default: true
);
}
return [$input->getOption('database') ?? $defaultDatabase, $migrate ?? $input->hasOption('database')];
}
/**
* Get the available database options.
*
* @return array
*/
protected function databaseOptions(): array
{
return collect([
'sqlite' => ['SQLite', extension_loaded('pdo_sqlite')],
'mysql' => ['MySQL', extension_loaded('pdo_mysql')],
'mariadb' => ['MariaDB', extension_loaded('pdo_mysql')],
'pgsql' => ['PostgreSQL', extension_loaded('pdo_pgsql')],
'sqlsrv' => ['SQL Server', extension_loaded('pdo_sqlsrv')],
])
->sortBy(fn ($database) => $database[1] ? 0 : 1)
->map(fn ($database) => $database[0].($database[1] ? '' : ' (Missing PDO extension)'))
->all();
}
/**
* Determine the stack for Breeze.
*
* @return void
*/
protected function promptForBreezeOptions(InputInterface $input)
{
if (! $input->getOption('stack')) {
$input->setOption('stack', select(
label: 'Which Breeze stack would you like to install?',
options: [
'blade' => 'Blade with Alpine',
'livewire' => 'Livewire (Volt Class API) with Alpine',
'livewire-functional' => 'Livewire (Volt Functional API) with Alpine',
'react' => 'React with Inertia',
'vue' => 'Vue with Inertia',
'api' => 'API only',
],
default: 'blade',
));
}
if (in_array($input->getOption('stack'), ['react', 'vue']) && (! $input->getOption('dark') || ! $input->getOption('ssr'))) {
collect(multiselect(
label: 'Would you like any optional features?',
options: [
'dark' => 'Dark mode',
'ssr' => 'Inertia SSR',
'typescript' => 'TypeScript',
'eslint' => 'ESLint with Prettier',
],
default: array_filter([
$input->getOption('dark') ? 'dark' : null,
$input->getOption('ssr') ? 'ssr' : null,
$input->getOption('typescript') ? 'typescript' : null,
$input->getOption('eslint') ? 'eslint' : null,
]),
))->each(fn ($option) => $input->setOption($option, true));
} elseif (in_array($input->getOption('stack'), ['blade', 'livewire', 'livewire-functional']) && ! $input->getOption('dark')) {
$input->setOption('dark', confirm(
label: 'Would you like dark mode support?',
default: false,
));
}
}
/**
* Determine the stack for Jetstream.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @return void
*/
protected function promptForJetstreamOptions(InputInterface $input)
{
if (! $input->getOption('stack')) {
$input->setOption('stack', select(
label: 'Which Jetstream stack would you like to install?',
options: [
'livewire' => 'Livewire',
'inertia' => 'Vue with Inertia',
],
default: 'livewire',
));
}
collect(multiselect(
label: 'Would you like any optional features?',
options: collect([
'api' => 'API support',
'dark' => 'Dark mode',
'verification' => 'Email verification',
'teams' => 'Team support',
])->when(
$input->getOption('stack') === 'inertia',
fn ($options) => $options->put('ssr', 'Inertia SSR')
)->all(),
default: array_filter([
$input->getOption('api') ? 'api' : null,
$input->getOption('dark') ? 'dark' : null,
$input->getOption('teams') ? 'teams' : null,
$input->getOption('verification') ? 'verification' : null,
$input->getOption('stack') === 'inertia' && $input->getOption('ssr') ? 'ssr' : null,
]),
))->each(fn ($option) => $input->setOption($option, true));
}
/**
* Validate the database driver input.
*
* @param \Symfony\Components\Console\Input\InputInterface
*/
protected function validateDatabaseOption(InputInterface $input)
{
if ($input->getOption('database') && ! in_array($input->getOption('database'), $drivers = ['mysql', 'mariadb', 'pgsql', 'sqlite', 'sqlsrv'])) {
throw new \InvalidArgumentException("Invalid database driver [{$input->getOption('database')}]. Valid options are: ".implode(', ', $drivers).'.');
}
}
/**
* Validate the starter kit stack input.
*
* @param \Symfony\Components\Console\Input\InputInterface
*/
protected function validateStackOption(InputInterface $input)
{
if ($input->getOption('breeze')) {
if (! in_array($input->getOption('stack'), $stacks = ['blade', 'livewire', 'livewire-functional', 'react', 'vue', 'api'])) {
throw new \InvalidArgumentException("Invalid Breeze stack [{$input->getOption('stack')}]. Valid options are: ".implode(', ', $stacks).'.');
}
return;
}
if ($input->getOption('jet')) {
if (! in_array($input->getOption('stack'), $stacks = ['inertia', 'livewire'])) {
throw new \InvalidArgumentException("Invalid Jetstream stack [{$input->getOption('stack')}]. Valid options are: ".implode(', ', $stacks).'.');
}
return;
}
}
/**
* Install Pest into the application.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function installPest(string $directory, InputInterface $input, OutputInterface $output)
{
$composerBinary = $this->findComposer();
$commands = [
$composerBinary.' remove phpunit/phpunit --dev --no-update',
$composerBinary.' require pestphp/pest pestphp/pest-plugin-laravel --no-update --dev',
$composerBinary.' update',
$this->phpBinary().' ./vendor/bin/pest --init',
];
$this->runCommands($commands, $input, $output, workingPath: $directory, env: [
'PEST_NO_SUPPORT' => 'true',
]);
$this->replaceFile(
'pest/Feature.php',
$directory.'/tests/Feature/ExampleTest.php',
);
$this->replaceFile(
'pest/Unit.php',
$directory.'/tests/Unit/ExampleTest.php',
);
$this->commitChanges('Install Pest', $directory, $input, $output);
}
/**
* Create a Git repository and commit the base Laravel skeleton.
*
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function createRepository(string $directory, InputInterface $input, OutputInterface $output)
{
$branch = $input->getOption('branch') ?: $this->defaultBranch();
$commands = [
'git init -q',
'git add .',
'git commit -q -m "Set up a fresh Laravel app"',
"git branch -M {$branch}",
];
$this->runCommands($commands, $input, $output, workingPath: $directory);
}
/**
* Commit any changes in the current working directory.
*
* @param string $message
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function commitChanges(string $message, string $directory, InputInterface $input, OutputInterface $output)
{
if (! $input->getOption('git') && $input->getOption('github') === false) {
return;
}
$commands = [
'git add .',
"git commit -q -m \"$message\"",
];
$this->runCommands($commands, $input, $output, workingPath: $directory);
}
/**
* Create a GitHub repository and push the git log to it.
*
* @param string $name
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function pushToGitHub(string $name, string $directory, InputInterface $input, OutputInterface $output)
{
$process = new Process(['gh', 'auth', 'status']);
$process->run();
if (! $process->isSuccessful()) {
$output->writeln(' <bg=yellow;fg=black> WARN </> Make sure the "gh" CLI tool is installed and that you\'re authenticated to GitHub. Skipping...'.PHP_EOL);
return;
}
$name = $input->getOption('organization') ? $input->getOption('organization')."/$name" : $name;
$flags = $input->getOption('github') ?: '--private';
$commands = [
"gh repo create {$name} --source=. --push {$flags}",
];
$this->runCommands($commands, $input, $output, workingPath: $directory, env: ['GIT_TERMINAL_PROMPT' => 0]);
}
/**
* Configure the Composer "dev" script.
*
* @param string $directory
* @return void
*/
protected function configureComposerDevScript(string $directory): void
{
$this->composer->modify(function (array $content) {
if (windows_os()) {
$content['scripts']['dev'] = [
'Composer\\Config::disableProcessTimeout',
"npx concurrently -c \"#93c5fd,#c4b5fd,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"npm run dev\" --names='server,queue,vite'",
];
}
return $content;
});
}
/**
* Verify that the application does not already exist.
*
* @param string $directory
* @return void
*/
protected function verifyApplicationDoesntExist($directory)
{
if ((is_dir($directory) || is_file($directory)) && $directory != getcwd()) {
throw new RuntimeException('Application already exists!');
}
}
/**
* Generate a valid APP_URL for the given application name.
*
* @param string $name
* @return string
*/
protected function generateAppUrl($name)
{
$hostname = mb_strtolower($name).'.'.$this->getTld();
return $this->canResolveHostname($hostname) ? 'http://'.$hostname : 'http://localhost';
}
/**
* Get the TLD for the application.
*
* @return string
*/
protected function getTld()
{
return $this->runOnValetOrHerd('tld') ?: 'test';
}
/**
* Determine whether the given hostname is resolvable.
*
* @param string $hostname
* @return bool
*/
protected function canResolveHostname($hostname)
{
return gethostbyname($hostname.'.') !== $hostname.'.';
}
/**
* Get the installation directory.
*
* @param string $name
* @return string
*/
protected function getInstallationDirectory(string $name)
{
return $name !== '.' ? getcwd().'/'.$name : '.';
}
/**
* Get the version that should be downloaded.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @return string
*/
protected function getVersion(InputInterface $input)
{
if ($input->getOption('dev')) {
return 'dev-master';
}
return '';
}
/**
* Get the composer command for the environment.
*
* @return string
*/
protected function findComposer()
{
return implode(' ', $this->composer->findComposer());
}
/**
* Get the path to the appropriate PHP binary.
*
* @return string
*/
protected function phpBinary()
{
$phpBinary = function_exists('Illuminate\Support\php_binary')
? \Illuminate\Support\php_binary()
: (new PhpExecutableFinder)->find(false);
return $phpBinary !== false
? ProcessUtils::escapeArgument($phpBinary)
: 'php';
}
/**
* Run the given commands.
*
* @param array $commands
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param string|null $workingPath
* @param array $env
* @return \Symfony\Component\Process\Process
*/
protected function runCommands($commands, InputInterface $input, OutputInterface $output, ?string $workingPath = null, array $env = [])
{
if (! $output->isDecorated()) {
$commands = array_map(function ($value) {
if (str_starts_with($value, 'chmod')) {
return $value;
}
if (str_starts_with($value, 'git')) {
return $value;
}
return $value.' --no-ansi';
}, $commands);
}
if (! $output->isVerbose() && $this->canUseSpinner($input, $output)) {
$commands = array_map(function ($value) {
if (str_starts_with($value, 'chmod')) {
return $value;
}
if (str_starts_with($value, 'git')) {
return $value;
}
return $value.' --quiet';
}, $commands);
}
foreach ($commands as $command) {
$process = $this->runCommand($command, $input, $output, $workingPath, $env);
if (! $process->isSuccessful()) {
$output->writeln(' <bg=red;fg=white> ERROR </> '.$process->getErrorOutput().PHP_EOL);
break;
}
}
return $process;
}
/**
* Run the given command.
*
* @param string $command
* @param InputInterface $input
* @param OutputInterface $output
* @param string|null $workingPath
* @param array $env
* @return \Symfony\Component\Process\Process
*/
protected function runCommand(string $command, InputInterface $input, OutputInterface $output, ?string $workingPath = null, array $env = [])
{
$process = Process::fromShellCommandline($command, $workingPath, $env, null, null);
if ($this->canUseSpinner($input, $output)) {
$terminalWidth = (new Terminal)->getWidth();
$description = mb_substr($command, 0, $terminalWidth - 6);
return spin(fn () => tap($process)->run(), "<fg=gray>{$description}...</>");
}
if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
try {
$process->setTty(true);
} catch (RuntimeException $e) {
$output->writeln(' <bg=yellow;fg=black> WARN </> '.$e->getMessage().PHP_EOL);
}
}
$process->run(function ($type, $line) use ($output) {