diff --git a/CHANGELOG.md b/CHANGELOG.md index 4debc273dda..1dc96afd6a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ API Platform 5.1 contains every change shipped in the v5.0.x releases, plus the * JSON:API: a `PATCH` or `PUT` whose `data.id` does not match the endpoint now returns `409 Conflict`, as the specification requires; it used to be applied to the endpoint's resource ([#8752](https://github.com/api-platform/core/pull/8752)). With `jsonapi.strict_resource_type` enabled, a mismatched `data.type` also returns `409` on `PATCH` and `PUT`, not only on `POST`. * JSON:API: `jsonapi.strict_member_names` (off by default) exposes the `id` and `type` properties as `resourceId` and `resourceType` attributes instead of `_id` and `_type`, which are not valid member names, and stops renaming `links`, `relationships` and `included` ([#8752](https://github.com/api-platform/core/pull/8752)). +* Resource polymorphism: resources whose class declares a serializer `#[DiscriminatorMap]` (or a Doctrine discriminator map with `doctrine.discriminator_map` / `doctrine_mongodb_odm.discriminator_map`) expose, validate and document their subtypes when `serializer.discriminator_map` is enabled (Laravel: `api-platform.serializer.discriminator_map`). It is off by default, as it changes the JSON-LD `@type`, the JSON Schemas and the denormalization of these resources ([#8620](https://github.com/api-platform/core/pull/8620)). ### Breaking changes diff --git a/src/Doctrine/Common/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoader.php b/src/Doctrine/Common/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoader.php new file mode 100644 index 00000000000..b7b0a95a0ad --- /dev/null +++ b/src/Doctrine/Common/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoader.php @@ -0,0 +1,159 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Doctrine\Common\Serializer\Mapping\Loader; + +use ApiPlatform\Metadata\ResourceClassResolverInterface; +use Doctrine\Persistence\ManagerRegistry; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\ClassMetadataInterface; +use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface; + +/** + * Exposes the Doctrine inheritance discriminator map (ORM and MongoDB ODM) of an API resource as a serializer + * discriminator map, so the subtypes of a Doctrine hierarchy are read, written and documented as such. + * + * A serializer discriminator map declared in the hierarchy always takes precedence. It is detected using the + * explicit serializer loaders (attributes, XML, YAML) when they are given, attributes only otherwise. + * + * The serializer does not inherit discriminator maps: every class having subclasses in the Doctrine map gets + * its own map, restricted to itself and its subclasses, so a resource declared in the middle of a hierarchy + * resolves its own subtypes too. + * + * @internal + */ +final class DoctrineDiscriminatorMappingLoader implements LoaderInterface +{ + /** @var array */ + private array $serializerDiscriminatorMaps = []; + + public function __construct( + private readonly ManagerRegistry $managerRegistry, + private readonly ResourceClassResolverInterface $resourceClassResolver, + private readonly ?LoaderInterface $serializerLoader = null, + ) { + } + + public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool + { + if (null !== $classMetadata->getClassDiscriminatorMapping()) { + return false; + } + + $class = $classMetadata->getName(); + if (!class_exists($class) || null === $manager = $this->managerRegistry->getManagerForClass($class)) { + return false; + } + + $doctrineMetadata = $manager->getClassMetadata($class); + $discriminatorMap = property_exists($doctrineMetadata, 'discriminatorMap') ? $doctrineMetadata->discriminatorMap : null; + if (!\is_array($discriminatorMap) || !$discriminatorMap || null === $typeProperty = $this->getTypeProperty($doctrineMetadata)) { + return false; + } + + $typesMapping = []; + $hasSubtypes = false; + foreach ($discriminatorMap as $typeValue => $typeClass) { + if (!\is_string($typeClass) || !is_a($typeClass, $class, true)) { + continue; + } + + $typesMapping[(string) $typeValue] = $typeClass; + $hasSubtypes = $hasSubtypes || $typeClass !== $class; + } + + // Leaves do not need a map: their type is resolved from the maps of their parents + if (!$hasSubtypes) { + return false; + } + + // The root of a hierarchy (e.g. an abstract class) is not necessarily part of the Doctrine map + $hierarchy = array_filter($discriminatorMap, 'is_string'); + for ($hierarchyClass = $class; false !== $hierarchyClass; $hierarchyClass = get_parent_class($hierarchyClass)) { + $hierarchy[] = $hierarchyClass; + } + $hierarchy = array_unique($hierarchy); + + if (!$this->isResourceHierarchy($hierarchy) || $this->hasSerializerDiscriminatorMap($hierarchy)) { + return false; + } + + $classMetadata->setClassDiscriminatorMapping(new ClassDiscriminatorMapping($typeProperty, $typesMapping)); + + return true; + } + + private function getTypeProperty(object $doctrineMetadata): ?string + { + // ORM: a DiscriminatorColumnMapping object (ORM 3) or an array (ORM 2) + if (property_exists($doctrineMetadata, 'discriminatorColumn') && null !== $column = $doctrineMetadata->discriminatorColumn) { + $name = \is_array($column) ? ($column['name'] ?? null) : ($column->name ?? null); + + return \is_string($name) && '' !== $name ? $name : null; + } + + // MongoDB ODM + if (property_exists($doctrineMetadata, 'discriminatorField') && \is_string($doctrineMetadata->discriminatorField) && '' !== $doctrineMetadata->discriminatorField) { + return $doctrineMetadata->discriminatorField; + } + + return null; + } + + /** + * @param list $hierarchy + */ + private function isResourceHierarchy(array $hierarchy): bool + { + foreach ($hierarchy as $class) { + if ($this->resourceClassResolver->isResourceClass($class)) { + return true; + } + } + + return false; + } + + /** + * A serializer map declared anywhere in the hierarchy is the explicit API contract: the Doctrine one is ignored. + * + * @param list $hierarchy + */ + private function hasSerializerDiscriminatorMap(array $hierarchy): bool + { + foreach ($hierarchy as $class) { + if (class_exists($class) && ($this->serializerDiscriminatorMaps[$class] ??= $this->declaresSerializerDiscriminatorMap($class))) { + return true; + } + } + + return false; + } + + /** + * @param class-string $class + */ + private function declaresSerializerDiscriminatorMap(string $class): bool + { + if (null === $this->serializerLoader) { + return (bool) (new \ReflectionClass($class))->getAttributes(DiscriminatorMap::class, \ReflectionAttribute::IS_INSTANCEOF); + } + + $classMetadata = new ClassMetadata($class); + $this->serializerLoader->loadClassMetadata($classMetadata); + + return null !== $classMetadata->getClassDiscriminatorMapping(); + } +} diff --git a/src/Doctrine/Common/Tests/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoaderTest.php b/src/Doctrine/Common/Tests/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoaderTest.php new file mode 100644 index 00000000000..50764bfd72f --- /dev/null +++ b/src/Doctrine/Common/Tests/Serializer/Mapping/Loader/DoctrineDiscriminatorMappingLoaderTest.php @@ -0,0 +1,244 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Doctrine\Common\Tests\Serializer\Mapping\Loader; + +use ApiPlatform\Doctrine\Common\Serializer\Mapping\Loader\DoctrineDiscriminatorMappingLoader; +use ApiPlatform\Metadata\ResourceClassResolverInterface; +use Doctrine\ODM\MongoDB\Mapping\ClassMetadata as OdmClassMetadata; +use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata; +use Doctrine\ORM\Mapping\DiscriminatorColumnMapping; +use Doctrine\Persistence\ManagerRegistry; +use Doctrine\Persistence\ObjectManager; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassMetadata; +use Symfony\Component\Serializer\Mapping\ClassMetadataInterface; +use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface; + +final class DoctrineDiscriminatorMappingLoaderTest extends TestCase +{ + private const ORM_MAP = [ + 'vehicle' => LoaderVehicle::class, + 'car' => LoaderCar::class, + 'sportsCar' => LoaderSportsCar::class, + 'truck' => LoaderTruck::class, + ]; + + public function testRootGetsTheWholeDoctrineMap(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + + $this->assertTrue($this->createOrmLoader()->loadClassMetadata($metadata)); + $this->assertEquals(new ClassDiscriminatorMapping('kind', self::ORM_MAP), $metadata->getClassDiscriminatorMapping()); + } + + public function testIntermediateClassGetsItselfAndItsSubclasses(): void + { + $metadata = new ClassMetadata(LoaderCar::class); + + $this->assertTrue($this->createOrmLoader()->loadClassMetadata($metadata)); + $this->assertEquals( + new ClassDiscriminatorMapping('kind', ['car' => LoaderCar::class, 'sportsCar' => LoaderSportsCar::class]), + $metadata->getClassDiscriminatorMapping(), + ); + } + + public function testLeavesAreLeftAlone(): void + { + $loader = $this->createOrmLoader(); + + foreach ([LoaderSportsCar::class, LoaderTruck::class] as $class) { + $metadata = new ClassMetadata($class); + $this->assertFalse($loader->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + } + + public function testExistingSerializerMappingWins(): void + { + $mapping = new ClassDiscriminatorMapping('type', ['car' => LoaderCar::class]); + $metadata = new ClassMetadata(LoaderVehicle::class, $mapping); + + $this->assertFalse($this->createOrmLoader()->loadClassMetadata($metadata)); + $this->assertSame($mapping, $metadata->getClassDiscriminatorMapping()); + } + + public function testSerializerDiscriminatorMapDeclaredInTheHierarchyWins(): void + { + $doctrineMetadata = $this->createOrmMetadata(LoaderSerializerMappedChild::class, [ + 'base' => LoaderSerializerMappedBase::class, + 'child' => LoaderSerializerMappedChild::class, + 'grandChild' => LoaderSerializerMappedGrandChild::class, + ]); + $metadata = new ClassMetadata(LoaderSerializerMappedChild::class); + + $this->assertFalse($this->createLoader([LoaderSerializerMappedChild::class => $doctrineMetadata])->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + + public function testSerializerDiscriminatorMapDeclaredWithAnotherLoaderWins(): void + { + $serializerLoader = $this->createStub(LoaderInterface::class); + $serializerLoader->method('loadClassMetadata')->willReturnCallback(static function (ClassMetadataInterface $metadata): bool { + if (LoaderVehicle::class !== $metadata->getName()) { + return false; + } + + $metadata->setClassDiscriminatorMapping(new ClassDiscriminatorMapping('type', ['car' => LoaderCar::class])); + + return true; + }); + $metadata = new ClassMetadata(LoaderCar::class); + + $this->assertFalse($this->createLoader([LoaderCar::class => $this->createOrmMetadata(LoaderCar::class, self::ORM_MAP)], serializerLoader: $serializerLoader)->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + + public function testNonResourceHierarchiesAreLeftAlone(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + $loader = $this->createLoader([LoaderVehicle::class => $this->createOrmMetadata(LoaderVehicle::class, self::ORM_MAP)], []); + + $this->assertFalse($loader->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + + public function testHierarchyIsExposedWhenOnlyASubclassIsAResource(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + $loader = $this->createLoader([LoaderVehicle::class => $this->createOrmMetadata(LoaderVehicle::class, self::ORM_MAP)], [LoaderTruck::class]); + + $this->assertTrue($loader->loadClassMetadata($metadata)); + $this->assertEqualsCanonicalizing(self::ORM_MAP, $metadata->getClassDiscriminatorMapping()?->getTypesMapping()); + } + + public function testUnmanagedClassesAreLeftAlone(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + + $this->assertFalse($this->createLoader([])->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + + public function testClassesWithoutInheritanceAreLeftAlone(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + $doctrineMetadata = new OrmClassMetadata(LoaderVehicle::class); + + $this->assertFalse($this->createLoader([LoaderVehicle::class => $doctrineMetadata])->loadClassMetadata($metadata)); + $this->assertNull($metadata->getClassDiscriminatorMapping()); + } + + public function testIntegerDiscriminatorValuesAreCastToStrings(): void + { + $metadata = new ClassMetadata(LoaderVehicle::class); + $loader = $this->createLoader([LoaderVehicle::class => $this->createOrmMetadata(LoaderVehicle::class, [1 => LoaderCar::class, 2 => LoaderTruck::class])]); + + $this->assertTrue($loader->loadClassMetadata($metadata)); + $this->assertEqualsCanonicalizing(['1' => LoaderCar::class, '2' => LoaderTruck::class], $metadata->getClassDiscriminatorMapping()?->getTypesMapping()); + $this->assertSame(LoaderCar::class, $metadata->getClassDiscriminatorMapping()->getClassForType('1')); + } + + public function testMongoDbOdmDiscriminatorField(): void + { + $doctrineMetadata = new OdmClassMetadata(LoaderVehicle::class); + $doctrineMetadata->discriminatorField = 'kind'; + $doctrineMetadata->discriminatorMap = ['car' => LoaderCar::class, 'truck' => LoaderTruck::class]; + $metadata = new ClassMetadata(LoaderVehicle::class); + + $this->assertTrue($this->createLoader([LoaderVehicle::class => $doctrineMetadata])->loadClassMetadata($metadata)); + $this->assertEquals( + new ClassDiscriminatorMapping('kind', ['car' => LoaderCar::class, 'truck' => LoaderTruck::class]), + $metadata->getClassDiscriminatorMapping(), + ); + } + + private function createOrmLoader(): DoctrineDiscriminatorMappingLoader + { + $metadata = []; + foreach (self::ORM_MAP as $class) { + $metadata[$class] = $this->createOrmMetadata($class, self::ORM_MAP); + } + + return $this->createLoader($metadata); + } + + /** + * @param array $discriminatorMap + */ + private function createOrmMetadata(string $class, array $discriminatorMap): OrmClassMetadata + { + $metadata = new OrmClassMetadata($class); + // ORM 2 stores the discriminator column as an array + $metadata->discriminatorColumn = class_exists(DiscriminatorColumnMapping::class) + ? new DiscriminatorColumnMapping('string', 'kind', 'kind') + : ['type' => 'string', 'fieldName' => 'kind', 'name' => 'kind']; + $metadata->discriminatorMap = $discriminatorMap; + + return $metadata; + } + + /** + * @param array $doctrineMetadata + * @param class-string[]|null $resourceClasses defaults to the root of every hierarchy + */ + private function createLoader(array $doctrineMetadata, ?array $resourceClasses = null, ?LoaderInterface $serializerLoader = null): DoctrineDiscriminatorMappingLoader + { + $resourceClasses ??= [LoaderVehicle::class, LoaderSerializerMappedBase::class]; + + $managers = []; + foreach ($doctrineMetadata as $class => $metadata) { + $managers[$class] = $this->createStub(ObjectManager::class); + $managers[$class]->method('getClassMetadata')->willReturn($metadata); + } + + $managerRegistry = $this->createStub(ManagerRegistry::class); + $managerRegistry->method('getManagerForClass')->willReturnCallback(static fn (string $class): ?ObjectManager => $managers[$class] ?? null); + + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturnCallback(static fn (string $class): bool => \in_array($class, $resourceClasses, true)); + + return new DoctrineDiscriminatorMappingLoader($managerRegistry, $resourceClassResolver, $serializerLoader); + } +} + +class LoaderVehicle +{ +} + +class LoaderCar extends LoaderVehicle +{ +} + +class LoaderSportsCar extends LoaderCar +{ +} + +class LoaderTruck extends LoaderVehicle +{ +} + +#[DiscriminatorMap(typeProperty: 'type', mapping: ['child' => LoaderSerializerMappedChild::class])] +class LoaderSerializerMappedBase +{ +} + +class LoaderSerializerMappedChild extends LoaderSerializerMappedBase +{ +} + +class LoaderSerializerMappedGrandChild extends LoaderSerializerMappedChild +{ +} diff --git a/src/Doctrine/Common/composer.json b/src/Doctrine/Common/composer.json index 2661c2e6469..7154e8e05b8 100644 --- a/src/Doctrine/Common/composer.json +++ b/src/Doctrine/Common/composer.json @@ -35,6 +35,7 @@ "doctrine/orm": "^2.17 || ^3.0", "phpspec/prophecy-phpunit": "^2.2", "phpunit/phpunit": "^11.5 || ^12.2 || ^13.0", + "symfony/serializer": "^7.4 || ^8.0", "symfony/type-info": "^7.4 || ^8.0" }, "conflict": { @@ -46,7 +47,8 @@ "symfony/config": "For XML resource configuration.", "api-platform/http-cache": "For HTTP cache invalidation.", "api-platform/graphql": "For GraphQl mercure subscriptions.", - "symfony/mercure-bundle": "For mercure updates publisher." + "symfony/mercure-bundle": "For mercure updates publisher.", + "symfony/serializer": "To expose Doctrine discriminator maps as polymorphic resources." }, "autoload": { "psr-4": { diff --git a/src/Hydra/Serializer/DocumentationNormalizer.php b/src/Hydra/Serializer/DocumentationNormalizer.php index 3492403a94d..85f6b0acc2c 100644 --- a/src/Hydra/Serializer/DocumentationNormalizer.php +++ b/src/Hydra/Serializer/DocumentationNormalizer.php @@ -29,7 +29,9 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\Metadata\Util\TypeHelper; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; @@ -59,6 +61,7 @@ public function __construct( private readonly ?NameConverterInterface $nameConverter = null, private readonly ?array $defaultContext = [], private readonly ?bool $entrypointEnabled = true, + private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, ) { } @@ -68,8 +71,11 @@ public function __construct( public function normalize(mixed $data, ?string $format = null, array $context = []): array { $classes = []; + $subtypeClasses = []; $entrypointProperties = []; $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext); + $resourceClasses = iterator_to_array($data->getResourceNameCollection(), false); + $resourceShortNames = null === $this->classDiscriminatorResolver ? [] : $this->getResourceShortNames($resourceClasses); foreach ($data->getResourceNameCollection() as $resourceClass) { $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass); @@ -84,10 +90,96 @@ public function normalize(mixed $data, ?string $format = null, array $context = $this->populateEntrypointProperties($resourceMetadata, $shortName, $prefixedShortName, $entrypointProperties, $hydraPrefix); $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix); + + if (null !== $this->classDiscriminatorResolver) { + [$propertyNameContext] = $this->getPropertyMetadataFactoryContext($resourceMetadata); + $propertyNames = array_fill_keys(iterator_to_array($this->propertyNameCollectionFactory->create($resourceClass, $propertyNameContext), false), true); + $this->addSubtypeClasses($subtypeClasses, $resourceClasses, $resourceShortNames, $resourceClass, $prefixedShortName, $propertyNames, $resourceMetadata, $context, $hydraPrefix); + } + } + } + + return $this->computeDoc($data, $this->getClasses($entrypointProperties, [...$classes, ...array_values($subtypeClasses)], $hydraPrefix), $hydraPrefix); + } + + /** + * Documents the subtypes declared in the discriminator map of a resource as subclasses of their parent, + * supporting the properties their parent does not expose. + * + * @param array> $subtypeClasses + * @param list $resourceClasses + * @param array $resourceShortNames + * @param array $propertyNames the properties exposed by the parent class + */ + private function addSubtypeClasses(array &$subtypeClasses, array $resourceClasses, array $resourceShortNames, string $class, string $prefixedShortName, array $propertyNames, ApiResource $resourceMetadata, array $context, string $hydraPrefix): void + { + if (null === $mapping = $this->classDiscriminatorResolver?->getMappingForClass($class)) { + return; + } + + [$propertyNameContext, $propertyContext] = $this->getPropertyMetadataFactoryContext($resourceMetadata); + foreach (ClassDiscriminatorHelper::getDirectSubtypes($mapping, $class) as $subtype) { + // A subtype being a resource is documented by its own class + if (\in_array($subtype, $resourceClasses, true)) { + continue; + } + + $subtypeShortName = ClassDiscriminatorHelper::getShortName($subtype); + // The short name already identifies a resource: its class must not be redefined, the subtypes of the subtype extend the parent + if (isset($resourceShortNames[$subtypeShortName])) { + $this->addSubtypeClasses($subtypeClasses, $resourceClasses, $resourceShortNames, $subtype, $prefixedShortName, $propertyNames, $resourceMetadata, $context, $hydraPrefix); + + continue; + } + + $subtypePrefixedShortName = "#$subtypeShortName"; + $subtypePropertyNames = $propertyNames; + $properties = []; + foreach ($this->propertyNameCollectionFactory->create($subtype, $propertyNameContext) as $propertyName) { + if (isset($subtypePropertyNames[$propertyName])) { + continue; + } + + $subtypePropertyNames[$propertyName] = true; + $propertyMetadata = $this->propertyMetadataFactory->create($subtype, $propertyName, $propertyContext); + if ((true === $propertyMetadata->isIdentifier() && false === $propertyMetadata->isWritable()) || false === $propertyMetadata->getHydra()) { + continue; + } + + $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $subtype, self::FORMAT, $context) : $propertyName; + $properties[] = $this->getProperty($propertyMetadata, $normalizedPropertyName, $subtypePrefixedShortName, $subtypeShortName, $hydraPrefix); + } + + $subtypeClasses[$subtypePrefixedShortName] ??= [ + '@id' => $subtypePrefixedShortName, + '@type' => $hydraPrefix.'Class', + $hydraPrefix.'title' => $subtypeShortName, + 'subClassOf' => $prefixedShortName, + $hydraPrefix.'supportedProperty' => $properties, + $hydraPrefix.'supportedOperation' => [], + ]; + + $this->addSubtypeClasses($subtypeClasses, $resourceClasses, $resourceShortNames, $subtype, $subtypePrefixedShortName, $subtypePropertyNames, $resourceMetadata, $context, $hydraPrefix); + } + } + + /** + * @param list $resourceClasses + * + * @return array + */ + private function getResourceShortNames(array $resourceClasses): array + { + $shortNames = []; + foreach ($resourceClasses as $resourceClass) { + foreach ($this->resourceMetadataFactory->create($resourceClass) as $resourceMetadata) { + if (true !== $resourceMetadata->getHideHydraOperation()) { + $shortNames[$resourceMetadata->getShortName()] = true; + } } } - return $this->computeDoc($data, $this->getClasses($entrypointProperties, $classes, $hydraPrefix), $hydraPrefix); + return $shortNames; } /** diff --git a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php index b83dbdcd8e2..680250f8758 100644 --- a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php +++ b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php @@ -36,6 +36,8 @@ use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\TypeInfo\Type; use const ApiPlatform\JsonLd\HYDRA_CONTEXT; @@ -1212,4 +1214,81 @@ public function testNormalizeWithStringGroups(): void $this->assertSame('#dummy', $doc['hydra:supportedClass'][0]['@id']); $this->assertNotEmpty($doc['hydra:supportedClass'][0]['hydra:supportedProperty']); } + + public function testSubtypeDoesNotRedefineTheClassOfAResourceWithTheSameShortName(): void + { + $documentation = new Documentation(new ResourceNameCollection([HydraDiscriminatedVehicle::class, HydraDiscriminatedOther::class]), 'Test Api', 'test', '0.0.0'); + + $propertyNames = [ + HydraDiscriminatedVehicle::class => ['name'], + HydraDiscriminatedCar::class => ['name', 'doors'], + HydraDiscriminatedTruck::class => ['name', 'payload'], + HydraDiscriminatedHeavyTruck::class => ['name', 'payload', 'axles'], + HydraDiscriminatedOther::class => ['title'], + ]; + $propertyNameCollectionFactory = $this->createStub(PropertyNameCollectionFactoryInterface::class); + $propertyNameCollectionFactory->method('create')->willReturnCallback(static fn (string $class): PropertyNameCollection => new PropertyNameCollection($propertyNames[$class])); + + $propertyMetadataFactory = $this->createStub(PropertyMetadataFactoryInterface::class); + $propertyMetadataFactory->method('create')->willReturn((new ApiProperty())->withNativeType(Type::string())->withReadable(true)->withWritable(true)); + + $resourceMetadataFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class); + $resourceMetadataFactory->method('create')->willReturnCallback(static function (string $class): ResourceMetadataCollection { + // An unrelated resource is named after a subtype of the discriminated resource + $shortName = HydraDiscriminatedOther::class === $class ? 'HydraDiscriminatedTruck' : 'HydraDiscriminatedVehicle'; + + return new ResourceMetadataCollection($class, [(new ApiResource())->withShortName($shortName)->withOperations(new Operations(['get' => (new Get())->withShortName($shortName)]))]); + }); + + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(false); + + $urlGenerator = $this->createStub(UrlGeneratorInterface::class); + $urlGenerator->method('generate')->willReturn('/doc'); + + $mappings = [ + HydraDiscriminatedVehicle::class => new ClassDiscriminatorMapping('kind', ['car' => HydraDiscriminatedCar::class, 'truck' => HydraDiscriminatedTruck::class]), + HydraDiscriminatedTruck::class => new ClassDiscriminatorMapping('size', ['heavy' => HydraDiscriminatedHeavyTruck::class]), + ]; + $classDiscriminatorResolver = $this->createStub(ClassDiscriminatorResolverInterface::class); + $classDiscriminatorResolver->method('getMappingForClass')->willReturnCallback(static fn (string $class): ?ClassDiscriminatorMapping => $mappings[$class] ?? null); + + $documentationNormalizer = new DocumentationNormalizer($resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, $resourceClassResolver, $urlGenerator, null, [], true, $classDiscriminatorResolver); + + $classes = array_values(array_filter($documentationNormalizer->normalize($documentation)['hydra:supportedClass'], static fn (array $class): bool => str_starts_with($class['@id'], '#HydraDiscriminated'))); + $properties = static fn (array $class): array => array_column(array_column($class['hydra:supportedProperty'], 'hydra:property'), '@id'); + + $this->assertSame(['#HydraDiscriminatedVehicle', '#HydraDiscriminatedTruck', '#HydraDiscriminatedCar', '#HydraDiscriminatedHeavyTruck'], array_column($classes, '@id')); + + // The class of the resource is left untouched + $this->assertArrayNotHasKey('subClassOf', $classes[1]); + $this->assertSame(['#HydraDiscriminatedTruck/title'], $properties($classes[1])); + + $this->assertSame('#HydraDiscriminatedVehicle', $classes[2]['subClassOf']); + $this->assertSame(['#HydraDiscriminatedCar/doors'], $properties($classes[2])); + + // The subtypes of the undocumented subtype extend the resource and support its properties + $this->assertSame('#HydraDiscriminatedVehicle', $classes[3]['subClassOf']); + $this->assertSame(['#HydraDiscriminatedHeavyTruck/payload', '#HydraDiscriminatedHeavyTruck/axles'], $properties($classes[3])); + } +} + +class HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedCar extends HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedTruck extends HydraDiscriminatedVehicle +{ +} + +class HydraDiscriminatedHeavyTruck extends HydraDiscriminatedTruck +{ +} + +class HydraDiscriminatedOther +{ } diff --git a/src/JsonApi/JsonSchema/SchemaFactory.php b/src/JsonApi/JsonSchema/SchemaFactory.php index 717a5b39723..8ddbd023756 100644 --- a/src/JsonApi/JsonSchema/SchemaFactory.php +++ b/src/JsonApi/JsonSchema/SchemaFactory.php @@ -19,6 +19,7 @@ use ApiPlatform\JsonSchema\DefinitionNameFactoryInterface; use ApiPlatform\JsonSchema\ResourceMetadataTrait; use ApiPlatform\JsonSchema\Schema; +use ApiPlatform\JsonSchema\SchemaFactory as BaseSchemaFactory; use ApiPlatform\JsonSchema\SchemaFactoryAwareInterface; use ApiPlatform\JsonSchema\SchemaFactoryInterface; use ApiPlatform\JsonSchema\SchemaUriPrefixTrait; @@ -27,7 +28,9 @@ use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\State\ApiResource\Error; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; /** * Decorator factory which adds JSON:API properties to the JSON Schema document. @@ -81,7 +84,7 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI private readonly ResourceLinkageResolver $resourceLinkageResolver; - public function __construct(private readonly SchemaFactoryInterface $schemaFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceClassResolverInterface $resourceClassResolver, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null, ?ResourceLinkageResolver $resourceLinkageResolver = null, private readonly bool $strictMemberNames = false) + public function __construct(private readonly SchemaFactoryInterface $schemaFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceClassResolverInterface $resourceClassResolver, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null, ?ResourceLinkageResolver $resourceLinkageResolver = null, private readonly bool $strictMemberNames = false, private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null) { if (!$definitionNameFactory) { $this->definitionNameFactory = new DefinitionNameFactory(); @@ -133,6 +136,7 @@ public function buildSchema(string $className, string $format = 'jsonapi', strin $prefix = $this->getSchemaUriPrefix($schema->getVersion()); $definitions = $schema->getDefinitions(); $collectionKey = $schema->getItemsDefinitionKey(); + $subtypeDefinitionName = $this->getSubtypeDefinitionNameFactory($className, $type, $operation, $jsonApiSerializerContext); // Already computed if (!$collectionKey && isset($definitions[$definitionName])) { @@ -165,7 +169,7 @@ public function buildSchema(string $className, string $format = 'jsonapi', strin if (!$collectionKey) { $definitions[$definitionName]['type'] = 'object'; - $definitions[$definitionName]['properties'] = $this->buildDefinitionPropertiesSchema($key, $definitionName, $inputOrOutputClass, $format, $type, $operation, $schema, []); + $definitions[$definitionName]['properties'] = $this->buildDefinitionPropertiesSchema($key, $definitionName, $inputOrOutputClass, $format, $type, $operation, $schema, [], $subtypeDefinitionName); $schema['$ref'] = $prefix.$definitionName; return $schema; @@ -263,7 +267,7 @@ public function buildSchema(string $className, string $format = 'jsonapi', strin unset($schema['items']); unset($schema['type']); - $properties = $this->buildDefinitionPropertiesSchema($key, $definitionName, $inputOrOutputClass, $format, $type, $operation, $schema, []); + $properties = $this->buildDefinitionPropertiesSchema($key, $definitionName, $inputOrOutputClass, $format, $type, $operation, $schema, [], $subtypeDefinitionName); $properties['data'] = [ 'type' => 'array', @@ -286,12 +290,23 @@ public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void } } - private function buildDefinitionPropertiesSchema(string $key, string $documentDefinitionName, string $propertyClass, string $format, string $type, ?Operation $operation, Schema $schema, ?array $serializerContext): array + /** + * @param (\Closure(class-string): string)|null $subtypeDefinitionName + */ + private function buildDefinitionPropertiesSchema(string $key, string $documentDefinitionName, string $propertyClass, string $format, string $type, ?Operation $operation, Schema $schema, ?array $serializerContext, ?\Closure $subtypeDefinitionName = null): array { // Capture the resource's operation up front; the relationship loop below reassigns $operation. $resourceOperation = $operation; $definitions = $schema->getDefinitions(); - $properties = $definitions[$key]['properties'] ?? []; + // A definition listing its subtypes in "oneOf" carries no properties: an instance of the class itself is described by its inline branch + $ownBranch = null; + foreach (null !== $this->classDiscriminatorResolver?->getMappingForClass($propertyClass) ? $definitions[$key]['oneOf'] ?? [] : [] as $branch) { + if (!isset($branch['$ref'])) { + $ownBranch = $branch; + break; + } + } + $properties = $ownBranch['properties'] ?? $definitions[$key]['properties'] ?? []; $attributes = []; $relationships = []; @@ -383,18 +398,112 @@ private function buildDefinitionPropertiesSchema(string $key, string $documentDe // Only relax the requirement on the input schema; responses still always carry an `id`. $required = Schema::TYPE_INPUT === $type && $resourceOperation instanceof HttpOperation && 'POST' === $resourceOperation->getMethod() ? ['type'] : ['type', 'id']; - $resourceDefinitionName = $documentDefinitionName.'.resource'; - $definitions[$resourceDefinitionName] = [ + $data = [ 'type' => 'object', 'properties' => $replacement, 'required' => $required, ]; + // Subtypes declared in a serializer discriminator map: the type property lives in "attributes" so an OpenAPI discriminator cannot be used + $oneOf = []; + foreach ($this->getDiscriminatedSubtypes($key, $propertyClass, $definitions, $schema->getVersion(), $subtypeDefinitionName) as [$subKey, $subClass, $typeProperty]) { + $attributeName = ReservedAttributeNameConverter::getReservedAttributes($this->strictMemberNames)[$typeProperty] ?? $typeProperty; + + // The inline branch of a class declared in its own discriminator map describes the instances of the class itself + if (!$oneOf && null !== $ownBranch) { + if (\in_array($typeProperty, $ownBranch['required'] ?? [], true)) { + $data['properties']['attributes']['required'] = [$attributeName]; + } + $oneOf[] = $data; + } + + $subDocumentDefinitionName = $documentDefinitionName.'.'.(new \ReflectionClass($subClass))->getShortName(); + $subSchema = $this->buildDefinitionPropertiesSchema($subKey, $subDocumentDefinitionName, $subClass, $format, $type, $resourceOperation, $schema, $serializerContext, $subtypeDefinitionName); + if (\in_array($typeProperty, $definitions[$subKey]['required'] ?? [], true)) { + $definitions[$subDocumentDefinitionName.'.resource']['properties']['attributes']['required'] = [$attributeName]; + } + $oneOf[] = $subSchema['data']; + + foreach ($subSchema['included']['items']['anyOf'] ?? [] as $relatedDefinition) { + $relatedDefinitions[$relatedDefinition['$ref']] = $relatedDefinition; + } + } + + // Every branch carries the common members: they are not repeated next to "oneOf" + if ($oneOf) { + $data = ['type' => 'object', 'oneOf' => $oneOf]; + } + + if ($relatedDefinitions && !$included) { + $included = [ + 'included' => [ + 'description' => 'Related resources requested via the "include" query parameter.', + 'type' => 'array', + 'items' => [], + 'readOnly' => true, + 'externalDocs' => [ + 'url' => 'https://jsonapi.org/format/#fetching-includes', + ], + ], + ]; + } + + if ($included) { + $included['included']['items'] = ['anyOf' => array_values($relatedDefinitions)]; + } + + $resourceDefinitionName = $documentDefinitionName.'.resource'; + $definitions[$resourceDefinitionName] = $data; + return [ 'data' => ['$ref' => $this->getSchemaUriPrefix($schema->getVersion()).$resourceDefinitionName], ] + $included; } + /** + * Mirrors the name the decorated factory gives to the definition of a subtype declared in a discriminator map. + * + * @return (\Closure(class-string): string)|null + */ + private function getSubtypeDefinitionNameFactory(string $className, string $type, ?Operation $operation, array $serializerContext): ?\Closure + { + if (null === $this->classDiscriminatorResolver) { + return null; + } + + $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET'; + $isInput = Schema::TYPE_INPUT === $type; + $definitionFormat = $isInput && 'PATCH' === $method ? 'merge-patch+json' : 'json'; + $serializerContext += ($operation ? $this->getSerializerContext($operation, $type) : []) + [ + 'schema_type' => $type, + BaseSchemaFactory::PARTIAL_UPDATE => $isInput && 'PUT' === $method && !($operation?->getExtraProperties()['standard_put'] ?? true), + ]; + + return fn (string $subClass): string => $this->definitionNameFactory->create($className, $definitionFormat, $subClass, $operation, $serializerContext); + } + + /** + * @param (\Closure(class-string): string)|null $subtypeDefinitionName + * + * @return iterable + */ + private function getDiscriminatedSubtypes(string $key, string $className, \ArrayObject $definitions, string $version, ?\Closure $subtypeDefinitionName): iterable + { + if (null === $subtypeDefinitionName || !isset($definitions[$key]['oneOf']) || null === $mapping = $this->classDiscriminatorResolver?->getMappingForClass($className)) { + return; + } + + // The "$ref" branches of "oneOf" reference the definitions of the direct subtypes + $refs = array_flip(array_column($definitions[$key]['oneOf'], '$ref')); + $prefix = $this->getSchemaUriPrefix($version); + foreach (ClassDiscriminatorHelper::getDirectSubtypes($mapping, $className) as $subClass) { + $subKey = $subtypeDefinitionName($subClass); + if (isset($refs[$prefix.$subKey], $definitions[$subKey])) { + yield [$subKey, $subClass, $mapping->getTypeProperty()]; + } + } + } + private function getRelationship(string $resourceClass, string $property, ?array $serializerContext): ?array { $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property, $serializerContext ?? []); @@ -409,6 +518,8 @@ private function getRelationship(string $resourceClass, string $property, ?array $relatedClasses = []; foreach ($relationships as [$className, $isCollection]) { $isOne = $isOne || !$isCollection; + // A relation narrowed to a subtype of a resource (e.g. declared in a discriminator map) targets the resource itself + $className = $this->resourceClassResolver->getResourceClass(null, $className); $relatedClasses[$className] = $className; } diff --git a/src/JsonApi/Tests/JsonSchema/SchemaFactoryTest.php b/src/JsonApi/Tests/JsonSchema/SchemaFactoryTest.php index 64f46013138..fbc01c69b3f 100644 --- a/src/JsonApi/Tests/JsonSchema/SchemaFactoryTest.php +++ b/src/JsonApi/Tests/JsonSchema/SchemaFactoryTest.php @@ -80,6 +80,7 @@ protected function setUp(): void ); $resourceClassResolver = $this->prophesize(ResourceClassResolverInterface::class); + $resourceClassResolver->getResourceClass(null, Argument::type('string'))->willReturnArgument(1); $resourceClassResolver->isResourceClass(Dummy::class)->willReturn(true); $resourceClassResolver->isResourceClass(Error::class)->willReturn(true); @@ -368,6 +369,7 @@ private function buildSchemaFactoryWithPolymorphicRelation(?Operation $relatedOp ); $resourceClassResolver = $this->prophesize(ResourceClassResolverInterface::class); + $resourceClassResolver->getResourceClass(null, Argument::type('string'))->willReturnArgument(1); $resourceClassResolver->isResourceClass(Dummy::class)->willReturn(true); $resourceClassResolver->isResourceClass(RelatedDummy::class)->willReturn(true); $resourceClassResolver->isResourceClass(OtherRelatedDummy::class)->willReturn(true); @@ -430,6 +432,7 @@ private function buildSchemaFactoryWithRelation(?Operation $relatedOperation = n ); $resourceClassResolver = $this->prophesize(ResourceClassResolverInterface::class); + $resourceClassResolver->getResourceClass(null, Argument::type('string'))->willReturnArgument(1); $resourceClassResolver->isResourceClass(Dummy::class)->willReturn(true); $resourceClassResolver->isResourceClass(RelatedDummy::class)->willReturn(true); diff --git a/src/JsonLd/ContextBuilder.php b/src/JsonLd/ContextBuilder.php index 82f90e6f21b..057a34c0b91 100644 --- a/src/JsonLd/ContextBuilder.php +++ b/src/JsonLd/ContextBuilder.php @@ -23,7 +23,9 @@ use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\ResourceMetadataCollection; use ApiPlatform\Metadata\UrlGeneratorInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\Metadata\Util\ClassInfoTrait; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; /** @@ -40,7 +42,7 @@ final class ContextBuilder implements AnonymousContextBuilderInterface, Operatio public const HYDRA_PREFIX = 'hydra:'; public const HYDRA_CONTEXT_HAS_PREFIX = 'hydra_prefix'; - public function __construct(private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly UrlGeneratorInterface $urlGenerator, private readonly ?IriConverterInterface $iriConverter = null, private readonly ?NameConverterInterface $nameConverter = null, private array $defaultContext = []) + public function __construct(private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly UrlGeneratorInterface $urlGenerator, private readonly ?IriConverterInterface $iriConverter = null, private readonly ?NameConverterInterface $nameConverter = null, private array $defaultContext = [], private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null) { } @@ -234,40 +236,57 @@ private function getResourceContextWithShortname(string $resourceClass, int $ref $propertyNameCollectionContext = $serializerGroups ? ['serializer_groups' => $serializerGroups] : []; } + $propertyNames = []; foreach ($this->propertyNameCollectionFactory->create($resourceClass, $propertyNameCollectionContext) as $propertyName) { - $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $propertyContext); + $propertyNames[$propertyName] = true; + $this->addPropertyContext($context, $resourceClass, $propertyName, $shortName, $propertyContext); + } - if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) { - continue; + // The properties of the subtypes declared in the discriminator map of the resource are defined by their own class + foreach (null === $this->classDiscriminatorResolver ? [] : ClassDiscriminatorHelper::getSubtypes($this->classDiscriminatorResolver, $resourceClass) as $subtype) { + foreach ($this->propertyNameCollectionFactory->create($subtype, $propertyNameCollectionContext) as $propertyName) { + if (!isset($propertyNames[$propertyName])) { + $propertyNames[$propertyName] = true; + $this->addPropertyContext($context, $subtype, $propertyName, ClassDiscriminatorHelper::getShortName($subtype), $propertyContext); + } } + } - $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName; - $jsonldContext = $propertyMetadata->getJsonldContext() ?? []; + return $context; + } - if ($id = $propertyMetadata->getIris()) { - $id = 1 === (is_countable($id) ? \count($id) : 0) ? $id[0] : $id; - } + private function addPropertyContext(array &$context, string $resourceClass, string $propertyName, string $shortName, array $propertyContext): void + { + $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $propertyContext); - if (!$id) { - $id = \sprintf('%s/%s', $shortName, $convertedName); - } + if ($propertyMetadata->isIdentifier() && true !== $propertyMetadata->isWritable()) { + return; + } - if (false === $propertyMetadata->isReadableLink()) { - $jsonldContext += [ - '@id' => $id, - '@type' => '@id', - ]; - } + $convertedName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $resourceClass, self::FORMAT) : $propertyName; + $jsonldContext = $propertyMetadata->getJsonldContext() ?? []; - if (empty($jsonldContext)) { - $context[$convertedName] = $id; - } else { - $context[$convertedName] = $jsonldContext + [ - '@id' => $id, - ]; - } + if ($id = $propertyMetadata->getIris()) { + $id = 1 === (is_countable($id) ? \count($id) : 0) ? $id[0] : $id; } - return $context; + if (!$id) { + $id = \sprintf('%s/%s', $shortName, $convertedName); + } + + if (false === $propertyMetadata->isReadableLink()) { + $jsonldContext += [ + '@id' => $id, + '@type' => '@id', + ]; + } + + if (empty($jsonldContext)) { + $context[$convertedName] = $id; + } else { + $context[$convertedName] = $jsonldContext + [ + '@id' => $id, + ]; + } } } diff --git a/src/JsonLd/Serializer/ItemNormalizer.php b/src/JsonLd/Serializer/ItemNormalizer.php index e63202613f6..e512011aa45 100644 --- a/src/JsonLd/Serializer/ItemNormalizer.php +++ b/src/JsonLd/Serializer/ItemNormalizer.php @@ -24,6 +24,7 @@ use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Serializer\AbstractItemNormalizer; use ApiPlatform\Serializer\ContextTrait; @@ -130,7 +131,7 @@ public function normalize(mixed $data, ?string $format = null, array $context = return $normalizedData; } - if (!isset($metadata['@type']) && null !== ($type = $this->resolveType($resourceClass, $isResourceClass, $context))) { + if (!isset($metadata['@type']) && null !== ($type = $this->resolveType($data, $resourceClass, $isResourceClass, $context))) { $metadata['@type'] = $type; } @@ -140,7 +141,7 @@ public function normalize(mixed $data, ?string $format = null, array $context = /** * @return string|array|null */ - private function resolveType(string $resourceClass, bool $isResourceClass, array $context): string|array|null + private function resolveType(object $data, string $resourceClass, bool $isResourceClass, array $context): string|array|null { $operation = $context['operation'] ?? null; @@ -157,6 +158,11 @@ private function resolveType(string $resourceClass, bool $isResourceClass, array } $types = $operation instanceof HttpOperation ? $operation->getTypes() : null; + // A subtype declared in the discriminator map of the resource is typed by its own class, documented as a subclass of the resource + if (null === $types && $isResourceClass && null !== $discriminatedClass = $this->getDiscriminatedClass($data, $resourceClass)) { + return ClassDiscriminatorHelper::getShortName($discriminatedClass); + } + if (null === $types) { $typeClass = $isResourceClass ? $resourceClass : ($operation->getClass() ?? $resourceClass); if (isset($context['item_uri_template']) || $operation->getClass() === $typeClass) { diff --git a/src/JsonSchema/SchemaFactory.php b/src/JsonSchema/SchemaFactory.php index 6593e985870..fca5eb53bf1 100644 --- a/src/JsonSchema/SchemaFactory.php +++ b/src/JsonSchema/SchemaFactory.php @@ -22,7 +22,9 @@ use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\Metadata\Util\TypeHelper; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\TypeInfo\Type\BuiltinType; @@ -49,7 +51,7 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI public const OPENAPI_DEFINITION_NAME = 'openapi_definition_name'; public const PARTIAL_UPDATE = 'partial_update'; - public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null) + public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null, private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null) { if (!$definitionNameFactory) { $this->definitionNameFactory = new DefinitionNameFactory(); @@ -155,22 +157,138 @@ public function buildSchema(string $className, string $format = 'json', string $ } $options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups); - foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) { - $propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName, $options); + $this->buildDefinitionProperties($schema, $definition, $definitionName, $inputOrOutputClass, $options, $serializerContext, $format, $type, $isPartialUpdate); + + // Subtypes explicitly declared in a serializer discriminator map are documented using "oneOf" (and a "discriminator" in OpenAPI) + $this->buildDiscriminatedDefinitions($schema, $definition, $className, $inputOrOutputClass, $definitionFormat, $operation, $options, $serializerContext, $serializerContext + [ + 'schema_type' => $type, + self::PARTIAL_UPDATE => $isPartialUpdate && !$isJsonMergePatch, + ], $format, $type, $isPartialUpdate); + + return $schema; + } + + /** + * @param \ArrayObject $definition + */ + private function buildDefinitionProperties(Schema $schema, \ArrayObject $definition, string $definitionName, string $class, array $options, array $serializerContext, string $format, string $type, bool $isPartialUpdate): void + { + foreach ($this->propertyNameCollectionFactory->create($class, $options) as $propertyName) { + $propertyMetadata = $this->propertyMetadataFactory->create($class, $propertyName, $options); if (false === $propertyMetadata->isReadable() && false === $propertyMetadata->isWritable()) { continue; } - $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $inputOrOutputClass, $format, $serializerContext) : $propertyName; + $normalizedPropertyName = $this->nameConverter ? $this->nameConverter->normalize($propertyName, $class, $format, $serializerContext) : $propertyName; if ($propertyMetadata->isRequired() && !$isPartialUpdate) { $definition['required'][] = $normalizedPropertyName; } $this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type); } + } - return $schema; + /** + * @param \ArrayObject $definition + * @param array> $parentTypeProperties type properties of the outer discriminator maps the class belongs to + */ + private function buildDiscriminatedDefinitions(Schema $schema, \ArrayObject $definition, string $className, string $class, string $definitionFormat, ?Operation $operation, array $options, array $serializerContext, array $definitionNameContext, string $format, string $type, bool $isPartialUpdate, array $parentTypeProperties = []): void + { + if (null === $this->classDiscriminatorResolver || null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class)) { + return; + } + + $typeProperty = $mapping->getTypeProperty(); + $definitions = $schema->getDefinitions(); + $prefix = $this->getSchemaUriPrefix($schema->getVersion()); + $discriminatorMapping = []; + $oneOf = []; + + foreach (ClassDiscriminatorHelper::getDirectSubtypes($mapping, $class) as $typeValue => $subClass) { + $subDefinitionName = $this->definitionNameFactory->create($className, $definitionFormat, $subClass, $operation, $definitionNameContext); + $discriminatorMapping[$typeValue] = $oneOf[]['$ref'] = $prefix.$subDefinitionName; + + if (isset($definitions[$subDefinitionName])) { + continue; + } + + /** @var \ArrayObject $subDefinition */ + $subDefinition = new \ArrayObject(['type' => 'object']); + $definitions[$subDefinitionName] = $subDefinition; + if (isset($definition['additionalProperties'])) { + $subDefinition['additionalProperties'] = $definition['additionalProperties']; + } + + $this->buildDefinitionProperties($schema, $subDefinition, $subDefinitionName, $subClass, $options, $serializerContext, $format, $type, $isPartialUpdate); + + // The type properties of the outer maps are part of the payload of a nested subtype too + $typeProperties = $parentTypeProperties + [$typeProperty => ['type' => 'string', 'enum' => [(string) $typeValue]]]; + $this->addTypeProperties($subDefinition, $typeProperties, $isPartialUpdate); + + $this->buildDiscriminatedDefinitions($schema, $subDefinition, $className, $subClass, $definitionFormat, $operation, $options, $serializerContext, $definitionNameContext, $format, $type, $isPartialUpdate, $typeProperties); + } + + $ownTypeValues = ClassDiscriminatorHelper::getOwnTypes($mapping, $class); + foreach ($ownTypeValues as $typeValue) { + $discriminatorMapping[$typeValue] = $prefix.$this->definitionNameFactory->create($className, $definitionFormat, $class, $operation, $definitionNameContext); + } + + if (!$discriminatorMapping) { + return; + } + + if ($oneOf) { + // An instance of the class itself is described by its own branch: it carries its own type and none of the subtype properties + if ($ownTypeValues) { + $ownBranch = new \ArrayObject(['type' => 'object']); + foreach (['properties', 'required', 'additionalProperties'] as $keyword) { + if (isset($definition[$keyword])) { + $ownBranch[$keyword] = $definition[$keyword]; + } + } + + $this->addTypeProperties($ownBranch, [$typeProperty => ['type' => 'string', 'enum' => $ownTypeValues]], $isPartialUpdate || \in_array($mapping->getDefaultType(), $ownTypeValues, true)); + array_unshift($oneOf, $ownBranch->getArrayCopy()); + } + + $definition['oneOf'] = $oneOf; + + // Every branch carries the common properties: they are not repeated next to "oneOf" + // "additionalProperties" ignores the properties declared in the "oneOf" branches, they are restricted by the branches instead + unset($definition['properties'], $definition['required'], $definition['additionalProperties']); + } + + // An instance of the class itself carries its own type + if ($ownTypeValues && !$oneOf && !isset($definition['properties'][$typeProperty])) { + $this->addTypeProperties($definition, [$typeProperty => ['type' => 'string', 'enum' => $ownTypeValues]], $isPartialUpdate || \in_array($mapping->getDefaultType(), $ownTypeValues, true)); + } + + // "discriminator" is an OpenAPI keyword, plain JSON Schema relies on the "enum" of the type property in every branch + if (Schema::VERSION_OPENAPI === $schema->getVersion()) { + $definition['discriminator'] = ['propertyName' => $typeProperty, 'mapping' => $discriminatorMapping]; + } + } + + /** + * @param \ArrayObject $definition + * @param array> $typeProperties + */ + private function addTypeProperties(\ArrayObject $definition, array $typeProperties, bool $optional): void + { + $properties = $definition['properties'] ?? []; + $required = $definition['required'] ?? []; + foreach ($typeProperties as $name => $typePropertySchema) { + $properties[$name] = $typePropertySchema; + if (!$optional && !\in_array($name, $required, true)) { + $required[] = $name; + } + } + + $definition['properties'] = $properties; + if ($required) { + $definition['required'] = $required; + } } private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedAnimal.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedAnimal.php new file mode 100644 index 00000000000..783c723cef1 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedAnimal.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: 'species', mapping: ['cat' => DiscriminatedCat::class, 'dog' => DiscriminatedDog::class])] +abstract class DiscriminatedAnimal +{ + public string $name = ''; +} diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCat.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCat.php new file mode 100644 index 00000000000..ef4d9a91c41 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedCat.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator; + +final class DiscriminatedCat extends DiscriminatedAnimal +{ + public int $lives = 9; +} diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedDog.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedDog.php new file mode 100644 index 00000000000..547421bf54b --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedDog.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator; + +final class DiscriminatedDog extends DiscriminatedAnimal +{ + public bool $goodBoy = true; +} diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedGadget.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedGadget.php new file mode 100644 index 00000000000..038e31cf59c --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedGadget.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: 'kind', mapping: ['gadget' => DiscriminatedGadget::class, 'phone' => DiscriminatedPhone::class])] +class DiscriminatedGadget +{ + public string $name = ''; +} diff --git a/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedPhone.php b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedPhone.php new file mode 100644 index 00000000000..e5325c6f9b6 --- /dev/null +++ b/src/JsonSchema/Tests/Fixtures/Discriminator/DiscriminatedPhone.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator; + +final class DiscriminatedPhone extends DiscriminatedGadget +{ + public string $number = ''; +} diff --git a/src/JsonSchema/Tests/SchemaFactoryTest.php b/src/JsonSchema/Tests/SchemaFactoryTest.php index 56093795b2c..1aba5bce81d 100644 --- a/src/JsonSchema/Tests/SchemaFactoryTest.php +++ b/src/JsonSchema/Tests/SchemaFactoryTest.php @@ -19,6 +19,11 @@ use ApiPlatform\JsonSchema\Tests\Fixtures\ApiResource\ChildAttributeDummy; use ApiPlatform\JsonSchema\Tests\Fixtures\ApiResource\OverriddenOperationDummy; use ApiPlatform\JsonSchema\Tests\Fixtures\ApiResource\ParentAttributeDummy; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedAnimal; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedCat; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedDog; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedGadget; +use ApiPlatform\JsonSchema\Tests\Fixtures\Discriminator\DiscriminatedPhone; use ApiPlatform\JsonSchema\Tests\Fixtures\DummyResourceInterface; use ApiPlatform\JsonSchema\Tests\Fixtures\Enum\GenderTypeEnum; use ApiPlatform\JsonSchema\Tests\Fixtures\GenericChild; @@ -42,6 +47,9 @@ use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; +use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; +use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\TypeInfo\Type; @@ -484,6 +492,115 @@ public function testBuildSchemaForAssociativeArray(): void $this->assertSame('string', $definitions[$rootDefinitionKey]['properties']['bar']['additionalProperties']); } + public function testBuildSchemaDocumentsDiscriminatorMapSubtypes(): void + { + $schemaFactory = $this->createDiscriminatorSchemaFactory(); + $schema = $schemaFactory->buildSchema(DiscriminatedAnimal::class, 'json', Schema::TYPE_OUTPUT, null, new Schema(Schema::VERSION_OPENAPI)); + $definitions = $schema->getDefinitions(); + + $base = $definitions['DiscriminatedAnimal']; + $this->assertArrayNotHasKey('properties', $base); + $this->assertSame([ + ['$ref' => '#/components/schemas/DiscriminatedAnimal.DiscriminatedCat'], + ['$ref' => '#/components/schemas/DiscriminatedAnimal.DiscriminatedDog'], + ], $base['oneOf']); + $this->assertSame([ + 'propertyName' => 'species', + 'mapping' => [ + 'cat' => '#/components/schemas/DiscriminatedAnimal.DiscriminatedCat', + 'dog' => '#/components/schemas/DiscriminatedAnimal.DiscriminatedDog', + ], + ], $base['discriminator']); + + $cat = $definitions['DiscriminatedAnimal.DiscriminatedCat']; + $this->assertSame(['lives', 'name', 'species'], array_keys($cat['properties'])); + $this->assertSame(['type' => 'string', 'enum' => ['cat']], $cat['properties']['species']); + $this->assertSame(['species'], $cat['required']); + $this->assertArrayNotHasKey('allOf', $cat); + + $dog = $definitions['DiscriminatedAnimal.DiscriminatedDog']; + $this->assertSame(['goodBoy', 'name', 'species'], array_keys($dog['properties'])); + $this->assertSame(['type' => 'string', 'enum' => ['dog']], $dog['properties']['species']); + } + + public function testBuildJsonSchemaDocumentsDiscriminatorMapSubtypesWithoutOpenApiDiscriminator(): void + { + $definitions = $this->createDiscriminatorSchemaFactory()->buildSchema(DiscriminatedAnimal::class)->getDefinitions(); + + $this->assertSame([ + ['$ref' => '#/definitions/DiscriminatedAnimal.DiscriminatedCat'], + ['$ref' => '#/definitions/DiscriminatedAnimal.DiscriminatedDog'], + ], $definitions['DiscriminatedAnimal']['oneOf']); + $this->assertArrayNotHasKey('discriminator', $definitions['DiscriminatedAnimal']); + $this->assertSame(['type' => 'string', 'enum' => ['cat']], $definitions['DiscriminatedAnimal.DiscriminatedCat']['properties']['species']); + } + + public function testBuildSchemaDocumentsClassDeclaredInItsOwnDiscriminatorMap(): void + { + $schemaFactory = $this->createDiscriminatorSchemaFactory(); + $schema = $schemaFactory->buildSchema(DiscriminatedGadget::class, 'json', Schema::TYPE_INPUT, null, new Schema(Schema::VERSION_OPENAPI), [AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false]); + $definitions = $schema->getDefinitions(); + $rootDefinitionKey = $schema->getRootDefinitionKey(); + + $base = $definitions[$rootDefinitionKey]; + $this->assertArrayNotHasKey('properties', $base); + $this->assertArrayNotHasKey('additionalProperties', $base); + $this->assertSame([ + 'type' => 'object', + 'properties' => [ + 'name' => ['type' => 'string'], + 'kind' => ['type' => 'string', 'enum' => ['gadget']], + ], + 'additionalProperties' => false, + 'required' => ['kind'], + ], json_decode(json_encode($base['oneOf'][0]), true)); + $this->assertSame(['$ref' => '#/components/schemas/'.$rootDefinitionKey.'.DiscriminatedPhone'], $base['oneOf'][1]); + $this->assertSame('#/components/schemas/'.$rootDefinitionKey, $base['discriminator']['mapping']['gadget']); + + $phone = $definitions[$rootDefinitionKey.'.DiscriminatedPhone']; + $this->assertSame(['type' => 'string', 'enum' => ['phone']], $phone['properties']['kind']); + $this->assertFalse($phone['additionalProperties']); + } + + public function testBuildSchemaWithoutClassDiscriminatorResolverIgnoresDiscriminatorMap(): void + { + $schemaFactory = $this->createDiscriminatorSchemaFactory(false); + $definitions = $schemaFactory->buildSchema(DiscriminatedAnimal::class)->getDefinitions(); + + $this->assertSame(['DiscriminatedAnimal'], array_keys($definitions->getArrayCopy())); + $this->assertArrayNotHasKey('oneOf', $definitions['DiscriminatedAnimal']); + $this->assertArrayNotHasKey('discriminator', $definitions['DiscriminatedAnimal']); + } + + private function createDiscriminatorSchemaFactory(bool $withClassDiscriminatorResolver = true): SchemaFactory + { + $propertyNames = [ + DiscriminatedAnimal::class => ['name'], + DiscriminatedCat::class => ['lives', 'name'], + DiscriminatedDog::class => ['goodBoy', 'name'], + DiscriminatedGadget::class => ['name'], + DiscriminatedPhone::class => ['name', 'number'], + ]; + $propertyNameCollectionFactory = $this->createStub(PropertyNameCollectionFactoryInterface::class); + $propertyNameCollectionFactory->method('create')->willReturnCallback(static fn (string $class): PropertyNameCollection => new PropertyNameCollection($propertyNames[$class])); + + $schemas = ['name' => [Type::string(), 'string'], 'lives' => [Type::int(), 'integer'], 'number' => [Type::string(), 'string'], 'goodBoy' => [Type::bool(), 'boolean']]; + $propertyMetadataFactory = $this->createStub(PropertyMetadataFactoryInterface::class); + $propertyMetadataFactory->method('create')->willReturnCallback(static fn (string $class, string $property): ApiProperty => (new ApiProperty())->withNativeType($schemas[$property][0])->withReadable(true)->withWritable(true)->withSchema(['type' => $schemas[$property][1]])); + + $resourceClassResolver = $this->createStub(ResourceClassResolverInterface::class); + $resourceClassResolver->method('isResourceClass')->willReturn(false); + + return new SchemaFactory( + resourceMetadataFactory: $this->createStub(ResourceMetadataCollectionFactoryInterface::class), + propertyNameCollectionFactory: $propertyNameCollectionFactory, + propertyMetadataFactory: $propertyMetadataFactory, + resourceClassResolver: $resourceClassResolver, + definitionNameFactory: new DefinitionNameFactory(), + classDiscriminatorResolver: $withClassDiscriminatorResolver ? new ClassDiscriminatorFromClassMetadata(new ClassMetadataFactory(new AttributeLoader())) : null, + ); + } + public function testPartialUpdateRequiredPropertiesUseDistinctDefinitions(): void { $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index bf55f8c4ed0..2b152be6b36 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -217,6 +217,8 @@ use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Serializer\Encoder\CsvEncoder; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; @@ -312,6 +314,10 @@ public function register(): void ); }); + $this->app->singleton(ClassDiscriminatorResolverInterface::class, static function (Application $app) { + return new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)); + }); + $this->app->singleton(SerializerClassMetadataFactory::class, static function (Application $app) { return new SerializerClassMetadataFactory($app->make(ClassMetadataFactoryInterface::class)); }); @@ -713,7 +719,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(IriConverterInterface::class), $app->make(NameConverterInterface::class), - $defaultContext + $defaultContext, + self::getResourceClassDiscriminatorResolver($app), ); }); @@ -970,6 +977,7 @@ public function register(): void $app->make(NameConverterInterface::class), $app->make(ResourceClassResolverInterface::class), $app->make(DefinitionNameFactoryInterface::class), + self::getResourceClassDiscriminatorResolver($app), ); }); $this->app->singleton(JsonApiSchemaFactory::class, static function (Application $app) { @@ -980,6 +988,7 @@ public function register(): void $app->make(ResourceMetadataCollectionFactoryInterface::class), $app->make(DefinitionNameFactoryInterface::class), strictMemberNames: (bool) $app['config']->get('api-platform.jsonapi.strict_member_names', false), + classDiscriminatorResolver: self::getResourceClassDiscriminatorResolver($app), ); }); $this->app->singleton(HydraSchemaFactory::class, static function (Application $app) { @@ -1013,7 +1022,8 @@ public function register(): void $app->make(UrlGeneratorInterface::class), $app->make(NameConverterInterface::class), $defaultContext, - $entrypointEnabled + $entrypointEnabled, + self::getResourceClassDiscriminatorResolver($app), ); }); @@ -1690,4 +1700,12 @@ public function boot(): void $this->loadRoutesFrom(__DIR__.'/routes/api.php'); } + + /** + * Resource polymorphism through serializer discriminator maps is opt-in (api-platform.serializer.discriminator_map). + */ + private static function getResourceClassDiscriminatorResolver(Application $app): ?ClassDiscriminatorResolverInterface + { + return $app['config']->get('api-platform.serializer.discriminator_map', false) ? $app->make(ClassDiscriminatorResolverInterface::class) : null; + } } diff --git a/src/Laravel/config/api-platform.php b/src/Laravel/config/api-platform.php index 0f1ff2c4d75..d283788b1b3 100644 --- a/src/Laravel/config/api-platform.php +++ b/src/Laravel/config/api-platform.php @@ -192,6 +192,8 @@ 'serializer' => [ 'hydra_prefix' => false, + // Read, write and document the subtypes declared in the serializer discriminator map of a resource + 'discriminator_map' => false, // 'datetime_format' => \DateTimeInterface::RFC3339, ], diff --git a/src/Metadata/Tests/Fixtures/Discriminator/Car.php b/src/Metadata/Tests/Fixtures/Discriminator/Car.php new file mode 100644 index 00000000000..c42265beb53 --- /dev/null +++ b/src/Metadata/Tests/Fixtures/Discriminator/Car.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Fixtures\Discriminator; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +/** + * Concrete class declaring itself in its own map, which also (wrongly) lists an ancestor. + */ +#[DiscriminatorMap(typeProperty: 'body', mapping: ['car' => Car::class, 'sports' => SportsCar::class, 'vehicle' => Vehicle::class])] +class Car extends Vehicle +{ +} diff --git a/src/Metadata/Tests/Fixtures/Discriminator/Hatchback.php b/src/Metadata/Tests/Fixtures/Discriminator/Hatchback.php new file mode 100644 index 00000000000..c4a02cb5c79 --- /dev/null +++ b/src/Metadata/Tests/Fixtures/Discriminator/Hatchback.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Fixtures\Discriminator; + +/** + * Not declared in any discriminator map. + */ +final class Hatchback extends Car +{ +} diff --git a/src/Metadata/Tests/Fixtures/Discriminator/SportsCar.php b/src/Metadata/Tests/Fixtures/Discriminator/SportsCar.php new file mode 100644 index 00000000000..db0fc4b4744 --- /dev/null +++ b/src/Metadata/Tests/Fixtures/Discriminator/SportsCar.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Fixtures\Discriminator; + +final class SportsCar extends Car +{ +} diff --git a/src/Metadata/Tests/Fixtures/Discriminator/Truck.php b/src/Metadata/Tests/Fixtures/Discriminator/Truck.php new file mode 100644 index 00000000000..5cee8478ed1 --- /dev/null +++ b/src/Metadata/Tests/Fixtures/Discriminator/Truck.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Fixtures\Discriminator; + +final class Truck extends Vehicle +{ +} diff --git a/src/Metadata/Tests/Fixtures/Discriminator/Vehicle.php b/src/Metadata/Tests/Fixtures/Discriminator/Vehicle.php new file mode 100644 index 00000000000..4e81d33eddf --- /dev/null +++ b/src/Metadata/Tests/Fixtures/Discriminator/Vehicle.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Fixtures\Discriminator; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: 'kind', mapping: ['car' => Car::class, 'truck' => Truck::class])] +abstract class Vehicle +{ +} diff --git a/src/Metadata/Tests/Util/ClassDiscriminatorHelperTest.php b/src/Metadata/Tests/Util/ClassDiscriminatorHelperTest.php new file mode 100644 index 00000000000..5fb18cfa262 --- /dev/null +++ b/src/Metadata/Tests/Util/ClassDiscriminatorHelperTest.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Tests\Util; + +use ApiPlatform\Metadata\Tests\Fixtures\Discriminator\Car; +use ApiPlatform\Metadata\Tests\Fixtures\Discriminator\Hatchback; +use ApiPlatform\Metadata\Tests\Fixtures\Discriminator\SportsCar; +use ApiPlatform\Metadata\Tests\Fixtures\Discriminator\Truck; +use ApiPlatform\Metadata\Tests\Fixtures\Discriminator\Vehicle; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; +use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; + +final class ClassDiscriminatorHelperTest extends TestCase +{ + private ClassDiscriminatorFromClassMetadata $resolver; + + protected function setUp(): void + { + $this->resolver = new ClassDiscriminatorFromClassMetadata(new ClassMetadataFactory(new AttributeLoader())); + } + + public function testGetDirectSubtypesOnlyReturnsStrictSubclasses(): void + { + $mapping = new ClassDiscriminatorMapping('body', ['car' => Car::class, 'sports' => SportsCar::class, 'vehicle' => Vehicle::class, 'truck' => Truck::class]); + + $this->assertSame(['sports' => SportsCar::class], ClassDiscriminatorHelper::getDirectSubtypes($mapping, Car::class)); + $this->assertSame(['car'], ClassDiscriminatorHelper::getOwnTypes($mapping, Car::class)); + } + + public function testGetSubtypesWalksNestedMaps(): void + { + $this->assertEqualsCanonicalizing([Car::class, SportsCar::class, Truck::class], ClassDiscriminatorHelper::getSubtypes($this->resolver, Vehicle::class)); + $this->assertSame([SportsCar::class], ClassDiscriminatorHelper::getSubtypes($this->resolver, Car::class)); + } + + public function testResolveTerminatesWhenANestedMapListsAnAncestor(): void + { + $resolved = ClassDiscriminatorHelper::resolve($this->resolver, Vehicle::class, Hatchback::class); + + $this->assertNotNull($resolved); + $this->assertSame(Car::class, $resolved['class']); + $this->assertSame(['kind', 'body'], $resolved['type_properties']); + } + + public function testResolveMostSpecificNestedSubtype(): void + { + $resolved = ClassDiscriminatorHelper::resolve($this->resolver, Vehicle::class, SportsCar::class); + + $this->assertNotNull($resolved); + $this->assertSame(SportsCar::class, $resolved['class']); + $this->assertSame(['kind', 'body'], $resolved['type_properties']); + } + + public function testResolveClassDeclaredInItsOwnMap(): void + { + $resolved = ClassDiscriminatorHelper::resolve($this->resolver, Car::class, Car::class); + + $this->assertNotNull($resolved); + $this->assertSame(Car::class, $resolved['class']); + $this->assertSame(['body'], $resolved['type_properties']); + } + + public function testResolveReturnsNullForAClassOutsideOfTheMaps(): void + { + $this->assertNull(ClassDiscriminatorHelper::resolve($this->resolver, Vehicle::class, Vehicle::class)); + $this->assertNull(ClassDiscriminatorHelper::resolve($this->resolver, Truck::class, Vehicle::class)); + $this->assertNull(ClassDiscriminatorHelper::resolve($this->resolver, \stdClass::class, \stdClass::class)); + } +} diff --git a/src/Metadata/Util/ClassDiscriminatorHelper.php b/src/Metadata/Util/ClassDiscriminatorHelper.php new file mode 100644 index 00000000000..5f7ec84a2c1 --- /dev/null +++ b/src/Metadata/Util/ClassDiscriminatorHelper.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Metadata\Util; + +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; + +/** + * Walks the (possibly nested) serializer discriminator maps of a class. + * + * Only strict subclasses declared in a map are considered as subtypes: walking down nested maps + * always descends the class hierarchy, which guarantees termination even with misconfigured maps. + * + * @internal + */ +final class ClassDiscriminatorHelper +{ + /** + * Returns the name identifying a subtype in JSON-LD (its type) and in the Hydra documentation. + */ + public static function getShortName(string $class): string + { + return false === ($position = strrpos($class, '\\')) ? $class : substr($class, $position + 1); + } + + /** + * Returns the subtypes declared in the given map of a class, indexed by their type value. + * + * @return array + */ + public static function getDirectSubtypes(ClassDiscriminatorMapping $mapping, string $class): array + { + $subtypes = []; + foreach ($mapping->getTypesMapping() as $typeValue => $typeClass) { + if ($typeClass !== $class && is_a($typeClass, $class, true)) { + $subtypes[(string) $typeValue] = $typeClass; + } + } + + return $subtypes; + } + + /** + * Returns the type values the given map assigns to the class itself. + * + * @return list + */ + public static function getOwnTypes(ClassDiscriminatorMapping $mapping, string $class): array + { + $types = []; + foreach ($mapping->getTypesMapping() as $typeValue => $typeClass) { + if ($typeClass === $class) { + $types[] = (string) $typeValue; + } + } + + return $types; + } + + /** + * Lists the subtypes declared, possibly through nested maps, in the discriminator map of a class. + * + * @return list + */ + public static function getSubtypes(ClassDiscriminatorResolverInterface $resolver, string $class): array + { + if (null === $mapping = $resolver->getMappingForClass($class)) { + return []; + } + + $subtypes = []; + foreach (self::getDirectSubtypes($mapping, $class) as $subtype) { + $subtypes[] = $subtype; + foreach (self::getSubtypes($resolver, $subtype) as $nestedSubtype) { + $subtypes[] = $nestedSubtype; + } + } + + return array_values(array_unique($subtypes)); + } + + /** + * Resolves the most specific class declared in the discriminator maps of a resource for the given class. + * + * Classes that are not part of a discriminator map resolve to their closest mapped parent. + * A class declaring itself in its own map carries the type property of that map too. + * + * @param class-string $resourceClass + * @param class-string $class + * + * @return array{class: class-string, type_properties: list, mappings: list}|null + */ + public static function resolve(ClassDiscriminatorResolverInterface $resolver, string $resourceClass, string $class): ?array + { + if (!is_a($class, $resourceClass, true)) { + return null; + } + + $mappedClass = $resourceClass; + $typeProperties = []; + $mappings = []; + while (null !== $mapping = $resolver->getMappingForClass($mappedClass)) { + $candidate = null; + foreach (self::getDirectSubtypes($mapping, $mappedClass) as $typeClass) { + if (is_a($class, $typeClass, true) && (null === $candidate || is_a($typeClass, $candidate, true))) { + $candidate = $typeClass; + } + } + + if (null === $candidate && !self::getOwnTypes($mapping, $mappedClass)) { + break; + } + + $typeProperties[] = $mapping->getTypeProperty(); + $mappings[] = $mapping; + if (null === $candidate) { + break; + } + + $mappedClass = $candidate; + } + + if (!$mappings) { + return null; + } + + return ['class' => $mappedClass, 'type_properties' => array_values(array_unique($typeProperties)), 'mappings' => $mappings]; + } +} diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index c08a967ad45..f388eeab686 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -26,6 +26,7 @@ use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; +use ApiPlatform\Metadata\Util\ClassDiscriminatorHelper; use ApiPlatform\Metadata\Util\ClassInfoTrait; use ApiPlatform\Metadata\Util\CloneTrait; use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException as PropertyAccessInvalidArgumentException; @@ -41,6 +42,8 @@ use Symfony\Component\Serializer\Exception\NotNormalizableValueException; use Symfony\Component\Serializer\Exception\RuntimeException; use Symfony\Component\Serializer\Exception\UnexpectedValueException; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; @@ -76,6 +79,12 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement */ public const SKIP_NULL_TO_ONE_RELATIONS = 'skip_null_to_one_relations'; + /** + * Default context flag exposing the subtypes declared in the serializer discriminator map of a resource + * (polymorphic resources): their properties are read and written. + */ + public const DISCRIMINATOR_MAP = 'discriminator_map'; + protected PropertyAccessorInterface $propertyAccessor; protected array $localCache = []; protected array $localFactoryOptionsCache = []; @@ -83,6 +92,20 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer implement protected array $attributesCache = []; protected ?ResourceAccessCheckerInterface $resourceAccessChecker; + /** + * The class discriminator resolver, only set when resource polymorphism is enabled. + */ + private ?ClassDiscriminatorResolverInterface $resourceDiscriminatorResolver = null; + + /** @var array, mappings: list}|null> */ + private array $discriminatorMappingCache = []; + + /** @var array> */ + private array $discriminatorTypeMappingsCache = []; + + /** @var array */ + private array $discriminatorTypePropertyCache = []; + public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected IriConverterInterface $iriConverter, protected ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null, protected ?OperationResourceClassResolverInterface $operationResourceResolver = null) { if (!isset($defaultContext['circular_reference_handler'])) { @@ -93,6 +116,9 @@ public function __construct(protected PropertyNameCollectionFactoryInterface $pr $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor(); $this->resourceAccessChecker = $resourceAccessChecker; $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory; + if ($defaultContext[self::DISCRIMINATOR_MAP] ?? false) { + $this->resourceDiscriminatorResolver = $this->classDiscriminatorResolver; + } } /** @@ -269,7 +295,12 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a // An IRI references an existing resource, its type is resolved when it is retrieved if (null === ($objectToPopulate = $this->extractObjectToPopulate($resourceClass, $context, static::OBJECT_TO_POPULATE)) && !\is_string($data)) { $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data); - $type = $this->getClassDiscriminatorResolvedClass($normalizedData, $type, $context); + // With resource polymorphism, nested discriminator maps are resolved down to the most specific class + $resolvedTypes = []; + do { + $resolvedTypes[$type] = true; + $type = $this->getClassDiscriminatorResolvedClass($normalizedData, $type, $context); + } while (null !== $this->resourceDiscriminatorResolver && !isset($resolvedTypes[$type])); } $context['api_denormalize'] = true; @@ -277,6 +308,13 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a if ($this->resourceClassResolver->isResourceClass($type)) { $resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $type); $context['resource_class'] = $resourceClass; + + // A subtype declared in the serializer discriminator map of the resource is described by its own + // metadata: pin the resource class to it so its properties can be written. + if (\is_array($data) && null !== $discriminatorMapping = $this->getDiscriminatorMapping($resourceClass, null !== $objectToPopulate ? $this->getObjectClass($objectToPopulate) : $type)) { + $data = $this->prepareDiscriminatedData($data, $discriminatorMapping, $objectToPopulate, $type, $context); + $resourceClass = $context['resource_class'] = $discriminatorMapping['class']; + } } elseif (($context['api_platform_input'] ?? false) && isset($context['resource_class'])) { // A discriminated input DTO base (not itself a resource) resolves to a concrete // subclass here: pin the resource class to that concrete class so constructor and @@ -510,6 +548,107 @@ protected function getClassDiscriminatorResolvedClass(array $data, string $class return $mappedClass; } + /** + * @return array{class: class-string, type_properties: list, mappings: list}|null + */ + private function getDiscriminatorMapping(string $resourceClass, string $class): ?array + { + if (null === $this->resourceDiscriminatorResolver) { + return null; + } + + $cacheKey = $resourceClass.'|'.$class; + if (!\array_key_exists($cacheKey, $this->discriminatorMappingCache)) { + $this->discriminatorMappingCache[$cacheKey] = ClassDiscriminatorHelper::resolve($this->resourceDiscriminatorResolver, $resourceClass, $class); + } + + return $this->discriminatorMappingCache[$cacheKey]; + } + + /** + * Returns the most specific class declared in the discriminator maps of the resource for the given object, + * when it differs from the resource class. + * + * @internal + */ + protected function getDiscriminatedClass(object $object, string $resourceClass): ?string + { + $class = $this->getDiscriminatorMapping($resourceClass, $this->getObjectClass($object))['class'] ?? null; + + return $class !== $resourceClass ? $class : null; + } + + /** + * @param array{class: class-string, type_properties: list, mappings: list} $discriminatorMapping + */ + private function prepareDiscriminatedData(array $data, array $discriminatorMapping, ?object $objectToPopulate, string $type, array $context): array + { + // A class declaring its own map is resolved again by the Symfony serializer, which reads the type property of that map + $resolvedTypeProperty = null === $objectToPopulate ? $this->resourceDiscriminatorResolver?->getMappingForClass($type)?->getTypeProperty() : null; + foreach ($discriminatorMapping['mappings'] as $mapping) { + $typeProperty = $mapping->getTypeProperty(); + if (!\array_key_exists($typeProperty, $data)) { + continue; + } + + // The type of an existing object cannot be changed + if (null !== $objectToPopulate && (!\is_string($data[$typeProperty]) || null === ($typeClass = $mapping->getClassForType($data[$typeProperty])) || $typeClass !== $this->getMostSpecificMappedClass($mapping, $objectToPopulate))) { + throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" does not match the type of the object being updated.', \is_scalar($data[$typeProperty]) ? $data[$typeProperty] : get_debug_type($data[$typeProperty])), $data[$typeProperty], ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$typeProperty : $typeProperty, true); + } + + // The type property is computed from the discriminator map, it is not a writable property of the object + if ($typeProperty !== $resolvedTypeProperty && !property_exists($discriminatorMapping['class'], $typeProperty)) { + unset($data[$typeProperty]); + } + } + + return $data; + } + + /** + * A map can list a class along with its own subclasses: the object is only of the most specific one. + */ + private function getMostSpecificMappedClass(ClassDiscriminatorMapping $mapping, object $object): ?string + { + $mostSpecificClass = null; + foreach ($mapping->getTypesMapping() as $class) { + if ($object instanceof $class && (null === $mostSpecificClass || is_a($class, $mostSpecificClass, true))) { + $mostSpecificClass = $class; + } + } + + return $mostSpecificClass; + } + + private function getDiscriminatorTypeValue(object $object, string $attribute, string $resourceClass): ?string + { + if (null === $this->resourceDiscriminatorResolver) { + return null; + } + + $class = $this->getObjectClass($object); + $typeMappings = $this->discriminatorTypeMappingsCache[$resourceClass.'|'.$class] ??= $this->getDiscriminatorTypeMappings($resourceClass, $class); + + return isset($typeMappings[$attribute]) ? $typeMappings[$attribute]->getMappedObjectType($object) : null; + } + + /** + * @return array the discriminator maps of the resource the class belongs to, indexed by type property + */ + private function getDiscriminatorTypeMappings(string $resourceClass, string $class): array + { + if (!$this->resourceClassResolver->isResourceClass($resourceClass)) { + return []; + } + + $typeMappings = []; + foreach ($this->getDiscriminatorMapping($this->resourceClassResolver->getResourceClass(null, $resourceClass), $class)['mappings'] ?? [] as $mapping) { + $typeMappings[$mapping->getTypeProperty()] ??= $mapping; + } + + return $typeMappings; + } + protected function createConstructorArgument(mixed $parameterData, string $key, \ReflectionParameter $constructorParameter, array $context, ?string $format = null): mixed { return $this->createAndValidateAttributeValue($constructorParameter->name, $parameterData, $format, $context); @@ -537,6 +676,12 @@ protected function getAllowedAttributes(string|object $classOrObject, array $con } $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']); // fix for abstract classes and interfaces + // Subtypes are only exposed when they are explicitly declared in the serializer discriminator map of the resource + $discriminatorMapping = $this->getDiscriminatorMapping($resourceClass, $context['resource_class']); + if (null !== $discriminatorMapping) { + $resourceClass = $discriminatorMapping['class']; + } + $options = $this->getFactoryOptions($context); $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options); @@ -554,6 +699,20 @@ protected function getAllowedAttributes(string|object $classOrObject, array $con } } + // The type property is always part of a discriminated output, its value is computed from the discriminator map + if (null !== $discriminatorMapping && isset($context['api_normalize'])) { + foreach ($discriminatorMapping['type_properties'] as $typeProperty) { + if (!\in_array($typeProperty, $allowedAttributes, true) && $this->isAllowedAttribute($classOrObject, $typeProperty, null, $context)) { + array_unshift($allowedAttributes, $typeProperty); + } + } + } + + // The type property of the map declared by the class being created is read by the serializer to resolve the class + if (isset($context['api_denormalize']) && \is_string($classOrObject) && null !== ($typeProperty = $this->resourceDiscriminatorResolver?->getMappingForClass($classOrObject)?->getTypeProperty()) && !\in_array($typeProperty, $allowedAttributes, true)) { + $allowedAttributes[] = $typeProperty; + } + return $allowedAttributes; } @@ -636,14 +795,14 @@ protected function isCacheKeySafe(array $context): bool return $this->safeCacheKeysCache[$cacheKey]; } - $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options); - $this->safeCacheKeysCache[$cacheKey] = true; - foreach ($propertyNames as $propertyName) { - $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options); - if (null !== ($propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy())) { - $this->safeCacheKeysCache[$cacheKey] = false; - break; + // Subtypes declared in the discriminator map of the resource are exposed too, their properties must be checked as well + foreach ([$resourceClass, ...(null === $this->resourceDiscriminatorResolver ? [] : ClassDiscriminatorHelper::getSubtypes($this->resourceDiscriminatorResolver, $resourceClass))] as $class) { + foreach ($this->propertyNameCollectionFactory->create($class, $options) as $propertyName) { + $propertyMetadata = $this->propertyMetadataFactory->create($class, $propertyName, $options); + if (null !== ($propertyMetadata->getSecurity() ?? $propertyMetadata->getPolicy())) { + return $this->safeCacheKeysCache[$cacheKey] = false; + } } } @@ -674,6 +833,11 @@ protected function canAccessAttributePostDenormalize(?object $object, ?object $p */ protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void { + // The type property is computed from the discriminator map, it is not a writable property of the object + if (null !== $this->resourceDiscriminatorResolver && $attribute === ($this->discriminatorTypePropertyCache[$this->getObjectClass($object)] ??= $this->resourceDiscriminatorResolver->getMappingForMappedObject($object)?->getTypeProperty() ?? false) && !property_exists($object, $attribute)) { + return; + } + // symfony/serializer only reads the current value of typed attributes (https://github.com/symfony/symfony/pull/67883), and it can't type them here if (!isset($context[static::OBJECT_TO_POPULATE]) && ($context[static::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[static::DEEP_OBJECT_TO_POPULATE] ?? false) @@ -883,6 +1047,11 @@ protected function getFactoryOptions(array $context): array */ protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed { + // Symfony only computes the type property of the innermost discriminator map, compute those of the outer ones + if (!($context['api_denormalize'] ?? false) && isset($context['resource_class']) && null !== $typeValue = $this->getDiscriminatorTypeValue($object, $attribute, $context['resource_class'])) { + return $typeValue; + } + $context['api_attribute'] = $attribute; $context['property_metadata'] = $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context)); diff --git a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php index 52531dfb23f..2976d25e0a9 100644 --- a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php @@ -59,6 +59,7 @@ use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\OpenApi\Model\Tag; use ApiPlatform\RamseyUuid\Serializer\UuidDenormalizer; +use ApiPlatform\Serializer\AbstractItemNormalizer; use ApiPlatform\State\ApiResource\Error; use ApiPlatform\State\ParameterProviderInterface; use ApiPlatform\State\ProcessorInterface; @@ -346,7 +347,16 @@ private function registerCommonConfiguration(ContainerBuilder $container, array $container->setDefinition('serializer.normalizer.number', $numberNormalizerDefinition); } - $defaultContext = ['hydra_prefix' => $config['serializer']['hydra_prefix']] + ($container->hasParameter('serializer.default_context') ? $container->getParameter('serializer.default_context') : []); + // Doctrine discriminator maps are exposed as serializer discriminator maps: they need resource polymorphism + $discriminatorMap = $config['serializer']['discriminator_map'] + || ($this->isConfigEnabled($container, $config['doctrine']) && $config['doctrine']['discriminator_map']) + || ($this->isConfigEnabled($container, $config['doctrine_mongodb_odm']) && $config['doctrine_mongodb_odm']['discriminator_map']); + $container->setParameter('api_platform.serializer.discriminator_map', $discriminatorMap); + if ($discriminatorMap) { + $container->setAlias('api_platform.serializer.class_discriminator_resolver', 'serializer.mapping.class_discriminator_resolver'); + } + + $defaultContext = ['hydra_prefix' => $config['serializer']['hydra_prefix'], AbstractItemNormalizer::DISCRIMINATOR_MAP => $discriminatorMap] + ($container->hasParameter('serializer.default_context') ? $container->getParameter('serializer.default_context') : []); $container->setParameter('api_platform.serializer.default_context', $defaultContext); if (!$container->hasParameter('serializer.default_context')) { @@ -725,7 +735,7 @@ private function registerJsonApiConfiguration(ContainerBuilder $container, array $itemNormalizer->replaceArgument(7, [ JsonApiItemNormalizer::ALLOW_CLIENT_GENERATED_ID => $config['jsonapi']['allow_client_generated_id'] ?? false, JsonApiItemNormalizer::STRICT_RESOURCE_TYPE => $config['jsonapi']['strict_resource_type'] ?? false, - ]); + ] + $itemNormalizer->getArgument(7)); $itemNormalizer->addArgument($useIriAsId); $itemNormalizer->addArgument(new Reference('api_platform.jsonapi.resource_linkage_resolver')); @@ -733,7 +743,7 @@ private function registerJsonApiConfiguration(ContainerBuilder $container, array $itemDenormalizer->replaceArgument(7, [ JsonApiItemNormalizer::ALLOW_CLIENT_GENERATED_ID => $config['jsonapi']['allow_client_generated_id'] ?? false, JsonApiItemNormalizer::STRICT_RESOURCE_TYPE => $config['jsonapi']['strict_resource_type'] ?? false, - ]); + ] + $itemDenormalizer->getArgument(7)); $itemDenormalizer->addArgument($useIriAsId); } @@ -864,6 +874,10 @@ private function registerDoctrineOrmConfiguration(ContainerBuilder $container, a $loader->load('graphql/doctrine_orm.php'); } + if (!$config['doctrine']['discriminator_map']) { + $container->removeDefinition('api_platform.doctrine.orm.serializer.discriminator_mapping_loader'); + } + if ($this->isConfigEnabled($container, $config['eager_loading'])) { return; } @@ -898,6 +912,10 @@ private function registerDoctrineMongoDbOdmConfiguration(ContainerBuilder $conta if ($this->isConfigEnabled($container, $config['graphql'])) { $loader->load('graphql/doctrine_mongodb_odm.php'); } + + if (!$config['doctrine_mongodb_odm']['discriminator_map']) { + $container->removeDefinition('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader'); + } } private function registerHttpCacheConfiguration(ContainerBuilder $container, array $config, PhpFileLoader $loader): void diff --git a/src/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPass.php b/src/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPass.php index 7a9cc0d5c1d..0ba7267ada4 100644 --- a/src/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPass.php +++ b/src/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPass.php @@ -15,6 +15,8 @@ use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\Serializer\Mapping\Loader\LoaderChain; final class SerializerMappingLoaderPass implements CompilerPassInterface { @@ -22,7 +24,20 @@ public function process(ContainerBuilder $container): void { $chainLoader = $container->getDefinition('serializer.mapping.chain_loader'); $loaders = $chainLoader->getArgument(0); - $loaders[] = $container->getDefinition('api_platform.serializer.property_metadata_loader'); - $container->getDefinition('serializer.mapping.cache_warmer')->replaceArgument(0, $loaders); + $warmerLoaders = [...$loaders, $container->getDefinition('api_platform.serializer.property_metadata_loader')]; + + // Doctrine discriminator maps are loaded last so explicit serializer maps take precedence + foreach (['api_platform.doctrine.orm.serializer.discriminator_mapping_loader', 'api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader'] as $id) { + if ($container->hasDefinition($id)) { + $loader = $container->getDefinition($id); + // The explicit serializer loaders (attributes, XML, YAML) tell whether a class of the hierarchy declares its own map + $loader->setArgument('$serializerLoader', new Definition(LoaderChain::class, [$loaders])); + $chainLoader->replaceArgument(0, [...$chainLoader->getArgument(0), $loader]); + // The warmer builds the final metadata of the classes mapped by the other loaders: without the Doctrine map they would lose their subtypes + $warmerLoaders[] = $loader; + } + } + + $container->getDefinition('serializer.mapping.cache_warmer')->replaceArgument(0, $warmerLoaders); } } diff --git a/src/Symfony/Bundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/DependencyInjection/Configuration.php index a65e60f9d10..1a151c7993d 100644 --- a/src/Symfony/Bundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/DependencyInjection/Configuration.php @@ -173,6 +173,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->addDefaultsIfNotSet() ->children() ->booleanNode('hydra_prefix')->defaultFalse()->info('Use the "hydra:" prefix.')->end() + ->booleanNode('discriminator_map')->defaultFalse()->info('Expose the subtypes declared in the serializer discriminator map of a resource (polymorphic resources): subtype properties are readable, writable and documented. Always enabled when "doctrine.discriminator_map" or "doctrine_mongodb_odm.discriminator_map" is.')->end() ->end() ->end() ->end(); @@ -236,6 +237,12 @@ private function addDoctrineOrmSection(ArrayNodeDefinition $rootNode): void ->children() ->arrayNode('doctrine') ->{class_exists(DoctrineBundle::class) && interface_exists(EntityManagerInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}() + ->children() + ->booleanNode('discriminator_map') + ->defaultFalse() + ->info('Expose the subtypes declared in the Doctrine ORM discriminator map of a resource as a serializer discriminator map (polymorphic resources): mapped subclass properties are exposed and writable. An explicit serializer discriminator map always takes precedence.') + ->end() + ->end() ->end() ->end(); } @@ -246,6 +253,12 @@ private function addDoctrineMongoDbOdmSection(ArrayNodeDefinition $rootNode): vo ->children() ->arrayNode('doctrine_mongodb_odm') ->{class_exists(DoctrineMongoDBBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}() + ->children() + ->booleanNode('discriminator_map') + ->defaultFalse() + ->info('Expose the subtypes declared in the Doctrine MongoDB ODM discriminator map of a resource as a serializer discriminator map (polymorphic resources): mapped subclass properties are exposed and writable. An explicit serializer discriminator map always takes precedence.') + ->end() + ->end() ->end() ->end(); } diff --git a/src/Symfony/Bundle/Resources/config/api.php b/src/Symfony/Bundle/Resources/config/api.php index 65bfb38c5f1..30a49d3a651 100644 --- a/src/Symfony/Bundle/Resources/config/api.php +++ b/src/Symfony/Bundle/Resources/config/api.php @@ -172,7 +172,7 @@ null, service('api_platform.metadata.resource.metadata_collection_factory')->ignoreOnInvalid(), service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), - [], + ['discriminator_map' => '%api_platform.serializer.discriminator_map%'], service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) @@ -191,7 +191,7 @@ null, service('api_platform.metadata.resource.metadata_collection_factory')->ignoreOnInvalid(), service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), - [], + ['discriminator_map' => '%api_platform.serializer.discriminator_map%'], service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), service('api_platform.serializer.operation_resource_resolver'), ]) diff --git a/src/Symfony/Bundle/Resources/config/doctrine_mongodb_odm.php b/src/Symfony/Bundle/Resources/config/doctrine_mongodb_odm.php index 8e7625bf4af..e38210c8550 100644 --- a/src/Symfony/Bundle/Resources/config/doctrine_mongodb_odm.php +++ b/src/Symfony/Bundle/Resources/config/doctrine_mongodb_odm.php @@ -14,6 +14,7 @@ namespace Symfony\Component\DependencyInjection\Loader\Configurator; use ApiPlatform\Doctrine\Common\Metadata\Property\DoctrineDiscriminatorSerializerPropertyMetadataFactory; +use ApiPlatform\Doctrine\Common\Serializer\Mapping\Loader\DoctrineDiscriminatorMappingLoader; use ApiPlatform\Doctrine\Common\State\PersistProcessor; use ApiPlatform\Doctrine\Common\State\RemoveProcessor; use ApiPlatform\Doctrine\Odm\Extension\FilterExtension; @@ -196,6 +197,12 @@ service('api_platform.doctrine_mongodb.odm.metadata.property.metadata_factory.inner'), ]); + $services->set('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader', DoctrineDiscriminatorMappingLoader::class) + ->args([ + service('doctrine_mongodb'), + service('api_platform.resource_class_resolver'), + ]); + $services->set('api_platform.doctrine_mongodb.odm.metadata.property.metadata_factory.discriminator_serializer', DoctrineDiscriminatorSerializerPropertyMetadataFactory::class) ->decorate('api_platform.metadata.property.metadata_factory', null, 31) ->args([ diff --git a/src/Symfony/Bundle/Resources/config/doctrine_orm.php b/src/Symfony/Bundle/Resources/config/doctrine_orm.php index 13806ccf0fb..a3f6f8bf1a6 100644 --- a/src/Symfony/Bundle/Resources/config/doctrine_orm.php +++ b/src/Symfony/Bundle/Resources/config/doctrine_orm.php @@ -14,6 +14,7 @@ namespace Symfony\Component\DependencyInjection\Loader\Configurator; use ApiPlatform\Doctrine\Common\Metadata\Property\DoctrineDiscriminatorSerializerPropertyMetadataFactory; +use ApiPlatform\Doctrine\Common\Serializer\Mapping\Loader\DoctrineDiscriminatorMappingLoader; use ApiPlatform\Doctrine\Common\State\PersistProcessor; use ApiPlatform\Doctrine\Common\State\RemoveProcessor; use ApiPlatform\Doctrine\Orm\Extension\EagerLoadingExtension; @@ -214,6 +215,12 @@ service('api_platform.doctrine.orm.metadata.property.metadata_factory.inner'), ]); + $services->set('api_platform.doctrine.orm.serializer.discriminator_mapping_loader', DoctrineDiscriminatorMappingLoader::class) + ->args([ + service('doctrine'), + service('api_platform.resource_class_resolver'), + ]); + $services->set('api_platform.doctrine.orm.metadata.property.metadata_factory.discriminator_serializer', DoctrineDiscriminatorSerializerPropertyMetadataFactory::class) ->decorate('api_platform.metadata.property.metadata_factory', null, 31) ->args([ diff --git a/src/Symfony/Bundle/Resources/config/hal.php b/src/Symfony/Bundle/Resources/config/hal.php index b94f88b30a1..ae5b1ff8b4c 100644 --- a/src/Symfony/Bundle/Resources/config/hal.php +++ b/src/Symfony/Bundle/Resources/config/hal.php @@ -60,7 +60,7 @@ service('api_platform.property_accessor'), service('api_platform.name_converter')->ignoreOnInvalid(), service('serializer.mapping.class_metadata_factory')->ignoreOnInvalid(), - [], + ['discriminator_map' => '%api_platform.serializer.discriminator_map%'], service('api_platform.metadata.resource.metadata_collection_factory')->ignoreOnInvalid(), service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), diff --git a/src/Symfony/Bundle/Resources/config/hydra.php b/src/Symfony/Bundle/Resources/config/hydra.php index 1ce0d98c9d5..acec80bf1bf 100644 --- a/src/Symfony/Bundle/Resources/config/hydra.php +++ b/src/Symfony/Bundle/Resources/config/hydra.php @@ -45,6 +45,7 @@ service('api_platform.name_converter')->ignoreOnInvalid(), '%api_platform.serializer.default_context%', '%api_platform.enable_entrypoint%', + service('api_platform.serializer.class_discriminator_resolver')->ignoreOnInvalid(), ]) ->tag('serializer.normalizer', ['priority' => -800]); diff --git a/src/Symfony/Bundle/Resources/config/json_schema.php b/src/Symfony/Bundle/Resources/config/json_schema.php index b1a21cf8c1f..d2228da3db4 100644 --- a/src/Symfony/Bundle/Resources/config/json_schema.php +++ b/src/Symfony/Bundle/Resources/config/json_schema.php @@ -31,6 +31,7 @@ service('api_platform.name_converter')->ignoreOnInvalid(), service('api_platform.resource_class_resolver'), service('api_platform.json_schema.definition_name_factory')->ignoreOnInvalid(), + service('api_platform.serializer.class_discriminator_resolver')->ignoreOnInvalid(), ]); $services->alias(SchemaFactoryInterface::class, 'api_platform.json_schema.schema_factory'); diff --git a/src/Symfony/Bundle/Resources/config/jsonapi.php b/src/Symfony/Bundle/Resources/config/jsonapi.php index 0b2d4b1c760..be103d16f90 100644 --- a/src/Symfony/Bundle/Resources/config/jsonapi.php +++ b/src/Symfony/Bundle/Resources/config/jsonapi.php @@ -43,6 +43,7 @@ service('api_platform.json_schema.definition_name_factory')->ignoreOnInvalid(), service('api_platform.jsonapi.resource_linkage_resolver'), false, + service('api_platform.serializer.class_discriminator_resolver')->ignoreOnInvalid(), ]); $services->set('api_platform.jsonapi.encoder', JsonEncoder::class) @@ -77,7 +78,7 @@ service('api_platform.property_accessor'), service('api_platform.jsonapi.name_converter.reserved_attribute_name'), service('serializer.mapping.class_metadata_factory')->ignoreOnInvalid(), - [], + ['discriminator_map' => '%api_platform.serializer.discriminator_map%'], service('api_platform.metadata.resource.metadata_collection_factory'), service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), @@ -96,7 +97,7 @@ service('api_platform.property_accessor'), service('api_platform.jsonapi.name_converter.reserved_attribute_name'), service('serializer.mapping.class_metadata_factory')->ignoreOnInvalid(), - [], + ['discriminator_map' => '%api_platform.serializer.discriminator_map%'], service('api_platform.metadata.resource.metadata_collection_factory'), service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(), diff --git a/src/Symfony/Bundle/Resources/config/jsonld.php b/src/Symfony/Bundle/Resources/config/jsonld.php index 368295f0ea8..8162fb565e6 100644 --- a/src/Symfony/Bundle/Resources/config/jsonld.php +++ b/src/Symfony/Bundle/Resources/config/jsonld.php @@ -34,6 +34,7 @@ service('api_platform.symfony.iri_converter.skolem'), service('api_platform.name_converter'), '%api_platform.serializer.default_context%', + service('api_platform.serializer.class_discriminator_resolver')->ignoreOnInvalid(), ]); $services->set('api_platform.jsonld.normalizer.item', ItemNormalizer::class) diff --git a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php index 8f80ae8e788..52179869e13 100644 --- a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php +++ b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php @@ -643,4 +643,49 @@ public function testHttpCachePurgeListenerRegisteredForMongoDbOdmWhenInvalidatio $tags = $this->container->getDefinition('api_platform.doctrine_mongodb.odm.listener.http_cache.purge')->getTags(); $this->assertSame([['event' => 'onFlush'], ['event' => 'postFlush']], $tags['doctrine_mongodb.odm.event_listener']); } + + public function testDoctrineDiscriminatorMappingLoadersAreNotRegisteredByDefault(): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform']['doctrine']['enabled'] = true; + $config['api_platform']['doctrine_mongodb_odm']['enabled'] = true; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertContainerHasService('api_platform.doctrine.orm.state.item_provider'); + $this->assertNotContainerHasService('api_platform.doctrine.orm.serializer.discriminator_mapping_loader'); + $this->assertContainerHasService('api_platform.doctrine_mongodb.odm.state.item_provider'); + $this->assertNotContainerHasService('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader'); + } + + public function testDoctrineDiscriminatorMappingLoadersCanBeEnabled(): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform']['doctrine'] = ['enabled' => true, 'discriminator_map' => true]; + $config['api_platform']['doctrine_mongodb_odm'] = ['enabled' => true, 'discriminator_map' => true]; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertContainerHasService('api_platform.doctrine.orm.serializer.discriminator_mapping_loader'); + $this->assertContainerHasService('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader'); + // Doctrine discriminator maps need resource polymorphism + $this->assertTrue($this->container->getParameter('api_platform.serializer.discriminator_map')); + } + + public function testResourcePolymorphismIsDisabledByDefault(): void + { + (new ApiPlatformExtension())->load(self::DEFAULT_CONFIG, $this->container); + + $this->assertFalse($this->container->getParameter('api_platform.serializer.discriminator_map')); + $this->assertFalse($this->container->getParameter('api_platform.serializer.default_context')['discriminator_map']); + $this->assertFalse($this->container->hasAlias('api_platform.serializer.class_discriminator_resolver')); + } + + public function testResourcePolymorphismCanBeEnabled(): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform']['serializer']['discriminator_map'] = true; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertTrue($this->container->getParameter('api_platform.serializer.default_context')['discriminator_map']); + $this->assertSame('serializer.mapping.class_discriminator_resolver', (string) $this->container->getAlias('api_platform.serializer.class_discriminator_resolver')); + } } diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedBike.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedBike.php new file mode 100644 index 00000000000..717c7597fde --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedBike.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: 'frame', mapping: [ + 'bike' => DiscriminatedBike::class, + 'mountain' => DiscriminatedMountainBike::class, +])] +class DiscriminatedBike extends DiscriminatedVehicle +{ + public int $gears = 1; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedCar.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedCar.php new file mode 100644 index 00000000000..9190cc55db2 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedCar.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +use ApiPlatform\Metadata\ApiProperty; + +class DiscriminatedCar extends DiscriminatedVehicle +{ + /** + * Native property types are invariant in PHP: the narrowing is declared through PHPDoc. + * + * @var DiscriminatedCar|null + */ + public ?DiscriminatedVehicle $tows = null; + + #[ApiProperty(writable: false)] + public ?string $plate = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedMountainBike.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedMountainBike.php new file mode 100644 index 00000000000..5a06c6ba11d --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedMountainBike.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +final class DiscriminatedMountainBike extends DiscriminatedBike +{ + public ?string $suspension = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedSportsCar.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedSportsCar.php new file mode 100644 index 00000000000..ea4eeb63ffa --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedSportsCar.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +use ApiPlatform\Metadata\ApiProperty; + +/** + * Not declared in the discriminator map: it must be exposed exactly as a DiscriminatedCar. + */ +final class DiscriminatedSportsCar extends DiscriminatedCar +{ + #[ApiProperty(readable: false)] + public string $name = ''; + + public ?string $topSpeed = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedTruck.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedTruck.php new file mode 100644 index 00000000000..20e92a8338e --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedTruck.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +use ApiPlatform\Metadata\ApiProperty; +use Symfony\Component\Validator\Constraints as Assert; + +final class DiscriminatedTruck extends DiscriminatedVehicle +{ + #[Assert\Length(min: 5)] + public string $name = ''; + + #[ApiProperty(security: "is_granted('ROLE_ADMIN')")] + public ?string $plate = null; + + public ?int $payload = null; + + /** + * The setter cannot narrow its parameter (contravariance): writes are narrowed through validation. + */ + #[Assert\Type(self::class)] + protected ?DiscriminatedVehicle $trailer = null; + + /** + * Covariant return type: a truck only tows trucks. + */ + public function getTrailer(): ?self + { + \assert(null === $this->trailer || $this->trailer instanceof self); + + return $this->trailer; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicle.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicle.php new file mode 100644 index 00000000000..ca80987a2cd --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicle.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; +use Symfony\Component\Validator\Constraints as Assert; + +/** + * Polymorphic resource: its subtypes override inherited properties (narrowed types, metadata, constraints), + * bikes are discriminated by a nested map listing the bike itself. + */ +#[ApiResource( + operations: [ + new Get(), + new GetCollection(), + new Post(), + new Put(), + new Patch(), + new Delete(), + ], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], +)] +#[DiscriminatorMap(typeProperty: 'kind', mapping: [ + 'car' => DiscriminatedCar::class, + 'truck' => DiscriminatedTruck::class, + 'bike' => DiscriminatedBike::class, +])] +abstract class DiscriminatedVehicle +{ + #[ApiProperty(identifier: true, writable: false)] + public ?int $id = null; + + #[Assert\NotBlank] + public string $name = ''; + + public ?string $plate = null; + + public ?DiscriminatedVehicle $tows = null; + + protected ?DiscriminatedVehicle $trailer = null; + + public function getTrailer(): ?self + { + return $this->trailer; + } + + public function setTrailer(?self $trailer): void + { + $this->trailer = $trailer; + } + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): self|array|null + { + if ($operation instanceof GetCollection) { + return array_values(DiscriminatedVehicleStore::$vehicles); + } + + return DiscriminatedVehicleStore::$vehicles[(int) $uriVariables['id']] ?? null; + } + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?self + { + if ($operation instanceof Delete) { + unset(DiscriminatedVehicleStore::$vehicles[(int) $uriVariables['id']]); + + return null; + } + + if (isset($uriVariables['id'])) { + $data->id = (int) $uriVariables['id']; + } + + $data->id ??= (DiscriminatedVehicleStore::$vehicles ? max(array_keys(DiscriminatedVehicleStore::$vehicles)) : 0) + 1; + + return DiscriminatedVehicleStore::$vehicles[$data->id] = $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicleStore.php b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicleStore.php new file mode 100644 index 00000000000..78a4337799a --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/DiscriminatedResource/DiscriminatedVehicleStore.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource; + +final class DiscriminatedVehicleStore +{ + /** @var array */ + public static array $vehicles = []; +} diff --git a/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedCar.php b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedCar.php new file mode 100644 index 00000000000..4e6ed7df270 --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedCar.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Post; +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; +use Symfony\Component\Validator\Constraints as Assert; + +#[ApiResource(operations: [new Get(), new Post()])] +#[ODM\Document] +class DoctrineDiscriminatedCar extends DoctrineDiscriminatedVehicle +{ + #[ODM\Field(type: 'int')] + #[Assert\Positive] + public int $seats = 4; + + #[ODM\Field(nullable: true)] + #[ApiProperty(security: "is_granted('ROLE_ADMIN')")] + public ?string $vin = null; +} diff --git a/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php new file mode 100644 index 00000000000..23fddd176dc --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated; + +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ODM\Document] +class DoctrineDiscriminatedSportsCar extends DoctrineDiscriminatedCar +{ + #[ODM\Field(type: 'int')] + public int $topSpeed = 0; +} diff --git a/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php new file mode 100644 index 00000000000..ec3a076caad --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated; + +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +/** + * Not an API resource: exposed as a subtype of the vehicle resource. + */ +#[ODM\Document] +class DoctrineDiscriminatedTruck extends DoctrineDiscriminatedVehicle +{ + #[ODM\Field(type: 'int')] + public int $payload = 0; +} diff --git a/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php new file mode 100644 index 00000000000..49b0552b8dd --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; +use Symfony\Component\Validator\Constraints as Assert; + +/** + * Single collection inheritance: the subtypes are only declared in the Doctrine discriminator map. + */ +#[ApiResource(operations: [new Get(), new GetCollection(), new Post(), new Put(), new Patch(), new Delete()])] +#[ODM\Document] +#[ODM\InheritanceType('SINGLE_COLLECTION')] +#[ODM\DiscriminatorField('kind')] +#[ODM\DiscriminatorMap([ + 'car' => DoctrineDiscriminatedCar::class, + 'sportsCar' => DoctrineDiscriminatedSportsCar::class, + 'truck' => DoctrineDiscriminatedTruck::class, +])] +abstract class DoctrineDiscriminatedVehicle +{ + #[ODM\Id(strategy: 'INCREMENT', type: 'int')] + public ?int $id = null; + + #[ODM\Field] + #[Assert\NotBlank] + public string $name = ''; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedAnimal.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedAnimal.php new file mode 100644 index 00000000000..b06b49ad510 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedAnimal.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Post; +use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +/** + * The serializer discriminator map is the API contract: it takes precedence over the Doctrine one. + */ +#[ApiResource(operations: [new Get(), new GetCollection(), new Post()])] +#[ORM\Entity] +#[ORM\InheritanceType('SINGLE_TABLE')] +#[ORM\DiscriminatorColumn(name: 'discr', type: 'string')] +#[ORM\DiscriminatorMap(['dog' => DoctrineDiscriminatedDog::class, 'cat' => DoctrineDiscriminatedCat::class])] +#[DiscriminatorMap(typeProperty: 'species', mapping: ['canine' => DoctrineDiscriminatedDog::class])] +abstract class DoctrineDiscriminatedAnimal +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column(type: 'integer')] + public ?int $id = null; + + #[ORM\Column] + public string $name = ''; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCar.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCar.php new file mode 100644 index 00000000000..3f80e948131 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCar.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Post; +use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\Validator\Constraints as Assert; + +/** + * A resource in the middle of the hierarchy: it resolves its own subtypes from the Doctrine map. + */ +#[ApiResource(operations: [new Get(), new Post()])] +#[ORM\Entity] +class DoctrineDiscriminatedCar extends DoctrineDiscriminatedVehicle +{ + #[ORM\Column(type: 'integer')] + #[Assert\Positive] + public int $seats = 4; + + #[ORM\Column(nullable: true)] + #[ApiProperty(security: "is_granted('ROLE_ADMIN')")] + public ?string $vin = null; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCat.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCat.php new file mode 100644 index 00000000000..5d05aaf174d --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCat.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class DoctrineDiscriminatedCat extends DoctrineDiscriminatedAnimal +{ + #[ORM\Column(type: 'integer')] + public int $lives = 9; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCircle.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCircle.php new file mode 100644 index 00000000000..6061585f4a1 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedCircle.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class DoctrineDiscriminatedCircle extends DoctrineDiscriminatedShape +{ + #[ORM\Column(type: 'float')] + public float $radius = 0.0; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedDog.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedDog.php new file mode 100644 index 00000000000..e23f23d240e --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedDog.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class DoctrineDiscriminatedDog extends DoctrineDiscriminatedAnimal +{ + #[ORM\Column(type: 'boolean')] + public bool $goodBoy = true; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedShape.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedShape.php new file mode 100644 index 00000000000..3197e984d69 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedShape.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use Doctrine\ORM\Mapping as ORM; + +/** + * Class table inheritance with integer discriminator values. + */ +#[ApiResource(operations: [new Get(), new GetCollection(), new Post(), new Patch()])] +#[ORM\Entity] +#[ORM\InheritanceType('JOINED')] +#[ORM\DiscriminatorColumn(name: 'shapeType', type: 'integer')] +#[ORM\DiscriminatorMap([1 => DoctrineDiscriminatedCircle::class, 2 => DoctrineDiscriminatedSquare::class])] +abstract class DoctrineDiscriminatedShape +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column(type: 'integer')] + public ?int $id = null; + + #[ORM\Column] + public string $color = ''; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php new file mode 100644 index 00000000000..df93ec9801a --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSportsCar.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class DoctrineDiscriminatedSportsCar extends DoctrineDiscriminatedCar +{ + #[ORM\Column(type: 'integer')] + public int $topSpeed = 0; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSquare.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSquare.php new file mode 100644 index 00000000000..5c5546be455 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedSquare.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +#[ORM\Entity] +class DoctrineDiscriminatedSquare extends DoctrineDiscriminatedShape +{ + #[ORM\Column(type: 'float')] + public float $side = 0.0; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php new file mode 100644 index 00000000000..4a4ed70b69b --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedTruck.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use Doctrine\ORM\Mapping as ORM; + +/** + * Not an API resource: exposed as a subtype of the vehicle resource. + */ +#[ORM\Entity] +class DoctrineDiscriminatedTruck extends DoctrineDiscriminatedVehicle +{ + #[ORM\Column(type: 'integer')] + public int $payload = 0; +} diff --git a/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php new file mode 100644 index 00000000000..172ac1a88ad --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DoctrineDiscriminated/DoctrineDiscriminatedVehicle.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\Validator\Constraints as Assert; + +/** + * Single table inheritance: the subtypes are only declared in the Doctrine discriminator map. + */ +#[ApiResource(operations: [new Get(), new GetCollection(), new Post(), new Put(), new Patch(), new Delete()])] +#[ORM\Entity] +#[ORM\InheritanceType('SINGLE_TABLE')] +#[ORM\DiscriminatorColumn(name: 'kind', type: 'string')] +#[ORM\DiscriminatorMap([ + 'car' => DoctrineDiscriminatedCar::class, + 'sportsCar' => DoctrineDiscriminatedSportsCar::class, + 'truck' => DoctrineDiscriminatedTruck::class, +])] +abstract class DoctrineDiscriminatedVehicle +{ + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column(type: 'integer')] + public ?int $id = null; + + #[ORM\Column] + #[Assert\NotBlank] + public string $name = ''; +} diff --git a/tests/Fixtures/app/config/config_common.yml b/tests/Fixtures/app/config/config_common.yml index b1d280c406f..606c7bbc028 100644 --- a/tests/Fixtures/app/config/config_common.yml +++ b/tests/Fixtures/app/config/config_common.yml @@ -46,6 +46,8 @@ api_platform: Made with love enable_swagger: true enable_swagger_ui: true + serializer: + discriminator_map: true formats: jsonld: ['application/ld+json'] jsonhal: ['application/hal+json'] diff --git a/tests/Functional/DiscriminatedResourceTest.php b/tests/Functional/DiscriminatedResourceTest.php new file mode 100644 index 00000000000..0cd1e2bed07 --- /dev/null +++ b/tests/Functional/DiscriminatedResourceTest.php @@ -0,0 +1,349 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedBike; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedMountainBike; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedSportsCar; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedVehicle; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedResource\DiscriminatedVehicleStore; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use PHPUnit\Framework\Attributes\DataProvider; +use Symfony\Component\Security\Core\User\InMemoryUser; + +/** + * Polymorphic resources declared through a serializer discriminator map. + */ +final class DiscriminatedResourceTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [DiscriminatedVehicle::class]; + } + + protected function setUp(): void + { + $car = new DiscriminatedCar(); + $car->id = 1; + $car->name = 'Beetle'; + $car->plate = 'AB-123'; + + $truck = new DiscriminatedTruck(); + $truck->id = 2; + $truck->name = 'Actros'; + $truck->plate = 'TR-999'; + $truck->payload = 18000; + + $sportsCar = new DiscriminatedSportsCar(); + $sportsCar->id = 3; + $sportsCar->name = 'Carrera'; + $sportsCar->topSpeed = '300'; + + $mountainBike = new DiscriminatedMountainBike(); + $mountainBike->id = 4; + $mountainBike->name = 'Rocky'; + $mountainBike->gears = 21; + $mountainBike->suspension = 'full'; + + $bike = new DiscriminatedBike(); + $bike->id = 5; + $bike->name = 'Fixie'; + + DiscriminatedVehicleStore::$vehicles = [1 => $car, 2 => $truck, 3 => $sportsCar, 4 => $mountainBike, 5 => $bike]; + } + + protected function tearDown(): void + { + DiscriminatedVehicleStore::$vehicles = []; + + parent::tearDown(); + } + + /** + * @return iterable + */ + public static function formatProvider(): iterable + { + yield 'jsonld' => ['application/ld+json', 'jsonld']; + yield 'json' => ['application/json', 'json']; + yield 'jsonapi' => ['application/vnd.api+json', 'jsonapi']; + yield 'hal' => ['application/hal+json', 'jsonhal']; + } + + #[DataProvider('formatProvider')] + public function testGetItemExposesSubtypeProperties(string $accept, string $format): void + { + $json = self::createClient()->request('GET', '/discriminated_vehicles/2', ['headers' => ['Accept' => $accept]])->toArray(); + + $this->assertResponseIsSuccessful(); + $attributes = $json['data']['attributes'] ?? $json; + $this->assertSame('truck', $attributes['kind']); + $this->assertSame('Actros', $attributes['name']); + $this->assertSame(18000, $attributes['payload']); + // Subtype property security + $this->assertArrayNotHasKey('plate', $attributes); + if ('jsonhal' !== $format) { + $this->assertMatchesResourceItemJsonSchema(DiscriminatedVehicle::class, format: $format); + } + } + + /** + * @return iterable, list}> + */ + public static function typeProvider(): iterable + { + yield 'nested map' => [4, ['@type' => 'DiscriminatedMountainBike', 'kind' => 'bike', 'frame' => 'mountain', 'gears' => 21, 'suspension' => 'full'], []]; + yield 'class declared in its own nested map' => [5, ['@type' => 'DiscriminatedBike', 'kind' => 'bike', 'frame' => 'bike', 'gears' => 1], ['suspension']]; + yield 'unmapped subclass exposed as its mapped parent' => [3, ['@type' => 'DiscriminatedCar', 'kind' => 'car', 'name' => 'Carrera'], ['topSpeed']]; + } + + /** + * @param array $expected + * @param list $absent + */ + #[DataProvider('typeProvider')] + public function testGetItemExposesTheTypeOfEveryMap(int $id, array $expected, array $absent): void + { + $json = self::createClient()->request('GET', '/discriminated_vehicles/'.$id)->toArray(); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains($expected); + foreach ($absent as $property) { + $this->assertArrayNotHasKey($property, $json); + } + $this->assertMatchesResourceItemJsonSchema(DiscriminatedVehicle::class); + } + + /** + * The allowed attributes are cached per cache key, subtype property security must make that key unsafe + * or the attributes allowed for a user leak to the next ones in long-running processes. + */ + public function testSubtypePropertySecurityIsNotCachedAcrossUsers(): void + { + $client = self::createClient(); + $client->disableReboot(); + + foreach ([true, false, true] as $admin) { + $client->getCookieJar()->clear(); + if ($admin) { + $client->loginUser(new InMemoryUser('admin', 'password', ['ROLE_ADMIN'])); + } + + $json = $client->request('GET', '/discriminated_vehicles/2', ['headers' => ['Accept' => 'application/json']])->toArray(); + $this->assertSame($admin ? 'TR-999' : null, $json['plate'] ?? null); + } + } + + public function testGetCollectionExposesEachSubtype(): void + { + $members = self::createClient()->request('GET', '/discriminated_vehicles')->toArray()['hydra:member']; + + $this->assertResponseIsSuccessful(); + $this->assertSame(['car', 'truck', 'car', 'bike', 'bike'], array_column($members, 'kind')); + $this->assertSame(['DiscriminatedCar', 'DiscriminatedTruck', 'DiscriminatedCar', 'DiscriminatedMountainBike', 'DiscriminatedBike'], array_column($members, '@type')); + $this->assertSame(18000, $members[1]['payload']); + $this->assertArrayNotHasKey('payload', $members[0]); + $this->assertMatchesResourceCollectionJsonSchema(DiscriminatedVehicle::class); + } + + /** + * @return iterable, class-string}> + */ + public static function postProvider(): iterable + { + yield 'subtype' => [['kind' => 'truck', 'name' => 'Scania', 'payload' => 12000], DiscriminatedTruck::class]; + yield 'nested subtype' => [['kind' => 'bike', 'frame' => 'mountain', 'name' => 'Trek', 'suspension' => 'hardtail'], DiscriminatedMountainBike::class]; + yield 'class declared in its own nested map' => [['kind' => 'bike', 'frame' => 'bike', 'name' => 'Brompton', 'gears' => 3], DiscriminatedBike::class]; + } + + /** + * @param array $payload + * @param class-string $class + */ + #[DataProvider('postProvider')] + public function testPostCreatesTheMostSpecificSubtype(array $payload, string $class): void + { + self::createClient()->request('POST', '/discriminated_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => $payload, + ]); + + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['@id' => '/discriminated_vehicles/6', '@type' => substr($class, strrpos($class, '\\') + 1)] + $payload); + $this->assertSame($class, DiscriminatedVehicleStore::$vehicles[6]::class); + } + + public function testOverriddenPropertyMetadataIsEnforcedOnWrite(): void + { + $client = self::createClient(); + + // "plate" is not writable on cars + $client->request('POST', '/discriminated_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'car', 'name' => 'Golf', 'plate' => 'not writable'], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertNull(DiscriminatedVehicleStore::$vehicles[6]->plate); + + // "plate" is restricted to admins on trucks + $client->request('POST', '/discriminated_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Scania', 'plate' => 'admins only'], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertNull(DiscriminatedVehicleStore::$vehicles[7]->plate); + } + + /** + * @return iterable}> + */ + public static function invalidPayloadProvider(): iterable + { + yield 'no type' => ['POST', '/discriminated_vehicles', ['name' => 'Untyped']]; + yield 'unknown type' => ['POST', '/discriminated_vehicles', ['kind' => 'plane', 'name' => 'Unknown']]; + yield 'no nested type' => ['POST', '/discriminated_vehicles', ['kind' => 'bike', 'name' => 'Untyped bike']]; + yield 'relation narrowed by the subtype' => ['POST', '/discriminated_vehicles', ['kind' => 'car', 'name' => 'Polo', 'tows' => '/discriminated_vehicles/2']]; + yield 'type change' => ['PATCH', '/discriminated_vehicles/1', ['kind' => 'truck', 'payload' => 1]]; + yield 'nested type change' => ['PATCH', '/discriminated_vehicles/4', ['frame' => 'bike']]; + } + + /** + * @param array $payload + */ + #[DataProvider('invalidPayloadProvider')] + public function testInvalidPayloadIsRejected(string $method, string $uri, array $payload): void + { + $classes = array_map(static fn (DiscriminatedVehicle $vehicle): string => $vehicle::class, DiscriminatedVehicleStore::$vehicles); + + self::createClient()->request($method, $uri, [ + 'headers' => ['Content-Type' => 'PATCH' === $method ? 'application/merge-patch+json' : 'application/ld+json'], + 'json' => $payload, + ]); + + $this->assertResponseStatusCodeSame(400); + $this->assertSame($classes, array_map(static fn (DiscriminatedVehicle $vehicle): string => $vehicle::class, DiscriminatedVehicleStore::$vehicles)); + } + + /** + * @return iterable, string}> + */ + public static function constraintViolationProvider(): iterable + { + yield 'subtype constraint on POST' => ['POST', '/discriminated_vehicles', ['kind' => 'truck', 'name' => 'MAN'], 'name']; + yield 'subtype constraint on PATCH' => ['PATCH', '/discriminated_vehicles/2', ['name' => 'MAN'], 'name']; + // A setter parameter cannot be narrowed (contravariance): the covariant getter is enforced by validation + yield 'covariant getter' => ['POST', '/discriminated_vehicles', ['kind' => 'truck', 'name' => 'Volvo FH', 'trailer' => '/discriminated_vehicles/1'], 'trailer']; + } + + /** + * @param array $payload + */ + #[DataProvider('constraintViolationProvider')] + public function testSubtypeConstraintsAreValidated(string $method, string $uri, array $payload, string $propertyPath): void + { + self::createClient()->request($method, $uri, [ + 'headers' => ['Content-Type' => 'PATCH' === $method ? 'application/merge-patch+json' : 'application/ld+json'], + 'json' => $payload, + ]); + + $this->assertResponseStatusCodeSame(422); + $this->assertJsonContains(['violations' => [['propertyPath' => $propertyPath]]]); + } + + public function testPatchUpdatesSubtypeProperties(): void + { + self::createClient()->request('PATCH', '/discriminated_vehicles/2', [ + 'headers' => ['Content-Type' => 'application/merge-patch+json'], + 'json' => ['kind' => 'truck', 'payload' => 20000], + ]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains(['kind' => 'truck', 'name' => 'Actros', 'payload' => 20000]); + $this->assertInstanceOf(DiscriminatedTruck::class, DiscriminatedVehicleStore::$vehicles[2]); + } + + public function testPutReplacesTheResourceWithTheGivenSubtype(): void + { + self::createClient()->request('PUT', '/discriminated_vehicles/1', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Unimog', 'payload' => 5000], + ]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains(['@id' => '/discriminated_vehicles/1', '@type' => 'DiscriminatedTruck', 'kind' => 'truck', 'payload' => 5000]); + $this->assertInstanceOf(DiscriminatedTruck::class, DiscriminatedVehicleStore::$vehicles[1]); + } + + public function testOpenApiDocumentsSubtypes(): void + { + $json = self::createClient()->request('GET', '/docs', [ + 'headers' => ['Accept' => 'application/vnd.openapi+json'], + ])->toArray(); + $schemas = $json['components']['schemas']; + + $output = $schemas['DiscriminatedVehicle.jsonld']['allOf'][1] ?? $schemas['DiscriminatedVehicle.jsonld']; + $this->assertSame([ + 'propertyName' => 'kind', + 'mapping' => [ + 'car' => '#/components/schemas/DiscriminatedVehicle.DiscriminatedCar.jsonld', + 'truck' => '#/components/schemas/DiscriminatedVehicle.DiscriminatedTruck.jsonld', + 'bike' => '#/components/schemas/DiscriminatedVehicle.DiscriminatedBike.jsonld', + ], + ], $output['discriminator']); + $this->assertCount(3, $output['oneOf']); + $this->assertArrayNotHasKey('properties', $output); + + $truck = $schemas['DiscriminatedVehicle.DiscriminatedTruck.jsonld']; + $this->assertSame(['type' => 'string', 'enum' => ['truck']], $truck['properties']['kind']); + $this->assertArrayHasKey('payload', $truck['properties']); + $this->assertSame(5, $truck['properties']['name']['minLength']); + $this->assertArrayNotHasKey('minLength', $schemas['DiscriminatedVehicle.DiscriminatedCar.jsonld']['properties']['name']); + + // The nested map lists the bike itself: an instance of the bike is described by an inline branch + $bike = $schemas['DiscriminatedVehicle.DiscriminatedBike.jsonld']; + $this->assertSame('frame', $bike['discriminator']['propertyName']); + $this->assertSame(['type' => 'string', 'enum' => ['bike']], $bike['oneOf'][0]['properties']['frame']); + $this->assertSame(['$ref' => '#/components/schemas/DiscriminatedVehicle.DiscriminatedMountainBike.jsonld'], $bike['oneOf'][1]); + + // Unmapped subclasses are never documented + $this->assertArrayNotHasKey('DiscriminatedVehicle.DiscriminatedSportsCar.jsonld', $schemas); + } + + public function testHydraDocumentsSubtypesAsSubclasses(): void + { + $client = self::createClient(); + + $classes = array_column($client->request('GET', '/docs.jsonld')->toArray()['hydra:supportedClass'], null, '@id'); + $truck = $classes['#DiscriminatedTruck']; + $this->assertSame('#DiscriminatedVehicle', $truck['subClassOf']); + $this->assertSame(['#DiscriminatedTruck/payload'], array_column(array_column($truck['hydra:supportedProperty'], 'hydra:property'), '@id')); + $this->assertSame('#DiscriminatedBike', $classes['#DiscriminatedMountainBike']['subClassOf']); + $this->assertArrayNotHasKey('#DiscriminatedSportsCar', $classes); + + $context = $client->request('GET', '/contexts/DiscriminatedVehicle')->toArray()['@context']; + $this->assertSame('DiscriminatedVehicle/name', $context['name']); + $this->assertSame('DiscriminatedTruck/payload', $context['payload']); + $this->assertSame('DiscriminatedMountainBike/suspension', $context['suspension']); + } +} diff --git a/tests/Functional/DoctrineDiscriminatedDocumentTest.php b/tests/Functional/DoctrineDiscriminatedDocumentTest.php new file mode 100644 index 00000000000..ec87799a015 --- /dev/null +++ b/tests/Functional/DoctrineDiscriminatedDocumentTest.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated\DoctrineDiscriminatedSportsCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +/** + * Polymorphic resources declared through the Doctrine MongoDB ODM discriminator map only. + */ +final class DoctrineDiscriminatedDocumentTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DoctrineDiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [DoctrineDiscriminatedVehicle::class, DoctrineDiscriminatedCar::class]; + } + + protected function setUp(): void + { + if (!$this->isMongoDB()) { + $this->markTestSkipped('MongoDB ODM only, see DoctrineDiscriminatedResourceTest.'); + } + + $this->recreateSchema([ + DoctrineDiscriminatedVehicle::class, + DoctrineDiscriminatedCar::class, + DoctrineDiscriminatedSportsCar::class, + DoctrineDiscriminatedTruck::class, + ]); + + $car = new DoctrineDiscriminatedCar(); + $car->name = 'Family car'; + $car->seats = 5; + $car->vin = 'secret-vin'; + + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Big truck'; + $truck->payload = 20000; + + $manager = $this->getManager(); + $manager->persist($car); + $manager->persist($truck); + $manager->flush(); + $manager->clear(); + } + + public function testGetAndPostANonResourceSubtype(): void + { + $client = self::createClient(); + + $client->request('GET', '/doctrine_discriminated_vehicles/2'); + $this->assertResponseIsSuccessful(); + $this->assertJsonEquals([ + '@context' => '/contexts/DoctrineDiscriminatedVehicle', + '@id' => '/doctrine_discriminated_vehicles/2', + '@type' => 'DoctrineDiscriminatedTruck', + 'kind' => 'truck', + 'id' => 2, + 'name' => 'Big truck', + 'payload' => 20000, + ]); + + $client->request('POST', '/doctrine_discriminated_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Small truck', 'payload' => 3500], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['@id' => '/doctrine_discriminated_vehicles/3', 'kind' => 'truck', 'payload' => 3500]); + + $manager = $this->getManager(); + $manager->clear(); + $this->assertInstanceOf(DoctrineDiscriminatedTruck::class, $manager->find(DoctrineDiscriminatedVehicle::class, 3)); + } +} diff --git a/tests/Functional/DoctrineDiscriminatedResourceTest.php b/tests/Functional/DoctrineDiscriminatedResourceTest.php new file mode 100644 index 00000000000..97d352e843c --- /dev/null +++ b/tests/Functional/DoctrineDiscriminatedResourceTest.php @@ -0,0 +1,207 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedAnimal; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCat; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedCircle; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedDog; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedShape; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedSportsCar; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedSquare; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedTruck; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DoctrineDiscriminated\DoctrineDiscriminatedVehicle; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +/** + * Polymorphic resources declared through the Doctrine ORM discriminator map only. + */ +final class DoctrineDiscriminatedResourceTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + protected static function getKernelClass(): string + { + return DoctrineDiscriminatorMapAppKernel::class; + } + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [ + DoctrineDiscriminatedVehicle::class, + DoctrineDiscriminatedCar::class, + DoctrineDiscriminatedShape::class, + DoctrineDiscriminatedAnimal::class, + ]; + } + + protected function setUp(): void + { + if ($this->isMongoDB()) { + $this->markTestSkipped('ORM only, see DoctrineDiscriminatedDocumentTest.'); + } + + $this->recreateSchema([ + DoctrineDiscriminatedVehicle::class, + DoctrineDiscriminatedCar::class, + DoctrineDiscriminatedSportsCar::class, + DoctrineDiscriminatedTruck::class, + DoctrineDiscriminatedShape::class, + DoctrineDiscriminatedCircle::class, + DoctrineDiscriminatedSquare::class, + DoctrineDiscriminatedAnimal::class, + DoctrineDiscriminatedDog::class, + DoctrineDiscriminatedCat::class, + ]); + + $car = new DoctrineDiscriminatedCar(); + $car->name = 'Family car'; + $car->seats = 5; + $car->vin = 'secret-vin'; + + $truck = new DoctrineDiscriminatedTruck(); + $truck->name = 'Big truck'; + $truck->payload = 20000; + + $sportsCar = new DoctrineDiscriminatedSportsCar(); + $sportsCar->name = 'Fast car'; + $sportsCar->seats = 2; + $sportsCar->topSpeed = 320; + + $circle = new DoctrineDiscriminatedCircle(); + $circle->color = 'red'; + $circle->radius = 2.5; + + $dog = new DoctrineDiscriminatedDog(); + $dog->name = 'Rex'; + + $manager = $this->getManager(); + foreach ([$car, $truck, $sportsCar, $circle, $dog] as $entity) { + $manager->persist($entity); + } + $manager->flush(); + $manager->clear(); + } + + public function testGetAndPostANonResourceSubtype(): void + { + $client = self::createClient(); + + $client->request('GET', '/doctrine_discriminated_vehicles/2'); + $this->assertResponseIsSuccessful(); + $this->assertJsonEquals([ + '@context' => '/contexts/DoctrineDiscriminatedVehicle', + '@id' => '/doctrine_discriminated_vehicles/2', + '@type' => 'DoctrineDiscriminatedTruck', + 'kind' => 'truck', + 'id' => 2, + 'name' => 'Big truck', + 'payload' => 20000, + ]); + + $client->request('POST', '/doctrine_discriminated_vehicles', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['kind' => 'truck', 'name' => 'Small truck', 'payload' => 3500], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['@id' => '/doctrine_discriminated_vehicles/4', '@type' => 'DoctrineDiscriminatedTruck', 'kind' => 'truck', 'payload' => 3500]); + + $truck = $this->findVehicle(4); + $this->assertInstanceOf(DoctrineDiscriminatedTruck::class, $truck); + $this->assertSame(3500, $truck->payload); + } + + public function testGetItemOfAResourceSubtypeUsesItsOwnResource(): void + { + self::createClient()->request('GET', '/doctrine_discriminated_cars/3'); + + $this->assertResponseIsSuccessful(); + $this->assertJsonEquals([ + '@context' => '/contexts/DoctrineDiscriminatedCar', + '@id' => '/doctrine_discriminated_cars/3', + '@type' => 'DoctrineDiscriminatedSportsCar', + 'kind' => 'sportsCar', + 'id' => 3, + 'name' => 'Fast car', + 'seats' => 2, + 'topSpeed' => 320, + ]); + } + + public function testJoinedInheritanceWithIntegerDiscriminatorValues(): void + { + $client = self::createClient(); + + $client->request('GET', '/doctrine_discriminated_shapes/1'); + $this->assertResponseIsSuccessful(); + $this->assertJsonEquals([ + '@context' => '/contexts/DoctrineDiscriminatedShape', + '@id' => '/doctrine_discriminated_shapes/1', + '@type' => 'DoctrineDiscriminatedCircle', + 'shapeType' => '1', + 'id' => 1, + 'color' => 'red', + 'radius' => 2.5, + ]); + + $client->request('POST', '/doctrine_discriminated_shapes', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['shapeType' => '2', 'color' => 'blue', 'side' => 3], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertJsonContains(['shapeType' => '2', 'side' => 3]); + $this->assertInstanceOf(DoctrineDiscriminatedSquare::class, $this->getManager()->find(DoctrineDiscriminatedShape::class, 2)); + } + + public function testSerializerDiscriminatorMapTakesPrecedence(): void + { + $client = self::createClient(); + + $client->request('GET', '/doctrine_discriminated_animals/1'); + $this->assertResponseIsSuccessful(); + $this->assertJsonEquals([ + '@context' => '/contexts/DoctrineDiscriminatedAnimal', + '@id' => '/doctrine_discriminated_animals/1', + '@type' => 'DoctrineDiscriminatedDog', + 'species' => 'canine', + 'id' => 1, + 'name' => 'Rex', + 'goodBoy' => true, + ]); + + // Only the subtypes of the serializer map can be created, using its type property + $client->request('POST', '/doctrine_discriminated_animals', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['discr' => 'cat', 'name' => 'Tom', 'lives' => 7], + ]); + $this->assertResponseStatusCodeSame(400); + } + + private function findVehicle(int $id): ?DoctrineDiscriminatedVehicle + { + $manager = $this->getManager(); + $manager->clear(); + + return $manager->find(DoctrineDiscriminatedVehicle::class, $id); + } +} diff --git a/tests/Functional/DoctrineDiscriminatorMapAppKernel.php b/tests/Functional/DoctrineDiscriminatorMapAppKernel.php new file mode 100644 index 00000000000..e7d1315c029 --- /dev/null +++ b/tests/Functional/DoctrineDiscriminatorMapAppKernel.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Functional; + +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * Enables the (opt-in) Doctrine discriminator maps of the active Doctrine integration. + */ +class DoctrineDiscriminatorMapAppKernel extends \AppKernel +{ + public function getCacheDir(): string + { + return parent::getCacheDir().'/doctrine_discriminator_map'; + } + + public function getLogDir(): string + { + return parent::getLogDir().'/doctrine_discriminator_map'; + } + + protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader): void + { + parent::configureContainer($c, $loader); + + $integration = 'mongodb' === $this->environment ? 'doctrine_mongodb_odm' : 'doctrine'; + $loader->load(static function (ContainerBuilder $container) use ($integration): void { + $container->loadFromExtension('api_platform', [ + $integration => ['discriminator_map' => true], + ]); + }); + } +} diff --git a/tests/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPassTest.php b/tests/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPassTest.php new file mode 100644 index 00000000000..4f6c5ca9c68 --- /dev/null +++ b/tests/Symfony/Bundle/DependencyInjection/Compiler/SerializerMappingLoaderPassTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Tests\Symfony\Bundle\DependencyInjection\Compiler; + +use ApiPlatform\Doctrine\Common\Serializer\Mapping\Loader\DoctrineDiscriminatorMappingLoader; +use ApiPlatform\Serializer\Mapping\Loader\PropertyMetadataLoader; +use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\SerializerMappingLoaderPass; +use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; +use Symfony\Component\Serializer\Mapping\Loader\LoaderChain; + +final class SerializerMappingLoaderPassTest extends TestCase +{ + public function testDoctrineDiscriminatorMappingLoadersAreAppendedAfterTheOtherLoaders(): void + { + $container = $this->createContainer(); + $orm = $container->register('api_platform.doctrine.orm.serializer.discriminator_mapping_loader', DoctrineDiscriminatorMappingLoader::class); + $odm = $container->register('api_platform.doctrine_mongodb.odm.serializer.discriminator_mapping_loader', DoctrineDiscriminatorMappingLoader::class); + + (new SerializerMappingLoaderPass())->process($container); + + $chainLoaders = $container->getDefinition('serializer.mapping.chain_loader')->getArgument(0); + $this->assertCount(3, $chainLoaders); + $this->assertSame([$orm, $odm], \array_slice($chainLoaders, 1)); + + foreach ([$orm, $odm] as $loader) { + $serializerLoader = $loader->getArgument('$serializerLoader'); + $this->assertSame(LoaderChain::class, $serializerLoader->getClass()); + $this->assertSame([$chainLoaders[0]], $serializerLoader->getArgument(0)); + } + + // The cache warmer builds the metadata of the classes mapped by the other loaders: they must get their Doctrine map too + $warmerLoaders = $container->getDefinition('serializer.mapping.cache_warmer')->getArgument(0); + $this->assertSame([$chainLoaders[0], $container->getDefinition('api_platform.serializer.property_metadata_loader'), $orm, $odm], $warmerLoaders); + } + + public function testChainLoaderIsUntouchedWithoutDoctrineDiscriminatorMappingLoader(): void + { + $container = $this->createContainer(); + + (new SerializerMappingLoaderPass())->process($container); + + $this->assertCount(1, $container->getDefinition('serializer.mapping.chain_loader')->getArgument(0)); + $this->assertCount(2, $container->getDefinition('serializer.mapping.cache_warmer')->getArgument(0)); + } + + private function createContainer(): ContainerBuilder + { + $container = new ContainerBuilder(); + $attributeLoader = new Definition(AttributeLoader::class); + $container->register('serializer.mapping.chain_loader')->setArguments([[$attributeLoader]]); + $container->register('serializer.mapping.cache_warmer')->setArguments([[], '%kernel.cache_dir%/serializer.php']); + $container->register('api_platform.serializer.property_metadata_loader', PropertyMetadataLoader::class); + + return $container; + } +} diff --git a/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php b/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php index 8da7010b910..cb8bceb5715 100644 --- a/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php +++ b/tests/Symfony/Bundle/DependencyInjection/ConfigurationTest.php @@ -200,9 +200,11 @@ private function runDefaultConfigTests(array $doctrineIntegrationsToLoad = ['orm ], 'doctrine' => [ 'enabled' => \in_array('orm', $doctrineIntegrationsToLoad, true), + 'discriminator_map' => false, ], 'doctrine_mongodb_odm' => [ 'enabled' => \in_array('odm', $doctrineIntegrationsToLoad, true), + 'discriminator_map' => false, ], 'messenger' => [ 'enabled' => true, @@ -240,6 +242,7 @@ private function runDefaultConfigTests(array $doctrineIntegrationsToLoad = ['orm 'handle_symfony_errors' => false, 'serializer' => [ 'hydra_prefix' => null, + 'discriminator_map' => false, ], 'enable_phpdoc_parser' => true, 'mcp' => [