ksassnowski / venture

Venture allows you to create and manage complex, async workflows in your Laravel apps.
https://laravel-venture.com
MIT License
804 stars 32 forks source link

Add method to configure definition conditionally #53

Closed ksassnowski closed 2 years ago

ksassnowski commented 2 years ago

This PR adds a when method to the WorkflowDefinition class to conditionally run a callback when configuring a definition. This allows users to conditionally add jobs to a workflow without having to litter definition with tons of if-statements.

This has been previously suggested in #2 where I initially declined the proposal. I have since then changed my mind on this and agree that this would be a useful addition. The method's API works slightly different than in the original PR but is otherwise pretty similar.

@morrislaptop I will add you as a co-author on this feature since you were the one who originally proposed it.

Usage

class MyWorkflow extends AbstractWorkflow
{
    public function __construct(private User $user)
    {
    }

    public function definition(): WorkflowDefinition
    {
        return Workflow::define('My conditional workflow')
            ->addJob(new JobThatShouldAlwaysRun())
            ->when($this->user->isProUser(), function (WorkflowDefinition $definition): void {
                $definition->addJob(new ProUserOnlyFeature());
            });
            // it's also possible to pass in a callable that returns a boolean as the condition
            ->when(fn (): bool => false, function (WorkflowDefinition $definition): void {
                $definition->addJob(new NeverGetsAdded());
            });
    }
}
morrislaptop commented 2 years ago

Nice! What about the dependencies?

ksassnowski commented 2 years ago

The callback gets passed the whole WorkflowDefinition object. So you can add dependencies just like you normally would.

ksassnowski commented 2 years ago

I've updated the PR to use the Conditionable trait instead. I also decided to remove the test cases as these would just be testing the trait.