The problem

In our online shop, every order of the order service follows a Symfony state machine named order. It starts as draft, then moves to placed, paid and shipped. Before shipping, it can be cancelled (cancelled), with a mandatory reason.

The shortest path is to expose the status as an ordinary field: PATCH /orders/{id} with {"status": "shipped"}. The client then writes the state itself.

Every jump becomes possible. A Choice constraint checks that the value exists, not the path. A placed order moves to shipped without a payment.

The workflow is bypassed. Writing the property does not call apply(): no guard, no listener. The event that the completed listener puts in the outbox is never sent.

Two requests, two decisions. The warehouse ships while support cancels. Both requests read paid and each writes its own status: both effects take place.

Data out of context. The cancellation reason becomes a free field, written at any time, empty or not.

Relations written as IRIs. The front end handles UUIDs, but must send /customers/{id} to designate the customer. The write contract depends on the routes.

The options

A writable status field, checked by a validator

  • What it solves: no extra route. A validator compares the old and the new status.
  • What it costs: this validator copies the workflow, without its guards or listeners, and does not see the concurrent request.

A generic transition operation

POST /orders/{id}/transitions, with {"transition": "ship"} in the body.

  • What it solves: a single route, and the workflow applies the transition.
  • What it costs: one input schema for every transition. The reason becomes an optional field, and rights are decided in code, invisible in OpenAPI.

One operation per transition

PATCH /orders/{id}/place, /pay, /ship and /cancel.

  • What it solves: each transition has its own input, access rule and documentation. A shared processor applies the workflow.
  • What it costs: one operation to declare per transition, and three API Platform settings to know.

Our recommendation

The status is read-only. Each transition is a PATCH /orders/{id}/<transition> operation, handled by a shared processor, in a single transaction.

API Platform first does its usual work: it reads the order (404), evaluates the security rule (403) and validates the payload (422). An empty reason never reaches the workflow. The processor then locks the row and reads it again, asks the workflow can(), then calls apply() and flush() before committing.

One PATCH per transition: API Platform filters, the processor decides under lock API Platform, before the processor 1. read the order (Doctrine provider) 2. check the rights ( security ) 3. validate CancelOrderInput 404 unknown or filtered-out order 403 neither owner nor support 422 reason missing, blank or too long WorkflowTransitionProcessor , one transaction 4. BEGIN, lock() FOR UPDATE, refresh() a concurrent transition waits here 5. can('cancel') ? no 409 ROLLBACK, the workflow's reasons 6. reason copied, apply() , flush() listeners write to the outbox PATCH /orders/{id}/cancel {"reason": "Order placed twice."} yes 7. COMMIT 200 OrderResource , @id /orders/{id}

The two error codes differ. A 422 reports a request that is invalid in itself, whatever the state. A 409 reports a conflict with the current state: the same cancellation would have succeeded before shipping.

Relations are written as UUIDs: a constraint checks that they exist during validation, then ObjectMapper turns them into entities. The resource becomes flat: the case where our article on ObjectMapper recommends this component.

PATCH, and API Platform's read

POST with status: 200 would work too: it is the form used in our article on the outbox. But that example turns the read off (read: false) and loads the order in the processor.

We keep API Platform's read. An unknown order answers 404, security receives the entity, and Doctrine query extensions filter what the user can reach. The processor only has to lock and read again.

The trade-offs we accept

One operation per transition. The resource grows, and so does OpenAPI. That is also what documents who can do what.

A wait under lock. A second transition on the same order waits for the first one to end. We keep the transaction short: no HTTP call in the listeners, the outbox takes care of that.

A lock rather than a version. An optimistic lock (a version column) would avoid the wait, and API Platform answers 409 by default on OptimisticLockException. But the client then has to retry.

UUIDs instead of IRIs. "customerId": "0199..." cannot be followed like an @id. The OpenAPI schema announces format: uuid without naming the target resource: we name it in the field's description.

The signal that should make us reconsider: a transition that calls an external service, such as a payment provider. It then becomes asynchronous, applied by a Messenger handler.

