Skip to content

feat(serializer): resource polymorphism via DiscriminatorMap - #8874

Closed
soyuka wants to merge 31 commits into
api-platform:mainfrom
soyuka:feat/resource-polymorphism
Closed

soyuka wants to merge 31 commits into
api-platform:mainfrom
soyuka:feat/resource-polymorphism

Conversation

@soyuka

@soyuka soyuka commented Nov 25, 2026 •

Copy link
Copy Markdown
Member
Q A
Branch? main
Tickets Closes #8865, closes #2931, closes #6915. Supersedes #8620 and #7815
License MIT
Doc PR api-platform/docs#...

Resource polymorphism. With api_platform.serializer.discriminator_map: true (Laravel: api-platform.serializer.discriminator_map), the subtypes listed in the serializer #[DiscriminatorMap] of a resource are read, written and documented: subtype properties in every format, the most specific mapped class as JSON-LD @type, oneOf (plus discriminator in OpenAPI) in the JSON Schemas, subClassOf classes in /docs.jsonld. doctrine.discriminator_map / doctrine_mongodb_odm.discriminator_map derive that map from the Doctrine inheritance mapping; an explicit serializer map wins. Everything is off by default, nothing changes when the flag is off.

Rules:

  • An update never changes the subtype: a PUT or PATCH whose type differs from the stored one returns a 422 on the type property (code UnprocessableValueException::TYPE_MISMATCH_ERROR), also when the subtype is itself a resource without a map of its own.
  • In JSON-LD, a payload whose @type names a class the type property does not select returns the same 422. @type does not select the class, the type property does.
  • #[ApiSubtype(shortName: ..., types: [...])] describes a non-resource subtype. shortName defaults to the class short name; it names the subtype in the JSON Schema and OpenAPI definitions and scopes its properties in JSON-LD and Hydra. types defaults to [shortName]; it is the JSON-LD @type of the subtype and the id of its Hydra class (#[ApiSubtype(types: ['https://schema.org/Truck'])] alone works).
  • A subtype name or type already used by a resource or another subtype is an error, raised by an optional kernel.cache_warmer (cache:warmup), not on a request. Laravel has no warmup step: there it is raised by the first JSON-LD request.
  • A property several sibling subtypes declare (Car::$seats, Bus::$seats) is one property, scoped to their closest common mapped parent (Vehicle/seats). Sibling subtypes must define it the same way: different iris, jsonldContext or link type throw.
  • The type property (kind) is a documented property: a Hydra supportedProperty of the class declaring the map and a JSON-LD context term.
  • @type stays a single, most specific value. Clients matching on the parent type follow subClassOf, which every subtype class has, resource or not.

Limits and security notes:

  • GraphQL is not wired: GraphQL operations keep the behaviour of a resource without polymorphism.
  • Creating through the root endpoint runs only the security of the root operation. Checks that depend on the subtype go through securityPostDenormalize, which sees the created subtype.
  • doctrine.discriminator_map / doctrine_mongodb_odm.discriminator_map make every class of the Doctrine map readable and writable through the root resource; declare a serializer #[DiscriminatorMap] to expose only some of them.

Tests: tests/Functional/DiscriminatedResourceTest.php (formats, nested maps, writes, rejected payloads, type change and @type violations, property security cache, OpenAPI and Hydra docs), tests/Functional/DoctrineDiscriminatedResourceTest.php and DoctrineDiscriminatedDocumentTest.php for the Doctrine maps, src/Metadata/Tests/SubtypeResolverTest.php for naming, tests/JsonLd/ContextBuilderTest.php for the shared terms. The polymorphism functional tests boot a dedicated kernel (tests/Functional/DiscriminatorMapAppKernel.php), the rest of the fixture app keeps the flag off.

Compared to #8620: one opt-in mechanism (a SubtypeResolverInterface service, only registered when the flag is on, replaces the static ClassDiscriminatorHelper and the default-context flag), JSON:API matches subtype definitions on their type value instead of re-derived definition names, the Doctrine loader is back in the serializer cache warmer.

