Repository navigation
Conversation
|
Thanks for consolidating both PRs. The 1. JSON-LD
|
|
I really appreciate the consolidation of the previous PRs! I tried it on a DTO resource backed by
With concrete parents instead of abstract ones,
<?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? |
|
Thanks @Jules-Rabus I'll look into this! |
|
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 In any case, the whole object mapper path was not tested when I made this. |
|
@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. |
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.
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.
24f21c2 to
963edcd
Compare
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.
|
@dylan-rumble about the root @Jules-Rabus your stateOptions + ObjectMapper case works now (GET item, collection and POST), the mapper resolves the concrete subclass from the subtypes |
|
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. |
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(plusdiscriminatorin OpenAPI) in the JSON Schemas,subClassOfclasses in/docs.jsonld.doctrine.discriminator_map/doctrine_mongodb_odm.discriminator_mapderive 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:
PUTorPATCHwhose type differs from the stored one returns a 422 on the type property (codeUnprocessableValueException::TYPE_MISMATCH_ERROR), also when the subtype is itself a resource without a map of its own.@typenames a class the type property does not select returns the same 422.@typedoes not select the class, the type property does.#[ApiSubtype(shortName: ..., types: [...])]describes a non-resource subtype.shortNamedefaults 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.typesdefaults to[shortName]; it is the JSON-LD@typeof the subtype and the id of its Hydra class (#[ApiSubtype(types: ['https://schema.org/Truck'])]alone works).kernel.cache_warmer(cache:warmup), not on a request. Laravel has no warmup step: there it is raised by the first JSON-LD request.Car::$seats,Bus::$seats) is one property, scoped to their closest common mapped parent (Vehicle/seats). Sibling subtypes must define it the same way: differentiris,jsonldContextor link type throw.kind) is a documented property: a HydrasupportedPropertyof the class declaring the map and a JSON-LD context term.@typestays a single, most specific value. Clients matching on the parent type followsubClassOf, which every subtype class has, resource or not.Limits and security notes:
securityPostDenormalize, which sees the created subtype.doctrine.discriminator_map/doctrine_mongodb_odm.discriminator_mapmake 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@typeviolations, property security cache, OpenAPI and Hydra docs),tests/Functional/DoctrineDiscriminatedResourceTest.phpandDoctrineDiscriminatedDocumentTest.phpfor the Doctrine maps,src/Metadata/Tests/SubtypeResolverTest.phpfor naming,tests/JsonLd/ContextBuilderTest.phpfor 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
SubtypeResolverInterfaceservice, only registered when the flag is on, replaces the staticClassDiscriminatorHelperand 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