Skip to content
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

Allow customizing the cancel behaviour #100

Merged
merged 5 commits into from
Dec 29, 2023
Merged
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
18 changes: 17 additions & 1 deletion src/Prompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ abstract class Prompt
*/
protected ?Closure $validate;

/**
* The cancellation callback.
*/
protected static Closure $cancelUsing;

/**
* Indicates if the prompt has been validated.
*/
Expand Down Expand Up @@ -108,7 +113,11 @@ public function prompt(): mixed

if ($continue === false || $key === Key::CTRL_C) {
if ($key === Key::CTRL_C) {
static::terminal()->exit();
if (isset(static::$cancelUsing)) {
return (static::$cancelUsing)();
} else {
static::terminal()->exit();
}
}

return $this->value();
Expand All @@ -119,6 +128,13 @@ public function prompt(): mixed
}
}

/**
* Register a callback to be invoked when a user cancels a prompt.
*/
public static function cancelUsing(Closure $callback): void {
static::$cancelUsing = $callback;
}

/**
* How many new lines were written by the last output.
*/
Expand Down
7 changes: 7 additions & 0 deletions tests/Feature/TextPromptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,10 @@

text('What is your name?', required: true);
})->throws(NonInteractiveValidationException::class, 'Required.');

it('allows customizing the cancellation', function () {
Prompt::cancelUsing(fn () => throw new Exception('Cancelled.'));
Prompt::fake([Key::CTRL_C]);

text('What is your name?');
})->throws(Exception::class, 'Cancelled.');