-
Notifications
You must be signed in to change notification settings - Fork 46
/
Interviewer.php
267 lines (231 loc) · 8.92 KB
/
Interviewer.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
<?php
declare(strict_types=1);
namespace DrupalCodeGenerator\InputOutput;
use DrupalCodeGenerator\Application;
use DrupalCodeGenerator\Attribute\Generator as GeneratorDefinition;
use DrupalCodeGenerator\Helper\Drupal\ExtensionInfoInterface;
use DrupalCodeGenerator\Helper\Drupal\PermissionInfo;
use DrupalCodeGenerator\Helper\Drupal\ServiceInfo;
use DrupalCodeGenerator\Utils;
use DrupalCodeGenerator\Validator\Chained;
use DrupalCodeGenerator\Validator\MachineName;
use DrupalCodeGenerator\Validator\Optional;
use DrupalCodeGenerator\Validator\Required;
use DrupalCodeGenerator\Validator\RequiredClassName;
use DrupalCodeGenerator\Validator\RequiredMachineName;
use DrupalCodeGenerator\Validator\ServiceExists;
use DrupalCodeGenerator\Validator\ServiceName;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* Defines a helper to interact with a user.
*/
final class Interviewer {
/**
* Constructs the object.
*
* @noinspection PhpPropertyCanBeReadonlyInspection
*/
public function __construct(
private readonly IO $io,
// With readonly attribute it fails on CI by some reason.
private array &$vars,
private readonly GeneratorDefinition $generatorDefinition,
private readonly ServiceInfo $serviceInfo,
private readonly ExtensionInfoInterface $extensionInfo,
private readonly PermissionInfo $permissionInfo,
) {}
/**
* Asks a question.
*
* @psalm-param callable(mixed $value): mixed $validator
*/
public function ask(string $question, ?string $default = NULL, ?callable $validator = NULL): mixed {
$question = $this->processText($question);
if ($default !== NULL) {
$default = $this->processText($default);
}
return $this->io->ask($question, $default, $validator);
}
/**
* Asks for confirmation.
*/
public function confirm(string $question, bool $default = TRUE): bool {
$question = $this->processText($question);
return $this->io->confirm($question, $default);
}
/**
* Asks a choice question.
*
* @psalm-param array<array-key, string> $choices
*/
public function choice(string $question, array $choices, ?string $default = NULL, bool $multiselect = FALSE): array|string|int {
$question = $this->processText($question);
// The choices can be an associative array.
$choice_labels = \array_values($choices);
// Start choices list form '1'.
\array_unshift($choice_labels, NULL);
unset($choice_labels[0]);
$question = new ChoiceQuestion($question, $choice_labels, $default);
$question->setMultiselect($multiselect);
// Do not use IO choice here as it prints choice key as default value.
// @see \Symfony\Component\Console\Style\SymfonyStyle::choice().
$answer = $this->io->askQuestion($question);
/** @psalm-suppress FalsableReturnStatement, InvalidFalsableReturnType */
$get_key = static fn (string $answer): string|int => \array_search($answer, $choices);
return \is_array($answer) ? \array_map($get_key, $answer) : $get_key($answer);
}
/**
* Asks name question.
*/
public function askName(): string {
$machine_name = $this->vars['machine_name'] ?? NULL;
$type = $this->generatorDefinition->type;
// Try to determine the name without interaction with the user.
if ($machine_name && !$type->isNewExtension()) {
$name = $this->extensionInfo->getExtensionName($machine_name);
if ($name) {
return $name;
}
}
$default = $machine_name ? Utils::machine2human($machine_name) : NULL;
$question = new Question($type->getNameLabel(), $default);
$question->setValidator(new Required());
return $this->io->askQuestion($question);
}
/**
* Asks machine name question.
*/
public function askMachineName(): string {
$type = $this->generatorDefinition->type;
if (isset($this->vars['name'])) {
$default = $type->isNewExtension() ?
Utils::human2machine($this->vars['name']) : $this->extensionInfo->getExtensionMachineName($this->vars['name']);
}
$default ??= $this->extensionInfo->getExtensionFromPath($this->io->getWorkingDirectory())?->getName();
$question = new Question($type->getMachineNameLabel(), $default);
$question->setValidator(new Chained(new Required(), new MachineName()));
if ($extensions = $this->extensionInfo->getExtensions()) {
$question->setAutocompleterValues(\array_keys($extensions));
}
return $this->io->askQuestion($question);
}
/**
* Asks class question.
*/
public function askClass(string $question = 'Class', ?string $default = NULL): string {
return $this->ask($question, $default, new RequiredClassName());
}
/**
* Asks plugin label question.
*/
public function askPluginLabel(string $question = 'Plugin label', ?string $default = NULL): string {
return $this->ask($question, $default, new Required());
}
/**
* Asks plugin ID question.
*/
public function askPluginId(string $question = 'Plugin ID', ?string $default = '{machine_name}_{plugin_label|h2m}'): string {
return $this->ask($question, $default, new RequiredMachineName());
}
/**
* Asks plugin class question.
*/
public function askPluginClass(string $question = 'Plugin class', ?string $default = NULL, string $suffix = ''): ?string {
if ($default === NULL && isset($this->vars['machine_name'], $this->vars['plugin_id'])) {
$unprefixed_plugin_id = Utils::removePrefix($this->vars['plugin_id'], $this->vars['machine_name'] . '_');
$default = Utils::camelize($unprefixed_plugin_id) . $suffix;
}
return $this->askClass($question, $default);
}
/**
* Collects services.
*
* @psalm-param list<string> $forced_services
*
* @psalm-return array<string, array{name: string, type?: string, description: string, short_type: string}>
*/
public function askServices(bool $default = TRUE, array $forced_services = []): array {
$services = $forced_services;
if ($this->io->confirm('Would you like to inject dependencies?', $default)) {
$service_ids = $this->serviceInfo->getServicesIds();
$validator = new Chained(
new Optional(new ServiceName()),
new Optional(new ServiceExists($this->serviceInfo)),
);
while (TRUE) {
$question = new Question('Type the service name or use arrows up/down. Press enter to continue');
$question->setValidator($validator);
$question->setAutocompleterValues($service_ids);
$service = $this->io->askQuestion($question);
if (!$service) {
break;
}
$services[] = $service;
}
}
$definitions = [];
foreach (\array_unique($services) as $service_id) {
$definitions[$service_id] = $this->serviceInfo->getServiceMeta($service_id);
}
return $definitions;
}
/**
* Asks permission.
*/
public function askPermission(string $question = 'Permission', ?string $default = NULL): string {
$question = new Question($question, $default);
$question->setValidator(new Required());
$permissions = $this->permissionInfo->getPermissionNames();
if (\count($permissions) > 0) {
$question->setAutocompleterValues($permissions);
}
return $this->io->askQuestion($question);
}
/**
* Gets service definition.
*
* @psalm-return array{name: string, type?: string, description: string, short_type: string}
*/
protected function getServiceDefinition(string $service_id): array {
// @todo Fetch service information runtime.
$service_definitions = self::getDumpedServiceDefinitions();
if (isset($service_definitions[$service_id])) {
$definition = $service_definitions[$service_id];
}
else {
// Make up service definition.
$name_parts = \explode('.', $service_id);
$definition = [
'name' => \end($name_parts),
'type' => 'Drupal\example\ExampleInterface',
'description' => "The $service_id service.",
];
// Try to guess correct type of service instance.
$compiled_definition = $this->serviceInfo->getServiceDefinition($service_id);
if ($compiled_definition && isset($compiled_definition['class'])) {
$interface = $compiled_definition['class'] . 'Interface';
$definition['type'] = \interface_exists($interface) ? $interface : $compiled_definition['class'];
}
}
$type_parts = \explode('\\', $definition['type']);
$definition['short_type'] = \end($type_parts);
return $definition;
}
/**
* Gets service definitions.
*
* @return array
* List of service definitions keyed by service ID.
*/
private static function getDumpedServiceDefinitions(): array {
$data_encoded = \file_get_contents(Application::ROOT . '/resources/service-definitions.json');
return \json_decode($data_encoded, TRUE);
}
/**
* Processes the text using previously collected variables.
*/
private function processText(string $question): string {
return Utils::stripSlashes(Utils::replaceTokens($question, $this->vars));
}
}