Skip to content

Commit

Permalink
Adds support for conditional steps (#171)
Browse files Browse the repository at this point in the history
* add support for conditional forms - #

* add testcases - #

* implement the change with a new addIf method - #

* Update src/FormBuilder.php

* Update FormBuilder.php

---------

Co-authored-by: Jess Archer <[email protected]>
Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
3 people authored Oct 9, 2024
1 parent 547587f commit 7f2060e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/FormBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ public function add(Closure $step, ?string $name = null, bool $ignoreWhenReverti
return $this;
}

/**
* Add a new conditional step.
*/
public function addIf(Closure|bool $condition, Closure $step, ?string $name = null, bool $ignoreWhenReverting = false): self
{
$this->steps[] = new FormStep($step, $condition, $name, $ignoreWhenReverting);

return $this;
}

/**
* Run all of the given steps.
*
Expand Down
48 changes: 48 additions & 0 deletions tests/Feature/FormTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\form;
use function Laravel\Prompts\outro;
use function Laravel\Prompts\text;

it('can run multiple steps', function () {
Prompt::fake([
Expand Down Expand Up @@ -179,3 +180,50 @@

Prompt::assertOutputDoesntContain('This should not appear!');
});

it('can revert steps with conditions', function () {
Prompt::fake([
'L', 'u', 'k', 'e', Key::ENTER, // name
Key::DOWN, Key::ENTER, // JS
Key::CTRL_U, // revert
Key::UP, Key::ENTER, // PHP
'8', '.', '3', Key::ENTER, // version
Key::ENTER,
]);

$responses = form()
->text('What is your name?')
->select('What is your language?', ['PHP', 'JS'])
->addIf(fn ($responses) => $responses[1] === 'PHP', fn ($responses) => text("Which version?"))
->confirm('Are you sure?')
->submit();

expect($responses)->toBe([
'Luke',
'PHP',
'8.3',
true,
]);
});

it('leaves skipped conditional field empty', function () {
Prompt::fake([
'L', 'u', 'k', 'e', Key::ENTER, // name
Key::DOWN, Key::ENTER, // JS
Key::ENTER,
]);

$responses = form()
->text('What is your name?')
->select('What is your language?', ['PHP', 'JS'])
->addIf(fn ($responses) => $responses[1] === 'PHP', fn ($responses) => text("Which version?"))
->confirm('Are you sure?')
->submit();

expect($responses)->toBe([
'Luke',
'JS',
null,
true,
]);
});

0 comments on commit 7f2060e

Please sign in to comment.