Skip to content

Composite attributes

The core composite attribute types — Obj, OneOf and the Shape constraint — let a resource expose a structured attribute stored as one value: a typed nested object, a discriminated union, or a free-form map whose overall shape is asserted by a composite JSON Schema. Core defines the types and their semantics; this page covers what the bundle adds — how each validates, and how the values persist through Doctrine.

The three kinds at a glance:

// A typed nested object in one value — children are declared fields.
Obj::make('address')->nullable()->fields(
    Str::make('street')->required(),
    Str::make('city')->required(),
    Str::make('postcode')->required()->maxLength(10),
),

// A discriminated union — `kind` selects which variant's children apply.
OneOf::make('block')->nullable()->discriminator('kind')
    ->variant('heading', Str::make('text')->required(), Integer::make('level')->min(1)->max(6))
    ->variant('image', Url::make('src')->required(), Str::make('alt')),

// A free-form map, its shape asserted by raw member schemas.
ArrayHash::make('contact')->nullable()->constrain(
    Shape::oneOf($emailShape, $phoneShape)->discriminator('kind'),
),

How each kind validates

The split follows the constructive/assertional divide:

Obj and OneOf children run through the Symfony Validator bridge — the same translated cascade as a Map's children. Each child's constraint vocabulary translates to native Symfony constraints, and a violation points at the child: /data/attributes/address/city, /data/attributes/block/level. For a OneOf, only the selected variant's children are validated, and an unknown or missing discriminator is itself the violation — a 422 pointing at /data/attributes/block/kind. An undiscriminated OneOf (no discriminator()) selects its variant by the required member only that variant declares; a value carrying no variant's signature, or two, is a 422 at the field itself, and since every write replaces the whole value, a PATCH must carry every member the variant requires.

A Shape is value-validated by core's SchemaValueValidator (opis), not by constraint translation — its members are raw JSON Schema no Symfony constraint can express. The bundle wires the validator into ResourceValidator automatically when opis/json-schema is installed, and each violation's pointer extends the field's own: a missing member of the matched variant surfaces under /data/attributes/contact/....

Two wiring notes:

  • The Shape pass is independent of the json_api.schema_validation structural linter toggle — a Shape's value validation is on whenever opis is present, because the declaration exists solely to be enforced.
  • Without opis a Shape still documents (its combinator projects into the OpenAPI schema); it just doesn't validate. Install opis/json-schema to get the 422s.

Lists of structured elements

An ArrayList whose elements are an Obj or a OneOf holds a list of objects in one value. Core's field docs cover the semantics; this list of edits is their example:

ArrayList::make('steps')
    ->of(OneOf::make('step')
        ->discriminator('operation')
        ->variant('trim')
        ->variant('find_replace', Str::make('find')->required(), Str::make('replace')->required()))
    ->maxItems(50),

The bridge validates each element the client sends the way the element's shape validates as an attribute, with the index in the pointer. A bad child of the third element points at /data/attributes/steps/2/replace, and an unknown or missing discriminator at /data/attributes/steps/2/operation. A scalar or null where an element belongs is a 422 at /data/attributes/steps/2. The list's own minItems(), maxItems() and uniqueItems() still point at /data/attributes/steps, and a list nested inside an element validates at both indexes, /data/attributes/stops/0/legs/1/mode.

A write replaces the whole list and builds each element fresh, so a required() child must be in every element of a PATCH too, matching the update schema core projects. A child read-only for the caller is skipped, as core's hydration skips it. A PATCH that leaves the list out keeps it and doesn't re-check the stored elements.

Core rejects the structural mistakes itself, with ATTRIBUTE_VALUE_INVALID: an object sent for the list, a list sent for an element, and a list sent for an object child. The bridge leaves those values alone so core's 422 is the one the client sees.

Open objects

An Obj declaring additionalProperties() also takes members it does not declare, each one checked by that member field. Core's field docs cover the semantics. An inline spreadsheet import keyed by the user's column headers looks like this:

