Skip to content

Commit

Permalink
Fix type error in suggest with collection (#134)
Browse files Browse the repository at this point in the history
* Fix type error in suggest with collection

* add @phpstan-ignore-next-line

* Update types

* Replace expensive operation

---------

Co-authored-by: Jess Archer <[email protected]>
  • Loading branch information
macocci7 and jessarcher authored Apr 16, 2024
1 parent e1ef9d3 commit 0ab75ac
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
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

0 comments on commit 0ab75ac

Please sign in to comment.