-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBuildCommand.php
More file actions
370 lines (324 loc) · 12.3 KB
/
BuildCommand.php
File metadata and controls
370 lines (324 loc) · 12.3 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
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
<?php
declare(strict_types=1);
namespace OpenForgeProject\MageForge\Console\Command\Theme;
use Laravel\Prompts\MultiSearchPrompt;
use Laravel\Prompts\Spinner;
use OpenForgeProject\MageForge\Console\Command\AbstractCommand;
use OpenForgeProject\MageForge\Model\ThemeList;
use OpenForgeProject\MageForge\Model\ThemePath;
use OpenForgeProject\MageForge\Service\ThemeBuilder\BuilderPool;
use OpenForgeProject\MageForge\Service\ThemeSuggester;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Command for building Magento themes
*/
class BuildCommand extends AbstractCommand
{
/**
* @param ThemePath $themePath
* @param ThemeList $themeList
* @param BuilderPool $builderPool
* @param ThemeSuggester $themeSuggester
*/
public function __construct(
private readonly ThemePath $themePath,
private readonly ThemeList $themeList,
private readonly BuilderPool $builderPool,
private readonly ThemeSuggester $themeSuggester,
) {
parent::__construct();
}
/**
* Configure command.
*
* @return void
*/
protected function configure(): void
{
$this
->setName($this->getCommandName('theme', 'build'))
->setDescription('Builds a Magento theme')
->addArgument(
'themeCodes',
InputArgument::IS_ARRAY,
'Theme codes to build (format: Vendor/theme, Vendor/theme 2, ...)',
)
->setAliases(['frontend:build']);
}
/**
* Execute command.
*
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function executeCommand(InputInterface $input, OutputInterface $output): int
{
$themeCodes = $input->getArgument('themeCodes');
$isVerbose = $this->isVerbose($output);
if (empty($themeCodes)) {
$themes = $this->themeList->getAllThemes();
$options = array_values(array_map(fn($theme) => $theme->getCode(), $themes));
// Check if we're in an interactive terminal environment
if (!$this->isInteractiveTerminal($output)) {
// Fallback for non-interactive environments
$this->displayAvailableThemes($this->io);
return Command::SUCCESS;
}
// Set environment variables for Laravel Prompts
$this->setPromptEnvironment();
$themeCodesPrompt = new MultiSearchPrompt(
label: 'Select themes to build',
options: fn(string $value) => empty($value)
? $options
: array_values(array_filter($options, fn($option) => stripos((string)$option, $value) !== false)),
placeholder: 'Type to search theme...',
hint: 'Type to search, arrow keys to navigate, Space to toggle, Enter to confirm',
required: false,
);
try {
$themeCodes = $themeCodesPrompt->prompt();
\Laravel\Prompts\Prompt::terminal()->restoreTty();
// Reset environment
$this->resetPromptEnvironment();
// If no themes selected, show available themes
if (empty($themeCodes)) {
$this->io->info('No themes selected.');
return Command::SUCCESS;
}
} catch (\Exception $e) {
// Reset environment on exception
$this->resetPromptEnvironment();
// Fallback if prompt fails
$this->io->error('Interactive mode failed: ' . $e->getMessage());
$this->displayAvailableThemes($this->io);
$this->io->newLine();
return Command::SUCCESS;
}
}
return $this->processBuildThemes($themeCodes, $this->io, $output, $isVerbose);
}
/**
* Display available themes
*
* @param SymfonyStyle $io
* @return int
*/
private function displayAvailableThemes(SymfonyStyle $io): int
{
$table = new Table($io);
$table->setHeaders(['Theme Code', 'Title']);
foreach ($this->themeList->getAllThemes() as $theme) {
$table->addRow([$theme->getCode(), $theme->getThemeTitle()]);
}
$table->render();
$io->info('Usage: bin/magento mageforge:theme:build <theme-code> [<theme-code>...]');
return Command::SUCCESS;
}
/**
* Process theme building
*
* @param array<string> $themeCodes
* @param SymfonyStyle $io
* @param OutputInterface $output
* @param bool $isVerbose
* @return int
*/
private function processBuildThemes(
array $themeCodes,
SymfonyStyle $io,
OutputInterface $output,
bool $isVerbose,
): int {
$startTime = microtime(true);
$successList = [];
$totalThemes = count($themeCodes);
if ($isVerbose) {
$io->title(sprintf('Building %d theme(s)', $totalThemes));
foreach ($themeCodes as $themeCode) {
if (!$this->processTheme($themeCode, $io, $output, $isVerbose, $successList)) {
continue;
}
}
} else {
// Use the existing spinner with a customized message
foreach ($themeCodes as $index => $themeCode) {
$currentTheme = $index + 1;
// Validate theme and handle suggestions BEFORE showing spinner
$validatedTheme = $this->validateAndCorrectTheme($themeCode, $io, $output);
if ($validatedTheme === null) {
// Theme validation failed or user cancelled - skip this theme
continue;
}
// Show which theme is currently being built (with validated/corrected name)
$themeNameCyan = sprintf('<fg=cyan>%s</>', $validatedTheme);
$spinner = new Spinner(sprintf(
'Building %s (%d of %d) ...',
$themeNameCyan,
$currentTheme,
$totalThemes,
));
$success = false;
$spinner->spin(function () use ($validatedTheme, $io, $output, $isVerbose, &$successList, &$success) {
$success = $this->buildValidatedTheme($validatedTheme, $io, $output, $isVerbose, $successList);
return true;
});
if ($success) {
// Show that the theme was successfully built
$io->writeln(sprintf(
' Building %s (%d of %d) ... <fg=green>done</>',
$themeNameCyan,
$currentTheme,
$totalThemes,
));
} else {
// Show that an error occurred while building the theme
$io->writeln(sprintf(
' Building %s (%d of %d) ... <fg=red>failed</>',
$themeNameCyan,
$currentTheme,
$totalThemes,
));
}
}
}
$this->displayBuildSummary($io, $successList, microtime(true) - $startTime);
return Command::SUCCESS;
}
/**
* Validate theme and correct if invalid (with suggestions)
*
* @param string $themeCode
* @param SymfonyStyle $io
* @param OutputInterface $output
* @return string|null Validated/corrected theme code or null if invalid/cancelled
*/
private function validateAndCorrectTheme(string $themeCode, SymfonyStyle $io, OutputInterface $output): ?string
{
// Get theme path
$themePath = $this->themePath->getPath($themeCode);
if ($themePath === null) {
// Try to suggest similar themes
$correctedTheme = $this->handleInvalidThemeWithSuggestions($themeCode, $this->themeSuggester, $output);
// If no theme was selected, return null
if ($correctedTheme === null) {
return null;
}
// Double-check the corrected theme exists
$themePath = $this->themePath->getPath($correctedTheme);
if ($themePath === null) {
$io->error("Theme $correctedTheme is not installed.");
return null;
}
$io->info("Using theme: $correctedTheme");
return $correctedTheme;
}
return $themeCode;
}
/**
* Build a validated theme (theme existence already confirmed)
*
* @param string $themeCode
* @param SymfonyStyle $io
* @param OutputInterface $output
* @param bool $isVerbose
* @param array<string> $successList
* @return bool
*/
private function buildValidatedTheme(
string $themeCode,
SymfonyStyle $io,
OutputInterface $output,
bool $isVerbose,
array &$successList,
): bool {
$themePath = $this->themePath->getPath($themeCode);
if ($themePath === null) {
$io->error("Could not find path for theme $themeCode.");
return false;
}
// Find appropriate builder
$builder = $this->builderPool->getBuilder($themePath);
if ($builder === null) {
$io->error("No suitable builder found for theme $themeCode.");
return false;
}
if ($isVerbose) {
$io->section(sprintf('Building theme %s using %s builder', $themeCode, $builder->getName()));
}
// Build the theme
if (!$builder->build($themeCode, $themePath, $io, $output, $isVerbose)) {
$io->error("Failed to build theme $themeCode.");
return false;
}
$successList[] = sprintf('%s: Built successfully using %s builder', $themeCode, $builder->getName());
return true;
}
/**
* Process a single theme
*
* @param string $themeCode
* @param SymfonyStyle $io
* @param OutputInterface $output
* @param bool $isVerbose
* @param array<string> $successList
* @return bool
*/
private function processTheme(
string $themeCode,
SymfonyStyle $io,
OutputInterface $output,
bool $isVerbose,
array &$successList,
): bool {
// Validate and correct theme
$validatedTheme = $this->validateAndCorrectTheme($themeCode, $io, $output);
if ($validatedTheme === null) {
return false;
}
// Build the validated theme
return $this->buildValidatedTheme($validatedTheme, $io, $output, $isVerbose, $successList);
}
/**
* Display build summary
*
* @param SymfonyStyle $io
* @param array<string> $successList
* @param float $duration
*/
private function displayBuildSummary(SymfonyStyle $io, array $successList, float $duration): void
{
$io->newLine();
$io->success(sprintf('🚀 Build process completed in %.2f seconds with the following results:', $duration));
$io->writeln('Summary:');
$io->newLine();
if (empty($successList)) {
$io->warning('No themes were built successfully.');
return;
}
foreach ($successList as $success) {
$parts = explode(': ', $success, 2);
if (count($parts) === 2) {
$themeName = $parts[0];
$details = $parts[1];
// Color the builder name in magenta
if (preg_match('/(using\s+)([^\s]+)(\s+builder)/', $details, $matches)) {
$details = str_replace(
$matches[0],
$matches[1] . '<fg=magenta>' . $matches[2] . '</>' . $matches[3],
$details,
);
}
$io->writeln(sprintf('✅ <fg=cyan>%s</>: %s', $themeName, $details));
} else {
$io->writeln("✅ $success");
}
}
$io->newLine();
}
}