Declaring the head

Responses

Declare a JsonResource with descriptors and render it in the client's revision.

A resource implements Revisioned, uses RevisionedResource, and returns the head descriptors from toArray().

app/Http/Resources/OrderResource.php
use Ark4ne\ApiRevisions\Laravel\Resources\RevisionedResource;
use Ark4ne\ApiRevisions\Schema\Revisioned;
use Ark4ne\ApiRevisions\Schema\Schema;

final class OrderResource extends JsonResource implements Revisioned
{
    use RevisionedResource;

    public function toArray(Request $request): array
    {
        return [
            'title' => Schema::string(),
            'status' => Schema::enum(OrderStatus::class)
                ->was(ApiRevision::Winter25, name: 'state'),
            'address' => Schema::object([
                'street' => Schema::string(),
                'zip' => Schema::string('postcode'),
            ], 'shippingAddress')->component('Address'),
            'customer' => Schema::resource(CustomerResource::class)
                ->whenLoaded('customer'),
        ];
    }
}

How a field is rendered

For each field, in the order of toArray():

  1. its conditions run;
  2. its source is read;
  3. the value is normalized to the head type;
  4. it is converted down to the client's revision;
  5. it is serialized once.

with(), additional(), wrapping, response(), collections and pagination work as on any JsonResource. resolve() renders in the current revision, which makes the resource usable outside HTTP.

Collections

OrderResource::collection($orders) runs toArray() once per render, on a template instance whose resource is set to each order in turn, and renders every order through one projection plan. This is several times faster than running toArray() per item.

It requires toArray() to depend on the order only through the closures and conditions of its descriptors. A resource deciding its structure in plain PHP on the model (an if adding a key, a ternary choosing the descriptor, a native $this->when($condition, Schema::string())) would apply the first order's choice to all. Such a resource opts out:

public static function revisionedPerSubject(): bool
{
    return true;
}

A resource with plain values or native conditions, and a custom ResourceCollection, keep the per-item path.

Plain values

A plain value ('x' => $this->x) is rendered as is in every revision and typed any. The check reports it as an error (eager-value): wrap it in a descriptor.

Value errors

A value its type refuses ('abc' for an int, null for a non-nullable field, a failed conversion) follows strict_values:

strict_valuesEffect
truethrows ValueException, naming the class, the field and the revision
falsethe value is cast, and the error reported once per class and field
null (default)true when app.debug is on, false otherwise

A class added or removed

A whole resource can exist only in some revisions: see class lifetime.