Response and check extensions
Four kinds act on responses, the OpenAPI document and rest:check: AddsSearchMeta, AddsDetailsMeta, DocumentsExtension and ChecksResources. See Extensions for registering an extension.
Adding search meta
AddsSearchMeta::searchMeta(SearchMetaContext $context) returns keys that a search page renders under meta.{name}:
use Lomkit\Rest\Extensions\Contexts\SearchMetaContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AddsSearchMeta;
final class QuotaExtension extends Extension implements AddsSearchMeta
{
public function __construct(private readonly ReadQuota $quota) {}
#[\Override]
public static function name(): string
{
return 'quota';
}
#[\Override]
public function searchMeta(SearchMetaContext $context): array
{
return ['remaining' => $this->quota->remaining($context->user)];
}
}
{
"current_page": 1,
"data": [...],
"total": 2,
"meta": {
"quota": {"remaining": 98}
}
}
- The key is an object,
{}when the array is empty. It comes after thecreategate, thesearchMeta()keys of the resource andinstructions, extensions in name order. See Meta. - It runs on the received page, after
searched()andsearchMeta()of the resource, on the database and on a search engine, for HTTP searches andRest::search()->page()andrender(). Not forlazy(), nor for includes. $context->rowsare copies of the rows of the page, with$context->total,$context->page,$context->perPage,$context->search(theSearchContextof the search),$context->resourceand$context->user,nullfor a guest.- Reading a column that the search did not load throws
MissingColumnException. - The rows can hold columns that the response does not render:
alwaysSelect()andAugmentsQueriescolumns, and the columns of the fields thatNarrowsFieldshides. Keep them out of the meta, which the client receives. - On a search engine page, the rows can hold a row that the
RestrictsQueriesrestrictions would exclude while the index still matches it.
Values and names
The values may be null, booleans, integers, finite floats, strings, arrays, stdClass, backed enums and JsonSerializable objects. Return the values that the client needs. These throw Lomkit\Rest\Exceptions\InvalidMetaExtensionException:
- a model, an Eloquent collection or a
JsonResource, aResourceCollectiontoo, also inside a collection, a paginator or what thejsonSerialize()of another value returns: they would render every visible attribute past the fields of the resource; - another object, a pure enum, a float that is not finite, a string or key that is not UTF-8, an object that holds itself, a value nested deeper than 256 levels, or a
jsonSerialize()result that JSON refuses; - an extension named
instructionsor likerest.gates.key, and asearchMeta()key of the resource that equals the name of the extension.
A taken name is settled with another name(): the package returns another one, or the application lists a subclass that overrides name() in rest.extensions and the package class in rest.disabled_extensions. rest:check reports such a name for each reached resource.
Adding details meta
AddsDetailsMeta::detailsMeta(DetailsMetaContext $context) does the same under meta.{name} of /details:
use Lomkit\Rest\Extensions\Contexts\DetailsMetaContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AddsDetailsMeta;
final class FeaturesExtension extends Extension implements AddsDetailsMeta
{
public function __construct(private readonly FeatureFlags $flags) {}
#[\Override]
public static function name(): string
{
return 'features';
}
#[\Override]
public function detailsMeta(DetailsMetaContext $context): array
{
return ['beta' => $this->flags->enabled($context->user)];
}
}
{"data": {
"fields": [...],
"limits": [10, 25, 50],
"meta": {"features": {"beta": true}}
}}
- The keys come after the
detailsMeta()keys of the resource, extensions in name order, for the user of the request,$context->user. json_encode($resource)holds them too, for the user of the context of the resource.described()and theObservesReadsextensions receive the details with them.- The same values are refused as for search meta, with the same exception, and so is a
detailsMeta()key of the resource equal to the name of the extension. The namesinstructionsand the gates key are refused for search meta only. See Details.
Documenting an extension
DocumentsExtension documents an extension in the OpenAPI document, one method per moment of the document. Here, the extension that adds search meta also refuses writes, and documents both:
use Dedoc\Scramble\Support\Generator\Types\IntegerType;
use Dedoc\Scramble\Support\Generator\Types\ObjectType;
use Dedoc\Scramble\Support\Generator\Types\StringType;
use Lomkit\Rest\Extensions\Contexts\MetaDocumentationContext;
use Lomkit\Rest\Extensions\Contexts\OperationDocumentationContext;
use Lomkit\Rest\Extensions\Contexts\SearchMetaContext;
use Lomkit\Rest\Extensions\Contexts\WriteGuardContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AddsSearchMeta;
use Lomkit\Rest\Extensions\Kinds\DocumentsExtension;
use Lomkit\Rest\Extensions\Kinds\GuardsWrites;
use Lomkit\Rest\Http\Routing\Endpoint;
final class QuotaExtension extends Extension implements AddsSearchMeta, DocumentsExtension, GuardsWrites
{
public function __construct(private readonly ReadQuota $quota) {}
#[\Override]
public static function name(): string
{
return 'quota';
}
#[\Override]
public function searchMeta(SearchMetaContext $context): array
{
return ['remaining' => $this->quota->remaining($context->user)];
}
#[\Override]
public function guardWrite(WriteGuardContext $context): void
{
if ($context->endpoint === Endpoint::Mutate && $this->quota->remaining($context->user) === 0) {
$context->refuse('The monthly quota is reached.', 429);
}
}
#[\Override]
public function documentOperation(OperationDocumentationContext $context): void
{
if ($context->endpoint !== Endpoint::Mutate) {
return;
}
$message = new ObjectType;
$message->addProperty('message', new StringType);
$message->setRequired(['message']);
$context->response(429, 'Exceeded', 'The monthly quota is reached', $message);
}
#[\Override]
public function documentMeta(MetaDocumentationContext $context): void
{
$meta = new ObjectType;
$meta->addProperty('remaining', new IntegerType);
$context->searchMeta($meta);
}
}
- Both methods run only when Scramble builds the document, without a user.
documentOperation()runs at the end of each operation, after the responses of the package, with$context->resource(the class),$context->endpoint,$context->declaration(the action or metric of the operation, elsenull) and$context->authenticates.response(429, 'Exceeded', ...)adds the shared responsequota.Exceededto the operation.$context->documents(429)tells whether the operation already has that status. The responses stay sorted by status, so the document is the same in any extension order.documentMeta()gives the schema of the meta of the extension withsearchMeta(ObjectType $schema)anddetailsMeta(ObjectType $schema). Each extension that adds meta is one required property of the meta schema, since its key always renders, and an open object when it gives no schema. Themetaof a page whose resource does not overridesearchMeta()stays closed to other keys.- Without such an extension, the document does not change.
What it refuses
- A response name that holds another status or content than before throws
Lomkit\Rest\Exceptions\InvalidDocumentationException, and so does a body changed afterresponse()received it: pass a new object for each body. - These throw
Lomkit\Rest\Exceptions\InvalidDocumentationExtensionException: a status outside 400 to 599, a status that the package or another extension already documents on the operation, a response name that is not letters and digits starting with a letter, and a search or details meta schema of an extension that does not implementAddsSearchMetaorAddsDetailsMeta. - A refusal of
GuardsWritesnever answers409,422or428, which the package documents with its own bodies: document it under its own status, such as423,429or503.
Checking resources
ChecksResources::checkResource(ResourceCheckContext $context) adds checks to php artisan rest:check, for each resource that the checked controllers reach:
use Illuminate\Support\Facades\Schema;
use Lomkit\Rest\Extensions\Contexts\ResourceCheckContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\ChecksResources;
final class TenantColumnExtension extends Extension implements ChecksResources
{
#[\Override]
public static function name(): string
{
return 'tenant_columns';
}
#[\Override]
public function checkResource(ResourceCheckContext $context): void
{
$table = $context->resource::newModel()->getTable();
if (! Schema::hasColumn($table, 'tenant_id')) {
$context->problem("the {$table} table has no tenant_id column.");
}
}
}
extension checks ... FAILED
⇂ The [tenant_columns] extension Vendor\Tenancy\TenantColumnExtension reports App\Rest\Resources\TripResource: the trips table has no tenant_id column
- It runs in the console only, once per extension and per resource that the checked controllers reach, directly or through their relations, extensions in name order.
$context->resourceis the resource instance, built in the context ofrest:check: a check can calltext(),fields()orrelations().$context->resource::classis its class.$context->problem()reports a problem that names the extension and the resource, and failsrest:check. An exception that a check or itsappliesTo()throws is a problem too, and the other checks still run.- A resource that cannot be built is one
declarationsproblem, and no check runs on it. - Read neither the request nor a user, and write nothing.
- The problems show under
extension checks,2 checks passedwhen none fails, and under theextension_checkskey of--json:checked, a list of{extension, resource}, andproblems. See Extension checks.
toSearchableArray() or the index settings hold the attributes that an extension declares. A check of the extension can.