Extending

Descriptor macros

Add your own fluent methods to every descriptor.

A macro adds a fluent method to every descriptor. Register a closure under a name at boot, then call it like a modifier.

app/Schema/FieldMacros.php
use Ark4ne\ApiRevisions\Schema\Descriptor;

final class FieldMacros
{
    /**
     * @template TDescriptor of Descriptor<mixed>
     * @param TDescriptor $descriptor
     * @return TDescriptor
     */
    public static function documented(
        Descriptor $descriptor,
        string $description,
        int|float|string|null $example = null,
    ): Descriptor
    {
        $descriptor = $descriptor->describe($description);

        return $example === null ? $descriptor : $descriptor->example($example);
    }
}
app/Providers/AppServiceProvider.php
use Ark4ne\ApiRevisions\Schema\DescriptorMacros;

public function boot(): void
{
    DescriptorMacros::register('documented', FieldMacros::documented(...));
}
'total' => Schema::int()->documented('The total, in cents.', 1250),

Rules

  • The closure receives the descriptor first, then the arguments given. It builds with the public modifiers (when(), describe()…) and must return an instance of the descriptor's class, as the modifiers do; otherwise the call throws a DefinitionException.
  • The name is a method name Descriptor does not declare (when, nullable… are refused), case-sensitive.
  • A public method of the descriptor's own class wins over a macro of the same name: Schema::string()->min() stays StringSchema::min().
  • Registrations happen at boot and hold no request data, so they are safe under Octane. DescriptorMacros::flush() clears them in tests.

A condition as a macro

A macro can wrap a condition, for instance to keep a field only when the subject lists it:

public static function whenInFields(
    Descriptor $descriptor,
    string $field,
): Descriptor
{
    return $descriptor->when(
        fn (mixed $subject): bool => in_array($field, $subject->fields, true),
    );
}
'notes' => Schema::string()->nullable()->whenInFields('notes'),

For PHPStan, map each name to its static method: see static analysis.