diff --git a/src/SuggestPrompt.php b/src/SuggestPrompt.php index 85f2bf7b..dd8d2553 100644 --- a/src/SuggestPrompt.php +++ b/src/SuggestPrompt.php @@ -14,7 +14,7 @@ class SuggestPrompt extends Prompt /** * The options for the suggest prompt. * - * @var array|Closure(string): array + * @var array|Closure(string): (array|Collection) */ public array|Closure $options; @@ -28,7 +28,7 @@ class SuggestPrompt extends Prompt /** * Create a new SuggestPrompt instance. * - * @param array|Collection|Closure(string): array $options + * @param array|Collection|Closure(string): (array|Collection) $options */ public function __construct( public string $label, @@ -91,7 +91,9 @@ public function matches(): array } if ($this->options instanceof Closure) { - return $this->matches = array_values(($this->options)($this->value())); + $matches = ($this->options)($this->value()); + + return $this->matches = array_values($matches instanceof Collection ? $matches->all() : $matches); } return $this->matches = array_values(array_filter($this->options, function ($option) { diff --git a/tests/Feature/SuggestPromptTest.php b/tests/Feature/SuggestPromptTest.php index e0eae8e1..dd23d9c7 100644 --- a/tests/Feature/SuggestPromptTest.php +++ b/tests/Feature/SuggestPromptTest.php @@ -98,6 +98,26 @@ expect($result)->toBe('Blue'); }); +it('accepts a callback returning a collection', function () { + Prompt::fake(['b', Key::TAB, Key::ENTER]); + + $result = suggest( + label: 'What is your favorite color?', + options: fn ($value) => collect([ + 'Red', + 'Green', + 'Blue', + ])->filter( + fn ($name) => str_contains( + strtoupper($name), + strtoupper($value) + ) + ) + ); + + expect($result)->toBe('Blue'); +}); + it('validates', function () { Prompt::fake([Key::ENTER, 'X', Key::ENTER]);