Skip to content

Add default fallbacks #57

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

Closed
wants to merge 1 commit into from
Closed
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
49 changes: 47 additions & 2 deletions src/Concerns/Fallback.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ trait Fallback
/**
* Whether to fallback to a custom implementation
*/
protected static bool $shouldFallback = false;
protected static bool $shouldFallback = PHP_OS_FAMILY === 'Windows';

/**
* The fallback implementations.
Expand All @@ -32,7 +32,15 @@ public static function fallbackWhen(bool $condition): void
*/
public static function shouldFallback(): bool
{
return static::$shouldFallback && isset(static::$fallbacks[static::class]);
return static::$shouldFallback && static::hasFallback();
}

/**
* Whether the prompt has a fallback implementation.
*/
public static function hasFallback(): bool
{
return isset(static::$fallbacks[static::class]);
}

/**
Expand All @@ -58,4 +66,41 @@ public function fallback(): mixed

return $fallback($this);
}

/**
* Configure the default fallback behavior.
*/
abstract protected function configureDefaultFallback(): void;

/**
* Retry the callback until the validation passes.
*
* @param Closure(): mixed $callback
* @param Closure(mixed): string|null $validate
* @param Closure(string): void $fail
*/
protected function retryUntilValid(Closure $callback, bool|string $required, ?Closure $validate, Closure $fail): mixed
{
while (true) {
$result = $callback();

if ($required && ($result === '' || $result === [] || $result === false)) {
$fail(is_string($required) ? $required : 'Required.');

continue;
}

if ($validate) {
$error = $validate($result);

if (is_string($error) && strlen($error) > 0) {
$fail($error);

continue;
}
}

return $result;
}
}
}
15 changes: 15 additions & 0 deletions src/ConfirmPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Laravel\Prompts;

use Closure;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class ConfirmPrompt extends Prompt
{
Expand Down Expand Up @@ -49,4 +51,17 @@ public function label(): string
{
return $this->confirmed ? $this->yes : $this->no;
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
fn () => (new SymfonyStyle(new ArrayInput([]), static::output()))->confirm($prompt->label, $prompt->default),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd need to call the setInteractive method on the Input object to respect the --no-interaction option.

Implementing a first-party "non-interactive" feature in Prompts is probably worthwhile so we can return an appropriate value where possible and ensure that any required and validate arguments would pass regardless of the fallback configuration.

Symfony's choice component, for example, does not allow you to select no option but will return null in non-interactive mode.

$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}
42 changes: 42 additions & 0 deletions src/MultiSelectPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Closure;
use Illuminate\Support\Collection;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class MultiSelectPrompt extends Prompt
{
Expand Down Expand Up @@ -167,4 +169,44 @@ protected function toggleHighlighted(): void
$this->values[] = $value;
}
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(function (self $prompt) {
if ($prompt->default !== []) {
return $this->retryUntilValid(
fn () => (new SymfonyStyle(new ArrayInput([]), static::output()))->choice($prompt->label, $prompt->options, implode(',', $prompt->default), true),
$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
);
}

return $this->retryUntilValid(
function () use ($prompt) {
/** @var array<int, int|string> * */
$selected = (new SymfonyStyle(new ArrayInput([]), static::output()))->choice(
$prompt->label,
array_is_list($prompt->options)
? ['None', ...$prompt->options]
: ['none' => 'None', ...$prompt->options],
'None',
true
);

return collect($selected)
->reject(array_is_list($prompt->options) ? 'None' : 'none')
->unique()
->values()
->all();
},
$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
);
});
}
}
8 changes: 8 additions & 0 deletions src/Note.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,12 @@ public function value(): bool
{
return true;
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
//
}
}
15 changes: 15 additions & 0 deletions src/PasswordPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Laravel\Prompts;

