Skip to content

About

Generic utilities for API Platform projects: UUID resolver, partial-UUID matching, credential encryption, JWT security decorator, OpenAPI enhancements, Hydra operations, IriReferenceArray autocomplete, DB-JSON CLI.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dmstr/api-platform-utils-bundle

Generic helpers for API Platform projects.

Features (planned)

  • Partial-UUID lookups (UuidResolver, UuidSearchFilter)
  • JWT security decorator for the OpenAPI doc
  • Credential encryption service (CredentialEncryption)
  • #[IriReferenceArray] attribute + Doctrine listener + persist processor + OpenAPI schema factory for autocomplete-rendered IRI collections
  • DB-JSON CLI tools (db:export-json, db:import-json)
  • AbstractJsonSchemaInputCommand base class for JSON-Schema-validated CLI
  • Generated sort parameters, default sort and a stable-pagination tie-breaker (auto_order, #[AutoOrder], stable_order)
  • Relation label (x-label-property) in input and output schemas, and embedded in collection responses (relation_labels)
  • Custom actions announced as schema:Action in the Hydra documentation, opted in per operation (custom_action)
  • Discovery documents filtered per caller by operation security and access_control (discovery): the OpenAPI document, the Hydra documentation /api/docs.jsonld and the entrypoint /api, plus a guard test for apps (Dmstr\ApiPlatformUtils\Test)

Hydra operations (hydra:operation)

AddHydraOperationsSubscriber enriches JSON-LD runtime responses with a hydra:operation array so clients can discover the available operations of a concrete item or collection without parsing the Hydra documentation /api/docs.jsonld:

  • Item GET responses list every operation of the resource whose URI template contains the {id} placeholder (e.g. GET, PUT, PATCH, DELETE, POST /things/{id}/approve), with {id} resolved to the actual identifier.
  • Collection GET responses (hydra:Collection) list every operation whose URI template does not contain {id} (e.g. GET, create POST, POST /things/import).

The split is made by the {id} placeholder alone, at any path depth. This subscriber lists operations regardless of the custom_action marker (see Custom actions); marked and unmarked operations appear alike, typed hydra:Operation. The hydra:title is the operation's description, otherwise a title derived from an author-chosen operation name, otherwise a generated CRUD title such as "Retrieves a Thing resource".

Security filtering (HATEOAS)

By default each operation is checked against the current security token via API Platform's ResourceAccessChecker (api_platform.security.resource_access_checker); operations whose security expression does not grant access are omitted. The server therefore only advertises what the current user may actually execute — a UI can derive canCreate/canUpdate/canDelete directly from the runtime hydra:operation. The Hydra documentation /api/docs.jsonld is filtered per caller as well (see Hydra documentation and entrypoint filtered per caller), but it decides without an object, so only the runtime hydra:operation reflects object-dependent expressions for the loaded entity.

Rules:

  • Operations without a security expression stay visible (default: allowed).
  • Item operations are evaluated with the loaded entity as object (when resolvable from the request); collection operations are evaluated with object = null.
  • Only collection-level operations are checked on collection responses — one check per operation, never per hydra:member.
  • Expression evaluation errors fail closed (the operation is hidden).
  • Without symfony/security-bundle the checker service is absent and filtering is skipped.
  • The filter is expression-neutral: it hands the operation's security expression to the ResourceAccessChecker unchanged. A permission attribute such as is_granted('thing:write') (an example; this bundle defines no permissions of its own) is evaluated like any other expression. Collection operations are checked with object = null, so the voter answering the attribute must accept a null subject. With Symfony's default access-decision strategy the operation stays hidden when no voter answers the attribute.

Configuration:

dmstr_api_platform_utils:
    hydra_operations:
        enabled: true
        api_prefix: '/api'
        event_priority: -10
        # set to false to restore the unfiltered (pre-0.4) behavior
        filter_operations_by_security: true

HTTP caching

With filtering active, item and collection responses become user-dependent: the subscriber emits Vary: Authorization so shared HTTP caches never serve one user's operation set to another. The Hydra documentation /api/docs.jsonld and the entrypoint depend on the caller too while the discovery filter is on; they are marked private separately (see Cache headers of the Hydra documentation and the entrypoint). If your stack caches API responses in a reverse proxy, verify it honors Vary — otherwise exclude these responses from caching.

OpenAPI document filtered per caller (openapi)

SecurityFilteredOpenApiFactory decorates api_platform.openapi.factory and removes from the OpenAPI document (/api/docs.jsonopenapi, /api/docs.json, /api/docs.yamlopenapi, Swagger UI) every operation the current caller could not execute. A client, a generated SDK or a person reading Swagger UI sees what they may call, not every operation of the API.

The same filter covers three discovery documents: the OpenAPI document described here, the Hydra documentation /api/docs.jsonld and the entrypoint /api / /api/index.<format> in JSON-LD, HAL and JSON:API (see Hydra documentation and entrypoint filtered per caller). The rule below is the same for all three; one service, OperationAccessDecider, decides it.

An operation stays in the document only if both of these allow the current token:

  • the operation's security expression, evaluated with object = null like in the Hydra filter above. No expression: no restriction. An evaluation error or an unparsable expression hides the operation (fail closed);
  • the firewall's access_control rule for the operation's path and method, decided the way Symfony's AccessListener decides it: the first matching rule wins, a rule without roles allows, otherwise the access decision manager decides the rule's attributes for the current token (a NullToken for an anonymous caller).

Configuration (defaults shown):

dmstr_api_platform_utils:
    discovery:
        # false: documents, services and response headers as without this bundle
        filter_operations_by_security: true
        # list operations whose expression needs the object (object, previous_object)
        show_object_dependent_operations: true
    openapi:
        # seconds a built OpenAPI document is cached; 0 disables the cache
        cache_lifetime: 3600

Both discovery.* switches apply to all three discovery documents together. filter_operations_by_security decides at container build time which services are registered, so it takes only true or false; show_object_dependent_operations is read at runtime and may come from an environment variable.

Deprecated openapi.* switches and configuration errors

openapi.filter_operations_by_security and openapi.show_object_dependent_operations are deprecated aliases of the discovery.* keys and will be removed in 0.12.0. Setting one of them still works and triggers the deprecation The "<key>" option under "dmstr_api_platform_utils.openapi" is deprecated, use "dmstr_api_platform_utils.discovery.<key>" instead; it will be removed in 0.12.0. Setting neither triggers no deprecation; the effective value is discovery.*, else openapi.*, else true. openapi.cache_lifetime is not deprecated.

The container build fails with an InvalidConfigurationException when:

  • the old and the new key are both set to different values (Contradictory configuration: "dmstr_api_platform_utils.openapi.<key>" (deprecated) is false, but "dmstr_api_platform_utils.discovery.<key>" is true. Set only "dmstr_api_platform_utils.discovery.<key>".). This also happens when another package prepends the old key and the app sets the new one, so a package that prepends configuration for this bundle must prepend discovery.* only, never the old key;
  • filter_operations_by_security (old or new key) is set from an environment variable or another runtime value ("…" cannot be set from an environment variable or another runtime value: it decides at container build time which services are registered, a runtime value would never take effect. Set it to true or false.);
  • both show_object_dependent_operations keys are set to values that cannot be proven equal at build time: an environment variable against a literal, or two different environment expressions (Ambiguous configuration: … Set only "dmstr_api_platform_utils.discovery.show_object_dependent_operations".). The same literal or the same environment expression in both keys passes.

What each caller sees

  • Anonymous: only the operations an anonymous request may execute. Operations behind access_control roles or behind an expression such as is_granted('ROLE_USER') are gone. Clients that read the document anonymously, for example to take operation input schemas from it before the user logs in, get fewer operations or none; send the user's token with that request, or switch the filter off.
  • Authenticated callers: every operation their roles and permissions allow, no more. Two callers with the same decisions get the same document.
  • Paths: a path without a remaining operation disappears; on a path with several methods each method is decided on its own. Paths that another decorator adds without an API Platform operation behind them are decided by access_control alone.
  • Schemas and tags: components.schemas that only hidden operations referenced are removed (transitively via $ref), a schema still referenced by a visible operation stays. The global tags list keeps only tags of remaining operations, configured tags included. The short name of a fully hidden resource therefore appears nowhere in the caller's document.
  • For everyone: components.securitySchemes and the global security requirement are never removed, also when no operation remains, so Swagger UI can still offer the login.
  • Webhooks: decided by their security expression only; access_control does not apply to a request the API sends.

The console has no caller: without a main request (api:openapi:export, a factory call from a command) the document is returned unfiltered.

Object-dependent operations

An expression that references object or previous_object cannot be decided without the object, which a document does not have. show_object_dependent_operations decides instead: true (default) lists them, false hides them for every caller, in all three discovery documents. access_control applies to them either way. In the Hydra documentation a class that loses its last operation this way is removed like any other class without a remaining operation. Detecting object dependency needs API Platform's Symfony ResourceAccessChecker; with another access checker every expression is evaluated with object = null, and an object-dependent one usually fails and is hidden.

Expressions with other variables than the object, such as request, cannot be evaluated without a request for the operation and are hidden for every caller.

Without security component or expression language

  • Without symfony/security-bundle there is no access checker and no access_control: operations carrying a security expression are hidden, all others stay.
  • Without symfony/expression-language expressions cannot be evaluated: operations carrying one are hidden.

Apps in this situation that want the complete document switch the filter off.

Cache and response headers

Building a document costs time, so OpenApiDocumentCache keeps two stages in the pool dmstr_api_platform_utils.cache.openapi (derived from cache.system): the unfiltered document per base URL and spec version, and the filtered document per grant set, the set of decisions for the caller. The key never names a person; it contains the container build id, so a rebuilt container (a deploy, a changed access_control, changed resources) never serves documents of the previous build. cache_lifetime bounds an entry (default 3600 seconds, 0 disables the cache). The grant set itself is resolved on every request. Requests with filter_tags are built without the cache.

The document now depends on the Authorization header, so OpenApiDocsCacheHeadersListener forces Cache-Control: private (removes public and s-maxage, also when api_platform.http_cache sets them) and adds Vary: Authorization on the OpenAPI and HTML formats of /api/docs and on Swagger UI rendered for a resource URL. The Hydra documentation and the entrypoint get the same headers, see Cache headers of the Hydra documentation and the entrypoint.

Swagger UI on resource URLs

API Platform answers an HTML request on a resource URL with Swagger UI and pre-selects the requested operation; it fails with a 500 when that operation is missing from the document. Operations the caller may not execute never get there (API Platform's access checker or the firewall answers 401/403 first). For an operation the document hides although the request is allowed (an expression with request, an object-dependent one with show_object_dependent_operations: false), SwaggerUiPreselectionProcessor renders Swagger UI with the caller's document and without a pre-selected operation.

Your own OpenAPI decorators

The filter must run last to see the final document. It is registered at SecurityFilteredOpenApiFactory::DECORATION_PRIORITY (-1000); an app's own decorators of api_platform.openapi.factory (a JWT security decorator at -10, for example) must use a higher priority. A decorator registered further outside bypasses the filter: paths it adds stay visible to everyone, and operations it changes are not re-checked.

Limits

  • access_control is matched against a synthetic request: the document path with every {placeholder} replaced by 00000000-0000-4000-8000-000000000000, the operation's method, and host, port, scheme and client IP of the real request. Matchers on route attributes or request conditions do not match it like the real request; a path regex that accepts only a certain id format is tested with the dummy UUID; voters that inspect the subject see the synthetic request.
  • Voters that depend on runtime data (time, database) are asked on every request, but a cached document is rebuilt only when a decision, the build or the lifetime changes.
  • These limits apply to the Hydra documentation and the entrypoint as well, which are decided by the same rule. The JSON-LD contexts (/api/contexts/*) are not filtered.
  • Verified on API Platform 4.x; ^3.0 is allowed by the version constraint but untested.

To switch it off:

dmstr_api_platform_utils:
    discovery:
        filter_operations_by_security: false

All three discovery documents are then unchanged, none of the filter's services is registered and no response header is changed.

Guard test for apps (Dmstr\ApiPlatformUtils\Test)

The filter promises that a caller can execute what the document lists. The guard test checks that promise in the app's own test suite: per caller it fetches /api/docs.jsonopenapi and calls every documented operation. Requires phpunit/phpunit and symfony/browser-kit as dev dependencies of the app.

use Dmstr\ApiPlatformUtils\Test\OpenApiGuardTestCase;

final class OpenApiGuardTest extends OpenApiGuardTestCase
{
    protected function openApiGuardCallers(): array
    {
        return [
            'anonymous' => [],
            'editor' => ['HTTP_AUTHORIZATION' => 'Bearer ' . self::editorToken()],
        ];
    }

    protected function openApiGuardExclusions(): array
    {
        return ['GET /api/reports/{id}/download', '* /api/legacy'];
    }
}

Or use OpenApiGuardTrait in an existing WebTestCase and call assertOpenApiGuard() (or runOpenApiGuard() for the report without assertion).

Options (methods to override):

  • openApiGuardCallers() (required): caller name => server parameters, [] is anonymous.
  • openApiGuardReadingMethods(): default ['GET'], HEAD may be added.
  • openApiGuardWritingMethods(): default none; see the warning below.
  • openApiGuardRequestBody(): body of writing requests, default {}.
  • openApiGuardExclusions(): 'METHOD /path/template' as documented, or '* /path' for every method; they apply to all callers.
  • openApiGuardPlaceholderFiller(): values for path placeholders, default a UUID that no fixture is expected to use (PathPlaceholderFiller maps names or name patterns to values).

Status rules:

  • 403 on a documented operation is a forbidden violation; any status of 500 or above is a server error violation. There is no tolerance switch: exclude the operation instead.
  • 401, 404, 400, 405, 415 and 422 are fine. 401 is never a violation, so an expired test token shows only as a skipped caller or as 401 calls.
  • A caller who gets 401 or 403 on the document itself is skipped (skippedCallers()); any other failure to read the document is a document unavailable violation.

Limits: servers are ignored, query and header parameters are not filled, exclusions and placeholder values apply to all callers.

Warning: the guard sends real requests to the app's test kernel. With writing methods opted in it sends POST, PUT, PATCH and DELETE to every documented operation for every caller, with all their side effects: database writes, messages, mails, calls to external services. Opt in only against a disposable test database and with external services stubbed.

Hydra documentation and entrypoint filtered per caller (discovery)

With discovery.filter_operations_by_security on (the default, see the configuration above), the Hydra documentation and the entrypoint are filtered by the same rule as the OpenAPI document: an operation is shown only if its security expression and the firewall's access_control rule for its path and method allow the current token. show_object_dependent_operations and the limits listed for the OpenAPI document apply here too.

  • Hydra documentation: /api/docs.jsonld, and /api/docs negotiated to JSON-LD, in every successful response.
  • Entrypoint: /api and /api/index.<format> in JSON-LD, HAL and JSON:API.

hydra_operations.filter_operations_by_security is a different switch: it filters the runtime hydra:operation of item and collection responses (see Security filtering) and is unchanged.

Requirement: hydra_prefix: true

The filter reads the Hydra documentation by its hydra: keys, so API Platform must emit them:

api_platform:
    serializer:
        hydra_prefix: true

Without the prefix (API Platform's default) the filter does not recognise the document and answers with a document without classes (@context, @id, @type, the title and an empty class list), never with the unfiltered one. The same empty document replaces a body that is no JSON object, and a document the filter fails on. Either enable the prefix or switch the filter off.

Hydra documentation rules

  • A hydra:supportedOperation entry the caller may not execute disappears, on the class and on its entrypoint property.
  • A class that had operations (on the class or on its entrypoint property) and lost all of them is removed, together with its entrypoint property. A class keeps its place when only its collection side is gone.
  • Classes that never had operations (e.g. ConstraintViolationList) stay. The Entrypoint class stays with its own operation, also when no property is left.
  • Error classes always stay with their documented operations, for every caller and without a grant decision: resources that are an ErrorResource (in API Platform 4.4 Error and ConstraintViolation) and operations that are an Error operation. They are documented so that clients can read error responses; showing them grants nothing.
  • An entrypoint property keeps exactly the allowed operations: an allowed POST with a denied GET collection keeps the property with the POST.
  • An entry that cannot be matched to the operation it was built from is denied (fail closed), even when the caller may execute everything. This covers entries another listener added or reordered and entries whose hydra:method does not match.
  • The remaining classes lose their references to removed classes: the name is dropped from range, hydra:expects and subClassOf, the property or operation that carried it stays. hydra:returns deliberately keeps the name: clients built on @api-platform/api-doc-parser discard an operation without it, and a caller who may execute the operation sees that type in the response anyway. A name that a remaining class also carries (two resources with the same short name) is kept.

Entrypoint links

  • A format shows a resource's link only if the caller may execute the operation behind the URL that format emits, and every other API Platform GET operation served on the same path. The formats link different operations of a resource with several collection operations (JSON-LD the first one not hidden from Hydra, HAL the last one, JSON:API the last one without URI variables), and no format falls back to another allowed operation, so the link lists of the formats can differ for such resources.
  • Filtered are the top-level members except @context, @id and @type (JSON-LD), _links except self (HAL) and links except self (JSON:API).
  • A link that cannot be matched to an API Platform route is dropped, also one outside the request's base URL. Without a current request every link is dropped.
  • An absolute link whose host differs from the request's host is dropped. Behind a proxy that changes the host, configure Symfony's trusted proxies and trusted headers so the request carries the public host, or the entrypoint loses those links.
  • The entrypoint links only collections. An allowed POST alone therefore gives no link there, while the entrypoint property in /api/docs.jsonld stays with that POST.

Cache headers of the Hydra documentation and the entrypoint

Filtered responses of the Hydra documentation and of the entrypoint (every format) carry Cache-Control: private (public and s-maxage removed, other directives such as max-age kept) and Vary: Authorization, also under a public cache configuration (api_platform.http_cache.public: true). With the filter off, API Platform's headers stay. There is no per-grant-set cache for these two documents: they are filtered on every request, and openapi.cache_lifetime applies to the OpenAPI document only.

Clients built on @api-platform/api-doc-parser

Clients that read the Hydra documentation with @api-platform/api-doc-parser (react-admin, @api-platform/admin):

  • need hydra_prefix: true (see above);
  • must reload the documentation after login, and after any change of the caller, because it now depends on the caller;
  • receive, for a caller without any allowed operation, an Entrypoint class without properties, which the parser rejects with an error;
  • may find in hydra:returns a class that is not in the document.

Custom actions (custom_action)

A custom action is an operation that is not plain CRUD on the resource, such as approving, importing or re-sending something. Clients such as an admin UI build an actions menu from the Hydra documentation /api/docs.jsonld, which lists only the operations the caller may execute while the discovery filter is on: they pick the operations typed schema:Action. API Platform itself types every operation by its HTTP method (schema:CreateAction for any POST), so an action cannot be told apart from a create. CustomOperationHydraFactory therefore gives every operation the author marked as a custom action its own Hydra metadata. Which operations those are is the author's decision, stated with the marker custom_action:

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Post;

#[ApiResource(operations: [
    new Post(
        uriTemplate: '/things/{id}/approve',
        name: 'approve_thing',
        description: 'Approves the thing',
        extraProperties: ['custom_action' => true],
    ),
])]
final class Thing
{
}

Rules (Dmstr\ApiPlatformUtils\Metadata\CustomAction::isCustomAction() is the single source):

  • Only the boolean true marks. A missing key, false, 1, 'true' or '1' do not; there is no type coercion.
  • API Platform 4.x merges extraProperties flatly: operation over #[ApiResource] over api_platform.defaults.extra_properties. A marker on the resource or in the global defaults therefore marks all operations it reaches, and 'custom_action' => false on an operation exempts that operation from an inherited marker.
  • API Platform's NotExposed stub is never a custom action, even when it inherits a resource marker.
  • The path plays no part: a marked operation is a custom action at any path depth, also on /things or /things/{id}.
  • An unmarked operation stays an ordinary operation at any path depth: it keeps API Platform's own @type and hydra:title, and HydraDocumentationSubscriber gives it its own URL carrier.

Set the marker per operation. On the resource or in the global defaults it also marks the resource's Get, Post, Patch and Delete, and a client would offer them as actions.

Naming: the hydra:title of a custom action is the operation name, taken literally. Name the action via name or set hydraContext['hydra:title']; without an operation name no title is generated. Keys the author sets in hydraContext always win over the generated ones.

What the factory writes into the Hydra context of a custom action:

  • @type: ["hydra:Operation", "schema:Action"]
  • hydra:title: the operation name (omitted without one)
  • hydra:expects / hydra:returns: short class name of the input / output class, or owl:Nothing without one
  • hydra:description: the operation description, if set
  • exactly one URL carrier, built from API prefix, route prefix and URI template with {._format} stripped: @id when the URL has no placeholder, hydra:uriTemplate when it has one (e.g. /api/things/{id}/approve). An author-set @id or hydra:uriTemplate in hydraContext is the only carrier then.

There is no fallback based on the path. Up to 0.7 every operation deeper than /resource or /resource/{id} was treated as a custom action automatically; since 0.8.0 only the marker counts. When upgrading from 0.7 or older, set 'custom_action' => true on every real action, or it loses schema:Action and drops out of the clients' actions menus without an error.

Configuration: the custom actions and the other documented operations get their URL carrier from two separate services, each with its own prefix key. Both prefixes are prepended to the URL carrier.

dmstr_api_platform_utils:
    custom_operation_hydra:
        api_prefix: '/api'   # URL carrier of custom actions
    hydra_documentation:
        api_prefix: '/api'   # URL carrier of all other documented operations

The inheritance rules are verified for API Platform 4.x only; ^3.0 is allowed by the version constraint but untested.

Sorting

Generated sort parameters (auto_order)

With auto_order.enabled, every GetCollection operation of a Doctrine ORM resource gets one order[<property>] query parameter per sortable property, backed by API Platform's SortFilter. They appear in the OpenAPI document and in hydra:search, so a client can derive its sortable columns from the API instead of guessing. Requires API Platform >= 4.3 (nested SortFilter support).

Which properties get a parameter:

  • Scalar fields whose Doctrine type is sortable: string, ascii_string, integer, smallint, bigint, float, smallfloat, decimal, boolean, date, datetime, datetimetz, time (and their _immutable variants). Not offered: identifiers of any type, text, json, array/simple_array, blob/binary, guid/uuid, custom types such as vector, and embedded fields.
  • To-one relations (ManyToOne, owning OneToOne) as order[<relation>.<label>], sorted by the related entity's label via a LEFT JOIN (rows without a relation stay in the list). The label is the first entry of relation_field_decorator.label_property_candidates that is a sortable, readable field of the target entity. There is no fallback: a relation without a candidate gets no parameter.
  • Only properties the API exposes: the property must be in API Platform's property name collection and readable with the operation's normalization groups. #[ApiProperty(readable: false)] and properties outside the groups get no parameter.

Precedence and exclusions:

  • A parameter the operation declares itself under the same key wins.
  • An explicit #[ApiFilter(OrderFilter::class, properties: [...])] (class or property level) wins per property; a class-level OrderFilter without properties covers all properties, so no parameter is generated then. Order filters registered by service id (ApiResource(filters: [...])) are not recognised.
  • Operations with their own provider are skipped. DTO resources are mapped to their entity via stateOptions: new Options(entityClass: ...); the DTO's properties decide what is exposed.
dmstr_api_platform_utils:
    relation_field_decorator:
        label_property_candidates: [name, title, label, displayName, email]
    auto_order:
        enabled: true
        # default sort for GetCollection operations without an own `order`
        default_order:
            name: ASC
            createdAt: DESC

Default sort (auto_order.default_order)

A GetCollection operation without an own order gets the first entry of default_order that is a sortable property of the resource as its order (default: name ASC, else createdAt DESC). API Platform's OrderExtension applies it only when the client sends no sort parameter, so a client sort always replaces it. Without a match the operation keeps API Platform's own default (identifier). An empty map (default_order: {}) switches the default sort off. The map is replaced, not merged, when several config files set it.

Per class: #[AutoOrder]

use Dmstr\ApiPlatformUtils\Attribute\AutoOrder;

#[AutoOrder(enabled: false)]                      // no parameters, no default sort
#[AutoOrder(exclude: ['hash', 'collection'])]     // no order[hash], no order[collection.<label>]

The attribute is read from the resource class and, for DTO resources, from the entity class too. An exclude entry matches the path and everything below it; excluded properties are no default sort candidates either.

Stable pagination (stable_order)

Sorting by a non-unique column leaves the order of equal rows to the database, which may differ between two page requests: rows show up twice or never while paging. With stable_order.enabled, StableOrderExtension appends ORDER BY <root>.<identifier> ASC to every Doctrine ORM collection query whose ORDER BY does not contain the identifier yet. It is tagged with priority -40, after the sort (OrderExtension, -32) and before pagination (-64). Entities with a composite or foreign identifier and queries with GROUP BY are left alone.

dmstr_api_platform_utils:
    stable_order:
        enabled: true

Relation labels in schemas (x-label-property)

RelationFieldSchemaDecorator adds x-* extensions to relation properties (format: iri-reference) of Doctrine resources:

Input and output schemas get the same five extensions: x-collection, x-label-property, x-value-property, x-search-property and x-resource-class. Forms built from the read schema (resources with serialization groups have no plain schema) get the autocomplete picker, and lists can show and sort a relation by its label (order[<relation>.<label>], offered by auto_order only when the label is one of the candidates). The label is the first candidate the target class declares, else its first string property. Properties inside allOf are decorated too, which is where JSON-LD output definitions keep them. The resource's own definition gets x-label-property as well, so a client can title a record with the same property a relation to it uses.

Labels in collection responses (relation_labels)

The schema names the label property, but a plain relation value is just the IRI. With relation_labels enabled, JSON-LD collection responses embed the label next to it:

"parent": { "@id": "/api/ort/einheit/0b1…", "bezeichnung": "Erdgeschoss" }
dmstr_api_platform_utils:
    relation_labels:
        enabled: true

Only collection operations are affected; item responses keep the plain IRI, because forms edit relations as iri-reference strings and API Platform rejects nested documents on write. Each embedded label initialises the related entity, one query per distinct related row and page unless the collection query fetch-joins it.

Invalid defaults in schemas (schema_default_cleanup)

API Platform derives a property's default in the JSON/OpenAPI schema from the PHP property initializer. private string $slug = ''; next to a slug #[Assert\Regex] therefore produces default: "" that the property's own pattern rejects, and a form client that fills in schema defaults shows a validation error before anyone typed. With schema_default_cleanup.enabled (default true), InvalidDefaultSchemaDecorator decorates api_platform.json_schema.schema_factory and removes a default that the property's own schema rejects. Valid defaults are untouched.

Rules:

  • Checked keywords: pattern, minLength, maxLength, enum. A default that violates one of them is removed.
  • The cleanup visits every sub-schema reachable through properties, items (single schema and tuple form), prefixItems, additionalProperties (when it is a schema), allOf, anyOf and oneOf.
  • default: null is judged by enum only: it is removed when an enum exists that does not contain null. The typical case is a nullable enum property whose enum lacks null.
  • Patterns are evaluated with PHP's PCRE, with $ matching only at the very end of the string (ECMA reading: a trailing newline does not match).

Known limits:

  • $ref is not resolved, so a default next to a $ref is not checked.
  • A pattern PHP cannot compile keeps its default; nothing is removed.
  • There is no full translation of ECMA-262 regular expressions to PCRE, so a pattern that relies on ECMA-specific syntax may be judged differently than a browser would judge it.
  • Server-side validation is unchanged; only the emitted schema changes.

To switch the cleanup off:

dmstr_api_platform_utils:
    schema_default_cleanup:
        enabled: false

License

MIT © diemeisterei GmbH

About

Generic utilities for API Platform projects: UUID resolver, partial-UUID matching, credential encryption, JWT security decorator, OpenAPI enhancements, Hydra operations, IriReferenceArray autocomplete, DB-JSON CLI.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages