From 0ab75ac3434d9f610c5691758a6146a3d1940c18 Mon Sep 17 00:00:00 2001 From: macocci7 Date: Tue, 16 Apr 2024 23:20:35 +0900 Subject: [PATCH] Fix type error in suggest with collection (#134) * Fix type error in suggest with collection * add @phpstan-ignore-next-line * Update types * Replace expensive operation --------- Co-authored-by: Jess Archer --- src/SuggestPrompt.php | 8 +++++--- tests/Feature/SuggestPromptTest.php | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) 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]);