Conversions
When a was() changes the type of a field, its value is converted between the two types: down to the older type
in responses, up to the newer type in requests.
Automatic conversions
| Conversion | Automatic | Warning without a closure |
|---|---|---|
| int → float; int, float, bool → string; bool → int | yes | no |
| string → int, string → float, float → int; int, string → bool | yes | yes, conversion-lossy |
| date-time → date, date → date-time | yes: the day in the value's timezone; a date becomes midnight | date-time → date in a request (the time sent is dropped) |
| backed enum → string, or int when int-backed | yes (->value) | no |
| string or int → backed enum | yes (::from()) | no |
| object, list, custom type | no: give a closure, unless the custom type declares its conversions | — |
Any pair the table does not list (float ↔ bool, for instance) needs a closure. Without one, the check fails:
| Code | Field | Revision | Message |
|---|---|---|---|
conversion-missing | paid | winter-25 | No down conversion from bool to float for 'paid' (response) at was(Winter25): declare down:. |
A conversion-lossy warning does not fail the check, but tells you the cast may not be what clients expect: give a
closure to silence it.
Writing closures
A response only uses down:, a request only up:. A descriptor shared by both declares both.
| Closure | Receives | Returns |
|---|---|---|
down: | the PHP value of the newer shape, and the subject | the PHP value of the older shape |
up: | the typed value of the older shape, and the input of the step being upgraded | the PHP value of the newer shape |
'total' => Schema::int()->required()->min(0)
->was(
ApiRevision::Winter25,
schema: Schema::string(),
down: fn(int $cents): string => number_format($cents / 100, 2, '.', ''),
up: fn(string $amount): int => (int) round(((float) $amount) * 100),
)
->was(ApiRevision::Genesis, schema: Schema::float()),
The genesis step needs no closure: string ↔ float is automatic. In the response direction it is lossy (string →
float), so the check warns unless you give down:.
An up: closure that cannot convert an input throws ConversionException::invalid(). The client gets a validation
error on its key:
up: fn(string $amount): int => is_numeric($amount)
? (int) round(((float) $amount) * 100)
: throw ConversionException::invalid('The total must be an amount.'),
Rounding
Ark4ne\ApiRevisions\Conversion\Cast gives ready-made float → int conversions: Cast::round(), Cast::floor(),
Cast::ceil().
'quantity' => Schema::int()->was(
ApiRevision::Genesis,
schema: Schema::float(),
up: Cast::round(),
),