Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type error in suggest with collection #134

Merged
merged 4 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/SuggestPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class SuggestPrompt extends Prompt
/**
* The options for the suggest prompt.
*
* @var array<string>|Closure(string): array<string>
* @var array<string>|Closure(string): (array<string>|Collection<int, string>)
*/
public array|Closure $options;

Expand All @@ -28,7 +28,7 @@ class SuggestPrompt extends Prompt
/**
* Create a new SuggestPrompt instance.
*
* @param array<string>|Collection<int, string>|Closure(string): array<string> $options
* @param array<string>|Collection<int, string>|Closure(string): (array<string>|Collection<int, string>) $options
*/
public function __construct(
public string $label,
Expand Down Expand Up @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/SuggestPromptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);

Expand Down
Loading