← All writing

Parse an order status with a backed enum and reject unknown values

PHP 8.3+Sources checked 2026-09-13

A webhook sends an order status as text. Letting that text flow freely through the application means a misspelled status can reach a branch nobody tests. A backed enum gives the accepted values one explicit definition.

Parse at the boundary

<?php
enum OrderStatus: string {
    case Pending = 'pending';
    case Paid = 'paid';
    case Cancelled = 'cancelled';
}
assert(OrderStatus::tryFrom('paid') === OrderStatus::Paid);
assert(OrderStatus::tryFrom('payed') === null);

Use tryFrom when an unknown value is expected input that you want to reject or quarantine. from throws a ValueError for a value outside the enum, which may be appropriate for an internal invariant. Neither API is a replacement for checking the incoming JSON shape before passing a value of the wrong type.

Valid values can still be invalid transitions

cancelled is a recognized status, but your business may prohibit moving a dispatched order into it without a return workflow. Keep transition rules separate from enum parsing. An enum answers which states exist; it does not establish which state changes a particular actor may perform.

A useful test matrix includes every accepted value, an unknown spelling, an unexpected type, and a recognized but forbidden transition. Record unknown provider statuses in a redacted diagnostic event so a provider change is visible. Do not silently convert every unfamiliar status to Pending; that makes a broken integration look like ordinary unfinished work.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.