# Response and check extensions

> Add keys to the meta of search pages and details, document an extension in the OpenAPI document and add checks to rest:check.

Four kinds act on responses, the OpenAPI document and `rest:check`: `AddsSearchMeta`, `AddsDetailsMeta`, `DocumentsExtension` and `ChecksResources`. See [Extensions](/extensions/overview) for registering an extension.

## Adding search meta

`AddsSearchMeta::searchMeta(SearchMetaContext $context)` returns keys that a search page renders under `meta.{name}`:

```php [Vendor/Plans/QuotaExtension.php]
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)];
    }
}
```

```json [200 OK]
{
  "current_page": 1,
  "data": [...],
  "total": 2,
  "meta": {
    "quota": {"remaining": 98}
  }
}
```

- The key is an object, `{}` when the array is empty. It comes after the `create` gate, the `searchMeta()` keys of the resource and `instructions`, extensions in name order. See [Meta](/search/overview#meta).
- It runs on the received page, after `searched()` and `searchMeta()` of the resource, on the database and on a search engine, for HTTP searches and `Rest::search()->page()` and `render()`. Not for `lazy()`, nor for includes.
- `$context->rows` are copies of the rows of the page, with `$context->total`, `$context->page`, `$context->perPage`, `$context->search` (the `SearchContext` of the search), `$context->resource` and `$context->user`, `null` for 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()` and `AugmentsQueries` columns, and the columns of the fields that `NarrowsFields` hides. Keep them out of the meta, which the client receives.
- On a search engine page, the rows can hold a row that the `RestrictsQueries` restrictions 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`, a `ResourceCollection` too, also inside a collection, a paginator or what the `jsonSerialize()` 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 `instructions` or like `rest.gates.key`, and a `searchMeta()` 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`:

```php [Vendor/Flags/FeaturesExtension.php]
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)];
    }
}
```

```json [GET /api/artworks]
{"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 the `ObservesReads` extensions 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 names `instructions` and the gates key are refused for search meta only. See [Details](/digging-deeper/details#meta).

## Documenting an extension

`DocumentsExtension` documents an extension in the [OpenAPI document](/digging-deeper/openapi), one method per moment of the document. Here, the extension that adds search meta also refuses writes, and documents both:

```php [Vendor/Plans/QuotaExtension.php]
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, else `null`) and `$context->authenticates`.
- `response(429, 'Exceeded', ...)` adds the shared response `quota.Exceeded` to 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 with `searchMeta(ObjectType $schema)` and `detailsMeta(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. The `meta` of a page whose resource does not override `searchMeta()` 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 after `response()` 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 implement `AddsSearchMeta` or `AddsDetailsMeta`.
- A refusal of `GuardsWrites` never answers `409`, `422` or `428`, which the package documents with its own bodies: document it under its own status, such as `423`, `429` or `503`.

## Checking resources

`ChecksResources::checkResource(ResourceCheckContext $context)` adds checks to `php artisan rest:check`, for each resource that the checked controllers reach:

```php [Vendor/Tenancy/TenantColumnExtension.php]
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.");
        }
    }
}
```

```text
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->resource` is the resource instance, built in the context of `rest:check`: a check can call `text()`, `fields()` or `relations()`. `$context->resource::class` is its class.
- `$context->problem()` reports a problem that names the extension and the resource, and fails `rest:check`. An exception that a check or its `appliesTo()` throws is a problem too, and the other checks still run.
- A resource that cannot be built is one `declarations` problem, and no check runs on it.
- Read neither the request nor a user, and write nothing.
- The problems show under `extension checks`, `2 checks passed` when none fails, and under the `extension_checks` key of `--json`: `checked`, a list of `{extension, resource}`, and `problems`. See [Extension checks](/digging-deeper/artisan#extension-checks).

<tip>

The package cannot check that `toSearchableArray()` or the index settings hold the attributes that an extension declares. A check of the extension can.

</tip>