use Closure;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class PasswordPrompt extends Prompt
{
Expand Down Expand Up @@ -40,4 +42,17 @@ public function maskedWithCursor(int $maxWidth): string

return $this->addCursor($this->masked(), $this->cursorPosition, $maxWidth);
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
fn () => (new SymfonyStyle(new ArrayInput([]), static::output()))->askHidden($prompt->label) ?? '',
$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}
17 changes: 4 additions & 13 deletions src/Prompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Closure;
use Laravel\Prompts\Output\ConsoleOutput;
use RuntimeException;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;

Expand Down Expand Up @@ -75,12 +74,14 @@ public function prompt(): mixed
{
$this->capturePreviousNewLines();

if (! static::hasFallback()) {
$this->configureDefaultFallback();
}

if (static::shouldFallback()) {
return $this->fallback();
}

$this->checkEnvironment();

try {
static::terminal()->setTty('-icanon -isig -echo');
} catch (Throwable $e) {
Expand Down Expand Up @@ -326,14 +327,4 @@ private function validate(mixed $value): void
$this->error = $error;
}
}

/**
* Check whether the environment can support the prompt.
*/
private function checkEnvironment(): void
{
if (PHP_OS_FAMILY === 'Windows') {
throw new RuntimeException('Prompts is not currently supported on Windows. Please use WSL or configure a fallback.');
}
}
}
24 changes: 24 additions & 0 deletions src/SearchPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Laravel\Prompts;

use Closure;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class SearchPrompt extends Prompt
{
Expand Down Expand Up @@ -178,4 +180,26 @@ public function label(): ?string
{
return $this->matches[array_keys($this->matches)[$this->highlighted]] ?? null;
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
function () use ($prompt) {
$query = (new SymfonyStyle(new ArrayInput([]), static::output()))->ask($prompt->label) ?? '';

$options = ($prompt->options)($query);
if (! is_array($options) || count($options) === 0) {
return false;
}

return (new SymfonyStyle(new ArrayInput([]), static::output()))->choice($prompt->label, $options);
},
'Not found',
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}
15 changes: 15 additions & 0 deletions src/SelectPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Closure;
use Illuminate\Support\Collection;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class SelectPrompt extends Prompt
{
Expand Down Expand Up @@ -138,4 +140,17 @@ protected function highlightNext(): void
$this->firstVisible = 0;
}
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
fn () => (new SymfonyStyle(new ArrayInput([]), static::output()))->choice($prompt->label, $prompt->options, $prompt->default),
true,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}
8 changes: 8 additions & 0 deletions src/Spinner.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,12 @@ public function value(): bool
{
return true;
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
//
}
}
24 changes: 24 additions & 0 deletions src/SuggestPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

use Closure;
use Illuminate\Support\Collection;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;

class SuggestPrompt extends Prompt
{
Expand Down Expand Up @@ -169,4 +172,25 @@ protected function selectHighlighted(): void

$this->typedValue = $this->matches()[$this->highlighted];
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
function () use ($prompt) {
$question = new Question($prompt->label, $prompt->default);

is_callable($prompt->options)
? $question->setAutocompleterCallback($prompt->options)
: $question->setAutocompleterValues($prompt->options);

return (new SymfonyStyle(new ArrayInput([]), static::output()))->askQuestion($question);
},
$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}
15 changes: 15 additions & 0 deletions src/TextPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Laravel\Prompts;

use Closure;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Style\SymfonyStyle;

class TextPrompt extends Prompt
{
Expand Down Expand Up @@ -33,4 +35,17 @@ public function valueWithCursor(int $maxWidth): string

return $this->addCursor($this->value(), $this->cursorPosition, $maxWidth);
}

/**
* Configure the default fallback behavior.
*/
protected function configureDefaultFallback(): void
{
self::fallbackUsing(fn (self $prompt) => $this->retryUntilValid(
fn () => (new SymfonyStyle(new ArrayInput([]), static::output()))->ask($prompt->label, $prompt->default ?: null) ?? '',
$prompt->required,
$prompt->validate,
fn ($message) => static::output()->writeln("<error>{$message}</error>"),
));
}
}