Implementation

The examples target Symfony 7.4 and 8.1, API Platform 4.4, Doctrine ORM 3.7 and PostgreSQL. Version 5.0.7 has the same code on these points. Entities and resources follow our article on DTO resources, except relations, written here as UUIDs.

1. Places and transitions

The places are the constants of a final class OrderStatus (DRAFT, PLACED, PAID, SHIPPED, CANCELLED), the transitions those of a final class OrderTransition:

// src/Workflow/OrderTransition.php
namespace App\Workflow;

// The same names as config/packages/workflow.yaml.
final class OrderTransition
{
    public const PLACE = 'place';
    public const PAY = 'pay';
    public const SHIP = 'ship';
    public const CANCEL = 'cancel';
}
# config/packages/workflow.yaml (order service)
framework:
  workflows:
    order:
      type: state_machine
      marking_store:
        type: method
        property: status
      supports:
        - App\Entity\Order
      initial_marking: draft
      places: [draft, placed, paid, shipped, cancelled]
      transitions:
        place: { from: draft, to: placed }
        pay: { from: placed, to: paid }
        ship: { from: paid, to: shipped }
        cancel: { from: [placed, paid], to: cancelled }

Order has getStatus() and setStatus() for the marking store, setCancellationReason(), setCarrier() and setTrackingNumber(). No input carries status.

2. One operation per transition

// src/ApiResource/OrderResource.php
namespace App\ApiResource;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\ApiResource\Input\CancelOrderInput;
use App\ApiResource\Input\CreateOrderInput;
use App\ApiResource\Input\ShipOrderInput;
use App\Entity\Customer;
use App\Entity\Order;
use App\State\WorkflowTransitionProcessor;
use App\Workflow\OrderTransition;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;

#[ApiResource(
    shortName: 'Order',
    operations: [
        new GetCollection(),
        new Get(name: 'order_get'),
        new Post(input: CreateOrderInput::class, denormalizationContext: ['allow_extra_attributes' => false]),
        // place and pay follow this model, with input: false.
        new Patch(
            uriTemplate: '/orders/{id}/ship',
            security: "is_granted('ROLE_WAREHOUSE')",
            input: ShipOrderInput::class,
            map: false,
            processor: WorkflowTransitionProcessor::class,
            normalizationContext: ['item_uri_template' => 'order_get'],
            extraProperties: ['transition' => OrderTransition::SHIP],
        ),
        new Patch(
            uriTemplate: '/orders/{id}/cancel',
            security: "is_granted('ORDER_CANCEL', object)",
            input: CancelOrderInput::class,
            map: false,
            processor: WorkflowTransitionProcessor::class,
            normalizationContext: ['item_uri_template' => 'order_get'],
            extraProperties: ['transition' => OrderTransition::CANCEL],
        ),
    ],
    stateOptions: new Options(entityClass: Order::class),
    collectDenormalizationErrors: true,
)]
#[Map(source: Order::class)]
final readonly class OrderResource
{
    public function __construct(
        public Uuid $id,
        public string $reference,
        // Read from the entity: no input writes it.
        public string $status,
        // A UUID, as on writes.
        #[Map(source: 'customer', transform: [self::class, 'idOf'])]
        public Uuid $customerId,
        public ?string $cancellationReason,
        public ?string $carrier,
        public ?string $trackingNumber,
    ) {
    }

    public static function idOf(Customer $customer): Uuid
    {
        return $customer->getId();
    }
}
  • map: false: the Doctrine provider hands the entity itself to the processor. With the mapping on, it would get the resource.
  • security: object is the entity that was read. The ORDER_CANCEL voter accepts the owning customer and support: it judges identity, the workflow judges state.
  • allow_extra_attributes: false: a status sent to the POST is refused (400) instead of being ignored.
  • item_uri_template: API Platform computes the @id from the current operation, here /orders/{id}/cancel. itemUriTemplate only exists on Post and GetCollection, so this context names the Get by its name.

3. The shared processor

// src/State/WorkflowTransitionProcessor.php
namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use Doctrine\DBAL\LockMode;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\TransitionBlocker;