ArrayList::make('rows')
    ->of(Obj::make('row')
        ->fields(Str::make('Key')->required())
        ->additionalProperties(Str::make('*')->maxLength(200))
        ->maxProperties(50))
    ->maxItems(1000),

The bridge validates each undeclared member against the member field's translated constraints, with its nullability, at the member's own pointer. The key is escaped as a JSON Pointer token, so a too-long value under the Unit/Price header of the fourth row points at /data/attributes/rows/3/Unit~1Price and one under a~b at .../a~0b. A key holding brackets, such as Cost [GBP], keeps them, since the pointer is built from the key rather than from a Symfony property path. minProperties() and maxProperties() count every member the object carries and point at the object, /data/attributes/rows/3. Declared children validate as they always have, and a member field that is itself a structured value validates its own children under the member's pointer.

This holds wherever the object sits: an attribute, a child of an Obj, Map or OneOf variant at any depth, a list element, or a member of another open object. Core's ObjectValues walk finds each one. Only what the request sends is checked, so a PATCH that merges members onto a stored object counts only the members it sends. A member field read-only for the caller leaves its members unchecked, since core's hydration ignores them, and a closed object still refuses an undeclared member with a 400 ATTRIBUTE_MEMBER_UNRECOGNIZED.

Doctrine stores an open object in its json column like any other Obj, the undeclared members beside the declared children.

An object can also let a request select its keys one at a time with nestedFieldset(), fields[type]=<attribute>.<key>, which a table showing a few keys per row uses, and a nested object declaring it too takes <attribute>.<key>.<key>. See nested fieldsets.

Unions

A Union holds a value that may be a string, a number, a boolean or a list of those, with at most one member per JSON type, except that an Integer and a Decimal may sit together, a number sent without a fraction going to the Integer and one sent with it to the Decimal. Core's field docs cover the semantics. A setting whose value is a label, an amount, a flag or a short list of those looks like this:

Union::make('value')->of(
    Str::make()->maxLength(10),
    Decimal::make(),
    Boolean::make(),
    ArrayList::make()->maxItems(3)->of(Union::of(Str::make()->maxLength(5), Decimal::make(), Boolean::make())),
)->nullable(),

The value's JSON type picks the member, and the bridge runs that member's translated constraints at the union's own pointer. A twelve-character string is a 422 at /data/attributes/value for the string member's maxLength(), a four-element list one there for the list member's maxItems(), and a long string in that list one at /data/attributes/value/1. A value no member takes, such as an object here, is one type error at the union whose detail lists the types it does take. Core's UnionValues walk finds every place a member applies, so this holds for a union inside an Obj, Map or OneOf variant, for a list of unions, and for a union pivot field in a linkage member's meta.

A required union has to be present and not null. It also refuses "" and [], but only when its string or list member takes the value, so false and 0 pass. A nullable union takes null and a union that isn't nullable refuses it.

Doctrine stores a union in a json column, which keeps a string, a number, a boolean and a list apart, and encodes a whole float with its fraction, so 500.0 reads back as a float and 500 as an int. A date member is the one case that needs care. Core hydrates a union attribute's date to a \DateTimeImmutable, which Doctrine's json type would encode as an object no member reads back. So just before the write, the bundle replaces the value with core's Union::toStoredForm() whenever the column can't hold a date-time. That is the member's wire form, so a Date member stores its date string. Validation and the before-write events still see the hydrated value. A union pivot field is stored the same way. A column of your own type that can hold a date-time receives the object, and the in-memory provider keeps the \DateTimeImmutable as core gives it. Code reading a Doctrine-stored union off the entity gets the stored form, and Union::fromStoredForm() turns it back into the hydrated value.

The conformance witness is UnionConformanceTestCase, run against both kernels.

Authoring your own composite constraint

