-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathPromptManager.php
More file actions
755 lines (644 loc) Β· 26.6 KB
/
Copy pathPromptManager.php
File metadata and controls
755 lines (644 loc) Β· 26.6 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
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
<?php
declare(strict_types=1);
namespace DrevOps\VortexInstaller\Prompts;
use DrevOps\VortexInstaller\Prompts\Handlers\AbstractHandler;
use DrevOps\VortexInstaller\Prompts\Handlers\AiCodeInstructions;
use DrevOps\VortexInstaller\Prompts\Handlers\AssignAuthorPr;
use DrevOps\VortexInstaller\Prompts\Handlers\CiProvider;
use DrevOps\VortexInstaller\Prompts\Handlers\CodeCoverageProvider;
use DrevOps\VortexInstaller\Prompts\Handlers\CodeProvider;
use DrevOps\VortexInstaller\Prompts\Handlers\CustomModules;
use DrevOps\VortexInstaller\Prompts\Handlers\DatabaseDownloadSource;
use DrevOps\VortexInstaller\Prompts\Handlers\DatabaseImage;
use DrevOps\VortexInstaller\Prompts\Handlers\DependencyUpdatesProvider;
use DrevOps\VortexInstaller\Prompts\Handlers\DeployTypes;
use DrevOps\VortexInstaller\Prompts\Handlers\Domain;
use DrevOps\VortexInstaller\Prompts\Handlers\Dotenv;
use DrevOps\VortexInstaller\Prompts\Handlers\HandlerInterface;
use DrevOps\VortexInstaller\Prompts\Handlers\HostingProjectName;
use DrevOps\VortexInstaller\Prompts\Handlers\HostingProvider;
use DrevOps\VortexInstaller\Prompts\Handlers\Internal;
use DrevOps\VortexInstaller\Prompts\Handlers\LabelMergeConflictsPr;
use DrevOps\VortexInstaller\Prompts\Handlers\MachineName;
use DrevOps\VortexInstaller\Prompts\Handlers\Migration;
use DrevOps\VortexInstaller\Prompts\Handlers\MigrationDownloadSource;
use DrevOps\VortexInstaller\Prompts\Handlers\MigrationImage;
use DrevOps\VortexInstaller\Prompts\Handlers\ModulePrefix;
use DrevOps\VortexInstaller\Prompts\Handlers\Modules;
use DrevOps\VortexInstaller\Prompts\Handlers\Name;
use DrevOps\VortexInstaller\Prompts\Handlers\NotificationChannels;
use DrevOps\VortexInstaller\Prompts\Handlers\Org;
use DrevOps\VortexInstaller\Prompts\Handlers\OrgMachineName;
use DrevOps\VortexInstaller\Prompts\Handlers\PreserveDocsProject;
use DrevOps\VortexInstaller\Prompts\Handlers\Profile;
use DrevOps\VortexInstaller\Prompts\Handlers\ProfileCustom;
use DrevOps\VortexInstaller\Prompts\Handlers\ProvisionType;
use DrevOps\VortexInstaller\Prompts\Handlers\Services;
use DrevOps\VortexInstaller\Prompts\Handlers\Starter;
use DrevOps\VortexInstaller\Prompts\Handlers\Theme;
use DrevOps\VortexInstaller\Prompts\Handlers\ThemeCustom;
use DrevOps\VortexInstaller\Prompts\Handlers\Timezone;
use DrevOps\VortexInstaller\Prompts\Handlers\Tools;
use DrevOps\VortexInstaller\Prompts\Handlers\VersionScheme;
use DrevOps\VortexInstaller\Prompts\Handlers\Webroot;
use DrevOps\VortexInstaller\Schema\SchemaValidator;
use DrevOps\VortexInstaller\Utils\Config;
use DrevOps\VortexInstaller\Utils\Converter;
use DrevOps\VortexInstaller\Utils\Tui;
use Symfony\Component\Console\Output\OutputInterface;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\form;
use function Laravel\Prompts\info;
/**
* PromptManager.
*
* Centralised place for providing prompts and their processing.
*
* @package DrevOps\VortexInstaller
*/
class PromptManager {
/**
* Total number of top-level responses.
*
* Used to display the progress of the prompts.
*/
const TOTAL_RESPONSES = 33;
/**
* Array of responses.
*/
protected array $responses = [];
/**
* Current response index.
*
* Used to display the progress of the prompts.
*/
protected int $currentResponseIndex = 0;
/**
* Array of handlers.
*
* @var array<string, \DrevOps\VortexInstaller\Prompts\Handlers\HandlerInterface>
*/
protected array $handlers = [];
/**
* Prompt overrides from --prompts CLI option.
*
* Keyed by handler ID with validated values.
*
* @var array<string, mixed>
*/
protected array $promptOverrides = [];
/**
* PromptManager constructor.
*
* @param \DrevOps\VortexInstaller\Utils\Config $config
* The installer config.
*/
public function __construct(
protected Config $config,
) {
$this->initHandlers();
$this->resolvePromptOverrides();
}
/**
* Run prompts to get responses.
*
* If non-interactive mode is used, the values provided by $this->default()
* method, including discovery from the existing codebase, will be used.
*/
public function runPrompts(): void {
// Set verbosity for TUI output based on the config. This will be reset
// after the prompt is completed.
$original_verbosity = Tui::output()->getVerbosity();
if ($this->config->getNoInteraction()) {
Tui::output()->setVerbosity(OutputInterface::VERBOSITY_QUIET);
}
// @formatter:off
// phpcs:disable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma
// phpcs:disable Drupal.WhiteSpace.Comma.TooManySpaces
// phpcs:disable Drupal.WhiteSpace.ObjectOperatorIndent.Indent
// phpcs:disable Drupal.WhiteSpace.ScopeIndent.IncorrectExact
$form = form()
->intro('General information')
->add(fn($r, $pr, $n): mixed => $this->prompt(Name::class), Name::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(MachineName::class, $r), MachineName::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(Org::class, $r), Org::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(OrgMachineName::class, $r), OrgMachineName::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(Domain::class, $r), Domain::id())
->intro('Drupal')
->addIf(
fn(array $r): bool => $this->handlers[Starter::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(Starter::class, $r),
Starter::id()
)
->add(
fn(array $r, $pr, $n): string => $this->resolveOrPrompt(Profile::id(), $r, fn(): mixed => $this->prompt(Profile::class)),
Profile::id()
)
->addIf(
fn(array $r): bool => $this->handlers[ProfileCustom::id()]->shouldRun($r),
fn($r, $pr, $n): mixed => $this->prompt(ProfileCustom::class),
ProfileCustom::id()
)
->add(fn(array $r, $pr, $n): mixed => $this->prompt(Modules::class, $r), Modules::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(ModulePrefix::class, $r), ModulePrefix::id())
->add(fn(array $r, $pr, $n): mixed => $this->prompt(CustomModules::class, $r), CustomModules::id())
->add(
fn(array $r, $pr, $n): string => $this->resolveOrPrompt(Theme::id(), $r, fn(): mixed => $this->prompt(Theme::class)),
Theme::id()
)
->addIf(
fn(array $r): bool => $this->handlers[ThemeCustom::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(ThemeCustom::class, $r),
ThemeCustom::id()
)
->intro('Code repository')
->add(fn($r, $pr, $n): mixed => $this->prompt(CodeProvider::class), CodeProvider::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(VersionScheme::class), VersionScheme::id())
->intro('Environment')
->add(fn($r, $pr, $n): mixed => $this->prompt(Timezone::class), Timezone::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(Services::class), Services::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(Tools::class), Tools::id())
->intro('Hosting')
->add(fn($r, $pr, $n): mixed => $this->prompt(HostingProvider::class), HostingProvider::id())
->addIf(
fn(array $r): bool => $this->handlers[HostingProjectName::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(HostingProjectName::class, $r),
HostingProjectName::id()
)
->add(
fn(array $r, $pr, $n): string => $this->resolveOrPrompt(Webroot::id(), $r, fn(): mixed => $this->prompt(Webroot::class, $r)),
Webroot::id()
)
->intro('Deployment')
->add(fn(array $r, $pr, $n): mixed => $this->prompt(DeployTypes::class, $r), DeployTypes::id())
->intro('Workflow')
->add(fn($r, $pr, $n): mixed => $this->prompt(ProvisionType::class), ProvisionType::id())
->addIf(
fn(array $r): bool => $this->handlers[DatabaseDownloadSource::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(DatabaseDownloadSource::class, $r),
DatabaseDownloadSource::id()
)
->addIf(
fn(array $r): bool => $this->handlers[DatabaseImage::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(DatabaseImage::class, $r),
DatabaseImage::id()
)
->add(fn($r, $pr, $n): mixed => $this->prompt(Migration::class), Migration::id())
->addIf(
fn(array $r): bool => $this->handlers[MigrationDownloadSource::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(MigrationDownloadSource::class, $r),
MigrationDownloadSource::id()
)
->addIf(
fn(array $r): bool => $this->handlers[MigrationImage::id()]->shouldRun($r),
fn(array $r, $pr, $n): mixed => $this->prompt(MigrationImage::class, $r),
MigrationImage::id()
)
->intro('Notifications')
->add(fn($r, $pr, $n): mixed => $this->prompt(NotificationChannels::class), NotificationChannels::id())
->intro('Continuous Integration')
->add(fn(array $r, $pr, $n): mixed => $this->prompt(CiProvider::class, $r), CiProvider::id())
->intro('Automations')
->add(fn($r, $pr, $n): mixed => $this->prompt(DependencyUpdatesProvider::class), DependencyUpdatesProvider::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(CodeCoverageProvider::class), CodeCoverageProvider::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(AssignAuthorPr::class), AssignAuthorPr::id())
->add(fn($r, $pr, $n): mixed => $this->prompt(LabelMergeConflictsPr::class), LabelMergeConflictsPr::id())
->intro('Documentation')
->add(fn($r, $pr, $n): mixed => $this->prompt(PreserveDocsProject::class), PreserveDocsProject::id())
->intro('AI')
->add(fn($r, $pr, $n): mixed => $this->prompt(AiCodeInstructions::class), AiCodeInstructions::id());
// @formatter:on
// phpcs:enable Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma
// phpcs:enable Drupal.WhiteSpace.Comma.TooManySpaces
// phpcs:enable Drupal.WhiteSpace.ObjectOperatorIndent.Indent
// phpcs:enable Drupal.WhiteSpace.ScopeIndent.IncorrectExact
$responses = $form->submit();
// Filter out elements with numeric keys returned from intro()'s.
$responses = array_filter($responses, fn($key): bool => !is_numeric($key), ARRAY_FILTER_USE_KEY);
// Handle Profile custom name merging.
if (isset($responses[Profile::id()]) && $responses[Profile::id()] === Profile::CUSTOM && isset($responses[ProfileCustom::id()])) {
$responses[Profile::id()] = $responses[ProfileCustom::id()];
}
// Always remove ProfileCustom key (it's only used for internal merging)
unset($responses[ProfileCustom::id()]);
// Handle Theme custom name merging.
if (isset($responses[Theme::id()]) && $responses[Theme::id()] === Theme::CUSTOM && isset($responses[ThemeCustom::id()])) {
$responses[Theme::id()] = $responses[ThemeCustom::id()];
}
// Always remove ThemeCustom key (it's only used for internal merging)
unset($responses[ThemeCustom::id()]);
// Handle DatabaseDownloadSource when ProvisionType is PROFILE.
if (isset($responses[ProvisionType::id()]) && $responses[ProvisionType::id()] === ProvisionType::PROFILE) {
$responses[DatabaseDownloadSource::id()] = DatabaseDownloadSource::NONE;
}
// Handle Starter when the installer is running in update mode.
if ($this->config->isVortexProject() && !isset($responses[Starter::id()])) {
$responses[Starter::id()] = Starter::LOAD_DATABASE_DEMO;
}
if ($this->config->getNoInteraction()) {
Tui::output()->setVerbosity($original_verbosity);
}
$this->responses = $responses;
}
/**
* Get all received responses.
*
* Used to provide direct access to the responses values.
*
* @return array
* An associative array of responses, where keys are handler IDs and values
* are the responses provided by the user or discovered by handlers.
*/
public function getResponses(): array {
return $this->responses;
}
/**
* Run all processors.
*/
public function runProcessors(): void {
// Run processors in the reverse order of how they are defined in the
// runPrompts() to ensure that the handlers for string replacements process
// more specific values first, and the more generic ones last.
$ids = [
Dotenv::id(),
Webroot::id(),
AiCodeInstructions::id(),
PreserveDocsProject::id(),
LabelMergeConflictsPr::id(),
AssignAuthorPr::id(),
CodeCoverageProvider::id(),
DependencyUpdatesProvider::id(),
CiProvider::id(),
MigrationImage::id(),
MigrationDownloadSource::id(),
Migration::id(),
DatabaseImage::id(),
DatabaseDownloadSource::id(),
ProvisionType::id(),
NotificationChannels::id(),
DeployTypes::id(),
HostingProvider::id(),
Tools::id(),
Services::id(),
Timezone::id(),
VersionScheme::id(),
CodeProvider::id(),
Modules::id(),
Starter::id(),
ProfileCustom::id(),
Profile::id(),
Domain::id(),
HostingProjectName::id(),
CustomModules::id(),
ModulePrefix::id(),
ThemeCustom::id(),
Theme::id(),
OrgMachineName::id(),
MachineName::id(),
Org::id(),
Name::id(),
// Always last.
Internal::id(),
];
foreach ($ids as $id) {
if (!array_key_exists($id, $this->handlers)) {
throw new \RuntimeException(sprintf('Handler for "%s" not found.', $id));
}
$this->handlers[$id]->setResponses($this->responses)->process();
}
}
/**
* Run all post-install processors.
*/
public function runPostInstall(): string {
$output = '';
$ids = [
Starter::id(),
HostingProvider::id(),
CiProvider::id(),
Internal::id(),
];
foreach ($ids as $id) {
if (!array_key_exists($id, $this->handlers)) {
throw new \RuntimeException(sprintf('Handler for "%s" not found.', $id));
}
$handler_output = $this->handlers[$id]->postInstall();
if (is_string($handler_output) && !empty($handler_output)) {
$output .= $handler_output;
}
}
return $output;
}
/**
* Run all post-build processors.
*
* @param string $result
* The result of the build operation.
*
* @return string
* The combined output from all post-build processors.
*/
public function runPostBuild(string $result): string {
$output = '';
$ids = [
Starter::id(),
HostingProvider::id(),
CiProvider::id(),
];
foreach ($ids as $id) {
if (!array_key_exists($id, $this->handlers)) {
throw new \RuntimeException(sprintf('Handler for "%s" not found.', $id));
}
$handler_output = $this->handlers[$id]->postBuild($result);
if (is_string($handler_output) && !empty($handler_output)) {
$output .= $handler_output;
}
}
return $output;
}
/**
* Check if the installation should proceed.
*
* This method checks the configuration for the no-interaction mode and
* prompts the user for confirmation if not in no-interaction mode.
*
* @return bool
* TRUE if the installation should proceed, FALSE otherwise.
*/
public function shouldProceed(): bool {
$proceed = TRUE;
if (!$this->config->getNoInteraction()) {
Tui::line(sprintf('Vortex will be installed into your project\'s directory "%s"', $this->config->getDst()));
$proceed = confirm(
label: 'Proceed with installing Vortex?',
);
}
// Kill-switch to not proceed with install. If FALSE, the installer will not
// proceed despite the answer received above.
if (!$this->config->get(Config::PROCEED)) {
$proceed = FALSE;
}
return $proceed;
}
public function getResponsesSummary(): array {
$responses = $this->responses;
$values['General information'] = Tui::LIST_SECTION_TITLE;
$values['Site name'] = $responses[Name::id()];
$values['Site machine name'] = $responses[MachineName::id()];
$values['Organization name'] = $responses[Org::id()];
$values['Organization machine name'] = $responses[OrgMachineName::id()];
$values['Public domain'] = $responses[Domain::id()];
$values['Drupal'] = Tui::LIST_SECTION_TITLE;
$values['Starter'] = $responses[Starter::id()];
$values['Modules'] = Converter::toList($responses[Modules::id()], ', ');
$values['Webroot'] = $responses[Webroot::id()];
$values['Profile'] = $responses[Profile::id()];
$values['Module prefix'] = $responses[ModulePrefix::id()];
$values['Custom modules'] = Converter::toList($responses[CustomModules::id()], ', ');
$values['Theme machine name'] = $responses[Theme::id()] ?? '<empty>';
$values['Code repository'] = Tui::LIST_SECTION_TITLE;
$values['Code provider'] = $responses[CodeProvider::id()];
$values['Version scheme'] = $responses[VersionScheme::id()];
$values['Environment'] = Tui::LIST_SECTION_TITLE;
$values['Timezone'] = $responses[Timezone::id()];
$values['Services'] = Converter::toList($responses[Services::id()], ', ');
$values['Tools'] = Converter::toList($responses[Tools::id()], ', ');
$values['Hosting'] = Tui::LIST_SECTION_TITLE;
$values['Hosting provider'] = $responses[HostingProvider::id()];
if (in_array($this->responses[HostingProvider::id()], [HostingProvider::LAGOON, HostingProvider::ACQUIA])) {
$values['Hosting project name'] = $responses[HostingProjectName::id()];
}
$values['Deployment'] = Tui::LIST_SECTION_TITLE;
$values['Deployment types'] = Converter::toList($responses[DeployTypes::id()]);
$values['Workflow'] = Tui::LIST_SECTION_TITLE;
$values['Provision type'] = $responses[ProvisionType::id()];
if ($responses[ProvisionType::id()] == ProvisionType::DATABASE) {
$values['Database source'] = $responses[DatabaseDownloadSource::id()];
if ($responses[DatabaseDownloadSource::id()] == DatabaseDownloadSource::CONTAINER_REGISTRY) {
$values['Database container image'] = $responses[DatabaseImage::id()];
}
}
if (isset($responses[Migration::id()])) {
$values['Migration database'] = Converter::bool($responses[Migration::id()]);
if ($responses[Migration::id()] === TRUE && isset($responses[MigrationDownloadSource::id()])) {
$values['Migration database source'] = $responses[MigrationDownloadSource::id()];
if ($responses[MigrationDownloadSource::id()] == MigrationDownloadSource::CONTAINER_REGISTRY && isset($responses[MigrationImage::id()])) {
$values['Migration database container image'] = $responses[MigrationImage::id()];
}
}
}
$values['Notifications'] = Tui::LIST_SECTION_TITLE;
$values['Channels'] = Converter::toList($responses[NotificationChannels::id()]);
$values['Continuous Integration'] = Tui::LIST_SECTION_TITLE;
$values['CI provider'] = $responses[CiProvider::id()];
$values['Automations'] = Tui::LIST_SECTION_TITLE;
$values['Dependency updates provider'] = $responses[DependencyUpdatesProvider::id()];
$values['Code coverage provider'] = $responses[CodeCoverageProvider::id()];
$values['Auto-assign PR author'] = Converter::bool($responses[AssignAuthorPr::id()]);
$values['Auto-add a CONFLICT label to PRs'] = Converter::bool($responses[LabelMergeConflictsPr::id()]);
$values['Documentation'] = Tui::LIST_SECTION_TITLE;
$values['Preserve project documentation'] = Converter::bool($responses[PreserveDocsProject::id()]);
$values['AI'] = Tui::LIST_SECTION_TITLE;
$values['AI agent instructions'] = Converter::bool($responses[AiCodeInstructions::id()]);
$values['Locations'] = Tui::LIST_SECTION_TITLE;
$values['Current directory'] = $this->config->getRoot();
$values['Destination directory'] = $this->config->getDst();
$values['Vortex repository'] = $this->config->get(Config::REPO);
$values['Vortex reference'] = $this->config->get(Config::REF);
return $values;
}
/**
* Get the initialized handlers.
*
* @return array<string, \DrevOps\VortexInstaller\Prompts\Handlers\HandlerInterface>
* An associative array of handler instances keyed by handler ID.
*/
public function getHandlers(): array {
return $this->handlers;
}
/**
* Generate a label for a prompt.
*
* @param string $text
* The text to display in the label.
* @param string|null $suffix
* An optional suffix to display in the label.
*
* @return string
* The formatted label text.
*/
protected function label(string $text, ?string $suffix = NULL): string {
if (is_null($suffix)) {
$this->currentResponseIndex++;
}
$suffix = $suffix !== NULL ? $this->currentResponseIndex . '.' . $suffix : $this->currentResponseIndex;
return $text . ' ' . Tui::dim('(' . $suffix . '/' . static::TOTAL_RESPONSES . ')');
}
/**
* Collect and initialise handlers.
*/
protected function initHandlers(): void {
$dir = __DIR__ . '/Handlers';
$files = scandir($dir);
if ($files === FALSE) {
throw new \RuntimeException(sprintf('Could not read the directory "%s".', $dir));
}
$handler_files = array_filter($files, fn(string $file): bool => !in_array($file, ['.', '..']));
$classes = [];
foreach ($handler_files as $handler_file) {
$class = 'DrevOps\\VortexInstaller\\Prompts\\Handlers\\' . basename($handler_file, '.php');
if (!class_exists($class) || !is_subclass_of($class, HandlerInterface::class) || $class === AbstractHandler::class) {
continue;
}
$classes[] = $class;
}
// Discover web root and set for all handlers to help with paths resolution.
$webroot = (new Webroot($this->config))->discover() ?: Webroot::WEB;
if (!is_string($webroot)) {
throw new \RuntimeException('Web root could not be discovered.');
}
foreach ($classes as $class) {
$handler = new $class($this->config);
$handler->setWebroot($webroot);
$this->handlers[$handler::id()] = $handler;
}
}
/**
* Resolve prompt overrides from --prompts CLI option.
*
* Reads the raw prompt array from Config, normalizes keys to handler IDs,
* validates values against handler types and options, and stores the
* validated overrides.
*
* @throws \RuntimeException
* If any prompt value is invalid.
*/
private function resolvePromptOverrides(): void {
$raw = $this->config->get(Config::PROMPTS);
if (!is_array($raw) || empty($raw)) {
return;
}
$validator = new SchemaValidator($this->handlers);
$result = $validator->validate($raw);
if (!empty($result['errors'])) {
$messages = array_map(fn(array $error): string => sprintf('%s: %s', $error['prompt'], $error['message']), $result['errors']);
throw new \RuntimeException(sprintf('Invalid --prompts values: %s', implode('; ', $messages)));
}
// Use the resolved values which include defaults for missing prompts.
foreach ($raw as $key => $value) {
if (isset($this->handlers[$key])) {
$this->promptOverrides[$key] = $value;
}
}
}
/**
* Dispatch a prompt using the handler's type enum.
*
* @param string $handler_class
* The handler class name.
* @param array $responses
* Current form responses for context-aware methods.
*
* @return mixed
* The prompt result.
*/
private function prompt(string $handler_class, array $responses = []): mixed {
$handler = $this->handlers[$handler_class::id()];
$fn = '\\Laravel\\Prompts\\' . $handler->type()->promptFunction();
// @phpstan-ignore callable.nonCallable
return $fn(...$this->args($handler_class, NULL, $responses));
}
/**
* Convert handler properties to Laravel prompts.
*
* Do not optimize this method to ease debugging and future changes.
*
* @param string $handler_class
* The handler class name.
* The handler id.
* @param mixed $default_override
* Optional override for the default value (for response dependencies).
* @param array $responses
* Current form responses for context-aware methods.
*
* @return array
* Array of prompt arguments suitable for Laravel prompts.
*/
private function args(string $handler_class, mixed $default_override = NULL, array $responses = []): array {
$id = $handler_class::id();
if (!array_key_exists($id, $this->handlers)) {
throw new \RuntimeException(sprintf('Handler for "%s" not found.', $id));
}
$handler = $this->handlers[$handler_class::id()];
$args = [
'label' => $this->label($handler->label()),
'hint' => $handler->hint($responses),
'placeholder' => $handler->placeholder($responses),
'transform' => $handler->transform(),
'validate' => $handler->validate(),
];
$description = $handler->description($responses);
if (!is_null($description)) {
$args['description'] = PHP_EOL . $description . PHP_EOL;
}
if ($handler->isRequired()) {
$args['required'] = TRUE;
}
$options = $handler->options($responses);
if (is_array($options)) {
$args['options'] = $options;
$args['scroll'] = 10;
}
// Find appropriate default value.
$default_from_handler = $handler->default($responses);
// Get from prompt overrides (--prompts CLI option).
$default_from_prompts = $this->promptOverrides[$id] ?? NULL;
// Get from discovery.
$default_from_discovery = $this->handlers[$id]->discover();
if (!is_null($default_from_prompts)) {
$default = $default_from_prompts;
}
elseif (!is_null($default_from_discovery)) {
$default = $default_from_discovery;
}
elseif (!is_null($default_override)) {
$default = $default_override;
}
else {
$default = $default_from_handler;
}
if (!is_null($default) && $default !== '') {
$args['default'] = $default;
}
return array_filter($args, fn($value): bool => $value !== NULL);
}
/**
* Resolve a value via handler or prompt the user.
*
* This method is used to resolve a value via a handler's resolvedValue()
* method. If the value is not resolved, it will prompt the user using the
* provided prompt callable.
*
* @param string $handler_id
* The handler ID.
* @param array $r
* Current form responses for context-aware methods.
* @param callable $prompt
* The prompt callable to use if the value is not resolved.
*
* @return string
* The resolved value.
*/
protected function resolveOrPrompt(string $handler_id, array $r, callable $prompt): string {
$handler = $this->handlers[$handler_id];
$resolved = $handler->resolvedValue($r);
if (is_string($resolved)) {
$message = $handler->resolvedMessage($r, $resolved);
if ($message) {
info($message);
}
return $resolved;
}
return (string) $prompt();
}
}