Extending

Samplers

Build the samples of a model your own way, when its factory and its declared types are not enough.

A sampler builds the instances a resource is run on (see Sampling). The first sampler that supports the request, by decreasing priority, builds the samples:

Built-in samplerPrioritySamples
ResourceFactorySampler400what the #[ResourceFactory] of the resource returns
ModelFactorySampler300a model with a factory: create() in the transaction, else make()
EnumSampler200the cases of an enum
FakeObjectSampler100a model filled from its declared types, or a fake object

A sampler that throws lets the next one try. Write one when a model needs a particular state to render every key of its resource, and you would rather not change its factory:

app/Docs/OrderSampler.php
namespace App\Docs;

use App\Models\Order;
use Ark4ne\OpenApi\Context\GenerationContext;
use Ark4ne\OpenApi\Sampling\SampleRequest;
use Ark4ne\OpenApi\Sampling\Sampler;

final class OrderSampler implements Sampler
{
    public const PRIORITY = 500;

    public function priority(): int
    {
        return self::PRIORITY;
    }

    public function supports(
        SampleRequest $request,
        GenerationContext $context,
    ): bool {
        return $request->target === Order::class;
    }

    public function sample(
        SampleRequest $request,
        GenerationContext $context,
    ): array {
        return array_map(
            static fn(int $i): Order => new Order([
                'id' => $i,
                'status' => 'paid',
                'total' => 19.99 * $i,
            ]),
            range(1, $request->count),
        );
    }
}
components.schemas.Order
{
  "type": "object",
  "required": ["id", "status", "total"],
  "properties": {
    "id": { "type": "integer", "example": 1 },
    "status": { "type": "string", "example": "paid" },
    "total": { "type": "number", "example": 19.99 }
  }
}
config/openapi.php
'extensions' => [
    'samplers' => [App\Docs\OrderSampler::class],
],

The sample request

PropertyHolds
targetthe class to sample: the model a resource receives, or an enum
resourcethe resource that receives the samples, when there is one
counthow many instances to return: 1 for a resource, sampling.collection_size for a collection

Return exactly count instances. Return different values from one instance to the next: a value that is the same in every sample is read as a discriminator.

Keep the database clean

A sampler runs inside the sampling session: what it writes through Eloquent on a connection with a transaction is rolled back at the end of the generation. Prefer make() and new Model([...]) anyway: a sampler should not depend on the transaction to leave the database as it was.

To build what a single resource receives when it is not a model (a DTO, an array), use #[ResourceFactory] on the resource: samplers are asked for models and enums.