Credits: @Maxcastel (#7815) and @dylan-rumble (#8620), whose commits are kept as is.

Co-authored-by: Maxcastel maxence.nord@gmail.com
Co-authored-by: Dylan van der Hout dylan@rumble.nl

@soyuka soyuka added this to the 5.1 milestone Nov 25, 2026
soyuka added a commit to soyuka/core that referenced this pull request Nov 25, 2026
@soyuka soyuka closed this Nov 25, 2026
@soyuka soyuka reopened this Nov 25, 2026
@dylan-rumble

Copy link
Copy Markdown
Contributor

Thanks for consolidating both PRs. The SubtypeResolverInterface service is a lot cleaner than my static helper + context flag, and rejecting a type change on PUT closes a real hole. I went through f342a2e, a few remarks:

1. JSON-LD @type drops the declared types

JsonLd\Serializer\ItemNormalizer::resolveType() now returns the subtype name before looking at types, so with types: ['https://schema.org/Vehicle'] a car is output as "@type": "DiscriminatedCar" only.

I saw it is listed in the known limitations, but resolveType() already returns string|array, so ["DiscriminatedCar", "https://schema.org/Vehicle"] would keep both and clients would not have to follow subClassOf. WDYT?

2. SubtypeResolver::getAmbiguousNames() walks every resource

The first getTypeName() call on a non-resource subtype loads the resource metadata and the discriminator mapping of every resource of the app. The result is only memoized on the instance, so outside of worker mode that is once per request serializing such a subtype in JSON-LD (item normalizer and context builder).

I did not benchmark it and the metadata is cached, but it is O(resources) per request. Could it be computed at cache warmup or stored in a cache pool?

3. PUT without the type property when the map has a defaultType

Map circle/square with defaultType: 'circle', stored square, PUT {"name": "x"}:

422  kind: The type "null" does not match the type of the resource being updated.

The 422 is right (the payload resolves to the default type), but the message is confusing since the client never sent a type. Something like The type must be "square" would be clearer. No test covers defaultType on updates either.

Nits

  • SubtypeResolverInterface is not @internal but has no alias, so it cannot be autowired. Either alias it when the flag is on, or mark it @internal?
  • DeserializeProvider adds REPLACED_CLASS to the context on every PUT, also when the feature is off. Harmless since AbstractItemNormalizer::denormalize() unsets it, just noting it.
  • Some comments explaining non-obvious logic in AbstractItemNormalizer were dropped (e.g. "the type property is computed from the discriminator map, it is not a writable property of the object" in prepareDiscriminatedData()). I would keep those.

@Jules-Rabus

Jules-Rabus commented Nov 25, 2026 •

Copy link
Copy Markdown

I really appreciate the consolidation of the previous PRs! I tried it on a DTO resource backed by stateOptions (part 2 of #8865) and it does not work there. No existing test covers it, the one below fails:

  • GET returns neither kind nor the subtype properties.
  • POST is a 400 (Unable to generate an IRI).

With concrete parents instead of abstract ones, POST was a 201 but stored the parent class, without the subtype fields.

tests/Functional/StateOptionsDiscriminatedResourceTest.php:

<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Functional;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedSportsCar;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Serializer\Attribute\DiscriminatorMap;

final class StateOptionsDiscriminatedResourceTest extends ApiTestCase
{
    use RecreateSchemaTrait;
    use SetupClassResourcesTrait;

    protected static ?bool $alwaysBootKernel = false;

    protected static function getKernelClass(): string
    {
        return DiscriminatorMapAppKernel::class;
    }

    public static function getResources(): array
    {
        return [VehicleApi::class];
    }

    protected function setUp(): void
    {
        if ($this->isMongoDB()) {
            $this->markTestSkipped('ORM only.');
        }

        $this->recreateSchema([DoctrineDiscriminatedVehicle::class, DoctrineDiscriminatedCar::class, DoctrineDiscriminatedSportsCar::class, DoctrineDiscriminatedTruck::class]);

        $truck = new DoctrineDiscriminatedTruck();
        $truck->name = 'Volvo';
        $truck->payload = 20000;
        $this->getManager()->persist($truck);
        $this->getManager()->flush();
        $this->getManager()->clear();
    }

    public function testGet(): void
    {
        self::createClient()->request('GET', '/vehicle_apis/1');
        $this->assertResponseIsSuccessful();
        $this->assertJsonContains(['kind' => 'truck', 'name' => 'Volvo', 'payload' => 20000]);
    }

    public function testPost(): void
    {
        self::createClient()->request('POST', '/vehicle_apis', [
            'headers' => ['Content-Type' => 'application/ld+json'],
            'json' => ['kind' => 'truck', 'name' => 'Scania', 'payload' => 3500],
        ]);
        $this->assertResponseStatusCodeSame(201);

        $this->getManager()->clear();
        $truck = $this->getManager()->find(DoctrineDiscriminatedVehicle::class, 2);
        $this->assertInstanceOf(DoctrineDiscriminatedTruck::class, $truck);
        $this->assertSame(3500, $truck->payload);
    }
}

#[ApiResource(stateOptions: new Options(entityClass: DoctrineDiscriminatedVehicle::class))]
#[DiscriminatorMap(typeProperty: 'kind', mapping: ['car' => CarApi::class, 'truck' => TruckApi::class])]
abstract class VehicleApi
{
    public ?int $id = null;
    public string $name = '';
}

#[Map(source: DoctrineDiscriminatedCar::class)]
#[Map(target: DoctrineDiscriminatedCar::class)]
final class CarApi extends VehicleApi
{
    public int $seats = 4;
}

#[Map(source: DoctrineDiscriminatedTruck::class)]
#[Map(target: DoctrineDiscriminatedTruck::class)]
final class TruckApi extends VehicleApi
{
    public int $payload = 0;
}

This PR closes #8865: should part 2 be handled here, or tracked in a separate issue?
For context, I'm using the DTO and Object Mapper pattern from the docs, to keep #[ApiResource] off the Doctrine entities.

@soyuka

soyuka commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Thanks @Jules-Rabus I'll look into this!

@dylan-rumble

dylan-rumble commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

When I created the initial commits this was something I was aware of, AFAIK the object mapper doesn't really have a great way to handle polymorphism. I think this is more of an issue on the object mapper's side of things, the input DTO would vary based on the discriminator type. This has all sorts of complications. I think for now, its reasonable to throw an error when trying to use it in combination with the object mapper.

We could potentially try and get the correct output class the mapper should map to inside backend/vendor/api-platform/state/Provider/ObjectMapperProvider.php. There is the issue of how we handle it in the output too.

In any case, the whole object mapper path was not tested when I made this.

@dylan-rumble

dylan-rumble commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

@soyuka maybe its a better idea to leave object mapper out of scope for this PR. its already rather large. but that is up to you.

Maxcastel and others added 9 commits November 26, 2026 17:17
Operation "_api_/authors{._format}_get_collection" is declared by both "ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Polymorphism\Author" and "ApiPlatform\Tests\Fixtures\TestBundle\Entity\IriFilterRelationsTest\Author".
…tor maps

Expose the ORM and MongoDB ODM inheritance discriminator map of an API
resource hierarchy as a serializer discriminator map, so subtypes are read,
written and documented without declaring them twice.

An explicit serializer DiscriminatorMap in the hierarchy takes precedence.
Every non-leaf class gets a map of itself and its subclasses, so resources
declared mid-hierarchy resolve their own subtypes.

Disabled by default; enable with api_platform.doctrine.discriminator_map
or api_platform.doctrine_mongodb_odm.discriminator_map.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…arent schema

Every oneOf branch already carries the common properties, repeating them
next to oneOf made Swagger UI display them twice.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…minator_map

- add the opt-in `serializer.discriminator_map` flag (Laravel: `api-platform.serializer.discriminator_map`), implied by the Doctrine flags
- expose subtypes in Hydra/JSON-LD: most specific `@type`, subtype terms in the context, `subClassOf` classes in /docs.jsonld
- only emit the `discriminator` keyword in OpenAPI schemas
- let serializer maps declared with any loader take precedence over Doctrine maps
- memoize the discriminator resolution in AbstractItemNormalizer
- reject type changes on nested maps listing their own class
- replace Prophecy with PHPUnit stubs, consolidate fixtures and functional tests

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The Book/Author hierarchy and its OpenAPI and normalizer tests exercise the same paths as the DiscriminatedVehicle fixtures.
- One opt-in: a SubtypeResolverInterface service, registered only when
  serializer.discriminator_map (or a Doctrine discriminator_map flag) is
  enabled, replaces the static ClassDiscriminatorHelper and the
  discriminator_map default-context flag.
- A non-resource subtype whose short name is also used by a resource or
  another subtype gets no JSON-LD @type, context terms or Hydra class.
  A subtype that is a resource is named after it and documented with
  subClassOf its parent.
- JSON-LD @type is the subtype also when the resource declares types.
- JSON:API matches the subtype definitions on their type value instead
  of re-deriving the names of the base definitions.
- An update never changes the subtype: a PUT or PATCH with another type
  is a 422 on the type property.
- A non-resource subtype is named after its class short name, or after
  #[ApiSubtype(shortName: ...)]. A name used by a resource or by another
  subtype throws instead of being dropped.
- Two subtypes defining the same property with different JSON-LD
  definitions throw instead of the first one winning.
- The type property of a discriminator map is documented in Hydra and
  defined in the JSON-LD context like any property.
- A JSON-LD "@type" naming a class the denormalized object is not an
  instance of is a 422 on the type property.
- Type violations use their own code,
  UnprocessableValueException::TYPE_MISMATCH_ERROR.
A subtype name clash fails cache:warmup instead of the first JSON-LD request.
- Sibling subtypes declaring the same property share one term, scoped
  to their closest common mapped parent; only contradictory explicit
  iris throw.
- #[ApiSubtype] takes an optional shortName (definition names, property
  scope) and types (JSON-LD @type, Hydra class id).
The fixture app keeps the flag off, only the polymorphism tests boot with it.
A leaf resource has no discriminator map of its own: check the type properties of its parents' maps on PATCH and PUT.
Sibling subtypes sharing a term must define it the same way, not only with the same iris.
soyuka and others added 6 commits November 26, 2026 17:18
Co-authored-by: Kévin Dunglas <kevin@dunglas.dev>
A non-resource subtype is named after its class short name. Removes
the per-request walk over every resource that validated subtype names.
Doctrine-derived maps default a concrete class to its own type, and a
PUT without the type property keeps the existing subtype.
A resource with a discriminator map is documented as a oneOf of its
subtypes, with the type property enum, only when resource polymorphism
is enabled.
With polymorphism off, a PUT without the type property keeps the
pre-existing 400 instead of reusing the stored class.
@soyuka

soyuka commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@dylan-rumble about the root types: a subtype doesn't carry them, otherwise a resource subtype would get a different @type through the parent than through its own endpoint, and clients would get an array where they had a string. The hierarchy is already in the Hydra docs as subClassOf. Note that ApiSubtype is gone, a non-resource subtype is named after its short class name, make it a resource (e.g. #[ApiResource(operations: [])]) to rename it.

@Jules-Rabus your stateOptions + ObjectMapper case works now (GET item, collection and POST), the mapper resolves the concrete subclass from the subtypes #[Map], see MappedDiscriminatedResourceTest. It ships as a decorator until symfony/symfony#68452 lands. Can you give it a try?

@soyuka

soyuka commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Split into a stack to make the review easier: #8883 → #8884 → #8885 → #8886 → #8887 → #8888 (https://github.com/api-platform/core/stack/8889). Same final code as this branch, @dylan-rumble @Jules-Rabus the answers above still apply. Closing in favor of the stack.

@soyuka soyuka closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants