Skip to content

Commit c61ed8c

Browse files
marky291Log1x
andauthored
✨ Add ->value() method to easily fetch option values in slash commands (#55)
🎨 Improve slash command method hinting --------- Co-authored-by: Brandon <[email protected]>
1 parent 79ce30c commit c61ed8c

File tree

1 file changed

+44
-11
lines changed

1 file changed

+44
-11
lines changed

src/Commands/SlashCommand.php

+44-11
Original file line numberDiff line numberDiff line change
@@ -150,12 +150,8 @@ protected function clearOptions(): void
150150

151151
/**
152152
* Retrieve the parsed command options.
153-
*
154-
* @param string|null $key
155-
* @param mixed $default
156-
* @return mixed
157153
*/
158-
protected function option($key = null, $default = null)
154+
protected function option(?string $key = null, mixed $default = null): mixed
159155
{
160156
if (is_null($key) || ! $this->getOptions()) {
161157
return $this->getOptions();
@@ -164,12 +160,24 @@ protected function option($key = null, $default = null)
164160
return Arr::get($this->getOptions(), $key, $default);
165161
}
166162

163+
/**
164+
* Retrieve the option value.
165+
*/
166+
public function value(?string $option = null, mixed $default = null): mixed
167+
{
168+
$options = $this->flattenOptions($this->getOptions());
169+
170+
if (is_null($option)) {
171+
return $options;
172+
}
173+
174+
return $options[$option] ?? $default;
175+
}
176+
167177
/**
168178
* Set the command options.
169-
*
170-
* @return array
171179
*/
172-
public function options()
180+
public function options(): array
173181
{
174182
return [];
175183
}
@@ -210,10 +218,8 @@ public function getPermissions(): ?string
210218

211219
/**
212220
* Retrieve the slash command options.
213-
*
214-
* @return array
215221
*/
216-
public function getRegisteredOptions()
222+
public function getRegisteredOptions(): ?array
217223
{
218224
if ($this->registeredOptions) {
219225
return $this->registeredOptions;
@@ -230,4 +236,31 @@ public function getRegisteredOptions()
230236
: new DiscordOption($this->discord(), $option)
231237
)->map(fn ($option) => $option->setName(Str::slug($option->name)))->all();
232238
}
239+
240+
/**
241+
* Flatten the options into dot notated keys.
242+
*/
243+
protected function flattenOptions(array $options, ?string $parent = null): array
244+
{
245+
return collect($options)->flatMap(function ($option) use ($parent) {
246+
$key = $parent ? "{$parent}.{$option['name']}" : $option['name'];
247+
248+
if (is_array($option) && isset($option['options'])) {
249+
$options = $this->flattenOptions($option['options'], $key);
250+
251+
if (array_key_exists('value', $option)) {
252+
return [
253+
...[$key => $option['value']],
254+
...$options,
255+
];
256+
}
257+
258+
return $options;
259+
}
260+
261+
return isset($option['value'])
262+
? [$key => $option['value']]
263+
: [];
264+
})->all();
265+
}
233266
}

0 commit comments

Comments
 (0)