Samplers
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 sampler | Priority | Samples |
|---|---|---|
ResourceFactorySampler | 400 | what the #[ResourceFactory] of the resource returns |
ModelFactorySampler | 300 | a model with a factory: create() in the transaction, else make() |
EnumSampler | 200 | the cases of an enum |
FakeObjectSampler | 100 | a 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:
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),
);
}
}
{
"type": "object",
"required": ["id", "status", "total"],
"properties": {
"id": { "type": "integer", "example": 1 },
"status": { "type": "string", "example": "paid" },
"total": { "type": "number", "example": 19.99 }
}
}
'extensions' => [
'samplers' => [App\Docs\OrderSampler::class],
],
The sample request
| Property | Holds |
|---|---|
target | the class to sample: the model a resource receives, or an enum |
resource | the resource that receives the samples, when there is one |
count | how 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.
#[ResourceFactory]
on the resource: samplers are asked for models and enums.