From e1379d8ead15edd6cc4369c22274345982edc95a Mon Sep 17 00:00:00 2001 From: Jess Archer Date: Fri, 27 Oct 2023 23:53:59 +1000 Subject: [PATCH] Allow empty strings on `select` prompt (#99) * Allow empty string keys on `select` prompts * Remove truthy check on `required` --- src/Prompt.php | 12 ++++++++++-- src/SelectPrompt.php | 8 ++++++++ tests/Feature/SelectPromptTest.php | 14 ++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Prompt.php b/src/Prompt.php index dfa0657e..fcc80baf 100644 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -307,9 +307,9 @@ private function validate(mixed $value): void { $this->validated = true; - if (($this->required ?? false) && ($value === '' || $value === [] || $value === false || $value === null)) { + if ($this->required !== false && $this->isInvalidWhenRequired($value)) { $this->state = 'error'; - $this->error = is_string($this->required) ? $this->required : 'Required.'; + $this->error = is_string($this->required) && strlen($this->required) > 0 ? $this->required : 'Required.'; return; } @@ -330,6 +330,14 @@ private function validate(mixed $value): void } } + /** + * Determine whether the given value is invalid when the prompt is required. + */ + protected function isInvalidWhenRequired(mixed $value): bool + { + return $value === '' || $value === [] || $value === false || $value === null; + } + /** * Check whether the environment can support the prompt. */ diff --git a/src/SelectPrompt.php b/src/SelectPrompt.php index 018b956c..6c9e5ed8 100644 --- a/src/SelectPrompt.php +++ b/src/SelectPrompt.php @@ -96,4 +96,12 @@ public function visible(): array { return array_slice($this->options, $this->firstVisible, $this->scroll, preserve_keys: true); } + + /** + * Determine whether the given value is invalid when the prompt is required. + */ + protected function isInvalidWhenRequired(mixed $value): bool + { + return $value === null; + } } diff --git a/tests/Feature/SelectPromptTest.php b/tests/Feature/SelectPromptTest.php index 26138776..6d57d3fb 100644 --- a/tests/Feature/SelectPromptTest.php +++ b/tests/Feature/SelectPromptTest.php @@ -257,6 +257,20 @@ expect($result)->toBe('Blue'); }); +it('allows empty strings', function () { + Prompt::fake([Key::ENTER]); + + $result = select( + label: 'What is your favorite color?', + options: [ + '' => 'Empty', + 'not-empty' => 'Not empty', + ], + ); + + expect($result)->toBe(''); +}); + it('fails when there is no default in non-interactive mode', function () { Prompt::interactive(false);