Extensions

Extensions

Add behavior to every resource from one class, registered by an app or a package, with a name, a list of kinds and checks at registration.

An extension adds behavior to every resource of an application from one class: a tenant restriction, field rules per plan, a quota on writes, a line in the meta of each page. The class extends Lomkit\Rest\Extensions\Extension and implements one or more kinds, the interfaces of Lomkit\Rest\Extensions\Kinds, each of which extends ExtensionKind.

app/Rest/Extensions/ArchiveExtension.php
use Lomkit\Rest\Extensions\Contexts\RestrictionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\RestrictsQueries;

final class ArchiveExtension extends Extension implements RestrictsQueries
{
    public function __construct(private readonly ArchivePolicy $policy) {}

    #[\Override]
    public static function name(): string
    {
        return 'archive';
    }

    #[\Override]
    public function appliesTo(string $resource): bool
    {
        return is_subclass_of($resource, ArchivableResource::class);
    }

    #[\Override]
    public function restrict(RestrictionContext $context): void
    {
        if (! $this->policy->showsArchived($context->user)) {
            $context->query->where($context->query->qualifyColumn('archived'), false);
        }
    }
}

The methods of the resources stay the path of the application. Extensions apply after them, and their order never changes the result.

The name

name() is the one abstract method of Extension. It returns the name of the extension:

  • The name is a public contract. It is the meta key (meta.archive of searches and /details) and the prefix of the instruction keys, response components, cache keys and SQL aliases that the extension adds. A package picks a name specific to it and keeps it for its whole major version.
  • A name has 1 to 32 lowercase letters or digits, starts with a letter and joins words with single underscores, such as acl or row_lock. Two underscores separate it from the keys it prefixes (acl__locked), so acl__x and acl_ are refused.
  • Return a constant. A name() that returns an invalid name, or that throws, is refused with Lomkit\Rest\Exceptions\InvalidExtensionException, which names the class and the value or the error.
  • A subclass inherits the name. Override it only to run the subclass beside its parent.

Registering an extension

An application lists its extension classes in config/rest.php:

config/rest.php
'extensions' => [
    App\Rest\Extensions\ArchiveExtension::class,
],

A package registers its classes from the register() method of a service provider, so they are active on install:

use Lomkit\Rest\Facades\Rest;

public function register(): void
{
    Rest::registerExtension(AccessControlExtension::class);
}

Rest::registerExtensions([AccessControlExtension::class, TenantExtension::class]) registers several classes.

  • Extensions are registered by class name. An instance passed to registerExtension() is a PHP TypeError. An instance, a value that is not a string, or an array that is not a list in registerExtensions() throws InvalidExtensionException, which shows the list form [AccessControlExtension::class]. In the config, a rest.extensions or rest.disabled_extensions value that is not a list throws Lomkit\Rest\Exceptions\InvalidConfigException, and an instance or a value that is not a string in the list throws InvalidExtensionException when a context first reads its extensions. Both name the config key.
  • A registration checks the class first: it exists, extends Extension and is not abstract. It then reads the name. A package author sees the error on install. The classes of the config get the same checks when a context first reads its extensions.
  • From register(), a registration works in any provider order. From boot(), it works only before every provider that declares Rest::resource() routes in its own boot().
  • Runtime registrations are fixed once the application has booted, or earlier when the package builds its first context or registers its first Rest::resource() route. A later registration throws InvalidExtensionException, which names the class: never register from a deferred provider or a booted() callback.
  • The config is read again for each context: a request, a queued action, Rest::search(), the OpenAPI document and rest:check. A config cached without the extensions key reads as no extension.
  • One class counts once, registered twice or both registered by a package and listed in the config. Its origin is config when rest.extensions lists it, else runtime.
In the tests of a package, register through a provider, defineEnvironment() or #[DefineEnvironment], which run before the boot, or with #[WithConfig('rest.extensions', [...])]. A registration from a test body throws.

Disabling or replacing an extension

disabled_extensions lists the classes to disable, wherever they come from:

config/rest.php
'disabled_extensions' => [
    Vendor\Acl\AccessControlExtension::class,
],
  • A disabled class is never built, and its name never collides with another.
  • The exact class is compared: a subclass stays enabled when its parent is disabled. A leading backslash or another letter case still designates the same class.
  • To replace a package extension, extend it, list the subclass in extensions and the package class in disabled_extensions. The subclass inherits the name, so its meta and instruction keys stay the same.
  • Two enabled classes with one name are refused when a context builds its extensions, with a message that names both classes: The extensions App\Rest\Extensions\AclExtension and Vendor\Acl\AccessControlExtension share the name [acl]. Add one of them to the [rest.disabled_extensions] config, or extend one of them and override name() to give it another name. A subclass listed beside its enabled parent is refused the same way.

