Skip to content

Commit

Permalink
Allow empty strings on select prompt (#99)
Browse files Browse the repository at this point in the history
* Allow empty string keys on `select` prompts

* Remove truthy check on `required`
  • Loading branch information
jessarcher authored Oct 27, 2023
1 parent 8c693ea commit e1379d8
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Prompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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.
*/
Expand Down
8 changes: 8 additions & 0 deletions src/SelectPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
14 changes: 14 additions & 0 deletions tests/Feature/SelectPromptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit e1379d8

Please sign in to comment.