/** @implements ProcessorInterface<object, object> */
final readonly class WorkflowTransitionProcessor implements ProcessorInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private Registry $workflows,
        private ObjectMapperInterface $objectMapper,
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): object
    {
        $transition = $operation->getExtraProperties()['transition'];

        // With an input, $data is the validated DTO, and API Platform keeps the entity it read in read_data.
        $hasInput = null !== ($operation->getInput()['class'] ?? null);
        $entity = $hasInput ? $context['read_data'] : $data;
        $workflow = $this->workflows->get($entity);

        $connection = $this->em->getConnection();
        $connection->beginTransaction();
        try {
            // SELECT 1 FROM orders t0 WHERE t0.id = ? FOR UPDATE: a concurrent transition waits here.
            $this->em->lock($entity, LockMode::PESSIMISTIC_WRITE);
            // Read again under the lock: the state is the one the previous request committed.
            $this->em->refresh($entity);

            if (!$workflow->can($entity, $transition)) {
                $reasons = array_map(
                    static fn (TransitionBlocker $blocker): string => $blocker->getMessage(),
                    iterator_to_array($workflow->buildTransitionBlockerList($entity, $transition)),
                );

                throw new ConflictHttpException(trim(\sprintf('The "%s" transition cannot be applied. %s', $transition, implode(' ', $reasons))));
            }

            if ($hasInput) {
                // The cancellation reason, or the carrier and the tracking number.
                $this->objectMapper->map($data, $entity);
            }

            // The workflow's listeners, the outbox among them, write in this transaction.
            $workflow->apply($entity, $transition);
            $this->em->flush();
            $connection->commit();
        } catch (ConflictHttpException $e) {
            // Nothing was written: the EntityManager stays usable.
            $connection->rollBack();

            throw $e;
        } catch (\Throwable $e) {
            // Unexpected error: roll back, then close, as Doctrine recommends.
            if ($connection->isTransactionActive()) {
                $connection->rollBack();
            }
            $this->em->close();

            throw $e;
        }

        return $this->objectMapper->map($entity, $operation->getClass());
    }
}

Lock the row alone. lock() runs SELECT 1 ... FOR UPDATE on the entity's table, then refresh() reads it again. find() or refresh() with a lock mode add FOR UPDATE to the whole loading query. PostgreSQL also locks the rows of the EAGER joins, or rejects the query on a LEFT JOIN.

Why we lock is explained in our article on the outbox: the cancellation that was waiting reads shipped again and gets its 409.

Copy the input after can(). On a 409, the entity in memory stays as the database returned it. If a guard must read the payload, copy it before can() and read the entity again in the 409 branch.

An explicit 409. The message carries the workflow's reasons, and API Platform returns it in detail for a 4xx. apply() throws NotEnabledTransitionException when the transition is not allowed: declared as 409 in exceptionToStatus, it covers transitions applied elsewhere.

No wrapInTransaction(). Doctrine documents it: on an exception, it rolls the transaction back and closes the EntityManager. After a 409, any code that still uses it would throw EntityManagerClosed, although nothing was written. The outbox article uses it safely: nothing there reuses the EntityManager afterwards, which a shared processor cannot guarantee.

4. The inputs: a 422 before the workflow

// src/ApiResource/Input/CancelOrderInput.php
namespace App\ApiResource\Input;

use App\Entity\Order;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Validator\Constraints as Assert;

#[Map(target: Order::class)]
final readonly class CancelOrderInput
{
    public function __construct(
        #[Assert\NotBlank(normalizer: 'trim')]
        #[Assert\Length(max: 500)]
        #[Map(target: 'cancellationReason')]
        public string $reason,
    ) {
    }
}
PATCH /orders/0199b1a0-7c3e-7d2a-9f10-2b6c1d4e5f60/cancel HTTP/1.1
Content-Type: application/merge-patch+json