How extensions run

  • The container builds each extension once per context, at first use, so its constructor can inject services. With no extension, nothing is built.
  • Keep settings in properties. For other settings, register a subclass with its own name(), or with the parent in disabled_extensions.
  • Never bind an extension as a singleton: one instance would serve every context of an Octane or queue worker. Bind it with bind(), or not at all.
  • Building an extension checks its class again: a class that implements no kind, or a binding that builds another class, throws InvalidExtensionException.
  • appliesTo(string $resource) returns true by default. Each context asks it once per resource class and keeps the answer, so it may read the resource class and the config, never the user or the request.
  • Each kind method receives one context object of Lomkit\Rest\Extensions\Contexts. Each kind calls its extensions in name order, so the order of the config never shows.
  • An exception thrown by an extension reaches the caller, except from ObservesWrites, whose exceptions are reported, and from ChecksResources, whose exceptions are problems of rest:check.

Errors

Every error about an extension extends Lomkit\Rest\Exceptions\ExtensionException: catch that class for all of them. Each message names the extension by its name and its class, and concerns($class) tells whether an error is about that extension class:

use Lomkit\Rest\Exceptions\ExtensionException;
use Lomkit\Rest\Facades\Rest;

try {
    $page = Rest::search(TicketResource::class)->as($user)->payload($search)->page();
} catch (ExtensionException $e) {
    if (! $e->concerns(AccessControlExtension::class)) {
        throw $e;
    }

    // ...
}
ExceptionThrown by
InvalidExtensionExceptionregistration, names and building
InvalidQueryExtensionExceptionthe query kinds
InvalidEngineExtensionExceptionthe engine kinds
InvalidAuthorizationExtensionExceptionthe authorization kinds
InvalidFieldExtensionExceptionNarrowsFields
InvalidRouteExtensionExceptionAddsRouteMiddleware
InvalidWriteExtensionExceptionGuardsWrites
InvalidMetaExtensionExceptionAddsSearchMeta and AddsDetailsMeta
InvalidDocumentationExtensionExceptionDocumentsExtension

The kinds

FamilyKindWhat it does
QueriesRestrictsQueriesAdds where clauses to the perimeter of a resource, wherever the perimeter applies
ProvidesPerimeterMarks a restriction that is the perimeter, for rest:check
AugmentsQueriesAdds columns, subqueries and eager loads to the rendered rows, for the policies
NarrowsLimitsNarrows the page sizes, the total cap and the include limit for the user, never upward
DeclaresInstructionsAdds search instructions, keyed by the extension name
Search enginesRestrictsEngineQueriesRestricts each search engine query, AND-ed with the perimeter and the client filters
DeclaresIndexAttributesDeclares server-only index attributes, lists of strings included
ProvidesEngineProfilesProvides the profile of a Scout engine
AuthorizationPreparesRowChecksPrepares the data that the policies read, before a batch of row checks
VersionsRowChecksAdds row versions to the key of a kept decision
ContributesCacheContextAdds items to the cache keys of decisions and metric results, shortens or drops kept decisions
DeclaresGatesAdds gates to a resource
NarrowsFieldsHides fields, or makes them read-only, unfilterable or unsortable, for the user
Routes and writesAddsRouteMiddlewareAdds middleware to the routes of an endpoint
GuardsWritesRefuses a write before it runs
ObservesWritesIs notified after the commit of each write
ObservesReadsIs notified after each HTTP search, metric and /details
Responses and checksAddsSearchMetaAdds keys under meta.{name} of a search page
AddsDetailsMetaAdds keys under meta.{name} of /details
DocumentsExtensionDocuments the extension in the OpenAPI document
ChecksResourcesAdds checks to rest:check

Checking extensions

php artisan rest:check lists each extension with its name, class, origin (config or runtime) and disabled state, and builds each enabled one:

extensions ... 2 extensions built, 1 disabled
Vendor\Notes\NotingExtension ... runtime, disabled
acl ... Vendor\Acl\AccessControlExtension, runtime
quota ... App\Rest\Extensions\QuotaExtension, config
  • The name of a disabled class is not read.
  • It fails on a rest.extensions or rest.disabled_extensions value that is not a list, on each refused entry, on each pair of classes with one name and on each class that cannot be built, and still lists the others.
  • It notes, without failing, a disabled_extensions entry that disables nothing: a class neither registered nor configured.
  • --json adds the extensions key: registered (name, class, origin, disabled), problems and notes.

See Extensions in rest:check and Extension checks.