-
-
Notifications
You must be signed in to change notification settings - Fork 974
Expand file tree
/
Copy pathInstallerCommand.php
More file actions
269 lines (221 loc) · 10.2 KB
/
Copy pathInstallerCommand.php
File metadata and controls
269 lines (221 loc) · 10.2 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
<?php
declare(strict_types=1);
namespace ApiPlatform\Installer;
use ApiPlatform\Installer\Scaffold\LaravelScaffold;
use ApiPlatform\Installer\Scaffold\ScaffoldOptions;
use ApiPlatform\Installer\Scaffold\SymfonyScaffold;
use InvalidArgumentException;
use Symfony\Component\Console\Attribute\AsCommand;
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\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\ExecutableFinder;
#[AsCommand(name: 'api-platform', description: 'Scaffold a new API Platform project')]
final class InstallerCommand extends Command
{
public const VERSION = '@package_version@';
public const FRAMEWORK_SYMFONY = 'symfony';
public const FRAMEWORK_LARAVEL = 'laravel';
public const FORMATS = ['jsonld', 'jsonapi', 'hal'];
public const DOCS = ['swagger_ui', 'redoc', 'scalar'];
private const NAME_PATTERN = '/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/';
public static function version(): string
{
return str_starts_with(self::VERSION, '@') ? 'dev' : self::VERSION;
}
protected function configure(): void
{
$this
->addArgument('name', InputArgument::OPTIONAL, 'Project name')
->addOption('framework', null, InputOption::VALUE_REQUIRED, 'Framework: symfony or laravel')
->addOption('with-pwa', null, InputOption::VALUE_NEGATABLE, 'Include Next.js PWA (Symfony only)')
->addOption('with-admin', null, InputOption::VALUE_NEGATABLE, 'Include React-admin SPA')
->addOption('with-docker', null, InputOption::VALUE_NEGATABLE, 'Use Docker (Symfony only)')
->addOption('with-agents', null, InputOption::VALUE_NEGATABLE, 'Write AI agent instruction files AGENTS.md and CLAUDE.md (default: yes)')
->addOption('format', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'API formats (jsonld|jsonapi|hal); repeat for several')
->addOption('docs', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Documentation (swagger_ui|redoc|scalar); repeat for several, empty disables');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('API Platform installer');
try {
$name = $this->resolveProjectName($io, $input);
$framework = $this->resolveFramework($io, $input);
$opts = $this->resolveOptions($io, $input, $framework);
} catch (InvalidArgumentException $e) {
$io->error($e->getMessage());
return Command::INVALID;
}
$projectDir = (getcwd() ?: '.').\DIRECTORY_SEPARATOR.$name;
if (file_exists($projectDir)) {
$io->error(sprintf('Directory %s already exists.', $projectDir));
return Command::INVALID;
}
$io->section(sprintf('Creating %s project "%s"', $framework, $name));
return self::FRAMEWORK_SYMFONY === $framework
? (new SymfonyScaffold($io))->run($projectDir, $name, $opts)
: (new LaravelScaffold($io))->run($projectDir, $name, $opts);
}
public static function validateName(string $name): string
{
if (!preg_match(self::NAME_PATTERN, $name)) {
throw new InvalidArgumentException('Project name must start with a letter or digit and contain only letters, digits, hyphens, dots, or underscores.');
}
return $name;
}
private function resolveProjectName(SymfonyStyle $io, InputInterface $input): string
{
$name = $input->getArgument('name');
if (\is_string($name) && '' !== $name) {
return self::validateName($name);
}
$question = new Question('Project name', 'my-app');
$question->setValidator(static fn ($v): string => self::validateName((string) $v));
$question->setMaxAttempts(3);
return (string) $io->askQuestion($question);
}
private function resolveFramework(SymfonyStyle $io, InputInterface $input): string
{
$framework = $input->getOption('framework');
if (\is_string($framework) && '' !== $framework) {
if (!\in_array($framework, [self::FRAMEWORK_SYMFONY, self::FRAMEWORK_LARAVEL], true)) {
throw new InvalidArgumentException(sprintf('Unsupported framework "%s" (must be symfony or laravel).', $framework));
}
return $framework;
}
$question = new ChoiceQuestion('Framework', [self::FRAMEWORK_SYMFONY, self::FRAMEWORK_LARAVEL], self::FRAMEWORK_SYMFONY);
return (string) $io->askQuestion($question);
}
private function resolveOptions(SymfonyStyle $io, InputInterface $input, string $framework): ScaffoldOptions
{
$withDocker = false;
$withPwa = false;
if (self::FRAMEWORK_SYMFONY === $framework) {
$dockerOption = $input->getOption('with-docker');
$withDocker = null !== $dockerOption
? (bool) $dockerOption
: (bool) $io->askQuestion(new ConfirmationQuestion('Use Docker?', true));
$pwaOption = $input->getOption('with-pwa');
if (null !== $pwaOption) {
$withPwa = (bool) $pwaOption;
} else {
$missing = $this->missingBinaries(['node', 'npx', 'pnpm']);
if ([] !== $missing) {
$io->note(sprintf('Skipping PWA prompt: %s not found in PATH.', implode(', ', $missing)));
} else {
$withPwa = (bool) $io->askQuestion(new ConfirmationQuestion('Include Next.js PWA?', false));
}
}
} else {
if (true === $input->getOption('with-docker')) {
throw new InvalidArgumentException('--with-docker is not supported with Laravel.');
}
if (true === $input->getOption('with-pwa')) {
throw new InvalidArgumentException('--with-pwa is not supported with Laravel.');
}
}
$withAdmin = $this->resolveWithAdmin($io, $input);
$formats = $this->resolveMulti($io, $input, 'format', self::FORMATS, self::FORMATS, 'API formats');
$docs = $this->resolveMulti($io, $input, 'docs', self::DOCS, self::DOCS, 'API documentation', allowEmpty: true);
// Agent instruction files are written by default (like create-next-app);
// --no-with-agents opts out. No interactive prompt: the files are tiny and
// always beneficial, so prompting would only add friction.
$withAgents = (bool) ($input->getOption('with-agents') ?? true);
return new ScaffoldOptions(
withPwa: $withPwa,
withDocker: $withDocker,
formats: $formats,
docs: $docs,
withAdmin: $withAdmin,
withAgents: $withAgents,
);
}
private function resolveWithAdmin(SymfonyStyle $io, InputInterface $input): bool
{
$option = $input->getOption('with-admin');
if (null !== $option) {
return (bool) $option;
}
if (!$input->isInteractive()) {
return false;
}
$missing = $this->missingBinaries(['node', 'npm']);
if ([] !== $missing) {
$io->note(sprintf('Skipping admin prompt: %s not found in PATH.', implode(', ', $missing)));
return false;
}
return (bool) $io->askQuestion(new ConfirmationQuestion('Include React-admin SPA?', false));
}
/**
* @param array<string> $binaries
*
* @return array<string>
*/
private function missingBinaries(array $binaries): array
{
$finder = new ExecutableFinder();
return array_values(array_filter($binaries, static fn (string $b): bool => null === $finder->find($b)));
}
/**
* @param array<string> $allowed
* @param array<string> $defaults
*
* @return array<string>
*/
private function resolveMulti(
SymfonyStyle $io,
InputInterface $input,
string $option,
array $allowed,
array $defaults,
string $label,
bool $allowEmpty = false,
): array {
$values = $input->getOption($option);
if ([] !== $values) {
if ($allowEmpty && \in_array('', $values, true)) {
if ([] !== array_diff($values, [''])) {
throw new InvalidArgumentException(sprintf('Cannot combine empty --%s with other values.', $option));
}
return [];
}
$unknown = array_diff($values, $allowed);
if ([] !== $unknown) {
throw new InvalidArgumentException(sprintf('Unknown --%s value(s): %s. Allowed: %s.', $option, implode(', ', $unknown), implode(', ', $allowed)));
}
return array_values(array_unique($values));
}
if (!$input->isInteractive()) {
return $defaults;
}
// SymfonyQuestionHelper renders a multiselect default by looking up
// each comma-separated token as a key of the choices array. Pass the
// numeric indices of the default values to satisfy that lookup.
$defaultKeys = array_keys(array_intersect($allowed, $defaults));
$question = new ChoiceQuestion(
$label.' (comma-separated)',
$allowed,
implode(',', $defaultKeys),
);
$question->setMultiselect(true);
if ($allowEmpty) {
// ChoiceQuestion's constructor always installs a validator.
$nativeValidator = $question->getValidator();
\assert(null !== $nativeValidator);
$question->setValidator(static function ($v) use ($nativeValidator): array {
if (null === $v || '' === $v) {
return [];
}
return array_values((array) $nativeValidator($v));
});
}
return (array) $io->askQuestion($question);
}
}