-
Notifications
You must be signed in to change notification settings - Fork 517
/
Copy pathInstallCommand.php
362 lines (314 loc) · 11.3 KB
/
InstallCommand.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
<?php
namespace Laravel\Breeze\Console;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\PromptsForMissingInput;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use RuntimeException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
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;
class InstallCommand extends Command implements PromptsForMissingInput
{
use InstallsApiStack, InstallsBladeStack, InstallsInertiaStacks;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'breeze:install {stack : The development stack that should be installed (blade,react,vue,api)}
{--dark : Indicate that dark mode support should be installed}
{--pest : Indicate that Pest should be installed}
{--ssr : Indicates if Inertia SSR support should be installed}
{--typescript : Indicates if TypeScript is preferred for the Inertia stack (Experimental)}
{--composer=global : Absolute path to the Composer binary which should be used to install packages}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install the Breeze controllers and resources';
/**
* Execute the console command.
*
* @return int|null
*/
public function handle()
{
if ($this->argument('stack') === 'vue') {
return $this->installInertiaVueStack();
} elseif ($this->argument('stack') === 'react') {
return $this->installInertiaReactStack();
} elseif ($this->argument('stack') === 'api') {
return $this->installApiStack();
} elseif ($this->argument('stack') === 'blade') {
return $this->installBladeStack();
}
$this->components->error('Invalid stack. Supported stacks are [blade], [react], [vue], and [api].');
return 1;
}
/**
* Install Breeze's tests.
*
* @return bool
*/
protected function installTests()
{
(new Filesystem)->ensureDirectoryExists(base_path('tests/Feature'));
$stubStack = $this->argument('stack') === 'api' ? 'api' : 'default';
if ($this->option('pest') || $this->isUsingPest()) {
if ($this->hasComposerPackage('phpunit/phpunit')) {
$this->removeComposerPackages(['phpunit/phpunit'], true);
}
if (! $this->requireComposerPackages(['pestphp/pest:^2.0', 'pestphp/pest-plugin-laravel:^2.0'], true)) {
return false;
}
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Feature', base_path('tests/Feature'));
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Unit', base_path('tests/Unit'));
(new Filesystem)->copy(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Pest.php', base_path('tests/Pest.php'));
} else {
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/tests/Feature', base_path('tests/Feature'));
}
return true;
}
/**
* Install the middleware to a group in the application Http Kernel.
*
* @param string $after
* @param string $name
* @param string $group
* @return void
*/
protected function installMiddlewareAfter($after, $name, $group = 'web')
{
$httpKernel = file_get_contents(app_path('Http/Kernel.php'));
$middlewareGroups = Str::before(Str::after($httpKernel, '$middlewareGroups = ['), '];');
$middlewareGroup = Str::before(Str::after($middlewareGroups, "'$group' => ["), '],');
if (! Str::contains($middlewareGroup, $name)) {
$modifiedMiddlewareGroup = str_replace(
$after.',',
$after.','.PHP_EOL.' '.$name.',',
$middlewareGroup,
);
file_put_contents(app_path('Http/Kernel.php'), str_replace(
$middlewareGroups,
str_replace($middlewareGroup, $modifiedMiddlewareGroup, $middlewareGroups),
$httpKernel
));
}
}
/**
* Determine if the given Composer package is installed.
*
* @param string $package
* @return bool
*/
protected function hasComposerPackage($package)
{
$packages = json_decode(file_get_contents(base_path('composer.json')), true);
return array_key_exists($package, $packages['require'] ?? [])
|| array_key_exists($package, $packages['require-dev'] ?? []);
}
/**
* Installs the given Composer Packages into the application.
*
* @param array $packages
* @param bool $asDev
* @return bool
*/
protected function requireComposerPackages(array $packages, $asDev = false)
{
$composer = $this->option('composer');
if ($composer !== 'global') {
$command = ['php', $composer, 'require'];
}
$command = array_merge(
$command ?? ['composer', 'require'],
$packages,
$asDev ? ['--dev'] : [],
);
return (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1']))
->setTimeout(null)
->run(function ($type, $output) {
$this->output->write($output);
}) === 0;
}
/**
* Removes the given Composer Packages from the application.
*
* @param array $packages
* @param bool $asDev
* @return bool
*/
protected function removeComposerPackages(array $packages, $asDev = false)
{
$composer = $this->option('composer');
if ($composer !== 'global') {
$command = ['php', $composer, 'remove'];
}
$command = array_merge(
$command ?? ['composer', 'remove'],
$packages,
$asDev ? ['--dev'] : [],
);
return (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1']))
->setTimeout(null)
->run(function ($type, $output) {
$this->output->write($output);
}) === 0;
}
/**
* Update the "package.json" file.
*
* @param callable $callback
* @param bool $dev
* @return void
*/
protected static function updateNodePackages(callable $callback, $dev = true)
{
if (! file_exists(base_path('package.json'))) {
return;
}
$configurationKey = $dev ? 'devDependencies' : 'dependencies';
$packages = json_decode(file_get_contents(base_path('package.json')), true);
$packages[$configurationKey] = $callback(
array_key_exists($configurationKey, $packages) ? $packages[$configurationKey] : [],
$configurationKey
);
ksort($packages[$configurationKey]);
file_put_contents(
base_path('package.json'),
json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
);
}
/**
* Delete the "node_modules" directory and remove the associated lock files.
*
* @return void
*/
protected static function flushNodeModules()
{
tap(new Filesystem, function ($files) {
$files->deleteDirectory(base_path('node_modules'));
$files->delete(base_path('yarn.lock'));
$files->delete(base_path('package-lock.json'));
});
}
/**
* Replace a given string within a given file.
*
* @param string $search
* @param string $replace
* @param string $path
* @return void
*/
protected function replaceInFile($search, $replace, $path)
{
file_put_contents($path, str_replace($search, $replace, file_get_contents($path)));
}
/**
* Get the path to the appropriate PHP binary.
*
* @return string
*/
protected function phpBinary()
{
return (new PhpExecutableFinder())->find(false) ?: 'php';
}
/**
* Run the given commands.
*
* @param array $commands
* @return void
*/
protected function runCommands($commands)
{
$process = Process::fromShellCommandline(implode(' && ', $commands), null, null, null, null);
if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
try {
$process->setTty(true);
} catch (RuntimeException $e) {
$this->output->writeln(' <bg=yellow;fg=black> WARN </> '.$e->getMessage().PHP_EOL);
}
}
$process->run(function ($type, $line) {
$this->output->write(' '.$line);
});
}
/**
* Remove Tailwind dark classes from the given files.
*
* @param \Symfony\Component\Finder\Finder $finder
* @return void
*/
protected function removeDarkClasses(Finder $finder)
{
foreach ($finder as $file) {
file_put_contents($file->getPathname(), preg_replace('/\sdark:[^\s"\']+/', '', $file->getContents()));
}
}
/**
* Prompt for missing input arguments using the returned questions.
*
* @return array
*/
protected function promptForMissingArgumentsUsing()
{
return [
'stack' => fn () => select(
label: 'Which Breeze stack would you like to install?',
options: [
'blade' => 'Blade',
'react' => 'React with Inertia',
'vue' => 'Vue with Inertia',
'api' => 'API only',
]
),
];
}
/**
* Interact further with the user if they were prompted for missing arguments.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function afterPromptingForMissingArguments(InputInterface $input, OutputInterface $output)
{
$stack = $input->getArgument('stack');
if (in_array($stack, ['react', 'vue'])) {
collect(multiselect(
label: 'Would you like any optional features?',
options: [
'dark' => 'Dark mode',
'ssr' => 'Inertia SSR',
'typescript' => 'TypeScript (experimental)',
]
))->each(fn ($option) => $input->setOption($option, true));
} elseif ($stack === 'blade') {
$input->setOption('dark', confirm(
label: 'Would you like dark mode support?',
default: false
));
}
$input->setOption('pest', select(
label: 'Which testing framework do you prefer?',
options: ['PHPUnit', 'Pest'],
default: $this->isUsingPest() ? 'Pest' : 'PHPUnit',
) === 'Pest');
}
/**
* Determine whether the project is already using Pest.
*
* @return bool
*/
protected function isUsingPest()
{
return class_exists(\Pest\TestSuite::class);
}
}