-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommand.php
More file actions
314 lines (287 loc) · 9.85 KB
/
Command.php
File metadata and controls
314 lines (287 loc) · 9.85 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
<?php
namespace Dragonfly\PluginLib\Commands;
use Dragonfly\PluginLib\Events\EventContext;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
use ReflectionType;
use RuntimeException;
/**
* Base command class with reflection-based argument parsing.
*
* Supported parameter types:
* - int, float, bool, string
* - Varargs (must be last)
* - Optional (wrapper; optional params must be last, may be multiple)
*
* Define parameters as public properties on a subclass, in the order they
* should be parsed. Example:
*
* class TpCommand extends Command {
* protected string $name = 'tpc';
* protected string $description = 'Teleport to coordinates';
* public float $x;
* /** @var Optional<float> *\/
* public Optional $y;
* public float $z;
* public function execute(CommandSender $sender, EventContext $ctx): void { ... }
* }
*/
abstract class Command {
// Metadata
protected string $name = '';
protected string $description = '';
/** @var string[] */
protected array $aliases = [];
abstract public function execute(CommandSender $sender, EventContext $ctx): void;
public function getName(): string {
return $this->name;
}
public function getDescription(): string {
return $this->description;
}
/**
* @return string[]
*/
public function getAliases(): array {
return $this->aliases;
}
/**
* Parse command arguments. Returns true on success, false on usage error.
*
* @param string[] $rawArgs
*/
public function parseArgs(array $rawArgs): bool {
try {
$this->validateSignature();
} catch (\Throwable) {
return false;
}
$schema = $this->inspectParameters();
$ref = new ReflectionClass($this);
$props = $this->getCommandProperties($ref);
$propMap = [];
foreach ($props as $p) {
$p->setAccessible(true);
$propMap[$p->getName()] = $p;
}
$argIndex = 0;
$argCount = count($rawArgs);
$paramCount = count($schema);
foreach ($schema as $idx => $param) {
$name = $param['name'];
$type = $param['type']; // int|float|bool|string|varargs
$optional = !empty($param['optional']);
$prop = $propMap[$name] ?? null;
if (!$prop) {
return false;
}
if ($type === 'varargs') {
if ($idx !== $paramCount - 1) {
return false;
}
$remaining = array_slice($rawArgs, $argIndex);
$prop->setValue($this, new Varargs(implode(' ', $remaining)));
return true;
}
if ($argIndex >= $argCount) {
if ($optional) {
if ($this->getTypeName($prop->getType()) === Optional::class) {
$prop->setValue($this, new Optional());
continue;
}
return false;
}
return false;
}
$parsed = $this->parseTypedValue($rawArgs[$argIndex], $type);
if ($parsed === null && $type !== 'string') {
return false;
}
if ($this->getTypeName($prop->getType()) === Optional::class) {
$opt = new Optional();
$opt->set($parsed);
$prop->setValue($this, $opt);
} else {
$prop->setValue($this, $parsed);
}
$argIndex++;
}
if ($argIndex < $argCount) {
return false;
}
return true;
}
/**
* Validate parameter ordering rules:
* - Optional parameters may only appear at the end (can be multiple).
* - Varargs must be the final parameter.
*/
public function validateSignature(): void {
$ref = new ReflectionClass($this);
$props = $this->getCommandProperties($ref);
$seenOptional = false;
foreach ($props as $index => $prop) {
$typeName = $this->getTypeName($prop->getType());
if ($typeName === Varargs::class) {
if ($index !== count($props) - 1) {
throw new RuntimeException('Varargs must be the last parameter.');
}
continue;
}
if ($seenOptional && $typeName !== Optional::class) {
throw new RuntimeException('Optional parameters must be at the end.');
}
if ($typeName === Optional::class) {
$seenOptional = true;
}
}
}
/**
* Generate a human-friendly usage string.
*/
public function generateUsage(): string {
$parts = ['/' . $this->name];
foreach ($this->inspectParameters() as $p) {
$name = $p['name'];
$type = $p['type'];
$optional = !empty($p['optional']);
if ($type === 'varargs') {
$parts[] = '<' . $name . '...>';
} elseif ($optional) {
$parts[] = '[' . $name . ']';
} else {
$parts[] = '<' . $name . '>';
}
}
return implode(' ', $parts);
}
/**
* Export parameter specification for transport to the host (Go) side.
* Format: list of ['name' => string, 'type' => string, 'optional' => bool]
* Types: int|float|bool|string|varargs
*
* @return array<int, array{name:string,type:string,optional?:bool}>
*/
public function serializeParamSpec(): array {
return $this->inspectParameters();
}
/**
* @return ReflectionProperty[]
*/
private function getCommandProperties(ReflectionClass $ref): array {
$props = $ref->getProperties(ReflectionProperty::IS_PUBLIC);
$filtered = [];
foreach ($props as $p) {
$n = $p->getName();
if ($n === 'name' || $n === 'description' || $n === 'aliases') {
continue;
}
$filtered[] = $p;
}
return $filtered;
}
private function getTypeName(?ReflectionType $type): ?string {
if ($type instanceof ReflectionNamedType) {
return $type->getName();
}
return null;
}
private function parseTypedValue(string $arg, ?string $typeName): mixed {
return match ($typeName) {
'int' => filter_var($arg, FILTER_VALIDATE_INT),
'float' => filter_var($arg, FILTER_VALIDATE_FLOAT),
'bool' => $this->parseBool($arg),
null, 'string' => $arg,
default => null,
};
}
private function parseBool(string $arg): ?bool {
$v = strtolower($arg);
return match ($v) {
'true', '1', 'yes', 'on' => true,
'false', '0', 'no', 'off' => false,
default => null,
};
}
/**
* Build a normalized parameter schema from the command's public properties.
* @return array<int, array{name:string,type:string,optional?:bool}>
*/
private function inspectParameters(): array {
$ref = new ReflectionClass($this);
$props = $this->getCommandProperties($ref);
$out = [];
foreach ($props as $prop) {
$name = $prop->getName();
$typeName = $this->getTypeName($prop->getType());
if ($typeName === Varargs::class) {
$out[] = ['name' => $name, 'type' => 'varargs'];
break;
}
if ($typeName === Optional::class) {
$t = $this->getOptionalWrappedType($prop);
$out[] = ['name' => $name, 'type' => $t, 'optional' => true];
continue;
}
$mapped = match ($typeName) {
'int' => 'int',
'float', 'double' => 'float',
'bool' => 'bool',
default => 'string',
};
$out[] = ['name' => $name, 'type' => $mapped];
}
return $out;
}
/**
* Convenience: attach enum values to a parameter in a schema.
*
* @param array<int, array{name:string,type:string,optional?:bool,enum_values?:array<int,string>}> $schema
* @param string $paramName
* @param string[] $values
* @return array
*/
protected function withEnum(array $schema, string $paramName, array $values): array {
foreach ($schema as &$p) {
if ($p['name'] === $paramName) {
$p['enum_values'] = array_values($values);
$p['type'] = 'enum';
break;
}
}
return $schema;
}
/**
* Convenience: enum names from a class' constants, with optional excludes.
*
* @param string $class Fully-qualified class name
* @param string[] $excludeNames
* @return string[]
*/
protected function enumNamesFromClass(string $class, array $excludeNames = []): array {
$names = array_keys((new \ReflectionClass($class))->getConstants());
if (!empty($excludeNames)) {
$names = array_values(array_filter($names, fn ($n) => !in_array($n, $excludeNames, true)));
}
return $names;
}
/**
* Attempt to infer the wrapped type for Optional<T> from @var docblock.
*/
private function getOptionalWrappedType(ReflectionProperty $prop): string {
$doc = $prop->getDocComment() ?: '';
if (preg_match('/@var\s+Optional<\s*([A-Za-z_][A-Za-z0-9_]*)\s*>/i', $doc, $m)) {
$t = strtolower($m[1]);
return match ($t) {
'int' => 'int',
'float', 'double' => 'float',
'bool', 'boolean' => 'bool',
'string' => 'string',
default => 'string',
};
}
// Default to string if not annotated.
return 'string';
}
}