{"reason": "Order placed twice."}
Situation Response Step
Unknown order, or filtered out by an extension 404 read
Neither the owning customer nor support 403 security
Reason missing, blank or too long 422 deserialization, then validation
Order in draft, shipped or already cancelled 409 can()
Order placed or paid 200 COMMIT

ShipOrderInput follows the same model, with two required fields:

// src/ApiResource/Input/ShipOrderInput.php
namespace App\ApiResource\Input;

use App\Entity\Order;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Validator\Constraints as Assert;

// The names of Order's properties: no #[Map] per field.
#[Map(target: Order::class)]
final readonly class ShipOrderInput
{
    public function __construct(
        #[Assert\NotBlank(normalizer: 'trim')]
        public string $carrier,
        #[Assert\NotBlank(normalizer: 'trim')]
        public string $trackingNumber,
    ) {
    }
}

A transition without input (input: false) expects neither a body nor a Content-Type. With an input, it accepts the PATCH formats, application/merge-patch+json by default, and answers 415 to the others.

5. Relations by UUID

// src/ApiResource/Input/CreateOrderInput.php
namespace App\ApiResource\Input;

use App\Entity\Customer;
use App\Entity\Order;
use App\Mapper\UuidToCustomer;
use App\Validator\EntityExists;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;

#[Map(target: Order::class)]
final readonly class CreateOrderInput
{
    public function __construct(
        #[Assert\NotBlank, Assert\Length(max: 32)]
        public string $reference,
        // A UUID, not an IRI: checked on validation, converted on mapping.
        #[EntityExists(entity: Customer::class)]
        #[Map(target: 'customer', transform: UuidToCustomer::class)]
        public Uuid $customerId,
    ) {
    }
}

EntityExists follows the Symfony documentation: an entity option (#[HasNamedArguments]) and a message. Its validator receives the EntityManager:

// src/Validator/EntityExistsValidator.php (excerpt)
public function validate(mixed $value, Constraint $constraint): void
{
    // Absent or null: NotNull decides whether the field is required.
    if ($value instanceof Uuid && null === $this->em->find($constraint->entity, $value)) {
        $this->context->buildViolation($constraint->message)
            ->setParameter('{{ uuid }}', $value->toRfc4122())
            ->addViolation();
    }
}
// src/Mapper/UuidToCustomer.php
namespace App\Mapper;

use App\Entity\Customer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\ObjectMapper\TransformCallableInterface;

/** @implements TransformCallableInterface<object, object> */
final readonly class UuidToCustomer implements TransformCallableInterface
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {
    }

    public function __invoke(mixed $value, object $source, ?object $target): ?Customer
    {
        // Already loaded by the validator: find() reads it from the identity map, without a query.
        return null === $value ? null : $this->em->find(Customer::class, $value);
    }
}

An unknown UUID gives a 422 on the customerId path, along with the other violations, before any mapping.

And in a PATCH? An absent field stays uninitialized, not null (see our article on DTO resources). ObjectMapper only skips such a property carrying a #[Map] since symfony/object-mapper 7.4.14 and 8.1.1 (27 June 2026). Before that, it threw an error.

A null on a required relation gives a 422: collectDenormalizationErrors turns the type error into a violation. A list of UUIDs replaces the collection through the adder and the remover, and [] unlinks everything. A nullable relation marked #[Map(if: new IsNotNull())] (Symfony 8.1) treats null like an absent field.

Checklist

  • No input carries the status, and allow_extra_attributes: false refuses an unknown field.
  • One PATCH /<resource>/{id}/<transition> operation per transition, with its security rule.
  • map: false on the transitions, and the transition named in extraProperties.
  • A lock on the row alone (lock()), then refresh(), in a transaction.
  • A 409 with the workflow's reasons, without closing the EntityManager.
  • A validated input (422) for every transition that needs data.
  • item_uri_template pointing at the resource's Get.
  • Relations written as UUIDs: an existence constraint, then a transform.
  • Tests that read the state back after a 409 and a 422.

Sources

Versions checked on 15 November 2026: Symfony 8.1.11 and 7.4.23, API Platform 4.4.8 and 5.0.7, Doctrine ORM 3.7.7.