Symfony workflow guards: blocking a transition

A guard, in Symfony's Workflow component, blocks a transition depending on a condition: the user's role, a date, the state of the object.

// workflow.yaml, under the "annuler" (cancel) transition: guard: "is_granted('ROLE_PATRON')"

#[AsGuardListener(workflow: 'reservation', transition: 'honorer')]
public function __invoke(GuardEvent $event): void
{
    $reservation = $event->getSubject();

    if ($reservation->getJour() > $this->horloge->now()->setTime(0, 0)) {
        $event->addTransitionBlocker(new TransitionBlocker('The meal has not taken place yet.', 'pas-avant-le-repas'));
    }
}

A simple rule fits in a guard expression in the configuration, evaluated with the logged-in user. A rule that needs code becomes an #[AsGuardListener] listener, which receives a GuardEvent and refuses with addTransitionBlocker(). The guard applies everywhere: can(), apply(), and workflow_transitions() in Twig, which then only offers the allowed buttons. To explain a refusal, buildTransitionBlockerList() returns the TransitionBlocker objects and their messages; apply() on a blocked transition throws a NotEnabledTransitionException, hence the can() beforehand. The trap: a comparison off by one character, >= instead of >, and the transition stays blocked on the day itself. Nothing breaks, the button simply disappears.

The exercises have you wire the buttons of Gorm's ledger to the bookings workflow, reserve cancellation for the boss and refuse to honour a booking before its day, with a message saying why; then find out, in a "simplified" ledger, why a booking can no longer be honoured on the evening itself.

3 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

WorkflowDebuggingWorkflow eventsMailer