Shape is not privileged — it is just a core ProvidesJsonSchema constraint that contributes a oneOf/anyOf/allOf. When a composite recurs across resources you can wrap it in a named constraint of your own (core's docs show a reusable GeoJsonGeometry), and the bundle needs nothing registered to honour it: unlike a custom scalar constraint, a composite has no translator to write — its members are raw JSON Schema, so there is nothing for the Symfony validator to translate. It rides the same documentation seam as NativeConstraints::schema(): the combinator lands in the served OpenAPI document, with nothing to wire.

The catch is runtime enforcement. The bundle value-validates the built-in Shape (through core's SchemaValueValidator, the 422 route above) but does not run a hand-rolled composite constraint — it only documents it. So:

  • Want the field-scoped 422 value pass? Attach the built-in Shape — it is the wired route.
  • Want a named, self-documenting shape in your vocabulary and are content with OpenAPI documentation? Author your own ProvidesJsonSchema constraint.
  • Want both — reuse and the 422 pass? Skip the constraint class and expose a small factory that returns a preconfigured Shape, so every call site gets the wired validation for free:
final class GeoJson
{
    /** A reusable, discriminated Point/LineString geometry. */
    public static function geometry(): Shape
    {
        $position = Schema::ofType('array')->withItems(Schema::ofType('number'));

        return Shape::oneOf(
            Schema::ofType('object')
                ->withProperties([
                    'type' => Schema::ofType('string')->withConst('Point'),
                    'coordinates' => $position,
                ])
                ->withRequired(['type', 'coordinates']),
            Schema::ofType('object')
                ->withProperties([
                    'type' => Schema::ofType('string')->withConst('LineString'),
                    'coordinates' => Schema::ofType('array')->withItems($position),
                ])
                ->withRequired(['type', 'coordinates']),
        )->discriminator('type');
    }
}

// on any resource, at the call site:
ArrayHash::make('location')->nullable()->constrain(GeoJson::geometry());

Storage: one json column

A composite attribute is one value — the natural Doctrine mapping is a single json column:

#[ORM\Entity]
class Release
{
    public function __construct(
        // …
        #[ORM\Column(type: 'json', nullable: true)]
        public ?array $format = null,
        #[ORM\Column(type: 'json', nullable: true)]
        public ?array $packaging = null,
    ) {}
}

No custom DBAL type is involved: the whole object round-trips as one JSON document, an Obj's partial PATCH merges per-child before the column is written, and an explicit null clears it.

A DateTime, Date or Time child needs nothing extra. Core hydrates a nested date to a string, so the column holds plain JSON. A DateTime child stores its instant in UTC as Y-m-d\TH:i:s.uP, and a Date or Time child stores its value in the field's own format. On a read a stored DateTime moves into the output timezone and renders in the field's format, and a Date or Time renders as stored. Code that reads a nested date off the entity gets that string, not a \DateTimeImmutable. Core's nested dates section has the exact rules. A child that needs a richer PHP type than JSON can hold, such as a value object, still goes through the field-level serializeUsing()/fillUsing() hooks rather than a recursive column type.

A serializeUsing() or extractUsing() hook on an Obj, Map or OneOf changes its read schema: the OpenAPI document keeps the children's properties but requires none of them, and a OneOf no longer requires its discriminator. An extractUsing() value still renders through the children. A serializeUsing() value skips them and goes out as the hook returns it, so keep it to the declared shape or the response won't match the document.

Worked example

The example app's releases resource (ReleaseResource over Release) showcases all three kinds on one type — a OneOf format discriminated by medium (vinyl / cd / digital), an Obj packaging, and Shape'd availability/dimensions maps — each a single json column, and each keyword (oneOf, anyOf, allOf, discriminator) visible in the served OpenAPI document. The dual-provider conformance witnesses are CompositeConformanceTestCase and, for structured lists, StructuredListConformanceTestCase, which run the same validation-pointer and json-column round-trip assertions against the in-memory and Doctrine kernels.

Next

  • Validation — the bridge, the 422 shape, and the translation map.
  • Core field types — Obj/OneOf semantics (merge, discriminator fallback, OpenAPI projection).
  • Core constraints — the Shape builders and the SchemaValueValidator execution route.