-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathSetupCpVite.php
More file actions
248 lines (193 loc) · 7.58 KB
/
SetupCpVite.php
File metadata and controls
248 lines (193 loc) · 7.58 KB
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
<?php
namespace Statamic\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use Statamic\Console\RunsInPlease;
use function Laravel\Prompts\spin;
class SetupCpVite extends Command
{
use RunsInPlease;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'statamic:setup-cp-vite {--only-necessary : Only configure the necessary parts for Vite to work with the Control Panel}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configures Vite for the Control Panel';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(): void
{
$this
->installDependencies()
->addScriptsToPackageJson()
->publishViteConfig()
->publishStubs()
->publishDevBuild()
->appendViteSnippetToAppServiceProvider();
}
private function installDependencies(): self
{
$result = spin(
callback: function () {
$packageJsonPath = base_path('package.json');
$contents = File::json($packageJsonPath);
$installedDependencies = collect($contents['dependencies'] ?? [])->merge($contents['devDependencies'] ?? []);
if (! $installedDependencies->has('vite')) {
$contents['devDependencies']['vite'] = '^8.0.0';
}
if (! $installedDependencies->has('@statamic/cms')) {
$contents['dependencies']['@statamic/cms'] = 'file:./vendor/statamic/cms/resources/dist-package';
}
File::put($packageJsonPath, json_encode($contents, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return Process::path(base_path())->run('npm install --ignore-scripts');
},
message: 'Installing dependencies...'
);
if ($result->failed()) {
$this->line($result->errorOutput() ?: $result->output());
$this->components->error('Failed to install dependencies. You need to run "npm install --ignore-scripts" manually.');
return $this;
}
$this->components->info('Installed dependencies');
return $this;
}
private function addScriptsToPackageJson(): self
{
$packageJsonPath = base_path('package.json');
$contents = File::json($packageJsonPath);
$contents['scripts'] = [
...$contents['scripts'] ?? [],
'cp:dev' => 'vite --config vite-cp.config.js',
'cp:build' => 'vite build --config vite-cp.config.js',
];
File::put($packageJsonPath, json_encode($contents, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
$this->components->info('Added cp:dev and cp:build scripts to package.json');
return $this;
}
private function publishViteConfig(): self
{
if (File::exists(base_path('vite-cp.config.js'))) {
$this->components->warn('vite-cp.config.js already exists. Skipping publishing.');
return $this;
}
File::put(
base_path('vite-cp.config.js'),
File::get(__DIR__.'/stubs/app/vite-cp.config.js.stub')
);
$this->components->info('Published vite-cp.config.js');
return $this;
}
private function publishStubs(): self
{
if (! File::exists(resource_path('css/cp.css'))) {
File::ensureDirectoryExists(resource_path('css'));
File::put(resource_path('css/cp.css'), File::get(__DIR__.'/stubs/app/cp.css.stub'));
}
if (! File::exists(resource_path('js/cp.js'))) {
File::ensureDirectoryExists(resource_path('js'));
File::put(resource_path('js/cp.js'), File::get(__DIR__.'/stubs/app/cp.js.stub'));
}
if (
! File::exists(resource_path('js/components/fieldtypes/ExampleFieldtype.vue'))
&& ! $this->option('only-necessary')
) {
File::ensureDirectoryExists(resource_path('js/components/fieldtypes'));
File::put(resource_path('js/components/fieldtypes/ExampleFieldtype.vue'), File::get(__DIR__.'/stubs/fieldtype.vue.stub'));
}
$this->components->info('Published stubs for Control Panel CSS & JavaScript.');
return $this;
}
private function publishDevBuild(): self
{
$this->call('vendor:publish', ['--tag' => 'statamic-cp-dev']);
return $this;
}
private function appendViteSnippetToAppServiceProvider(): self
{
spin(
callback: function () {
$this->addImportToAppServiceProvider('Statamic\\Statamic');
$this->addCodeToAppServiceProvidersBootMethod(<<<'PHP'
Statamic::vite('app', [
'input' => [
'resources/js/cp.js',
'resources/css/cp.css',
],
'hotFile' => public_path('cp-hot'),
'buildDirectory' => 'vendor/app',
]);
PHP);
},
message: 'Adding Statamic::vite() snippet to AppServiceProvider...'
);
$this->components->info('Added Statamic::vite() snippet to AppServiceProvider.');
return $this;
}
private function addImportToAppServiceProvider(string $class): void
{
$contents = File::get(app_path('Providers/AppServiceProvider.php'));
$lines = explode("\n", $contents);
$useLines = $originalUseLines = array_filter($lines, fn ($line) => Str::startsWith($line, 'use '));
$useLines[] = "use $class;";
// Filter out duplicate imports.
$useLines = array_unique($useLines);
// Sort the imports alphabetically.
usort($useLines, fn ($a, $b) => strcasecmp(substr($a, 4), substr($b, 4)));
// Get the position of the first and last "use " lines.
$firstUseLine = array_key_first($originalUseLines);
$lastUseLine = array_key_last($originalUseLines);
// Replace everything in between the first and last "use " lines with the new imports.
$contents = implode("\n", array_merge(
array_slice($lines, 0, $firstUseLine),
$useLines,
array_slice($lines, $lastUseLine + 1)
));
File::put(app_path('Providers/AppServiceProvider.php'), $contents);
}
private function addCodeToAppServiceProvidersBootMethod(string $code): void
{
$contents = File::get(app_path('Providers/AppServiceProvider.php'));
$starters = [
<<<'PHP'
public function boot()
{
PHP,
<<<'PHP'
public function boot(): void
{
PHP,
<<<'PHP'
public function boot() {
PHP,
<<<'PHP'
public function boot(): void {
PHP,
];
// Ensure the boot() method exists.
if (! Str::contains($contents, $starters)) {
throw new \Exception('Code could not be injected. No boot method found in AppServiceProvider.');
}
// Ensure this code snippet hasn't already been injected.
if (Str::contains(str_replace([' ', "\n"], '', $contents), str_replace([' ', "\n"], '', $code))) {
throw new \Exception('Code has already been injected.');
}
foreach ($starters as $starter) {
if (Str::contains($contents, $starter)) {
$contents = Str::replaceFirst($starter, $starter."\n $code\n", $contents);
break;
}
}
File::put(app_path('Providers/AppServiceProvider.php'), $contents);
}
}